@marktiderman/genesis-supabase 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/jobs.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jobs.ts"],"names":[],"mappings":";AAsCO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACT,WAAA,CAAY,SAAiB,IAAA,EAAe;AAC1C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEA,eAAe,IAAA,CAAQ,MAAA,EAAoB,EAAA,EAAY,IAAA,EAA2C;AAChG,EAAA,MAAM,EAAE,MAAM,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,GAAA,CAAI,IAAI,IAAI,CAAA;AACjD,EAAA,IAAI,KAAA,EAAO,MAAM,IAAI,SAAA,CAAU,CAAA,EAAG,EAAE,CAAA,EAAA,EAAK,KAAA,CAAM,OAAO,CAAA,CAAA,EAAI,KAAA,CAAM,IAAI,CAAA;AACpE,EAAA,OAAO,IAAA;AACT;AAmBO,SAAS,UAAA,CAAW,QAAoB,IAAA,EAAc,OAAA,GAAmC,EAAC,EAAG,OAAA,GAA0B,EAAC,EAAoB;AACjJ,EAAA,OAAO,IAAA,CAAa,QAAQ,qBAAA,EAAuB;AAAA,IACjD,MAAA,EAAQ,IAAA;AAAA,IACR,SAAA,EAAW,OAAA;AAAA,IACX,WAAA,EAAa,OAAA,CAAQ,QAAA,EAAU,WAAA,EAAY,IAAK,IAAA;AAAA,IAChD,iBAAA,EAAmB,QAAQ,cAAA,IAAkB,IAAA;AAAA,IAC7C,cAAA,EAAgB,QAAQ,WAAA,IAAe;AAAA,GACxC,CAAA;AACH;AA2BO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA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AsC,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,IAC7F;AAAA,EACF,CAAA;AACF","file":"jobs.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/jobs`: the server half of\n * `migrations/0007_genesis_jobs.sql`. Server only (it takes the service-role\n * client and the job secret); never import it into browser or app code.\n *\n * - `enqueueJob`: queue work from server code (triggers enqueue in SQL).\n * - `runJobs`: claim due jobs, run each kind's handler, settle each one, with\n * backoff on failure. Never throws for one job's failure.\n * - `createJobsHandler`: the app's one job route. It checks the request is\n * signed for the job (`genesis_schedule_job` signs; the secret never\n * travels) or carries the bearer secret (a platform cron, a person), with a\n * previous secret accepted while you rotate it, and runs the named job.\n *\n * ```ts\n * // src/routes/api/jobs/$job.ts (any server route that hands over a Request)\n * const handle = createJobsHandler({\n * secret: process.env.GENESIS_JOBS_SECRET,\n * previousSecret: process.env.GENESIS_JOBS_SECRET_PREVIOUS,\n * jobs: {\n * queue: () => runJobs(admin, { handlers: { \"email.digest\": sendDigest } }),\n * cleanup: () => removeQueuedFiles(admin),\n * },\n * });\n * export const POST = ({ request, params }) => handle(request, params.job);\n * ```\n *\n * @packageDocumentation\n */\n\n/** The parts of a Supabase client these helpers use: a service-role `SupabaseClient` fits. */\nexport interface JobsClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: { message: string; code?: string } | null }>;\n}\n\n/** A failure from the queue's own functions (not from a handler). */\nexport class JobsError extends Error {\n readonly code: string | undefined;\n constructor(message: string, code?: string) {\n super(message);\n this.name = \"JobsError\";\n this.code = code;\n }\n}\n\nasync function call<T>(client: JobsClient, fn: string, args: Record<string, unknown>): Promise<T> {\n const { data, error } = await client.rpc(fn, args);\n if (error) throw new JobsError(`${fn}: ${error.message}`, error.code);\n return data as T;\n}\n\n/** @stability Beta */\nexport interface EnqueueOptions {\n /** Run no earlier than this. Default now. */\n runAfter?: Date;\n /** One job per kind and key while it is queued or running: a repeat returns the queued job's id. */\n idempotencyKey?: string;\n /** Attempts before it fails for good, 1 to 100. Default 8. */\n maxAttempts?: number;\n}\n\n/**\n * Queue one job of `kind` (`\"email.digest\"`, lowercase) with a JSON object\n * payload. Returns the job's id. Payloads are readable by the service role:\n * put ids in them, never secrets.\n *\n * @stability Beta\n */\nexport function enqueueJob(client: JobsClient, kind: string, payload: Record<string, unknown> = {}, options: EnqueueOptions = {}): Promise<string> {\n return call<string>(client, \"genesis_job_enqueue\", {\n p_kind: kind,\n p_payload: payload,\n p_run_after: options.runAfter?.toISOString() ?? null,\n p_idempotency_key: options.idempotencyKey ?? null,\n p_max_attempts: options.maxAttempts ?? 8,\n });\n}\n\n/** One claimed job, as a handler sees it. @stability Beta */\nexport interface Job<Payload = Record<string, unknown>> {\n id: string;\n kind: string;\n payload: Payload;\n /** This attempt's number, from 1. */\n attempt: number;\n /** An earlier attempt's lease ran out: it may have done the work. Handlers that can look first, do. */\n redelivery: boolean;\n}\n\n/**\n * What a handler can return. Nothing (or `{ done: true }`) is done. Throwing\n * retries with backoff; throw a `PermanentJobError` (or return\n * `{ failed }`) to stop.\n *\n * @stability Beta\n */\nexport type JobOutcome =\n | void\n | { done: true }\n | { retryAfterSeconds: number; error?: string }\n | { failed: string };\n\n/** Thrown by a handler for a failure that won't get better with a retry (a bad payload, a 4xx). @stability Beta */\nexport class PermanentJobError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PermanentJobError\";\n }\n}\n\n// Handlers are keyed by kind, so each takes its own payload type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JobHandler = (job: Job<any>) => Promise<JobOutcome> | JobOutcome;\n\n/** @stability Beta */\nexport interface RunJobsOptions {\n /** Kind → handler. Only these kinds are claimed. */\n handlers: Readonly<Record<string, JobHandler>>;\n /** Jobs claimed in this run. Default 25. */\n limit?: number;\n /** How long a claim holds a job; a handler must finish inside it. Default 300. */\n leaseSeconds?: number;\n /** Jobs run at once. Default 4. */\n concurrency?: number;\n /** Seconds before retry `attempt` (from 1). Default 30 s doubling, jittered, at most an hour. */\n backoff?: (attempt: number) => number;\n /** Where one line per failed job goes (kind, id, attempt, the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\n/** @stability Beta */\nexport interface RunJobsReport {\n claimed: number;\n done: number;\n retried: number;\n failed: number;\n /** Settles refused because the lease ran out first (another run has the job). */\n stale: number;\n /** Settles that failed (the database unreachable): those jobs come back when their lease runs out. */\n unsettled: number;\n}\n\n/** 30 s, doubling per attempt, ±20% jitter, at most an hour. */\nexport function defaultBackoff(attempt: number): number {\n const base = Math.min(3600, 30 * 2 ** Math.max(0, attempt - 1));\n return Math.round(base * (0.8 + Math.random() * 0.4));\n}\n\nfunction messageOf(error: unknown): string {\n return (error instanceof Error ? `${error.name}: ${error.message}` : String(error)).slice(0, 1000);\n}\n\n/**\n * Claim due jobs of the handled kinds, run them, and settle each: done, a\n * retry after backoff, or failed. One job's failure, or a failure to record\n * it, never stops the others; only a failed claim throws. Nothing about a\n * payload is logged.\n *\n * @stability Beta\n */\nexport async function runJobs(client: JobsClient, options: RunJobsOptions): Promise<RunJobsReport> {\n const kinds = Object.keys(options.handlers);\n const report: RunJobsReport = { claimed: 0, done: 0, retried: 0, failed: 0, stale: 0, unsettled: 0 };\n if (kinds.length === 0) return report;\n const backoff = options.backoff ?? defaultBackoff;\n const log = options.log ?? ((line: string) => console.error(line));\n\n type Claimed = Job & { claim_id: string };\n const claimed =\n (await call<Claimed[] | null>(client, \"genesis_jobs_claim\", {\n p_kinds: kinds,\n p_limit: options.limit ?? 25,\n p_lease_seconds: options.leaseSeconds ?? 300,\n })) ?? [];\n report.claimed = claimed.length;\n\n const settle = async (job: Claimed, outcome: \"done\" | \"retry\" | \"failed\", retryAfter: number | null, error: string | null) => {\n const ok = await call<boolean>(client, \"genesis_jobs_settle\", {\n p_id: job.id,\n p_claim_id: job.claim_id,\n p_outcome: outcome,\n p_retry_after_seconds: retryAfter,\n p_error: error,\n });\n if (!ok) report.stale++;\n else if (outcome === \"done\") report.done++;\n else if (outcome === \"retry\") report.retried++;\n else report.failed++;\n };\n\n type Settle = [\"done\" | \"retry\" | \"failed\", number | null, string | null];\n\n // What the handler says, as a settle. Only the handler runs inside this try.\n const outcomeOf = async (job: Claimed): Promise<Settle> => {\n const handler = options.handlers[job.kind];\n const { claim_id: _claim, ...seen } = job;\n try {\n const outcome = handler ? await handler(seen) : { failed: `no handler for ${job.kind}` };\n if (outcome && \"failed\" in outcome) {\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt} failed: ${outcome.failed}`);\n return [\"failed\", null, outcome.failed.slice(0, 1000)];\n }\n if (outcome && \"retryAfterSeconds\" in outcome) return [\"retry\", Math.max(0, Math.round(outcome.retryAfterSeconds)), outcome.error ?? null];\n return [\"done\", null, null];\n } catch (error) {\n const message = messageOf(error);\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt}: ${message}`);\n return error instanceof PermanentJobError ? [\"failed\", null, message] : [\"retry\", backoff(job.attempt), message];\n }\n };\n\n const runOne = async (job: Claimed) => {\n const [outcome, retryAfter, error] = await outcomeOf(job);\n try {\n await settle(job, outcome, retryAfter, error);\n } catch (failure) {\n // The queue didn't take the outcome: the lease runs out and the job comes back as a\n // redelivery. The other jobs in this run carry on.\n report.unsettled++;\n log(`[jobs] ${job.kind} ${job.id}: could not record ${outcome}: ${messageOf(failure)}`);\n }\n };\n\n const queue = [...claimed];\n const workers = Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 4, queue.length)) }, async () => {\n for (let job = queue.shift(); job; job = queue.shift()) await runOne(job);\n });\n await Promise.all(workers);\n return report;\n}\n\nconst encoder = new TextEncoder();\n\nasync function digest(value: string): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value)));\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n let diff = a.length ^ b.length;\n for (let i = 0; i < a.length && i < b.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\n/** @stability Beta */\nexport interface VerifyJobRequestOptions {\n /** The job secret. Unset refuses every request (500). */\n secret: string | undefined;\n /** The secret before a rotation, accepted too. Remove it once every caller has the new one. */\n previousSecret?: string | undefined;\n /** How far a signed request's time may be from now, in seconds. Default 300. */\n maxSkewSeconds?: number;\n /** Now, in seconds (for tests). */\n now?: () => number;\n}\n\nconst hex = (bytes: ArrayBuffer) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\nasync function hmacHex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return hex(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(message)));\n}\n\n/**\n * The `Authorization` value a scheduler sends for `job`: `GenesisJob\n * t=<unix seconds>,sig=<hex HMAC-SHA256 of \"<t>.<job>\">`. What\n * `genesis_schedule_job` sends; for calling a job route from your own code.\n *\n * @stability Beta\n */\nexport async function signJobRequest(secret: string, job: string, now: number = Math.floor(Date.now() / 1000)): Promise<string> {\n return `GenesisJob t=${now},sig=${await hmacHex(secret, `${now}.${job}`)}`;\n}\n\n/**\n * Checks a request's `Authorization` in constant time against the secret and\n * the previous one. Two forms: `GenesisJob t=…,sig=…`, signed for `job` within\n * `maxSkewSeconds` (what schedules send: the secret never travels), or\n * `Bearer <secret>` (a platform cron, a person). The scheme's case and extra\n * spaces don't matter. Returns `null` when it passes, else the response to\n * send: 401, or 500 when no secret is configured.\n *\n * @stability Beta\n */\nexport async function verifyJobRequest(request: Request, options: VerifyJobRequestOptions, job?: string): Promise<Response | null> {\n if (!options.secret) return Response.json({ error: \"The job secret is not configured.\" }, { status: 500 });\n const secrets = [options.secret, ...(options.previousSecret ? [options.previousSecret] : [])];\n const header = (request.headers.get(\"authorization\") ?? \"\").trim();\n const unauthorized = () => Response.json({ error: \"Unauthorized.\" }, { status: 401 });\n\n const bearer = /^bearer\\s+([^\\s,]+)$/i.exec(header)?.[1];\n if (bearer) {\n const given = await digest(bearer);\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(secret)) || ok;\n return ok ? null : unauthorized();\n }\n\n const signed = /^genesisjob\\s+t=(\\d{1,12})\\s*,\\s*sig=([0-9a-f]{64})$/i.exec(header);\n if (signed && job) {\n const t = Number(signed[1]);\n const now = options.now?.() ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - t) > (options.maxSkewSeconds ?? 300)) return unauthorized();\n const given = await digest(signed[2]!.toLowerCase());\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(await hmacHex(secret, `${t}.${job}`))) || ok;\n return ok ? null : unauthorized();\n }\n return unauthorized();\n}\n\n/**\n * One named job a route can run. Its return value (JSON) is the response's `result` for a\n * bearer call; a signed call (a schedule) gets `{ job, ok: true }` and its `body` is always `{}`.\n *\n * @stability Beta\n */\nexport type NamedJob = (context: { request: Request; body: Record<string, unknown> }) => Promise<unknown> | unknown;\n\n/** @stability Beta */\nexport interface JobsHandlerOptions extends VerifyJobRequestOptions {\n /** Job name (`\"digests\"`, as `genesis_schedule_job` names it) → what it runs. */\n jobs: Readonly<Record<string, NamedJob>>;\n /** Where a job's failure goes (name and the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\nconst JOB_NAME = /^[a-z][a-z0-9]*([-_][a-z0-9]+)*$/;\n\n/**\n * The app's job route: checks the request is signed for (or carries the\n * secret of) the job named by the route (`name`, e.g. a path param), the\n * body's `job`, or the URL's last segment, then runs it. GET and POST (platform crons send GET). Answers 401, 404 for an\n * unknown job, 405, 200 with the job's result, or 500 with no detail.\n *\n * @stability Beta\n */\nexport function createJobsHandler(options: JobsHandlerOptions): (request: Request, name?: string) => Promise<Response> {\n const log = options.log ?? ((line: string) => console.error(line));\n return async (request, name) => {\n if (request.method !== \"GET\" && request.method !== \"POST\") {\n return Response.json({ error: \"Use GET or POST.\" }, { status: 405, headers: { Allow: \"GET, POST\" } });\n }\n // A signed call (a schedule) is signed for the job name only, so nothing else it carries is\n // trusted: its body is ignored, and its response carries no result (pg_net keeps responses\n // in net._http_response, which other roles may read).\n const signed = /^genesisjob\\s/i.test((request.headers.get(\"authorization\") ?? \"\").trim());\n const raw = request.method === \"POST\" && !signed ? await request.clone().json().catch(() => null) : null;\n const body = raw && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n const job = name ?? (typeof body[\"job\"] === \"string\" ? body[\"job\"] : new URL(request.url).pathname.split(\"/\").filter(Boolean).at(-1));\n\n // The signature is for one job name, so check it against the name the route will run.\n const refused = await verifyJobRequest(request, options, job);\n if (refused) return refused;\n\n const run = job && JOB_NAME.test(job) && Object.hasOwn(options.jobs, job) ? options.jobs[job] : undefined;\n if (!run) return Response.json({ error: \"No such job.\" }, { status: 404 });\n\n try {\n const result = (await run({ request, body })) ?? null;\n return Response.json(signed ? { job, ok: true } : { job, result });\n } catch (error) {\n log(`[jobs] ${job}: ${messageOf(error)}`);\n return Response.json({ job, error: \"The job failed; see the server log.\" }, { status: 500 });\n }\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/jobs.ts"],"names":[],"mappings":";;;AAwCO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACT,WAAA,CAAY,SAAiB,IAAA,EAAe;AAC1C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEA,eAAe,IAAA,CAAQ,MAAA,EAAoB,EAAA,EAAY,IAAA,EAA2C;AAChG,EAAA,MAAM,EAAE,MAAM,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,GAAA,CAAI,IAAI,IAAI,CAAA;AACjD,EAAA,IAAI,KAAA,EAA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AM,GAAG,EAAE,MAAA,CAAO,OAAO,CAAA,CAAE,EAAA,CAAG,EAAE,CAAA,CAAA;AAGnI,IAAA,MAAM,OAAA,GAAU,MAAM,gBAAA,CAAiB,OAAA,EAAS,SAAS,GAAG,CAAA;AAC5D,IAAA,IAAI,SAAS,OAAO,OAAA;AAEpB,IAAA,MAAM,GAAA,GAAM,GAAA,IAAO,QAAA,CAAS,IAAA,CAAK,GAAG,CAAA,IAAK,MAAA,CAAO,MAAA,CAAO,OAAA,CAAQ,MAAM,GAAG,CAAA,GAAI,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA,GAAI,MAAA;AAChG,IAAA,IAAI,CAAC,GAAA,EAAK,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,KAAA,EAAO,cAAA,EAAe,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAEzE,IAAA,IAAI;AACF,MAAA,MAAM,SAAU,MAAM,GAAA,CAAI,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA,IAAM,IAAA;AACjD,MAAA,OAAO,QAAA,CAAS,IAAA,CAAK,MAAA,GAAS,EAAE,GAAA,EAAK,EAAA,EAAI,IAAA,EAAK,GAAI,EAAE,GAAA,EAAK,MAAA,EAAQ,CAAA;AAAA,IACnE,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,UAAU,GAAG,CAAA,EAAA,EAAK,SAAA,CAAU,KAAK,CAAC,CAAA,CAAE,CAAA;AACxC,MAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,GAAA,EAAK,KAAA,EAAO,uCAAsC,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,IAC7F;AAAA,EACF,CAAA;AACF","file":"jobs.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/jobs`: the server half of\n * `migrations/0007_genesis_jobs.sql`. Server only (it takes the service-role\n * client and the job secret); never import it into browser or app code.\n *\n * - `enqueueJob`: queue work from server code (triggers enqueue in SQL).\n * - `runJobs`: claim due jobs, run each kind's handler, settle each one, with\n * backoff on failure. Never throws for one job's failure.\n * - `createJobsHandler`: the app's one job route. It checks the request is\n * signed for the job (`genesis_schedule_job` signs; the secret never\n * travels) or carries the bearer secret (a platform cron, a person), with a\n * previous secret accepted while you rotate it, and runs the named job.\n *\n * ```ts\n * // src/routes/api/jobs/$job.ts (any server route that hands over a Request)\n * const handle = createJobsHandler({\n * secret: process.env.GENESIS_JOBS_SECRET,\n * previousSecret: process.env.GENESIS_JOBS_SECRET_PREVIOUS,\n * jobs: {\n * queue: () => runJobs(admin, { handlers: { \"email.digest\": sendDigest } }),\n * cleanup: () => removeQueuedFiles(admin),\n * },\n * });\n * export const POST = ({ request, params }) => handle(request, params.job);\n * ```\n *\n * @packageDocumentation\n */\n\nimport { createRunner, type JobResult as EngineResult } from \"./runner\";\n\n/** The parts of a Supabase client these helpers use: a service-role `SupabaseClient` fits. */\nexport interface JobsClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: { message: string; code?: string } | null }>;\n}\n\n/** A failure from the queue's own functions (not from a handler). */\nexport class JobsError extends Error {\n readonly code: string | undefined;\n constructor(message: string, code?: string) {\n super(message);\n this.name = \"JobsError\";\n this.code = code;\n }\n}\n\nasync function call<T>(client: JobsClient, fn: string, args: Record<string, unknown>): Promise<T> {\n const { data, error } = await client.rpc(fn, args);\n if (error) throw new JobsError(`${fn}: ${error.message}`, error.code);\n return data as T;\n}\n\n/** @stability Beta */\nexport interface EnqueueOptions {\n /** Run no earlier than this. Default now. */\n runAfter?: Date;\n /** One job per kind and key while it is queued or running: a repeat returns the queued job's id. */\n idempotencyKey?: string;\n /** Attempts before it fails for good, 1 to 100. Default 8. */\n maxAttempts?: number;\n}\n\n/**\n * Queue one job of `kind` (`\"email.digest\"`, lowercase) with a JSON object\n * payload. Returns the job's id. Payloads are readable by the service role:\n * put ids in them, never secrets.\n *\n * @stability Beta\n */\nexport function enqueueJob(client: JobsClient, kind: string, payload: Record<string, unknown> = {}, options: EnqueueOptions = {}): Promise<string> {\n return call<string>(client, \"genesis_job_enqueue\", {\n p_kind: kind,\n p_payload: payload,\n p_run_after: options.runAfter?.toISOString() ?? null,\n p_idempotency_key: options.idempotencyKey ?? null,\n p_max_attempts: options.maxAttempts ?? 8,\n });\n}\n\n/** One claimed job, as a handler sees it. @stability Beta */\nexport interface Job<Payload = Record<string, unknown>> {\n id: string;\n kind: string;\n payload: Payload;\n /** This attempt's number, from 1. */\n attempt: number;\n /** An earlier attempt's lease ran out: it may have done the work. Handlers that can look first, do. */\n redelivery: boolean;\n}\n\n/**\n * What a handler can return. Nothing (or `{ done: true }`) is done. Throwing\n * retries with backoff; throw a `PermanentJobError` (or return\n * `{ failed }`) to stop.\n *\n * @stability Beta\n */\nexport type JobOutcome =\n | void\n | { done: true }\n | { retryAfterSeconds: number; error?: string }\n | { failed: string };\n\n/** Thrown by a handler for a failure that won't get better with a retry (a bad payload, a 4xx). @stability Beta */\nexport class PermanentJobError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PermanentJobError\";\n }\n}\n\n// Handlers are keyed by kind, so each takes its own payload type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JobHandler = (job: Job<any>) => Promise<JobOutcome> | JobOutcome;\n\n/** @stability Beta */\nexport interface RunJobsOptions {\n /** Kind → handler. Only these kinds are claimed. */\n handlers: Readonly<Record<string, JobHandler>>;\n /** Jobs claimed in this run. Default 25. */\n limit?: number;\n /** How long a claim holds a job; a handler must finish inside it. Default 300. */\n leaseSeconds?: number;\n /** Jobs run at once. Default 4. */\n concurrency?: number;\n /** Seconds before retry `attempt` (from 1). Default 30 s doubling, jittered, at most an hour. */\n backoff?: (attempt: number) => number;\n /** Where one line per failed job goes (kind, id, attempt, the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\n/** @stability Beta */\nexport interface RunJobsReport {\n claimed: number;\n done: number;\n retried: number;\n failed: number;\n /** Settles refused because the lease ran out first (another run has the job). */\n stale: number;\n /** Settles that failed (the database unreachable): those jobs come back when their lease runs out. */\n unsettled: number;\n}\n\n/** 30 s, doubling per attempt, ±20% jitter, at most an hour. */\nexport function defaultBackoff(attempt: number): number {\n const base = Math.min(3600, 30 * 2 ** Math.max(0, attempt - 1));\n return Math.round(base * (0.8 + Math.random() * 0.4));\n}\n\nfunction messageOf(error: unknown): string {\n return (error instanceof Error ? `${error.name}: ${error.message}` : String(error)).slice(0, 1000);\n}\n\n/**\n * Claim due jobs of the handled kinds, run them, and settle each: done, a\n * retry after backoff, or failed. One job's failure, or a failure to record\n * it, never stops the others; only a failed claim throws. Nothing about a\n * payload is logged. It runs on the shared engine (`createRunner` from\n * `/runner`): the queue's claim and settle are its store, each kind's handler\n * its sender, and the queue itself decides when a job is out of attempts.\n *\n * @stability Beta\n */\nexport async function runJobs(client: JobsClient, options: RunJobsOptions): Promise<RunJobsReport> {\n const kinds = Object.keys(options.handlers);\n const empty: RunJobsReport = { claimed: 0, done: 0, retried: 0, failed: 0, stale: 0, unsettled: 0 };\n if (kinds.length === 0) return empty;\n const backoff = options.backoff ?? defaultBackoff;\n const log = options.log ?? ((line: string) => console.error(line));\n\n type Claimed = Job & { claim_id: string };\n type Settle = [\"done\" | \"retry\" | \"failed\", number | null, string | null];\n // The settle each job's handler asked for, exactly as the queue takes it. The engine's own\n // outcome only decides which count it lands in; the queue keeps the attempts and backoff.\n const settles = new WeakMap<Claimed, Settle>();\n\n // What the handler says, as a settle. Only the handler runs inside this try.\n const outcomeOf = async (job: Claimed): Promise<Settle> => {\n const handler = options.handlers[job.kind];\n const { claim_id: _claim, ...seen } = job;\n try {\n const outcome = handler ? await handler(seen) : { failed: `no handler for ${job.kind}` };\n if (outcome && \"failed\" in outcome) {\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt} failed: ${outcome.failed}`);\n return [\"failed\", null, outcome.failed.slice(0, 1000)];\n }\n if (outcome && \"retryAfterSeconds\" in outcome) return [\"retry\", Math.max(0, Math.round(outcome.retryAfterSeconds)), outcome.error ?? null];\n return [\"done\", null, null];\n } catch (error) {\n const message = messageOf(error);\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt}: ${message}`);\n return error instanceof PermanentJobError ? [\"failed\", null, message] : [\"retry\", backoff(job.attempt), message];\n }\n };\n\n const resultOf = ([outcome, retryAfter, error]: Settle): EngineResult => {\n if (outcome === \"done\") return { ok: true };\n if (outcome === \"failed\") return { ok: false, retryable: false, error: error ?? \"failed\" };\n // Every retry is a deferral to the engine (with no attempt or deferral cap below), so it\n // never gives up a job or computes a backoff of its own: the queue does both.\n return { ok: false, retryable: true, retryAfterSeconds: retryAfter ?? 0, error: error ?? \"retry\" };\n };\n\n const runner = createRunner<Claimed>({\n claim: async ({ limit }) =>\n (await call<Claimed[] | null>(client, \"genesis_jobs_claim\", {\n p_kinds: kinds,\n p_limit: limit,\n p_lease_seconds: options.leaseSeconds ?? 300,\n })) ?? [],\n send: async ([job]) => {\n const settle = await outcomeOf(job!);\n settles.set(job!, settle);\n return [resultOf(settle)];\n },\n record: async (job) => {\n const [outcome, retryAfter, error] = settles.get(job)!;\n try {\n // Anything but true is a settle the queue refused (the lease ran out): stale.\n const ok = await call<boolean | null>(client, \"genesis_jobs_settle\", {\n p_id: job.id,\n p_claim_id: job.claim_id,\n p_outcome: outcome,\n p_retry_after_seconds: retryAfter,\n p_error: error,\n });\n return Boolean(ok);\n } catch (failure) {\n // The queue didn't take the outcome: the lease runs out and the job comes back as a\n // redelivery. The other jobs in this run carry on.\n log(`[jobs] ${job.kind} ${job.id}: could not record ${outcome}: ${messageOf(failure)}`);\n throw failure;\n }\n },\n concurrency: options.concurrency ?? 4,\n maxAttempts: Number.POSITIVE_INFINITY,\n maxDeferrals: Number.POSITIVE_INFINITY,\n });\n\n const report = await runner.run({ limit: options.limit ?? 25 });\n return {\n claimed: report.claimed,\n done: report.sent,\n retried: report.retrying + report.deferred,\n failed: report.failed,\n stale: report.stale,\n unsettled: report.unrecorded,\n };\n}\n\nconst encoder = new TextEncoder();\n\nasync function digest(value: string): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value)));\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n let diff = a.length ^ b.length;\n for (let i = 0; i < a.length && i < b.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\n/** @stability Beta */\nexport interface VerifyJobRequestOptions {\n /** The job secret. Unset refuses every request (500). */\n secret: string | undefined;\n /** The secret before a rotation, accepted too. Remove it once every caller has the new one. */\n previousSecret?: string | undefined;\n /** How far a signed request's time may be from now, in seconds. Default 300. */\n maxSkewSeconds?: number;\n /** Now, in seconds (for tests). */\n now?: () => number;\n}\n\nconst hex = (bytes: ArrayBuffer) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\nasync function hmacHex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return hex(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(message)));\n}\n\n/**\n * The `Authorization` value a scheduler sends for `job`: `GenesisJob\n * t=<unix seconds>,sig=<hex HMAC-SHA256 of \"<t>.<job>\">`. What\n * `genesis_schedule_job` sends; for calling a job route from your own code.\n *\n * @stability Beta\n */\nexport async function signJobRequest(secret: string, job: string, now: number = Math.floor(Date.now() / 1000)): Promise<string> {\n return `GenesisJob t=${now},sig=${await hmacHex(secret, `${now}.${job}`)}`;\n}\n\n/**\n * Checks a request's `Authorization` in constant time against the secret and\n * the previous one. Two forms: `GenesisJob t=…,sig=…`, signed for `job` within\n * `maxSkewSeconds` (what schedules send: the secret never travels), or\n * `Bearer <secret>` (a platform cron, a person). The scheme's case and extra\n * spaces don't matter. Returns `null` when it passes, else the response to\n * send: 401, or 500 when no secret is configured.\n *\n * @stability Beta\n */\nexport async function verifyJobRequest(request: Request, options: VerifyJobRequestOptions, job?: string): Promise<Response | null> {\n if (!options.secret) return Response.json({ error: \"The job secret is not configured.\" }, { status: 500 });\n const secrets = [options.secret, ...(options.previousSecret ? [options.previousSecret] : [])];\n const header = (request.headers.get(\"authorization\") ?? \"\").trim();\n const unauthorized = () => Response.json({ error: \"Unauthorized.\" }, { status: 401 });\n\n const bearer = /^bearer\\s+([^\\s,]+)$/i.exec(header)?.[1];\n if (bearer) {\n const given = await digest(bearer);\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(secret)) || ok;\n return ok ? null : unauthorized();\n }\n\n const signed = /^genesisjob\\s+t=(\\d{1,12})\\s*,\\s*sig=([0-9a-f]{64})$/i.exec(header);\n if (signed && job) {\n const t = Number(signed[1]);\n const now = options.now?.() ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - t) > (options.maxSkewSeconds ?? 300)) return unauthorized();\n const given = await digest(signed[2]!.toLowerCase());\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(await hmacHex(secret, `${t}.${job}`))) || ok;\n return ok ? null : unauthorized();\n }\n return unauthorized();\n}\n\n/**\n * One named job a route can run. Its return value (JSON) is the response's `result` for a\n * bearer call; a signed call (a schedule) gets `{ job, ok: true }` and its `body` is always `{}`.\n *\n * @stability Beta\n */\nexport type NamedJob = (context: { request: Request; body: Record<string, unknown> }) => Promise<unknown> | unknown;\n\n/** @stability Beta */\nexport interface JobsHandlerOptions extends VerifyJobRequestOptions {\n /** Job name (`\"digests\"`, as `genesis_schedule_job` names it) → what it runs. */\n jobs: Readonly<Record<string, NamedJob>>;\n /** Where a job's failure goes (name and the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\nconst JOB_NAME = /^[a-z][a-z0-9]*([-_][a-z0-9]+)*$/;\n\n/**\n * The app's job route: checks the request is signed for (or carries the\n * secret of) the job named by the route (`name`, e.g. a path param), the\n * body's `job`, or the URL's last segment, then runs it. GET and POST (platform crons send GET). Answers 401, 404 for an\n * unknown job, 405, 200 with the job's result, or 500 with no detail.\n *\n * @stability Beta\n */\nexport function createJobsHandler(options: JobsHandlerOptions): (request: Request, name?: string) => Promise<Response> {\n const log = options.log ?? ((line: string) => console.error(line));\n return async (request, name) => {\n if (request.method !== \"GET\" && request.method !== \"POST\") {\n return Response.json({ error: \"Use GET or POST.\" }, { status: 405, headers: { Allow: \"GET, POST\" } });\n }\n // A signed call (a schedule) is signed for the job name only, so nothing else it carries is\n // trusted: its body is ignored, and its response carries no result (pg_net keeps responses\n // in net._http_response, which other roles may read).\n const signed = /^genesisjob\\s/i.test((request.headers.get(\"authorization\") ?? \"\").trim());\n const raw = request.method === \"POST\" && !signed ? await request.clone().json().catch(() => null) : null;\n const body = raw && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n const job = name ?? (typeof body[\"job\"] === \"string\" ? body[\"job\"] : new URL(request.url).pathname.split(\"/\").filter(Boolean).at(-1));\n\n // The signature is for one job name, so check it against the name the route will run.\n const refused = await verifyJobRequest(request, options, job);\n if (refused) return refused;\n\n const run = job && JOB_NAME.test(job) && Object.hasOwn(options.jobs, job) ? options.jobs[job] : undefined;\n if (!run) return Response.json({ error: \"No such job.\" }, { status: 404 });\n\n try {\n const result = (await run({ request, body })) ?? null;\n return Response.json(signed ? { job, ok: true } : { job, result });\n } catch (error) {\n log(`[jobs] ${job}: ${messageOf(error)}`);\n return Response.json({ job, error: \"The job failed; see the server log.\" }, { status: 500 });\n }\n };\n}\n"]}
@@ -0,0 +1,179 @@
1
+ /**
2
+ * `@marktiderman/genesis-supabase/runner`: the one outbox engine. Claim a
3
+ * batch of due jobs, send them (grouped, so a destination that takes many at
4
+ * once gets one request), and record what happened. No dependencies: no
5
+ * `@supabase/supabase-js` and no Node built-ins, so a package can bundle it.
6
+ *
7
+ * The store is the caller's (a SQL outbox claimed with SKIP LOCKED, a
8
+ * queue): `claim` hands over leased jobs and `record` takes back outcomes.
9
+ * The engine owns the rest: turning each send result into an outcome with a
10
+ * retry time, jittered backoff, the deferral cap, and never throwing for one
11
+ * job's failure. It runs the background-job queue (`runJobs` in `/jobs`),
12
+ * genesis-notifications' push and email channels, and genesis-forms'
13
+ * destinations (Sheets, webhooks), each with its own claim. It knows nothing
14
+ * about recipients: preferences, windows and caps are the notifier's.
15
+ *
16
+ * Outcomes:
17
+ * - `sent`: delivered (or already there, on a redelivery: `alreadyThere`).
18
+ * - `filtered`: the sender decided it doesn't apply; nothing sent, nothing to retry.
19
+ * - `skipped`: deliberately not sent (`notSent`: a reason safe to store); never retried.
20
+ * - `retry`: a retryable failure. With the service's own Retry-After it is
21
+ * deferred without counting an attempt (`counted: false`), until
22
+ * `maxDeferrals`; otherwise it backs off by attempt (`counted: true`), until
23
+ * `maxAttempts`.
24
+ * - `failed`: permanent, or out of attempts. With `disable: true` the receiver
25
+ * asked to be switched off (a 410 Gone): stop sending to it.
26
+ *
27
+ * It never logs content, addresses or secrets: only what `label` gives and
28
+ * the senders' safe error messages.
29
+ *
30
+ * @packageDocumentation
31
+ */
32
+ /** One claimed job. Extend it with what your sender needs. */
33
+ interface RunnerJob {
34
+ /** Stable across retries (an idempotency key is made from it). */
35
+ id: string;
36
+ /** This attempt's number, from 1. */
37
+ attempt: number;
38
+ /** Deferrals so far (outcomes with `counted: false`); pass it back so `maxDeferrals` holds. Default 0. */
39
+ deferrals?: number | undefined;
40
+ /** An earlier attempt may have gone through (its lease ran out): senders that can look first do. */
41
+ redelivery?: boolean | undefined;
42
+ }
43
+ /** What a sender says about one job. */
44
+ type JobResult = {
45
+ ok: true;
46
+ /** Deliberately sent nothing; the reason, safe to store. Recorded as `skipped`. */
47
+ notSent?: string | undefined;
48
+ /** It was already there (a redelivery), so nothing was sent this time. */
49
+ alreadyThere?: boolean | undefined;
50
+ } | JobFailure;
51
+ interface JobFailure {
52
+ ok: false;
53
+ /** The same request may succeed later (rate limited, the service down, a timeout). */
54
+ retryable: boolean;
55
+ /** The service said when to come back: retry after this many seconds, without counting an attempt. */
56
+ retryAfterSeconds?: number | undefined;
57
+ status?: number | undefined;
58
+ /** The receiver asked to be switched off. Always with `retryable: false`. */
59
+ disable?: true | undefined;
60
+ /** Safe to store and log: never secrets, content or addresses. */
61
+ error: string;
62
+ }
63
+ type JobOutcome = {
64
+ status: "sent";
65
+ alreadyThere?: boolean;
66
+ } | {
67
+ status: "filtered";
68
+ } | {
69
+ status: "skipped";
70
+ reason: string;
71
+ } | {
72
+ status: "retry";
73
+ error: string;
74
+ retryAt: Date;
75
+ retryAfterSeconds: number;
76
+ /** Whether this attempt counts toward `maxAttempts`. False when the service said when to come back. */
77
+ counted: boolean;
78
+ httpStatus?: number;
79
+ } | {
80
+ status: "failed";
81
+ error: string;
82
+ httpStatus?: number;
83
+ disable?: true;
84
+ };
85
+ interface RunReport {
86
+ claimed: number;
87
+ sent: number;
88
+ filtered: number;
89
+ skipped: number;
90
+ /** Retryable failures, backed off by attempt. */
91
+ retrying: number;
92
+ /** Retryable failures the service said when to retry; no attempt used. */
93
+ deferred: number;
94
+ failed: number;
95
+ /** Recorded after the claim was lost (`record` resolved false). */
96
+ stale: number;
97
+ /** `record` threw. */
98
+ unrecorded: number;
99
+ }
100
+ interface ClaimRequest<Filter> {
101
+ limit: number;
102
+ filter?: Filter | undefined;
103
+ }
104
+ interface SendContext {
105
+ signal?: AbortSignal | undefined;
106
+ }
107
+ interface RunnerOptions<J extends RunnerJob, Filter = undefined> {
108
+ /** Claims up to `limit` due jobs, each leased so no other runner sends it meanwhile. */
109
+ claim(request: ClaimRequest<Filter>): Promise<readonly J[]>;
110
+ /**
111
+ * Sends one group of jobs (those with the same `group` key) and resolves one
112
+ * result per job, in order, or `"filtered"`. A throw fails the whole group
113
+ * with a retryable error.
114
+ */
115
+ send(group: readonly J[], context: SendContext): Promise<readonly (JobResult | "filtered")[]>;
116
+ /** Jobs with the same key are sent together. Default: each job alone. */
117
+ group?: ((job: J) => string) | undefined;
118
+ /**
119
+ * Records an outcome. Resolve `false` when the claim was no longer held: it
120
+ * is counted as stale. A rejection is counted as unrecorded; the lease runs
121
+ * out and the job comes back on its own.
122
+ */
123
+ record(job: J, outcome: JobOutcome): Promise<void | boolean>;
124
+ now?: (() => number) | undefined;
125
+ /** Safe lines (ids, kinds, short reasons). Default: nothing is logged. */
126
+ log?: ((message: string) => void) | undefined;
127
+ /** How a job is named in a log line, capitalised ("Delivery d1 (email)"). Default `Job <id>`. */
128
+ label?: ((job: J) => string) | undefined;
129
+ /** How a job is named when recording it failed ("delivery d1"). Default `job <id>`. */
130
+ recordLabel?: ((job: J) => string) | undefined;
131
+ /** Jobs claimed per run. Default 25. */
132
+ batchSize?: number | undefined;
133
+ /** Groups sent (and their outcomes recorded) at once. Default: every group at once. */
134
+ concurrency?: number | undefined;
135
+ /** Counted attempts before a retryable failure is given up. Default 8. */
136
+ maxAttempts?: number | undefined;
137
+ /** Deferrals allowed before a further one counts as an attempt. Default 24. */
138
+ maxDeferrals?: number | undefined;
139
+ /** Seconds to wait after a counted failed attempt. Default `defaultBackoff`. */
140
+ backoff?: ((attempt: number) => number) | undefined;
141
+ }
142
+ interface RunOptions<Filter> {
143
+ filter?: Filter | undefined;
144
+ /** Overrides `batchSize` for this run. */
145
+ limit?: number | undefined;
146
+ /** Aborts the sends in flight. */
147
+ signal?: AbortSignal | undefined;
148
+ }
149
+ interface Runner<Filter = undefined> {
150
+ /** One claim, its sends and their records. Never rejects for a job's failure; a failing `claim` rejects. */
151
+ run(options?: RunOptions<Filter>): Promise<RunReport>;
152
+ }
153
+ declare const DEFAULT_MAX_ATTEMPTS = 8;
154
+ declare const DEFAULT_MAX_DEFERRALS = 24;
155
+ declare const DEFAULT_BATCH_SIZE = 25;
156
+ /**
157
+ * 5 minutes, quadrupling each attempt, at most 24 hours: 5m, 20m, 80m, 5h20m,
158
+ * 21h20m, then 24h; about 3 days across 8 attempts. Each wait is jittered by
159
+ * up to ±20%, so jobs that failed together don't all come back at once.
160
+ */
161
+ declare function defaultBackoff(attempt: number, random?: () => number): number;
162
+ /** Turns a send result into an outcome for a job on its `attempt`. */
163
+ declare function jobOutcome(result: JobResult, attempt: number, options?: {
164
+ now?: number | undefined;
165
+ maxAttempts?: number | undefined;
166
+ backoff?: ((attempt: number) => number) | undefined;
167
+ deferrals?: number | undefined;
168
+ maxDeferrals?: number | undefined;
169
+ }): JobOutcome;
170
+ /** A thrown error as a retryable failure with a safe message. */
171
+ declare function failureOf(error: unknown): JobFailure;
172
+ /**
173
+ * The runner.
174
+ *
175
+ * @stability Beta
176
+ */
177
+ declare function createRunner<J extends RunnerJob, Filter = undefined>(options: RunnerOptions<J, Filter>): Runner<Filter>;
178
+
179
+ export { type ClaimRequest, DEFAULT_BATCH_SIZE, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_DEFERRALS, type JobFailure, type JobOutcome, type JobResult, type RunOptions, type RunReport, type Runner, type RunnerJob, type RunnerOptions, type SendContext, createRunner, defaultBackoff, failureOf, jobOutcome };
package/dist/runner.js ADDED
@@ -0,0 +1,3 @@
1
+ export { DEFAULT_BATCH_SIZE, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_DEFERRALS, createRunner, defaultBackoff, failureOf, jobOutcome } from './chunk-XGAXPUFY.js';
2
+ //# sourceMappingURL=runner.js.map
3
+ //# sourceMappingURL=runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"runner.js"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The one check for a web handoff's destination, used before a link is minted
3
+ * and again after the person is signed in: the path must stay on the app's
4
+ * own origin. Shared by `/web-handoff` (the page) and `/web-handoff/server`.
5
+ */
6
+ /**
7
+ * `value` as a path on this app (`/clients/1/forms?tab=questions`), normalized, or `null` when it
8
+ * could leave the origin or isn't a path: anything without a single leading `/`, `//host`,
9
+ * `/\host`, a scheme (`javascript:`, `https:`), whitespace or control characters, and the same
10
+ * tricks percent-encoded (`/%2F%2Fhost`, `/%5Chost`, `/%09/host`, up to three layers).
11
+ *
12
+ * @stability Beta
13
+ */
14
+ declare function appRelativePath(value: unknown): string | null;
15
+
16
+ export { appRelativePath as a };
@@ -0,0 +1,225 @@
1
+ export { a as appRelativePath } from './web-handoff-path-C_EEl_BC.js';
2
+
3
+ /** A user as Supabase Auth returns one: the fields used here. */
4
+ interface HandoffUser {
5
+ id: string;
6
+ email?: string | null;
7
+ }
8
+ /**
9
+ * The parts of a service-role Supabase client the handoff uses. A `SupabaseClient` made with the
10
+ * secret key fits. Loose on purpose: a client typed by an app's Database narrows `rpc`.
11
+ */
12
+ interface WebHandoffAdmin {
13
+ auth: {
14
+ getUser(jwt: string): PromiseLike<{
15
+ data: {
16
+ user: HandoffUser | null;
17
+ };
18
+ error: unknown;
19
+ }>;
20
+ admin: {
21
+ getUserById(id: string): PromiseLike<{
22
+ data: {
23
+ user: HandoffUser | null;
24
+ };
25
+ error: unknown;
26
+ }>;
27
+ generateLink(params: {
28
+ type: "magiclink";
29
+ email: string;
30
+ }): PromiseLike<{
31
+ data: {
32
+ properties?: {
33
+ hashed_token?: string | null;
34
+ } | null;
35
+ } | null;
36
+ error: unknown;
37
+ }>;
38
+ };
39
+ };
40
+ rpc: (fn: any, ...rest: any[]) => PromiseLike<{
41
+ data: unknown;
42
+ error: {
43
+ message: string;
44
+ code?: string;
45
+ } | null;
46
+ }>;
47
+ }
48
+ /** One line for the server log. Never carries a token, a nonce or an email. */
49
+ interface WebHandoffLogEvent {
50
+ event: "web_handoff.minted" | "web_handoff.refused" | "web_handoff.claimed" | "web_handoff.continued" | "web_handoff.discarded" | "web_handoff.signed_out";
51
+ userId?: string;
52
+ path?: string;
53
+ reason?: string;
54
+ count?: number;
55
+ at: string;
56
+ }
57
+ type Log = (event: WebHandoffLogEvent) => void;
58
+ /** @stability Beta */
59
+ interface WebHandoffOptions {
60
+ admin: WebHandoffAdmin;
61
+ /**
62
+ * The web app's origin (`https://app.example.com`), or a function of the request. Default: the
63
+ * mint request's own origin, so a preview deployment hands off to itself.
64
+ */
65
+ webOrigin?: string | ((request: Request) => string);
66
+ /** The page that completes the handoff. Default `/auth/handoff`. */
67
+ pagePath?: string;
68
+ /** How long a link works, 10 to 300 seconds. Default 60. */
69
+ ttlSeconds?: number;
70
+ /** How long the page's Continue works after it opened the link, 5 to 120 seconds. Default 30. */
71
+ continueSeconds?: number;
72
+ /** Links one person may mint per window. Default 10 a minute. */
73
+ rateLimit?: {
74
+ max: number;
75
+ windowSeconds: number;
76
+ };
77
+ /** Where each step is logged (who, which path, when). Default `console.info` as JSON. */
78
+ log?: Log;
79
+ }
80
+ /** @stability Beta */
81
+ interface MintWebHandoffOptions extends Omit<WebHandoffOptions, "webOrigin" | "continueSeconds"> {
82
+ /** The person, already verified by the caller (a bearer token checked with `auth.getUser`). */
83
+ userId: string;
84
+ /** Where on the web app to land. Must pass {@link appRelativePath}. */
85
+ path: string;
86
+ webOrigin: string;
87
+ /** The app session asking (the bearer's `session_id`): signing it out later ends the web session. */
88
+ sourceSessionId?: string | null;
89
+ }
90
+ type MintWebHandoffResult = {
91
+ ok: true;
92
+ url: string;
93
+ expiresAt: string;
94
+ } | {
95
+ ok: false;
96
+ reason: "bad_path" | "no_user" | "no_email" | "rate_limited";
97
+ /** For no_email and rate_limited: the page, signed out, where the person can sign in and carry on. */
98
+ fallbackUrl?: string;
99
+ };
100
+ type ClaimWebHandoffResult =
101
+ /** The browser is already signed in as this person: go to `next`, nothing to exchange. */
102
+ {
103
+ status: "same_user";
104
+ next: string;
105
+ }
106
+ /** Ask "Continue as <email>?"; `continueNonce` works once, for `continueSeconds`. */
107
+ | {
108
+ status: "confirm";
109
+ next: string;
110
+ email: string;
111
+ continueNonce: string;
112
+ }
113
+ /** Unknown, already used or older than its lifetime. */
114
+ | {
115
+ status: "expired";
116
+ } | {
117
+ status: "unavailable";
118
+ };
119
+ type ContinueWebHandoffResult = {
120
+ status: "ok";
121
+ next: string;
122
+ userId: string;
123
+ tokenHash: string;
124
+ }
125
+ /** The nonce is unknown, used, cancelled or out of time. */
126
+ | {
127
+ status: "expired";
128
+ } | {
129
+ status: "unavailable";
130
+ };
131
+ /** The SHA-256 of a handoff token or nonce, hex: what the database keeps instead. */
132
+ declare function handoffDigest(token: string): Promise<string>;
133
+ /**
134
+ * The `session_id` claim of an access token Supabase Auth has already verified (`auth.getUser`),
135
+ * or null. It only reads the payload; never call it on a token nobody verified.
136
+ */
137
+ declare function sessionIdOf(verifiedAccessToken: string): string | null;
138
+ /**
139
+ * Record a handoff for a person the caller has already verified and return the link that
140
+ * completes it. Refuses a path that could leave the app, a person without an email (Supabase
141
+ * signs in by email link; there is no phone equivalent), and more than `rateLimit` links a window.
142
+ *
143
+ * @stability Beta
144
+ */
145
+ declare function mintWebHandoff(options: MintWebHandoffOptions): Promise<MintWebHandoffResult>;
146
+ /**
147
+ * The page opened a link: use it (once, within its lifetime) and say whose it is. Mints nothing.
148
+ * When the browser is already that person (`currentUserId`) the handoff is spent and the page
149
+ * simply goes on; otherwise it gets a continue nonce for {@link continueWebHandoff}.
150
+ *
151
+ * @stability Beta
152
+ */
153
+ declare function claimWebHandoff(options: {
154
+ admin: WebHandoffAdmin;
155
+ token: string;
156
+ /** Who this browser is signed in as now, if anyone. Only ever skips the question; grants nothing. */
157
+ currentUserId?: string | null;
158
+ continueSeconds?: number;
159
+ log?: Log;
160
+ }): Promise<ClaimWebHandoffResult>;
161
+ /**
162
+ * The person chose Continue: spend the nonce (once, in time, not after Cancel) and only now ask
163
+ * Supabase Auth for a sign-in token for the handoff's own person.
164
+ *
165
+ * @stability Beta
166
+ */
167
+ declare function continueWebHandoff(options: {
168
+ admin: WebHandoffAdmin;
169
+ nonce: string;
170
+ log?: Log;
171
+ }): Promise<ContinueWebHandoffResult>;
172
+ /** The person chose Cancel: burn the nonce, so Continue is refused from now on. @stability Beta */
173
+ declare function discardWebHandoff(options: {
174
+ admin: WebHandoffAdmin;
175
+ nonce: string;
176
+ log?: Log;
177
+ }): Promise<boolean>;
178
+ /**
179
+ * The page reports the session Continue made: its access token is verified with `auth.getUser`,
180
+ * and its `session_id` is kept on the handoff (for the same person, within two minutes of
181
+ * Continue), so {@link signOutWebHandoffs} can end it.
182
+ *
183
+ * @stability Beta
184
+ */
185
+ declare function bindWebHandoffSession(options: {
186
+ admin: WebHandoffAdmin;
187
+ nonce: string;
188
+ accessToken: string;
189
+ }): Promise<boolean>;
190
+ /**
191
+ * The app is signing out: end the web sessions handed off from that app session (and only
192
+ * those; never the person's other devices). Call it before the app's own sign-out, with the
193
+ * app's still-valid access token. Supabase documents a session as signed out once its
194
+ * `auth.sessions` row is gone; that web session's access token works until it expires.
195
+ *
196
+ * @stability Beta
197
+ */
198
+ declare function signOutWebHandoffs(options: {
199
+ admin: WebHandoffAdmin;
200
+ userId: string;
201
+ sourceSessionId: string | null;
202
+ log?: Log;
203
+ }): Promise<number>;
204
+ /**
205
+ * The web handoff's routes, each `(request) => Response`, POST only, no CORS headers:
206
+ *
207
+ * - `mint` (the app): `Authorization: Bearer <access token>` and `{ path }`. 200 `{ url, expiresAt }`;
208
+ * 401 without a valid session; 400 for a path that could leave the app; 409 `no_email` and
209
+ * 429 `rate_limited` with a `fallbackUrl` (the page, signed out) the app may open instead.
210
+ * - `redeem` (the page), JSON `{ action, … }`:
211
+ * `claim` `{ t, currentUserId? }` → {@link ClaimWebHandoffResult};
212
+ * `continue` `{ nonce }` → {@link ContinueWebHandoffResult};
213
+ * `discard` `{ nonce }` → `{ status: "discarded" }`;
214
+ * `bind` `{ nonce }` with `Authorization: Bearer <the new web session's access token>` → `{ status: "bound" | "not_bound" }`.
215
+ * - `signOut` (the app, before its own sign-out): Bearer → `{ status: "signed_out", count }`.
216
+ *
217
+ * @stability Beta
218
+ */
219
+ declare function createWebHandoff(options: WebHandoffOptions): {
220
+ mint: (request: Request) => Promise<Response>;
221
+ redeem: (request: Request) => Promise<Response>;
222
+ signOut: (request: Request) => Promise<Response>;
223
+ };
224
+
225
+ export { type ClaimWebHandoffResult, type ContinueWebHandoffResult, type MintWebHandoffOptions, type MintWebHandoffResult, type WebHandoffAdmin, type WebHandoffLogEvent, type WebHandoffOptions, bindWebHandoffSession, claimWebHandoff, continueWebHandoff, createWebHandoff, discardWebHandoff, handoffDigest, mintWebHandoff, sessionIdOf, signOutWebHandoffs };