From 9a19bfbfa2465b31a915da026b4745e148eaefd8 Mon Sep 17 00:00:00 2001 From: Chad Miller Date: Thu, 17 Sep 2026 12:52:56 -0700 Subject: [PATCH] fix(oauth): resolve a handle by DNS and well-known before asking any PDS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A handle was resolved by asking one PDS: the local one in dev, the one behind a self-hosted relay, or bsky.social. Whichever it was, it only knew its own handles, so on a network whose members live on other hosts a sign-in failed at the first step with "resolveHandle failed: 400". The protocol defines two ways to resolve a handle that work for any PDS — the `_atproto` TXT record and the well-known document — and both are now asked first. The PDS fallback stays for names neither can answer: a dev network's `.test` handles have no DNS and no TLS. Co-Authored-By: Claude Fable 5.1 --- packages/hatk/src/oauth/discovery.ts | 47 +++++++++++++++- packages/hatk/test/discovery.test.ts | 67 +++++++++++++++++++---- packages/hatk/test/oauth-par-flow.test.ts | 10 +++- 3 files changed, 108 insertions(+), 16 deletions(-) diff --git a/packages/hatk/src/oauth/discovery.ts b/packages/hatk/src/oauth/discovery.ts index 0302efd..0ee1736 100644 --- a/packages/hatk/src/oauth/discovery.ts +++ b/packages/hatk/src/oauth/discovery.ts @@ -1,3 +1,5 @@ +import { resolveTxt } from 'node:dns/promises' + // packages/hatk/src/oauth/discovery.ts export interface AuthServerMetadata { @@ -61,10 +63,49 @@ export async function discoverAuthServer( return { pdsEndpoint, authServerEndpoint, authServerMetadata } } +const HANDLE_RESOLVE_TIMEOUT_MS = 5000 + +/** The DNS method: a `_atproto.` TXT record carrying `did=...`. */ +async function resolveHandleViaDns(handle: string): Promise { + try { + for (const chunks of await resolveTxt(`_atproto.${handle}`)) { + const txt = chunks.join('') + if (txt.startsWith('did=')) return txt.slice('did='.length).trim() + } + } catch { + // No record, or not a resolvable name: not this method. + } + return null +} + +/** The HTTPS method: `https:///.well-known/atproto-did`, the DID as plain text. */ +async function resolveHandleViaWellKnown(handle: string): Promise { + try { + const res = await fetch(`https://${handle}/.well-known/atproto-did`, { + signal: AbortSignal.timeout(HANDLE_RESOLVE_TIMEOUT_MS), + }) + if (!res.ok) return null + const did = (await res.text()).trim().split('\n')[0].trim() + return did.startsWith('did:') ? did : null + } catch { + return null + } +} + +/** + * A handle to its DID. + * + * The protocol defines two ways, and both are asked first: the DNS TXT record + * and the well-known document. Either answers for a handle on any PDS, which + * is what lets somebody from another host sign in here. A handle neither + * method knows — a dev network's `.test` names, which have no DNS and no TLS + * — falls back to asking a PDS: the local one in dev, the one behind a + * self-hosted relay, or bsky.social. + */ export async function resolveHandle(handle: string, relayUrl?: string): Promise { - // Resolve against the configured network: the localhost PDS in dev, the public - // AppView in prod, or a self-hosted PDS (e.g. preview environments) derived - // from its relay/firehose URL — otherwise self-hosted handles 400 against bsky. + const direct = (await resolveHandleViaDns(handle)) ?? (await resolveHandleViaWellKnown(handle)) + if (direct) return direct + let baseUrl: string if (relayUrl?.includes('localhost:2583')) { baseUrl = 'http://localhost:2583' diff --git a/packages/hatk/test/discovery.test.ts b/packages/hatk/test/discovery.test.ts index 4156259..96c36e6 100644 --- a/packages/hatk/test/discovery.test.ts +++ b/packages/hatk/test/discovery.test.ts @@ -1,4 +1,13 @@ import { afterEach, describe, expect, test, vi } from 'vitest' + +// Handle resolution asks DNS first. Nothing resolves unless a test says so, +// and no test reaches a real resolver. +const dns = vi.hoisted(() => ({ + resolveTxt: vi.fn(async (): Promise => { + throw new Error('ENOTFOUND') + }), +})) +vi.mock('node:dns/promises', () => dns) import { discoverAuthServer, fetchAuthServerMetadata, @@ -166,42 +175,76 @@ describe('discoverAuthServer', () => { describe('resolveHandle', () => { const answer = () => json({ did: 'did:plc:resolved' }) const path = '/xrpc/com.atproto.identity.resolveHandle?handle=alice.test' + const wellKnown = 'https://alice.test/.well-known/atproto-did' + + afterEach(() => { + dns.resolveTxt.mockReset() + dns.resolveTxt.mockImplementation(async () => { + throw new Error('ENOTFOUND') + }) + }) + + test('a DNS TXT record answers first, and nothing else is asked', async () => { + dns.resolveTxt.mockResolvedValueOnce([['did=did:plc:fromdns']]) + const seen = stubRoutes({}) + + expect(await resolveHandle('alice.test', 'wss://bsky.network')).toBe('did:plc:fromdns') + expect(dns.resolveTxt).toHaveBeenCalledWith('_atproto.alice.test') + expect(seen).toEqual([]) + }) + + test('the well-known document answers when DNS has nothing', async () => { + // A handle on any PDS resolves this way — including one on another host + // than the relay this instance tails. + const seen = stubRoutes({ [wellKnown]: new Response('did:plc:fromwellknown\n', { status: 200 }) }) + + expect(await resolveHandle('alice.test', 'wss://host.example')).toBe('did:plc:fromwellknown') + expect(seen).toEqual([wellKnown]) + }) + + test('a well-known body that is not a DID is ignored', async () => { + const seen = stubRoutes({ + [wellKnown]: new Response('parked', { status: 200 }), + [`https://bsky.social${path}`]: answer, + }) + + expect(await resolveHandle('alice.test', 'wss://bsky.network')).toBe('did:plc:resolved') + expect(seen).toEqual([wellKnown, `https://bsky.social${path}`]) + }) - test('resolves against the local dev PDS when the relay is the localhost one', async () => { + test('with neither, the local dev PDS is asked when the relay is the localhost one', async () => { const seen = stubRoutes({ [`http://localhost:2583${path}`]: answer }) expect(await resolveHandle('alice.test', 'ws://localhost:2583')).toBe('did:plc:resolved') - expect(seen).toEqual([`http://localhost:2583${path}`]) + expect(seen).toEqual([wellKnown, `http://localhost:2583${path}`]) }) - test('resolves against bsky.social for the public relay', async () => { + test('with neither, bsky.social is asked for the public relay', async () => { const seen = stubRoutes({ [`https://bsky.social${path}`]: answer }) expect(await resolveHandle('alice.test', 'wss://bsky.network')).toBe('did:plc:resolved') - expect(seen).toEqual([`https://bsky.social${path}`]) + expect(seen).toEqual([wellKnown, `https://bsky.social${path}`]) }) - test('with no relay configured, bsky.social is the default', async () => { + test('with neither and no relay configured, bsky.social is the default', async () => { const seen = stubRoutes({ [`https://bsky.social${path}`]: answer }) expect(await resolveHandle('alice.test')).toBe('did:plc:resolved') - expect(seen).toEqual([`https://bsky.social${path}`]) + expect(seen).toEqual([wellKnown, `https://bsky.social${path}`]) }) - test('a self-hosted relay is asked over HTTP at the same host', async () => { - // A preview environment's handles are unknown to bsky.social; asking there - // used to 400 every login on that PDS. + test('with neither, a self-hosted relay is asked over HTTP at the same host', async () => { const seen = stubRoutes({ [`https://pds.preview.example${path}`]: answer }) expect(await resolveHandle('alice.test', 'wss://pds.preview.example')).toBe('did:plc:resolved') - expect(seen).toEqual([`https://pds.preview.example${path}`]) + expect(seen).toEqual([wellKnown, `https://pds.preview.example${path}`]) }) - test('the handle is URL-encoded', async () => { + test('the handle is URL-encoded on the PDS fallback', async () => { const seen = stubRoutes({}) await resolveHandle('a b&c', 'wss://bsky.network').catch(() => {}) - expect(seen[0]).toContain('handle=a%20b%26c') + expect(seen.at(-1)).toContain('handle=a%20b%26c') }) test('an unresolvable handle is an error naming the status', async () => { diff --git a/packages/hatk/test/oauth-par-flow.test.ts b/packages/hatk/test/oauth-par-flow.test.ts index b9e5055..fe31205 100644 --- a/packages/hatk/test/oauth-par-flow.test.ts +++ b/packages/hatk/test/oauth-par-flow.test.ts @@ -1,4 +1,11 @@ import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest' + +// Handle resolution asks DNS before any PDS; no test here reaches a resolver. +vi.mock('node:dns/promises', () => ({ + resolveTxt: async () => { + throw new Error('ENOTFOUND') + }, +})) import { buildAuthorizeRedirect, getAuthServerMetadata, @@ -173,7 +180,8 @@ describe('handlePar', () => { expect(result.expires_in).toBe(600) const urls = calls.map((c) => c.url) - expect(urls[0]).toContain('com.atproto.identity.resolveHandle?handle=alice.test') + // The well-known lookup comes first and finds nothing for a .test name. + expect(urls.some((u) => u.includes('com.atproto.identity.resolveHandle?handle=alice.test'))).toBe(true) expect(urls).toContain(`${PLC}/${DID}`) expect(urls).toContain(PDS_PAR) -- knotmirror 0.0.1