diff --git a/docs/spaces-appview.md b/docs/spaces-appview.md index 7da7f67..a1aa756 100644 --- a/docs/spaces-appview.md +++ b/docs/spaces-appview.md @@ -365,14 +365,31 @@ by design, so it is fetched from the repo that holds it with the viewer's own credential and served `private, no-store` with a content-type allowlist. A viewer who may not read the space gets the same 404 as a missing blob. +**Write notices** (`spaces/notify.ts`, `spaces/verify.ts`). Registration happens +inside reconcile, where a credential is already in hand — `registerNotify` is +authenticated with one, so only somebody the authority already admits can +subscribe — and renews an hour before its 24-hour expiry. Two inbound routes +receive the forwarded notices, ahead of the XRPC catch-all that would otherwise +answer for those NSIDs first. A notice carries no records: it says look again, +and the read that follows uses hatk's own borrowed credential. It is answered +before the sync runs, and syncs are debounced per repo, because one member +writing a gallery sends a notice per record. + +The forwarded notice needed its own verifier. At origin a writer's host signs +with `iss` = the writer and `aud` = the bare authority DID; forwarded onward the +authority re-signs with `iss` = itself and `aud` = the service identifier +including its fragment. The reference PDS's own handler rejects exactly that +shape, so there was nothing to borrow. Verification also meant handling +secp256k1, which most `did:plc` accounts sign with and WebCrypto does not +implement at all — `@noble/curves` is the one dependency this added, and +`spaces/verify.ts` is base58btc plus multicodec prefix parsing on top of it. + +hatk publishes a `did:web` document at `/.well-known/did.json` naming where to +deliver. It carries a service entry and no verification method: a syncer signs +nothing, so there is no key to publish or to steal. + ### Known gaps, in the order they matter -- **No notice receiver**, so a write appears within one reconcile interval - rather than within a second. It needs verifying a service-auth JWT signed by - the authority's key, which for most `did:plc` accounts is secp256k1 — a curve - WebCrypto does not implement and hatk has no library for. That is a - dependency decision, not a coding one. The `registered_until` column is - already in place for it. - **Viewer resolution costs a round trip per followed space** on a cache miss, so an instance following many communities pays for all of them per viewer. Fine for a handful; a narrowing hook is the answer if it stops being. diff --git a/package-lock.json b/package-lock.json index 3ca2059..e066fd5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -310,6 +310,33 @@ "@emnapi/runtime": "^1.7.1" } }, + "node_modules/@noble/curves": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@oxc-project/types": { "version": "0.139.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz", @@ -4336,6 +4363,7 @@ "@bigmoves/lexicon": "^0.2.2", "@duckdb/node-api": "^1.4.4-r.1", "@hatk/oauth-client": "*", + "@noble/curves": "^2.4.0", "@resvg/resvg-js": "^2.6.2", "better-sqlite3": "^12.6.2", "satori": "^0.28.1", diff --git a/packages/hatk/package.json b/packages/hatk/package.json index 8558e81..5cdc0d5 100644 --- a/packages/hatk/package.json +++ b/packages/hatk/package.json @@ -38,6 +38,7 @@ "@bigmoves/lexicon": "^0.2.2", "@duckdb/node-api": "^1.4.4-r.1", "@hatk/oauth-client": "*", + "@noble/curves": "^2.4.0", "@resvg/resvg-js": "^2.6.2", "better-sqlite3": "^12.6.2", "satori": "^0.28.1", diff --git a/packages/hatk/src/adapter.ts b/packages/hatk/src/adapter.ts index b4df834..c609136 100644 --- a/packages/hatk/src/adapter.ts +++ b/packages/hatk/src/adapter.ts @@ -64,6 +64,7 @@ export const HATK_ROUTES = [ '/xrpc/', '/blob/', // dev image proxy — see blobUrl in xrpc.ts '/space-blob', // a blob inside a permissioned space, served per viewer + '/.well-known/did.json', // this instance's own DID, for space notice delivery '/oauth/', '/oauth-client-metadata.json', '/.well-known/oauth-authorization-server', diff --git a/packages/hatk/src/config.ts b/packages/hatk/src/config.ts index c4cc582..b18398d 100644 --- a/packages/hatk/src/config.ts +++ b/packages/hatk/src/config.ts @@ -113,6 +113,22 @@ export interface SpacesConfig { * what makes sync correct rather than merely prompt. */ reconcileInterval?: number + /** + * This instance's own DID, for receiving write notices — e.g. + * `did:web:appview.example.com`. hatk serves the matching document at + * `/.well-known/did.json`, so the DID has to resolve to this origin. + * + * Without it the sweep is the only thing that notices a write, which is + * correct but no faster than the interval. The DID publishes no signing key: + * notices are only ever verified here, never signed. + */ + serviceDid?: string + /** + * The service entry notices are delivered to, named in the DID document and + * in every registration. Its own fragment rather than the bare DID, so a + * notice cannot be confused with one addressed to an account. + */ + serviceFragment?: string } export interface JetstreamConfig { @@ -242,6 +258,8 @@ export async function loadConfig(configPath: string): Promise { .filter(Boolean) : parsed.spaces.watch || [], reconcileInterval: parseInt(env.SPACES_RECONCILE_INTERVAL || '') || parsed.spaces.reconcileInterval || 300, + serviceDid: env.SPACES_SERVICE_DID || parsed.spaces.serviceDid || undefined, + serviceFragment: parsed.spaces.serviceFragment || 'atproto_space_syncer', } : null, } diff --git a/packages/hatk/src/main.ts b/packages/hatk/src/main.ts index 659a18f..bda0b6b 100755 --- a/packages/hatk/src/main.ts +++ b/packages/hatk/src/main.ts @@ -200,6 +200,18 @@ const handler = createHandler({ oauth: config.oauth, admins: config.admins, onResync: runBackfillAndRestart, + ...(config.spaces?.serviceDid + ? { + spaces: { + serviceDid: config.spaces.serviceDid, + serviceFragment: config.spaces.serviceFragment ?? 'atproto_space_syncer', + // The origin an authority delivers to. The OAuth issuer is already + // the public origin an operator has had to get right, so it is the + // honest default rather than a second thing to configure wrong. + ...(config.oauth?.issuer ? { publicUrl: config.oauth.issuer } : {}), + }, + } + : {}), }) // Expose server bridge on globalThis so SvelteKit SSR can call XRPC handlers directly. diff --git a/packages/hatk/src/server.ts b/packages/hatk/src/server.ts index 562318f..5625cd2 100644 --- a/packages/hatk/src/server.ts +++ b/packages/hatk/src/server.ts @@ -83,6 +83,17 @@ import { collectionFromUri, isPrivateCollection } from './private-collections.ts import { enterReadableSpaces } from './spaces/visibility.ts' import { readableSpacesFor } from './spaces/viewer.ts' import { parseSpaceBlobRequest, serveSpaceBlob } from './spaces/blob.ts' +import { + handleWriteNotice, + NoticeError, + parseWriteNotice, + scheduleNoticeSync, + spaceDidDocument, + spaceServiceId, + unwatchSpace, + verifyNotice, +} from './spaces/index.ts' +import { parseSpaceRef } from './spaces/uri.ts' import { serve } from './adapter.ts' import { renderPage } from './renderer.ts' @@ -379,6 +390,13 @@ interface AdminStats { openReports: number } +export interface SpaceHandlerConfig { + serviceDid?: string + serviceFragment?: string + /** The origin an authority should deliver to, when it is not the request's own. */ + publicUrl?: string +} + export interface HandlerConfig { collections: string[] publicDir: string | null @@ -387,6 +405,8 @@ export interface HandlerConfig { renderer?: (request: Request, manifest: any) => Promise<{ html: string; head?: string }> resolveViewer?: (request: Request) => { did: string } | null onResync?: () => void + /** Permissioned-space notice delivery. Absent on an instance that indexes none. */ + spaces?: SpaceHandlerConfig } /** @@ -988,6 +1008,23 @@ export function createHandler(config: HandlerConfig): (request: Request) => Prom // --- OAuth Endpoints --- + // GET /.well-known/did.json — this instance's own DID document, so a space + // authority can resolve where to deliver notices. Published only when a + // service DID is configured; it carries a service entry and no key. + if (url.pathname === '/.well-known/did.json' && config.spaces?.serviceDid) { + return withCors( + json( + spaceDidDocument( + config.spaces.serviceDid, + config.spaces.publicUrl ?? requestOrigin, + config.spaces.serviceFragment ?? 'atproto_space_syncer', + ), + 200, + acceptEncoding, + ), + ) + } + // OAuth well-known endpoints if (url.pathname === '/.well-known/oauth-authorization-server' && oauth) { return withCors(json(getAuthServerMetadata(oauth.issuer, oauth), 200, acceptEncoding)) @@ -1374,6 +1411,57 @@ export function createHandler(config: HandlerConfig): (request: Request) => Prom } // GET/POST /xrpc/{nsid} — custom XRPC handlers (matched by full NSID from folder structure) + // POST /xrpc/com.atproto.space.notifyWrite — a space authority telling us + // one of its repos moved. Carries no records: it says look again, and the + // read that follows uses our own credential like any other. + // + // Best-effort by protocol, so this answers before syncing and never lets + // a sync failure become the authority's problem. A missed notice is + // recovered by the reconcile sweep. + if (url.pathname === '/xrpc/com.atproto.space.notifyWrite' && request.method === 'POST') { + const serviceId = spaceServiceId() + if (!serviceId) return withCors(jsonError(404, 'This instance receives no space notices', acceptEncoding)) + const notice = parseWriteNotice(await request.json().catch(() => null)) + if (!notice) return withCors(jsonError(400, 'Expected space, repo and rev', acceptEncoding)) + try { + await verifyNotice(request.headers.get('authorization'), { + iss: parseSpaceRef(notice.space)!.authority, + aud: serviceId, + lxm: 'com.atproto.space.notifyWrite', + }) + } catch (err: any) { + if (err instanceof NoticeError) return withCors(jsonError(err.status, err.message, acceptEncoding)) + throw err + } + // Debounced per repo: one member writing a gallery sends a notice per + // record, and each is an invitation to read the same repo again. + scheduleNoticeSync(`${notice.space}|${notice.repo}`, () => handleWriteNotice(notice).then(() => {})) + return withCors(json({}, 200, acceptEncoding)) + } + + // POST /xrpc/com.atproto.space.notifySpaceDeleted — the authority saying a + // space is gone and every copy of it should go too. + if (url.pathname === '/xrpc/com.atproto.space.notifySpaceDeleted' && request.method === 'POST') { + const serviceId = spaceServiceId() + if (!serviceId) return withCors(jsonError(404, 'This instance receives no space notices', acceptEncoding)) + const body = (await request.json().catch(() => null)) as { space?: unknown } | null + const space = typeof body?.space === 'string' ? body.space : null + const ref = space ? parseSpaceRef(space) : null + if (!space || !ref) return withCors(jsonError(400, 'Expected a space', acceptEncoding)) + try { + await verifyNotice(request.headers.get('authorization'), { + iss: ref.authority, + aud: serviceId, + lxm: 'com.atproto.space.notifySpaceDeleted', + }) + } catch (err: any) { + if (err instanceof NoticeError) return withCors(jsonError(err.status, err.message, acceptEncoding)) + throw err + } + await unwatchSpace(space) + return withCors(json({}, 200, acceptEncoding)) + } + if (url.pathname.startsWith('/xrpc/')) { const method = url.pathname.slice('/xrpc/'.length) const limit = parseInt(url.searchParams.get('limit') || '20') diff --git a/packages/hatk/src/spaces/engine.ts b/packages/hatk/src/spaces/engine.ts index 8217780..9040bb1 100644 --- a/packages/hatk/src/spaces/engine.ts +++ b/packages/hatk/src/spaces/engine.ts @@ -60,8 +60,23 @@ export interface SpaceEngineOptions { types: Set /** Collections hatk indexes at all; a space collection outside this is skipped. */ collections: Set + /** + * This instance's service identifier — `did:web:...#atproto_space_syncer`. + * Absent when the instance receives no notices, in which case the sweep is + * the only thing that notices a write. + */ + serviceId?: string } +/** + * Re-register this long before a registration lapses. + * + * The reference host holds one for a day, and a lapsed registration stops + * notices silently — the sweep would carry on working and nobody would notice + * the latency had gone back up. + */ +const REGISTRATION_RENEW_LEAD_MS = 60 * 60 * 1000 + let options: SpaceEngineOptions | null = null export function configureSpaceEngine(opts: SpaceEngineOptions): void { @@ -424,6 +439,46 @@ export async function syncSpaceRepo(watch: SpaceWatch, writer: string, credentia // --- Reconcile --- +/** + * Subscribe to this space's write notices, if this instance can receive them. + * + * Authenticated with the space credential, so only somebody the authority + * already admits can subscribe — which is why this happens inside reconcile, + * where a credential is already in hand. The delivery endpoint is not sent: + * the authority resolves it from our own DID document, so a registration can + * only ever point at an endpoint we published for ourselves. + * + * Best-effort. Failing to register costs latency, not correctness, and must + * not fail the sweep that was about to read the space anyway. + */ +async function ensureRegistered(watch: SpaceWatch, credential: SpaceCredential): Promise { + const { serviceId } = requireOptions() + if (!serviceId) return + const until = watch.registeredUntil ? Date.parse(watch.registeredUntil) : 0 + if (Number.isFinite(until) && until - REGISTRATION_RENEW_LEAD_MS > Date.now()) return + + try { + const authorityHost = await spaceHostEndpoint(watch.authority) + const res = await credential.fetch(`${authorityHost}/xrpc/com.atproto.space.registerNotify`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ space: watch.space, service: serviceId }), + }) + if (!res.ok) throw new Error(`registerNotify refused (${res.status})`) + const body = (await res.json()) as { expiresAt?: string } + if (body.expiresAt) { + await updateSpaceWatch(watch.space, { registeredUntil: body.expiresAt }) + watch.registeredUntil = body.expiresAt + } + emit('spaces', 'registered', { space: watch.space, expires_at: body.expiresAt }) + } catch (err) { + emit('spaces', 'register_failed', { + space: watch.space, + error: err instanceof Error ? err.message : String(err), + }) + } +} + async function listWriters( watch: SpaceWatch, credential: SpaceCredential, @@ -459,6 +514,7 @@ async function listWriters( export async function reconcileSpace(watch: SpaceWatch): Promise { const elapsed = timer() await withCredential(watch, async (credential) => { + await ensureRegistered(watch, credential) const writers = await listWriters(watch, credential) const remote = new Set(writers.map((w) => w.did)) @@ -522,6 +578,24 @@ export async function unwatchSpace(space: string): Promise { emit('spaces', 'unwatched', { space }) } +/** + * Act on a write notice: read the one repo it names. + * + * Only for a space already followed. A notice about anything else is not an + * instruction to start following it — that decision belongs to config or to the + * app, never to whoever can reach this endpoint. + * + * The notice's `rev` is deliberately not trusted as the new position: it is + * read from the repo's own host, which is the source of truth, by the ordinary + * sync path. The notice only says "look again". + */ +export async function handleWriteNotice(notice: { space: string; repo: string }): Promise { + const watch = await getSpaceWatch(notice.space) + if (!watch) return false + await withCredential(watch, (credential) => syncSpaceRepo(watch, notice.repo, credential)) + return true +} + /** * Reconcile every followed space. * diff --git a/packages/hatk/src/spaces/identity.ts b/packages/hatk/src/spaces/identity.ts index 215771a..ad71b94 100644 --- a/packages/hatk/src/spaces/identity.ts +++ b/packages/hatk/src/spaces/identity.ts @@ -13,9 +13,11 @@ */ import { pdsFor } from '../backfill.ts' +import { parseMultibaseKey, type PublicKey } from './verify.ts' interface DidDocument { service?: { id?: string; type?: string; serviceEndpoint?: string }[] + verificationMethod?: { id?: string; type?: string; publicKeyMultibase?: string }[] } let plcUrl = 'https://plc.directory' @@ -72,3 +74,24 @@ export function repoEndpoint(did: string): Promise { export function clearSpaceIdentityCache(): void { docCache.clear() } + +/** + * An account's atproto signing key, as its DID document publishes it. + * + * Used to check that a write notice really came from the space authority it + * claims to. `#atproto` is the entry every atproto DID document carries; + * `#atproto_space` is the optional dedicated credential-signing key, preferred + * when an authority publishes one. + */ +export async function atprotoSigningKey(did: string): Promise { + const doc = await fetchDidDoc(did) + const methods = doc?.verificationMethod ?? [] + const named = (id: string) => methods.find((m) => m.id === id || m.id?.endsWith(id)) + const method = named('#atproto_space') ?? named('#atproto') + if (!method?.publicKeyMultibase) return null + try { + return parseMultibaseKey(method.publicKeyMultibase) + } catch { + return null + } +} diff --git a/packages/hatk/src/spaces/index.ts b/packages/hatk/src/spaces/index.ts index ac7e2d9..46c9e04 100644 --- a/packages/hatk/src/spaces/index.ts +++ b/packages/hatk/src/spaces/index.ts @@ -11,6 +11,7 @@ import { emit } from '../logger.ts' import { log } from '../logger.ts' import { configureSpaceEngine, reconcileAll, unwatchSpace, watchSpace } from './engine.ts' import { configureSpaceIdentity } from './identity.ts' +import { clearPendingNotices } from './notify.ts' export { collectionsForSpaceType, @@ -23,10 +24,51 @@ export { export { getSpaceCredential, mintSpaceCredential, isNotAuthorized, isSpaceGone } from './credential.ts' export { listSpaceRepos, listSpaceWatches, type SpaceWatch } from './store.ts' export { isSpaceReadable, readableSpaces, withReadableSpaces } from './visibility.ts' +export { handleWriteNotice } from './engine.ts' +export { + clearPendingNotices, + NoticeError, + parseWriteNotice, + scheduleNoticeSync, + verifyNotice, + type WriteNotice, +} from './notify.ts' export * from './uri.ts' let sweepTimer: ReturnType | null = null +/** + * What a notice must be addressed to for this instance to act on it, and what + * every registration names. Null when no service DID is configured, which is + * also what makes the inbound routes refuse everything. + */ +let serviceId: string | null = null + +export function spaceServiceId(): string | null { + return serviceId +} + +/** + * The DID document an authority resolves to find where to deliver notices. + * + * It publishes a service entry and nothing else. A syncer signs nothing — it + * verifies inbound notices and presents credentials bound to an ephemeral key + * — so there is no verification method to publish and no key here to steal. + */ +export function spaceDidDocument(did: string, endpoint: string, fragment: string): Record { + return { + '@context': ['https://www.w3.org/ns/did/v1'], + id: did, + service: [ + { + id: `#${fragment}`, + type: 'AtprotoSpaceService', + serviceEndpoint: endpoint, + }, + ], + } +} + export interface StartSpacesOptions { spaces: SpacesConfig oauth: OAuthConfig | null @@ -55,7 +97,13 @@ export function startSpaces(opts: StartSpacesOptions): void { } configureSpaceIdentity(plc) - configureSpaceEngine({ oauth, types: new Set(spaces.types), collections }) + serviceId = spaces.serviceDid ? `${spaces.serviceDid}#${spaces.serviceFragment ?? 'atproto_space_syncer'}` : null + configureSpaceEngine({ + oauth, + types: new Set(spaces.types), + collections, + ...(serviceId ? { serviceId } : {}), + }) const intervalMs = Math.max(30, spaces.reconcileInterval ?? 300) * 1000 @@ -87,6 +135,8 @@ export function startSpaces(opts: StartSpacesOptions): void { export function stopSpaces(): void { if (sweepTimer) clearInterval(sweepTimer) sweepTimer = null + serviceId = null + clearPendingNotices() } /** Re-exported so an app's on-login hook can start following a space it just learned about. */ diff --git a/packages/hatk/src/spaces/notify.ts b/packages/hatk/src/spaces/notify.ts new file mode 100644 index 0000000..633cb8b --- /dev/null +++ b/packages/hatk/src/spaces/notify.ts @@ -0,0 +1,142 @@ +/** + * Receiving write notices from a space authority. + * + * A space's writes never reach a firehose, so an authority tells its + * subscribers directly: register once, and every write into the space arrives + * as a `notifyWrite` carrying the repo and the revision it reached — and no + * records. The notice says something moved; reading it is still the syncer's + * job, with its own credential. + * + * This only makes sync prompt, never correct. Delivery is best-effort by + * design: the reference host forwards each notice once from an in-memory queue + * and logs the failure, so a missed one is recovered by the reconcile sweep or + * by the next write. Nothing here may be load-bearing. + * + * ## Why this needs its own verifier + * + * A forwarded notice does not look like the one a PDS sends its own authority. + * At origin, a writer's host signs with `iss` = the writer and `aud` = the bare + * authority DID. Forwarded onward, the authority re-signs with `iss` = itself + * and `aud` = the registered service identifier *including its fragment*. The + * reference PDS's own inbound handler rejects exactly that shape — it requires + * `iss` to equal the claimed writer and `aud` to equal the bare authority — so + * a receiver cannot borrow it and has to check the forwarded shape itself. + */ + +import { emit } from '../logger.ts' +import { atprotoSigningKey } from './identity.ts' +import { parseSpaceRef } from './uri.ts' +import { verifySignature } from './verify.ts' + +/** Clock skew tolerated on a notice's expiry. The reference signs them for 60s. */ +const SKEW_SEC = 60 + +export class NoticeError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message) + } +} + +function base64UrlToBytes(value: string): Uint8Array { + const padded = value.replace(/-/g, '+').replace(/_/g, '/') + return new Uint8Array(Buffer.from(padded, 'base64')) +} + +interface ServiceAuthPayload { + iss?: string + aud?: string + lxm?: string + exp?: number +} + +/** + * Check a service-auth JWT that claims to come from `expectedIss`. + * + * The audience must match this instance's own service identifier exactly, + * fragment included: a token addressed to somebody else is not ours to act on + * however valid its signature. The method is checked for the same reason — a + * token minted for one call must not be replayable against another. + */ +export async function verifyNotice( + authorization: string | null, + expected: { iss: string; aud: string; lxm: string }, +): Promise { + const token = authorization?.match(/^Bearer (.+)$/)?.[1] + if (!token) throw new NoticeError(401, 'Missing service auth') + + const parts = token.split('.') + if (parts.length !== 3) throw new NoticeError(401, 'Malformed service auth') + + let payload: ServiceAuthPayload + try { + payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString()) as ServiceAuthPayload + } catch { + throw new NoticeError(401, 'Malformed service auth') + } + + // The issuer is checked against the space named in the body rather than + // trusted from the token, so a valid token from one authority cannot be used + // to speak about another authority's space. + if (payload.iss?.split('#')[0] !== expected.iss) { + throw new NoticeError(403, 'Notice issuer is not the space authority') + } + if (payload.aud !== expected.aud) throw new NoticeError(403, 'Notice is addressed elsewhere') + if (payload.lxm !== expected.lxm) throw new NoticeError(403, 'Notice is for a different method') + if (typeof payload.exp !== 'number' || payload.exp + SKEW_SEC < Date.now() / 1000) { + throw new NoticeError(401, 'Notice has expired') + } + + const key = await atprotoSigningKey(expected.iss) + if (!key) throw new NoticeError(502, `Could not resolve a signing key for ${expected.iss}`) + + const message = new TextEncoder().encode(`${parts[0]}.${parts[1]}`) + if (!verifySignature(key, base64UrlToBytes(parts[2]), message)) { + throw new NoticeError(403, 'Notice signature does not verify') + } +} + +export interface WriteNotice { + space: string + repo: string + rev: string +} + +export function parseWriteNotice(body: unknown): WriteNotice | null { + if (!body || typeof body !== 'object') return null + const { space, repo, rev } = body as Record + if (typeof space !== 'string' || typeof repo !== 'string' || typeof rev !== 'string') return null + if (!parseSpaceRef(space) || !repo.startsWith('did:')) return null + return { space, repo, rev } +} + +/** + * Collapse a burst of notices for the same repo into one sync. + * + * A member writing a gallery produces a notice per record, and syncing per + * notice would read the same repo a dozen times over a few seconds. A short + * trailing delay turns that into one read, which is also what keeps a flood — + * forged or otherwise — from costing more than one sync per interval. + */ +const DEBOUNCE_MS = 750 + +const pending = new Map>() + +export function scheduleNoticeSync(key: string, run: () => Promise, delay = DEBOUNCE_MS): void { + const existing = pending.get(key) + if (existing) clearTimeout(existing) + const timer = setTimeout(() => { + pending.delete(key) + void run().catch((err) => emit('spaces', 'notice_sync_failed', { key, error: err?.message ?? String(err) })) + }, delay) + timer.unref?.() + pending.set(key, timer) +} + +/** Drop every pending sync. For shutdown, and for tests. */ +export function clearPendingNotices(): void { + for (const timer of pending.values()) clearTimeout(timer) + pending.clear() +} diff --git a/packages/hatk/src/spaces/verify.ts b/packages/hatk/src/spaces/verify.ts new file mode 100644 index 0000000..6d8f312 --- /dev/null +++ b/packages/hatk/src/spaces/verify.ts @@ -0,0 +1,93 @@ +/** + * Verifying a signature made by somebody else's atproto signing key. + * + * Everything hatk signs, it signs with ES256, because it chose its own keys and + * WebCrypto implements that curve. Everything it has to *verify* here was + * signed by an account it does not control, and most `did:plc` accounts sign + * with secp256k1 — a curve WebCrypto does not implement at all. So the two + * curves atproto allows are handled explicitly, over @noble/curves. + * + * A key arrives as a multibase string in a DID document's verification method + * (`publicKeyMultibase` on a `Multikey`): base58btc, prefixed with a multicodec + * varint naming the curve, then the compressed point. The prefix is the only + * thing that says which curve it is, so it is read rather than guessed. + */ + +import { p256 } from '@noble/curves/nist.js' +import { secp256k1 } from '@noble/curves/secp256k1.js' +import { sha256 } from '@noble/hashes/sha2.js' + +const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' + +/** Multicodec varints for the two curves atproto allows. */ +const SECP256K1_PREFIX = [0xe7, 0x01] +const P256_PREFIX = [0x80, 0x24] + +export type AtprotoCurve = 'secp256k1' | 'p256' + +export class SignatureError extends Error {} + +/** + * Decode base58btc. Written out rather than pulled in: it is short, it is the + * only encoding needed, and a wrong answer here fails closed rather than + * silently accepting something. + */ +export function decodeBase58btc(input: string): Uint8Array { + if (input.length === 0) return new Uint8Array(0) + const bytes: number[] = [0] + for (const char of input) { + const value = BASE58_ALPHABET.indexOf(char) + if (value < 0) throw new SignatureError(`Not base58btc: ${char}`) + let carry = value + for (let i = 0; i < bytes.length; i++) { + carry += bytes[i] * 58 + bytes[i] = carry & 0xff + carry >>= 8 + } + while (carry > 0) { + bytes.push(carry & 0xff) + carry >>= 8 + } + } + // Every leading '1' is a leading zero byte that the arithmetic above drops. + for (const char of input) { + if (char !== '1') break + bytes.push(0) + } + return new Uint8Array(bytes.reverse()) +} + +export interface PublicKey { + curve: AtprotoCurve + /** The compressed point, 33 bytes. */ + bytes: Uint8Array +} + +/** Read a `publicKeyMultibase` from a DID document's verification method. */ +export function parseMultibaseKey(multibase: string): PublicKey { + if (!multibase.startsWith('z')) throw new SignatureError('Key is not base58btc multibase') + const decoded = decodeBase58btc(multibase.slice(1)) + const starts = (prefix: number[]) => prefix.every((b, i) => decoded[i] === b) + if (starts(SECP256K1_PREFIX)) return { curve: 'secp256k1', bytes: decoded.slice(SECP256K1_PREFIX.length) } + if (starts(P256_PREFIX)) return { curve: 'p256', bytes: decoded.slice(P256_PREFIX.length) } + throw new SignatureError('Key is neither secp256k1 nor p256') +} + +/** + * Verify a raw `r || s` signature over `message`. + * + * Low-S is required — atproto mandates it and a malleable signature would let + * the same assertion be presented twice with different bytes — and is what + * @noble enforces by default. + */ +export function verifySignature(key: PublicKey, signature: Uint8Array, message: Uint8Array): boolean { + if (signature.length !== 64) return false + const digest = sha256(message) + try { + const curve = key.curve === 'secp256k1' ? secp256k1 : p256 + return curve.verify(signature, digest, key.bytes) + } catch { + // A malformed point or scalar is a failed verification, not a crash. + return false + } +} diff --git a/packages/hatk/test/spaces-engine.test.ts b/packages/hatk/test/spaces-engine.test.ts index 2e9690d..de90158 100644 --- a/packages/hatk/test/spaces-engine.test.ts +++ b/packages/hatk/test/spaces-engine.test.ts @@ -23,8 +23,15 @@ vi.mock('../src/oauth/db.ts', async () => { return { ...actual, listSessionDids: () => listSessionDids() } }) -const { collectionsForSpaceType, configureSpaceEngine, reconcileAll, reconcileSpace, unwatchSpace, watchSpace } = - await import('../src/spaces/engine.ts') +const { + collectionsForSpaceType, + configureSpaceEngine, + handleWriteNotice, + reconcileAll, + reconcileSpace, + unwatchSpace, + watchSpace, +} = await import('../src/spaces/engine.ts') const { insertRecord, querySQL, runSQL } = await import('../src/database/db.ts') const { storeLexicons } = await import('../src/database/schema.ts') const { getSpaceRepo, getSpaceWatch, listSpaceRepos, putSpaceRepo, putSpaceWatch } = @@ -580,3 +587,110 @@ test('a synced record is stored under its space and served only in scope', async expect(row?.space).toBe(SPACE_URI) expect(row?.did).toBe(ALICE) }) + +// --- Write notices --- + +const SERVICE_ID = 'did:web:appview.test#atproto_space_syncer' + +function withService() { + configureSpaceEngine({ + oauth: oauth as any, + types: new Set([SPACE_TYPE]), + collections: new Set([PUBLIC_COLLECTION, PRIVATE_COLLECTION]), + serviceId: SERVICE_ID, + }) +} + +test('an instance that receives notices subscribes while it has a credential in hand', async () => { + // registerNotify is authenticated with the space credential, so only somebody + // the authority already admits can subscribe — which is why it happens inside + // reconcile rather than on its own. + withService() + await putSpaceWatch({ space: SPACE_URI, authority: SPACE_AUTHORITY, spaceType: SPACE_TYPE }) + routes = { + registerNotify: () => ({ expiresAt: '2030-01-01T00:00:00.000Z' }), + listRepos: () => ({ repos: [] }), + } + + await reconcileSpace({ ...watch }) + + expect(calls.map((c) => c.nsid)).toContain('registerNotify') + expect((await getSpaceWatch(SPACE_URI))?.registeredUntil).toBe('2030-01-01T00:00:00.000Z') +}) + +test('a registration still well inside its life is not renewed', async () => { + withService() + const far = new Date(Date.now() + 20 * 60 * 60 * 1000).toISOString() + routes = { listRepos: () => ({ repos: [] }) } + await reconcileSpace({ ...watch, registeredUntil: far }) + expect(calls.map((c) => c.nsid)).not.toContain('registerNotify') +}) + +test('a registration close to lapsing is renewed before it does', async () => { + // A lapsed one stops notices silently: the sweep carries on working and + // nobody notices the latency went back up. + withService() + const soon = new Date(Date.now() + 10 * 60 * 1000).toISOString() + routes = { + registerNotify: () => ({ expiresAt: '2030-01-01T00:00:00.000Z' }), + listRepos: () => ({ repos: [] }), + } + await reconcileSpace({ ...watch, registeredUntil: soon }) + expect(calls.map((c) => c.nsid)).toContain('registerNotify') +}) + +test('failing to subscribe costs latency, not the sweep', async () => { + withService() + routes = { + registerNotify: () => Response.json({ error: 'ServiceNotResolvable' }, { status: 400 }), + listRepos: () => ({ repos: [{ did: ALICE, rev: '3a' }] }), + getLatestCommit: () => ({ commit: { rev: '3a' } }), + listRecords: () => ({ records: [] }), + } + + await reconcileSpace({ ...watch }) + + expect((await getSpaceRepo(SPACE_URI, ALICE))?.rev).toBe('3a') +}) + +test('an instance that receives no notices never subscribes', async () => { + routes = { listRepos: () => ({ repos: [] }) } + await reconcileSpace({ ...watch }) + expect(calls.map((c) => c.nsid)).not.toContain('registerNotify') +}) + +test('a notice reads the one repo it names', async () => { + await putSpaceWatch({ space: SPACE_URI, authority: SPACE_AUTHORITY, spaceType: SPACE_TYPE }) + routes = { + getLatestCommit: () => ({ commit: { rev: '3a' } }), + listRecords: (p) => + p.get('collection') === PUBLIC_COLLECTION + ? { records: [{ rkey: 'fresh', cid: 'c1', value: { text: 'just written' } }] } + : { records: [] }, + } + + expect(await handleWriteNotice({ space: SPACE_URI, repo: ALICE })).toBe(true) + + expect(await indexedUris()).toEqual([spaceRecord(ALICE, PUBLIC_COLLECTION, 'fresh')]) + // The writer set is not re-listed: a notice names its repo, so there is + // nothing to enumerate. + expect(calls.map((c) => c.nsid)).not.toContain('listRepos') +}) + +test('a notice about a space this instance does not follow is ignored', async () => { + // Not an instruction to start following it: that decision belongs to config + // or to the app, never to whoever can reach the endpoint. + expect(await handleWriteNotice({ space: SPACE_URI, repo: ALICE })).toBe(false) + expect(calls).toEqual([]) +}) + +test('the revision a notice claims is not trusted as the new position', async () => { + // It is read from the repo's own host, which is the source of truth. + await putSpaceWatch({ space: SPACE_URI, authority: SPACE_AUTHORITY, spaceType: SPACE_TYPE }) + routes = { + getLatestCommit: () => ({ commit: { rev: '3real' } }), + listRecords: () => ({ records: [] }), + } + await handleWriteNotice({ space: SPACE_URI, repo: ALICE }) + expect((await getSpaceRepo(SPACE_URI, ALICE))?.rev).toBe('3real') +}) diff --git a/packages/hatk/test/spaces-identity.test.ts b/packages/hatk/test/spaces-identity.test.ts index ff94d3b..4bbf30d 100644 --- a/packages/hatk/test/spaces-identity.test.ts +++ b/packages/hatk/test/spaces-identity.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, expect, test, vi } from 'vitest' const pdsFor = vi.fn() vi.mock('../src/backfill.ts', () => ({ pdsFor: (...args: unknown[]) => pdsFor(...args) })) -const { clearSpaceIdentityCache, configureSpaceIdentity, repoEndpoint, spaceHostEndpoint } = +const { atprotoSigningKey, clearSpaceIdentityCache, configureSpaceIdentity, repoEndpoint, spaceHostEndpoint } = await import('../src/spaces/identity.ts') const AUTHORITY = 'did:plc:authority' @@ -91,3 +91,56 @@ test('a writer repo is resolved the way every other repo is', async () => { expect(await repoEndpoint('did:plc:alice')).toBe('https://alice.test') expect(pdsFor).toHaveBeenCalledWith('did:plc:alice') }) + +// --- Signing keys --- + +/** A DID document carrying verification methods rather than services. */ +function keyDoc(methods: { id: string; publicKeyMultibase?: string }[]) { + return async () => + Response.json({ + id: AUTHORITY, + verificationMethod: methods.map((m) => ({ ...m, type: 'Multikey', controller: AUTHORITY })), + }) +} + +// A real secp256k1 key, multicodec-prefixed and base58btc-encoded — the shape +// a did:plc document actually publishes. +const SECP_KEY = 'zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme' + +test('the atproto signing key is read from the DID document', async () => { + fetchMock.mockImplementation(keyDoc([{ id: '#atproto', publicKeyMultibase: SECP_KEY }])) + const key = await atprotoSigningKey(AUTHORITY) + expect(key?.curve).toBe('secp256k1') + expect(key?.bytes).toHaveLength(33) +}) + +test('a dedicated space-signing key is preferred over the account key', async () => { + fetchMock.mockImplementation( + keyDoc([ + { id: '#atproto', publicKeyMultibase: SECP_KEY }, + { id: '#atproto_space', publicKeyMultibase: SECP_KEY }, + ]), + ) + expect((await atprotoSigningKey(AUTHORITY))?.curve).toBe('secp256k1') +}) + +test('a document with no usable key answers null rather than guessing', async () => { + fetchMock.mockImplementation(keyDoc([{ id: '#something-else', publicKeyMultibase: SECP_KEY }])) + expect(await atprotoSigningKey(AUTHORITY)).toBeNull() +}) + +test('a verification method with no key material answers null', async () => { + fetchMock.mockImplementation(keyDoc([{ id: '#atproto' }])) + expect(await atprotoSigningKey(AUTHORITY)).toBeNull() +}) + +test('an unparseable key answers null rather than throwing', async () => { + // A malformed document must fail the notice, not the process. + fetchMock.mockImplementation(keyDoc([{ id: '#atproto', publicKeyMultibase: 'not-multibase' }])) + expect(await atprotoSigningKey(AUTHORITY)).toBeNull() +}) + +test('an unresolvable DID has no key', async () => { + fetchMock.mockImplementation(async () => new Response('nope', { status: 404 })) + expect(await atprotoSigningKey(AUTHORITY)).toBeNull() +}) diff --git a/packages/hatk/test/spaces-notify-routes.test.ts b/packages/hatk/test/spaces-notify-routes.test.ts new file mode 100644 index 0000000..6b3816d --- /dev/null +++ b/packages/hatk/test/spaces-notify-routes.test.ts @@ -0,0 +1,197 @@ +import { beforeEach, expect, test, vi } from 'vitest' + +const verifyNotice = vi.fn() +const handleWriteNotice = vi.fn() +const unwatchSpace = vi.fn() +const spaceServiceId = vi.fn() + +vi.mock('../src/spaces/index.ts', async () => { + const notify = await vi.importActual('../src/spaces/notify.ts') + const idx = await vi.importActual('../src/spaces/index.ts') + return { + ...notify, + spaceDidDocument: idx.spaceDidDocument, + verifyNotice: (...a: unknown[]) => verifyNotice(...a), + handleWriteNotice: (...a: unknown[]) => handleWriteNotice(...a), + unwatchSpace: (...a: unknown[]) => unwatchSpace(...a), + spaceServiceId: () => spaceServiceId(), + } +}) +vi.mock('../src/spaces/viewer.ts', () => ({ + readableSpacesFor: async () => [], + viewerCredential: async () => null, + forgetViewerSpaces: vi.fn(), + resetViewerSpaces: vi.fn(), +})) + +const { createHandler } = await import('../src/server.ts') +const { clearPendingNotices, NoticeError } = await import('../src/spaces/notify.ts') +const { setupFixtureDatabase, PUBLIC_COLLECTION } = await import('./fixture.ts') + +const AUTHORITY = 'did:plc:authority' +const SPACE = `at://${AUTHORITY}/space/test.hatk.board/self` +const WRITER = 'did:plc:writer' +const SERVICE_ID = 'did:web:appview.test#atproto_space_syncer' + +await setupFixtureDatabase() + +function handler(spaces?: { serviceDid?: string; serviceFragment?: string; publicUrl?: string }) { + return createHandler({ + collections: [PUBLIC_COLLECTION], + publicDir: null, + oauth: null, + admins: [], + ...(spaces ? { spaces } : {}), + }) +} + +const post = (path: string, body: unknown) => + new Request(`http://localhost${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: 'Bearer token' }, + body: JSON.stringify(body), + }) + +beforeEach(() => { + vi.useFakeTimers() + verifyNotice.mockReset() + verifyNotice.mockResolvedValue(undefined) + handleWriteNotice.mockReset() + handleWriteNotice.mockResolvedValue(true) + unwatchSpace.mockReset() + unwatchSpace.mockResolvedValue(undefined) + spaceServiceId.mockReset() + spaceServiceId.mockReturnValue(SERVICE_ID) + clearPendingNotices() +}) + +// --- notifyWrite --- + +test('a verified notice is acknowledged and the repo read afterwards', async () => { + // Answered before syncing: delivery is best-effort by protocol, and a sync + // failure is not the authority's problem to wait on. + const res = await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifyWrite', { space: SPACE, repo: WRITER, rev: '3a' }), + ) + expect(res.status).toBe(200) + expect(handleWriteNotice).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1000) + expect(handleWriteNotice).toHaveBeenCalledWith({ space: SPACE, repo: WRITER, rev: '3a' }) +}) + +test('the notice is verified against the authority the body names', async () => { + await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifyWrite', { space: SPACE, repo: WRITER, rev: '3a' }), + ) + expect(verifyNotice).toHaveBeenCalledWith('Bearer token', { + iss: AUTHORITY, + aud: SERVICE_ID, + lxm: 'com.atproto.space.notifyWrite', + }) +}) + +test('an unverified notice changes nothing', async () => { + verifyNotice.mockRejectedValue(new NoticeError(403, 'Notice signature does not verify')) + const res = await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifyWrite', { space: SPACE, repo: WRITER, rev: '3a' }), + ) + expect(res.status).toBe(403) + await vi.advanceTimersByTimeAsync(1000) + expect(handleWriteNotice).not.toHaveBeenCalled() +}) + +test('a malformed notice is refused before it is verified', async () => { + const res = await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifyWrite', { repo: WRITER }), + ) + expect(res.status).toBe(400) + expect(verifyNotice).not.toHaveBeenCalled() +}) + +test('an instance that receives no notices has no endpoint to speak of', async () => { + spaceServiceId.mockReturnValue(null) + const res = await handler()(post('/xrpc/com.atproto.space.notifyWrite', { space: SPACE, repo: WRITER, rev: '3a' })) + expect(res.status).toBe(404) + expect(verifyNotice).not.toHaveBeenCalled() +}) + +test('a burst about one repo becomes a single read', async () => { + const h = handler({ serviceDid: 'did:web:appview.test' }) + for (let i = 0; i < 4; i++) { + await h(post('/xrpc/com.atproto.space.notifyWrite', { space: SPACE, repo: WRITER, rev: `3${i}` })) + } + await vi.advanceTimersByTimeAsync(2000) + expect(handleWriteNotice).toHaveBeenCalledTimes(1) +}) + +// --- notifySpaceDeleted --- + +test('a verified deletion drops the space', async () => { + const res = await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifySpaceDeleted', { space: SPACE }), + ) + expect(res.status).toBe(200) + expect(unwatchSpace).toHaveBeenCalledWith(SPACE) +}) + +test('a deletion is verified as its own method', async () => { + await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifySpaceDeleted', { space: SPACE }), + ) + expect(verifyNotice.mock.calls[0][1].lxm).toBe('com.atproto.space.notifySpaceDeleted') +}) + +test('an unverified deletion drops nothing', async () => { + verifyNotice.mockRejectedValue(new NoticeError(403, 'nope')) + const res = await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifySpaceDeleted', { space: SPACE }), + ) + expect(res.status).toBe(403) + expect(unwatchSpace).not.toHaveBeenCalled() +}) + +test('a deletion naming something that is not a space is refused', async () => { + const res = await handler({ serviceDid: 'did:web:appview.test' })( + post('/xrpc/com.atproto.space.notifySpaceDeleted', { space: 'at://did:plc:x/app.bsky.feed.post/1' }), + ) + expect(res.status).toBe(400) + expect(unwatchSpace).not.toHaveBeenCalled() +}) + +// --- The DID document --- + +test('the DID document names where to deliver, and publishes no key', async () => { + // A syncer signs nothing: it verifies inbound notices and presents + // credentials bound to an ephemeral key, so there is no key to publish. + const res = await handler({ serviceDid: 'did:web:appview.test', publicUrl: 'https://appview.test' })( + new Request('http://localhost/.well-known/did.json'), + ) + expect(res.status).toBe(200) + const doc = (await res.json()) as any + expect(doc.id).toBe('did:web:appview.test') + expect(doc.service).toEqual([ + { id: '#atproto_space_syncer', type: 'AtprotoSpaceService', serviceEndpoint: 'https://appview.test' }, + ]) + expect(doc.verificationMethod).toBeUndefined() +}) + +test('the delivery endpoint falls back to the origin the request arrived on', async () => { + const res = await handler({ serviceDid: 'did:web:appview.test' })( + new Request('http://localhost/.well-known/did.json', { headers: { host: 'appview.test' } }), + ) + const doc = (await res.json()) as any + expect(doc.service[0].serviceEndpoint).toBe('http://appview.test') +}) + +test('a custom fragment is honoured in the document', async () => { + const res = await handler({ serviceDid: 'did:web:appview.test', serviceFragment: 'hatk' })( + new Request('http://localhost/.well-known/did.json'), + ) + const doc = (await res.json()) as any + expect(doc.service[0].id).toBe('#hatk') +}) + +test('an instance with no service DID publishes no document', async () => { + const res = await handler()(new Request('http://localhost/.well-known/did.json')) + expect(res.status).toBe(404) +}) diff --git a/packages/hatk/test/spaces-notify.test.ts b/packages/hatk/test/spaces-notify.test.ts new file mode 100644 index 0000000..b750c7f --- /dev/null +++ b/packages/hatk/test/spaces-notify.test.ts @@ -0,0 +1,195 @@ +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { secp256k1 } from '@noble/curves/secp256k1.js' +import { sha256 } from '@noble/hashes/sha2.js' + +const atprotoSigningKey = vi.fn() +vi.mock('../src/spaces/identity.ts', () => ({ + atprotoSigningKey: (...a: unknown[]) => atprotoSigningKey(...a), + spaceHostEndpoint: vi.fn(), + repoEndpoint: vi.fn(), + configureSpaceIdentity: vi.fn(), + clearSpaceIdentityCache: vi.fn(), +})) + +const { NoticeError, clearPendingNotices, parseWriteNotice, scheduleNoticeSync, verifyNotice } = + await import('../src/spaces/notify.ts') + +const AUTHORITY = 'did:plc:authority' +const SPACE = `at://${AUTHORITY}/space/test.hatk.board/self` +const WRITER = 'did:plc:writer' +const SERVICE_ID = 'did:web:appview.test#atproto_space_syncer' +const LXM = 'com.atproto.space.notifyWrite' + +const b64url = (input: string | Uint8Array) => + Buffer.from(typeof input === 'string' ? new TextEncoder().encode(input) : input).toString('base64url') + +let signingKey: Uint8Array + +/** A service-auth JWT signed the way an authority forwards one. */ +function notice(payload: Record, priv = signingKey): string { + const header = b64url(JSON.stringify({ typ: 'JWT', alg: 'ES256K' })) + const body = b64url( + JSON.stringify({ + iss: AUTHORITY, + aud: SERVICE_ID, + lxm: LXM, + exp: Math.floor(Date.now() / 1000) + 60, + ...payload, + }), + ) + const signature = secp256k1.sign(sha256(new TextEncoder().encode(`${header}.${body}`)), priv) + return `Bearer ${header}.${body}.${b64url(signature)}` +} + +const expected = { iss: AUTHORITY, aud: SERVICE_ID, lxm: LXM } + +beforeEach(() => { + signingKey = secp256k1.utils.randomSecretKey() + atprotoSigningKey.mockReset() + atprotoSigningKey.mockResolvedValue({ + curve: 'secp256k1', + bytes: secp256k1.getPublicKey(signingKey, true), + }) +}) + +afterEach(() => { + clearPendingNotices() + vi.useRealTimers() +}) + +// --- Verification --- + +test('a notice signed by the authority is accepted', async () => { + await expect(verifyNotice(notice({}), expected)).resolves.toBeUndefined() +}) + +test('a notice with no authorization is refused', async () => { + await expect(verifyNotice(null, expected)).rejects.toThrow(NoticeError) + await expect(verifyNotice('DPoP something', expected)).rejects.toThrow(/Missing service auth/) +}) + +test('a malformed token is refused before any key is resolved', async () => { + await expect(verifyNotice('Bearer not-a-jwt', expected)).rejects.toThrow(/Malformed/) + await expect(verifyNotice('Bearer a.b.c', expected)).rejects.toThrow(/Malformed/) + expect(atprotoSigningKey).not.toHaveBeenCalled() +}) + +test('a notice from anyone but the space authority is refused', async () => { + // The issuer is checked against the space the body names, so a valid token + // from one authority cannot be used to speak about another's space. + await expect(verifyNotice(notice({ iss: 'did:plc:someone-else' }), expected)).rejects.toThrow( + /not the space authority/, + ) +}) + +test('an issuer with a key fragment still matches the authority', async () => { + await expect(verifyNotice(notice({ iss: `${AUTHORITY}#atproto` }), expected)).resolves.toBeUndefined() +}) + +test('a notice addressed to another service is refused', async () => { + // A forwarded notice names the full service identifier, fragment included. + await expect(verifyNotice(notice({ aud: 'did:web:elsewhere.test#syncer' }), expected)).rejects.toThrow( + /addressed elsewhere/, + ) +}) + +test('a notice addressed to the bare DID rather than the service entry is refused', async () => { + await expect(verifyNotice(notice({ aud: 'did:web:appview.test' }), expected)).rejects.toThrow(/addressed elsewhere/) +}) + +test('a token minted for a different method is refused', async () => { + await expect(verifyNotice(notice({ lxm: 'com.atproto.repo.createRecord' }), expected)).rejects.toThrow( + /different method/, + ) +}) + +test('an expired notice is refused', async () => { + await expect(verifyNotice(notice({ exp: Math.floor(Date.now() / 1000) - 600 }), expected)).rejects.toThrow(/expired/) +}) + +test('a notice without an expiry is refused', async () => { + await expect(verifyNotice(notice({ exp: undefined }), expected)).rejects.toThrow(/expired/) +}) + +test('a small amount of clock skew is tolerated', async () => { + // These are signed for sixty seconds; refusing on a few seconds of drift + // would drop notices from a host whose clock is merely imperfect. + await expect(verifyNotice(notice({ exp: Math.floor(Date.now() / 1000) - 10 }), expected)).resolves.toBeUndefined() +}) + +test('a notice signed by the wrong key is refused', async () => { + const forged = notice({}, secp256k1.utils.randomSecretKey()) + await expect(verifyNotice(forged, expected)).rejects.toThrow(/does not verify/) +}) + +test('a tampered payload is refused', async () => { + const token = notice({}) + const [header, , signature] = token.replace('Bearer ', '').split('.') + const swapped = b64url(JSON.stringify({ iss: AUTHORITY, aud: SERVICE_ID, lxm: LXM, exp: 9999999999 })) + await expect(verifyNotice(`Bearer ${header}.${swapped}.${signature}`, expected)).rejects.toThrow(/does not verify/) +}) + +test('an authority whose key cannot be resolved is an upstream failure, not a pass', async () => { + atprotoSigningKey.mockResolvedValue(null) + const err = await verifyNotice(notice({}), expected).catch((e) => e) + expect(err).toBeInstanceOf(NoticeError) + expect(err.status).toBe(502) +}) + +// --- Payloads --- + +test('a write notice names the space, the repo and the revision', () => { + expect(parseWriteNotice({ space: SPACE, repo: WRITER, rev: '3a' })).toEqual({ + space: SPACE, + repo: WRITER, + rev: '3a', + }) +}) + +test('an incomplete or malformed notice is refused', () => { + expect(parseWriteNotice(null)).toBeNull() + expect(parseWriteNotice('nope')).toBeNull() + expect(parseWriteNotice({ space: SPACE, repo: WRITER })).toBeNull() + expect(parseWriteNotice({ space: 'at://x/y/z', repo: WRITER, rev: '3a' })).toBeNull() + expect(parseWriteNotice({ space: SPACE, repo: 'alice.test', rev: '3a' })).toBeNull() +}) + +// --- Debounce --- + +test('a burst of notices for one repo collapses into a single sync', async () => { + // One member writing a gallery sends a notice per record, and each is an + // invitation to read the same repo again. + vi.useFakeTimers() + const run = vi.fn().mockResolvedValue(undefined) + for (let i = 0; i < 5; i++) scheduleNoticeSync('space|writer', run, 100) + await vi.advanceTimersByTimeAsync(200) + expect(run).toHaveBeenCalledTimes(1) +}) + +test('different repos are synced separately', async () => { + vi.useFakeTimers() + const run = vi.fn().mockResolvedValue(undefined) + scheduleNoticeSync('space|alice', run, 100) + scheduleNoticeSync('space|bob', run, 100) + await vi.advanceTimersByTimeAsync(200) + expect(run).toHaveBeenCalledTimes(2) +}) + +test('a failing sync is reported rather than thrown at the authority', async () => { + vi.useFakeTimers() + const run = vi.fn().mockRejectedValue(new Error('host down')) + scheduleNoticeSync('space|writer', run, 100) + // A rejection here must stay inside the scheduler: an unhandled one would + // take the process down over a host being briefly unreachable. + await vi.advanceTimersByTimeAsync(200) + expect(run).toHaveBeenCalled() +}) + +test('clearing drops work that has not run yet', async () => { + vi.useFakeTimers() + const run = vi.fn().mockResolvedValue(undefined) + scheduleNoticeSync('space|writer', run, 100) + clearPendingNotices() + await vi.advanceTimersByTimeAsync(200) + expect(run).not.toHaveBeenCalled() +}) diff --git a/packages/hatk/test/spaces-start.test.ts b/packages/hatk/test/spaces-start.test.ts index 27636ee..a84c0d2 100644 --- a/packages/hatk/test/spaces-start.test.ts +++ b/packages/hatk/test/spaces-start.test.ts @@ -118,3 +118,48 @@ test('stopping ends the sweep', async () => { await vi.advanceTimersByTimeAsync(600_000) expect(reconcileAll).not.toHaveBeenCalled() }) + +// --- Receiving notices --- + +test('with no service DID the instance is addressable by nobody', async () => { + // Which is also what makes the inbound notice routes refuse everything. + const { spaceServiceId } = await import('../src/spaces/index.ts') + startSpaces(base) + expect(spaceServiceId()).toBeNull() + expect(configureSpaceEngine.mock.calls[0][0].serviceId).toBeUndefined() +}) + +test('a service DID gives the instance an identifier notices are addressed to', async () => { + const { spaceServiceId } = await import('../src/spaces/index.ts') + startSpaces({ ...base, spaces: { ...base.spaces, serviceDid: 'did:web:appview.test' } }) + expect(spaceServiceId()).toBe('did:web:appview.test#atproto_space_syncer') + expect(configureSpaceEngine.mock.calls[0][0].serviceId).toBe('did:web:appview.test#atproto_space_syncer') +}) + +test('the service fragment can be named rather than assumed', async () => { + const { spaceServiceId } = await import('../src/spaces/index.ts') + startSpaces({ + ...base, + spaces: { ...base.spaces, serviceDid: 'did:web:appview.test', serviceFragment: 'hatk' }, + }) + expect(spaceServiceId()).toBe('did:web:appview.test#hatk') +}) + +test('stopping makes the instance unaddressable again', async () => { + const { spaceServiceId } = await import('../src/spaces/index.ts') + startSpaces({ ...base, spaces: { ...base.spaces, serviceDid: 'did:web:appview.test' } }) + stopSpaces() + expect(spaceServiceId()).toBeNull() +}) + +test('the published document points an authority at this instance and carries no key', async () => { + const { spaceDidDocument } = await import('../src/spaces/index.ts') + const doc = spaceDidDocument('did:web:appview.test', 'https://appview.test', 'atproto_space_syncer') as any + expect(doc.id).toBe('did:web:appview.test') + expect(doc.service[0]).toEqual({ + id: '#atproto_space_syncer', + type: 'AtprotoSpaceService', + serviceEndpoint: 'https://appview.test', + }) + expect(doc.verificationMethod).toBeUndefined() +}) diff --git a/packages/hatk/test/spaces-verify.test.ts b/packages/hatk/test/spaces-verify.test.ts new file mode 100644 index 0000000..e6eef48 --- /dev/null +++ b/packages/hatk/test/spaces-verify.test.ts @@ -0,0 +1,142 @@ +import { expect, test } from 'vitest' +import { p256 } from '@noble/curves/nist.js' +import { secp256k1 } from '@noble/curves/secp256k1.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { decodeBase58btc, parseMultibaseKey, SignatureError, verifySignature } from '../src/spaces/verify.ts' + +const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' + +function encodeBase58btc(bytes: Uint8Array): string { + const digits = [0] + for (const byte of bytes) { + let carry = byte + for (let i = 0; i < digits.length; i++) { + carry += digits[i] << 8 + digits[i] = carry % 58 + carry = (carry / 58) | 0 + } + while (carry > 0) { + digits.push(carry % 58) + carry = (carry / 58) | 0 + } + } + let leading = '' + for (const byte of bytes) { + if (byte !== 0) break + leading += '1' + } + return ( + leading + + digits + .reverse() + .map((d) => BASE58[d]) + .join('') + ) +} + +function multikey(prefix: number[], key: Uint8Array): string { + return 'z' + encodeBase58btc(new Uint8Array([...prefix, ...key])) +} + +const SECP_PREFIX = [0xe7, 0x01] +const P256_PREFIX = [0x80, 0x24] + +// --- base58btc --- + +test('decodes a known base58btc vector', () => { + expect(new TextDecoder().decode(decodeBase58btc('StV1DL6CwTryKyV'))).toBe('hello world') +}) + +test('leading zero bytes survive the round trip', () => { + // Every leading zero is a '1' the arithmetic would otherwise drop, and a + // dropped one shifts the multicodec prefix and misreads the curve. + const bytes = new Uint8Array([0, 0, 1, 2, 3]) + expect([...decodeBase58btc(encodeBase58btc(bytes))]).toEqual([0, 0, 1, 2, 3]) +}) + +test('an empty string decodes to no bytes', () => { + expect(decodeBase58btc('')).toHaveLength(0) +}) + +test('a character outside the alphabet is refused', () => { + // '0', 'O', 'I' and 'l' are excluded precisely because they are confusable. + expect(() => decodeBase58btc('abc0def')).toThrow(SignatureError) +}) + +// --- Multikeys --- + +test('a secp256k1 key is recognised by its multicodec prefix', () => { + const pub = secp256k1.getPublicKey(secp256k1.utils.randomSecretKey(), true) + const parsed = parseMultibaseKey(multikey(SECP_PREFIX, pub)) + expect(parsed.curve).toBe('secp256k1') + expect([...parsed.bytes]).toEqual([...pub]) +}) + +test('a p256 key is recognised by its own prefix', () => { + const pub = p256.getPublicKey(p256.utils.randomSecretKey(), true) + const parsed = parseMultibaseKey(multikey(P256_PREFIX, pub)) + expect(parsed.curve).toBe('p256') + expect([...parsed.bytes]).toEqual([...pub]) +}) + +test('a key that is not multibase is refused', () => { + expect(() => parseMultibaseKey('QmNotMultibase')).toThrow(/not base58btc multibase/) +}) + +test('a curve atproto does not allow is refused rather than guessed', () => { + const pub = secp256k1.getPublicKey(secp256k1.utils.randomSecretKey(), true) + expect(() => parseMultibaseKey(multikey([0xed, 0x01], pub))).toThrow(/neither secp256k1 nor p256/) +}) + +// --- Signatures --- + +function sign(curve: typeof secp256k1 | typeof p256, message: string) { + const priv = curve.utils.randomSecretKey() + const pub = curve.getPublicKey(priv, true) + const signature = curve.sign(sha256(new TextEncoder().encode(message)), priv) + return { pub, signature } +} + +test('a real secp256k1 signature verifies', () => { + // The curve most did:plc accounts sign with, and the one WebCrypto does not + // implement — the whole reason this module exists. + const { pub, signature } = sign(secp256k1, 'a notice') + const key = parseMultibaseKey(multikey(SECP_PREFIX, pub)) + expect(verifySignature(key, signature, new TextEncoder().encode('a notice'))).toBe(true) +}) + +test('a real p256 signature verifies', () => { + const { pub, signature } = sign(p256, 'a notice') + const key = parseMultibaseKey(multikey(P256_PREFIX, pub)) + expect(verifySignature(key, signature, new TextEncoder().encode('a notice'))).toBe(true) +}) + +test('a signature over different bytes does not verify', () => { + const { pub, signature } = sign(secp256k1, 'a notice') + const key = parseMultibaseKey(multikey(SECP_PREFIX, pub)) + expect(verifySignature(key, signature, new TextEncoder().encode('another notice'))).toBe(false) +}) + +test('a signature is not accepted against a different key', () => { + const { signature } = sign(secp256k1, 'a notice') + const other = secp256k1.getPublicKey(secp256k1.utils.randomSecretKey(), true) + const key = parseMultibaseKey(multikey(SECP_PREFIX, other)) + expect(verifySignature(key, signature, new TextEncoder().encode('a notice'))).toBe(false) +}) + +test('a signature of the wrong length is refused before any curve maths', () => { + const { pub } = sign(secp256k1, 'a notice') + const key = parseMultibaseKey(multikey(SECP_PREFIX, pub)) + expect(verifySignature(key, new Uint8Array(32), new TextEncoder().encode('a notice'))).toBe(false) +}) + +test('a signature naming the wrong curve fails rather than throwing', () => { + const { pub, signature } = sign(secp256k1, 'a notice') + const mislabelled = parseMultibaseKey(multikey(P256_PREFIX, pub)) + expect(verifySignature(mislabelled, signature, new TextEncoder().encode('a notice'))).toBe(false) +}) + +test('a garbage key fails verification instead of crashing', () => { + const key = { curve: 'secp256k1' as const, bytes: new Uint8Array(33).fill(9) } + expect(verifySignature(key, new Uint8Array(64), new TextEncoder().encode('x'))).toBe(false) +})