diff --git a/packages/hatk/src/server.ts b/packages/hatk/src/server.ts index 5625cd2..8677969 100644 --- a/packages/hatk/src/server.ts +++ b/packages/hatk/src/server.ts @@ -32,7 +32,7 @@ import { getOpenReportCount, } from './database/db.ts' import { executeFeed, listFeeds } from './feeds.ts' -import { executeXrpc, InvalidRequestError, NotFoundError, registerCoreXrpcHandler, isLocalRelay } from './xrpc.ts' +import { executeXrpc, InvalidRequestError, NotFoundError, registerCoreXrpcHandler, isLocalRelay, paramsFromSearch } from './xrpc.ts' import { pdsFor } from './backfill.ts' import { resolveRecords } from './hydrate.ts' import { handleOpengraphRequest, buildOgMeta } from './opengraph.ts' @@ -318,7 +318,11 @@ export function registerCoreHandlers(collections: string[], oauth: OAuthConfig | if (!match) throw new InvalidRequestError('Invalid subject URI') subjectDid = match[1] } else if (body.subject.did) { - subjectUri = `at://${body.subject.did}` + // The bare DID, not `at://`: resolving this report labels + // `subjectUri`, and an account label is keyed by DID alone. Ozone + // writes it that way and every appview reads it that way, so the + // `at://` form would apply a label nothing ever looks up. + subjectUri = body.subject.did subjectDid = body.subject.did } else { throw new InvalidRequestError('Subject must have uri or did') @@ -573,10 +577,7 @@ export function createHandler(config: HandlerConfig): (request: Request) => Prom const limit = parseInt(url.searchParams.get('limit') || '30') const cursor = url.searchParams.get('cursor') || undefined - const params: Record = {} - for (const [key, value] of url.searchParams) { - params[key] = value - } + const params = paramsFromSearch(url.searchParams) const result = await executeFeed(feedName, params, cursor, limit, viewer) if (!result) return withCors(jsonError(404, `Unknown feed: ${feedName}`, acceptEncoding)) @@ -1467,10 +1468,7 @@ export function createHandler(config: HandlerConfig): (request: Request) => Prom const limit = parseInt(url.searchParams.get('limit') || '20') const cursor = url.searchParams.get('cursor') || undefined - const params: Record = {} - for (const [key, value] of url.searchParams) { - params[key] = value - } + const params = paramsFromSearch(url.searchParams) // Parse request body for POST (procedures) let input: unknown diff --git a/packages/hatk/src/xrpc.ts b/packages/hatk/src/xrpc.ts index 3addcc5..71a4ee1 100644 --- a/packages/hatk/src/xrpc.ts +++ b/packages/hatk/src/xrpc.ts @@ -136,7 +136,7 @@ export interface XrpcContext< interface XrpcHandler { name: string execute: ( - params: Record, + params: XrpcParams, cursor: string | undefined, limit: number, viewer: { did: string; handle?: string } | null, @@ -209,7 +209,7 @@ export function blobUrl(did: string, ref: unknown, preset: string = 'avatar'): s /** Build a full XrpcContext from request parameters. Reuses buildBaseContext for shared fields. */ export function buildXrpcContext( - params: Record, + params: XrpcParams, cursor: string | undefined, limit: number, viewer: { did: string; handle?: string } | null, @@ -304,20 +304,7 @@ export async function initXrpc(xrpcDir: string): Promise { handlers.set(name, { name, execute: async (params, cursor, limit, viewer, input) => { - // Apply defaults and coerce types from lexicon - for (const [key, def] of Object.entries(paramProperties)) { - if (params[key] == null && def.default != null) { - params[key] = String(def.default) - } - if (params[key] != null && def.type === 'integer') { - params[key] = Number(params[key]) as any - } - } - for (const param of requiredParams) { - if (!params[param]) { - throw new InvalidRequestError(`Missing required parameter: ${param}`, 'InvalidRequest') - } - } + coerceParams(params, paramProperties, requiredParams) const ctx = buildXrpcContext(params, cursor, limit, viewer, input) return handler.handler(ctx) @@ -337,19 +324,7 @@ export function registerXrpcHandler(nsid: string, handlerModule: { handler: (ctx handlers.set(nsid, { name: nsid, execute: async (params, cursor, limit, viewer, input) => { - for (const [key, def] of Object.entries(paramProperties)) { - if (params[key] == null && def.default != null) { - params[key] = String(def.default) - } - if (params[key] != null && def.type === 'integer') { - params[key] = Number(params[key]) as any - } - } - for (const param of requiredParams) { - if (!params[param]) { - throw new InvalidRequestError(`Missing required parameter: ${param}`, 'InvalidRequest') - } - } + coerceParams(params, paramProperties, requiredParams) const ctx = buildXrpcContext(params, cursor, limit, viewer, input) return handlerModule.handler(ctx) @@ -357,10 +332,65 @@ export function registerXrpcHandler(nsid: string, handlerModule: { handler: (ctx }) } +/** + * What the query string gives a handler: one value per key, or every value + * when the key was repeated (`?dids=a&dids=b`). + */ +export type XrpcParams = Record + +/** Collect a query string into params, keeping every value of a repeated key. */ +export function paramsFromSearch(search: URLSearchParams): XrpcParams { + const params: XrpcParams = {} + for (const [key, value] of search) { + const prior = params[key] + if (prior === undefined) params[key] = value + else if (Array.isArray(prior)) prior.push(value) + else params[key] = [prior, value] + } + return params +} + +function coerceScalar(value: unknown, def: any): unknown { + // Only integers, as before: a boolean still reaches the handler as the + // string it was sent as, and handlers written against that keep working. + return def?.type === 'integer' ? Number(value) : value +} + +/** + * Apply the lexicon's parameter schema before a handler runs: defaults, + * integer coercion, and arrays. A query string cannot say whether + * `dids=x` is one string or a one-element list, so the schema decides: a + * parameter declared `array` always reaches the handler as one, or a handler + * that spreads it would spread the characters of a DID instead. + */ +export function coerceParams(params: XrpcParams, properties: Record, required: string[]): void { + for (const [key, def] of Object.entries(properties)) { + if (params[key] == null && def.default != null) { + params[key] = def.type === 'array' ? [...def.default] : def.type === 'string' ? String(def.default) : def.default + } + if (params[key] == null) continue + if (def.type === 'array') { + const list = Array.isArray(params[key]) ? params[key] : [params[key]] + params[key] = list.map((v: unknown) => coerceScalar(v, def.items)) + } else if (Array.isArray(params[key])) { + // A scalar given twice: the last one wins, as a form submission would. + params[key] = coerceScalar(params[key][params[key].length - 1], def) + } else { + params[key] = coerceScalar(params[key], def) + } + } + for (const param of required) { + const v = params[param] + if (v == null || v === '' || (Array.isArray(v) && v.length === 0)) { + throw new InvalidRequestError(`Missing required parameter: ${param}`, 'InvalidRequest') + } + } +} + /** Execute a registered XRPC handler by name. Returns null if no handler matches. */ export async function executeXrpc( name: string, - params: Record, + params: XrpcParams, cursor: string | undefined, limit: number, viewer?: { did: string } | null, @@ -387,9 +417,11 @@ export async function callXrpc(nsid: string, params: Record = {}, i if (handlers.size === 0 && (globalThis as any).__hatk_callXrpc) { return (globalThis as any).__hatk_callXrpc(nsid, params, input) } - const stringParams: Record = {} + const stringParams: XrpcParams = {} for (const [k, v] of Object.entries(params)) { - if (v != null) stringParams[k] = String(v) + if (v == null) continue + // A list stays a list, as the query string would have carried it. + stringParams[k] = Array.isArray(v) ? v.map(String) : String(v) } const limit = params.limit ? Number(params.limit) : 20 const cursor = params.cursor ?? undefined @@ -405,7 +437,7 @@ export async function callXrpc(nsid: string, params: Record = {}, i export function registerCoreXrpcHandler( nsid: string, fn: ( - params: Record, + params: XrpcParams, cursor: string | undefined, limit: number, viewer: { did: string; handle?: string } | null, diff --git a/packages/hatk/test/xrpc-context.test.ts b/packages/hatk/test/xrpc-context.test.ts index fec51f8..7f55d1e 100644 --- a/packages/hatk/test/xrpc-context.test.ts +++ b/packages/hatk/test/xrpc-context.test.ts @@ -17,6 +17,7 @@ import { isLocalRelay, listXrpc, registerCoreXrpcHandler, + paramsFromSearch, registerXrpcHandler, } from '../src/xrpc.ts' import { storeLexicons } from '../src/database/schema.ts' @@ -248,6 +249,50 @@ test('a handler registered against a lexicon has defaults applied, integers coer }) }) +test('an array parameter reaches the handler as a list however many values were sent', async () => { + // A query string cannot say whether `dids=x` is one string or a list of + // one; the lexicon does. A handler that spread the string got the characters + // of a DID. + storeLexicons( + new Map([ + [ + 'xyz.test.getActors', + { + lexicon: 1, + id: 'xyz.test.getActors', + defs: { + main: { + type: 'query', + parameters: { + type: 'params', + required: ['dids'], + properties: { + dids: { type: 'array', items: { type: 'string' } }, + pages: { type: 'array', items: { type: 'integer' } }, + tag: { type: 'string' }, + }, + }, + }, + }, + }, + ], + ]), + ) + registerXrpcHandler('xyz.test.getActors', { handler: async (ctx) => ctx.params }) + + const one = paramsFromSearch(new URLSearchParams('dids=did:plc:a')) + expect(await executeXrpc('xyz.test.getActors', one, undefined, 10)).toEqual({ dids: ['did:plc:a'] }) + + const many = paramsFromSearch(new URLSearchParams('dids=did:plc:a&dids=did:plc:b&pages=1&pages=2&tag=x&tag=y')) + expect(await executeXrpc('xyz.test.getActors', many, undefined, 10)).toEqual({ + dids: ['did:plc:a', 'did:plc:b'], + pages: [1, 2], + tag: 'y', // a scalar sent twice: the last one wins + }) + + await expect(executeXrpc('xyz.test.getActors', {}, undefined, 10)).rejects.toThrow('Missing required parameter: dids') +}) + test('a handler without a lexicon still runs with its params untouched', async () => { registerXrpcHandler('xyz.test.noLexicon', { handler: async (ctx) => ({ params: ctx.params, input: ctx.input }) }) expect(await executeXrpc('xyz.test.noLexicon', { n: '1' }, undefined, 10, null, { b: 1 })).toEqual({