forked from
mary.my.id/atcute
a collection of lightweight TypeScript packages for AT Protocol, the protocol powering Bluesky
1import type { IdResolver } from '@atproto/identity';
2
3import axios from 'axios';
4
5import type { TestPdsServer } from './pds.js';
6
7export const mockNetworkUtilities = (pds: TestPdsServer) => {
8 mockResolvers(pds.ctx.idResolver, pds);
9};
10
11export const mockResolvers = (idResolver: IdResolver, pds: TestPdsServer) => {
12 // Map pds public url to its local url when resolving from plc
13 const origResolveDid = idResolver.did.resolveNoCache;
14 idResolver.did.resolveNoCache = async (did: string) => {
15 const result = await (origResolveDid.call(idResolver.did, did) as ReturnType<typeof origResolveDid>);
16 const service = result?.service?.find((svc) => svc.id === '#atproto_pds');
17
18 if (typeof service?.serviceEndpoint === 'string') {
19 service.serviceEndpoint = service.serviceEndpoint.replace(
20 pds.ctx.cfg.service.publicUrl,
21 `http://localhost:${pds.port}`,
22 );
23 }
24
25 return result;
26 };
27
28 const origResolveHandleDns = idResolver.handle.resolveDns;
29 idResolver.handle.resolve = async (handle: string) => {
30 const isPdsHandle = pds.ctx.cfg.identity.serviceHandleDomains.some((domain) => handle.endsWith(domain));
31
32 if (!isPdsHandle) {
33 return origResolveHandleDns.call(idResolver.handle, handle);
34 }
35
36 const url = `${pds.url}/.well-known/atproto-did`;
37 try {
38 const res = await axios.get(url, { headers: { host: handle } });
39 return res.data;
40 } catch (err) {
41 return undefined;
42 }
43 };
44};