@byollm/server 0.1.0-alpha.24 → 0.1.0-alpha.25
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/README.md +2 -2
- package/dist/{chunk-QTRX2LSF.js → chunk-MXP5L5WO.js} +17 -4
- package/dist/chunk-MXP5L5WO.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/next.js +1 -1
- package/dist/supabase/index.js +6 -3
- package/dist/supabase/index.js.map +1 -1
- package/package.json +2 -2
- package/supabase/migrations/20260821000000_rename_collected.sql +91 -0
- package/dist/chunk-QTRX2LSF.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
> [!WARNING]
|
|
2
|
-
> **Alpha (`0.1.0-alpha.
|
|
2
|
+
> **Alpha (`0.1.0-alpha.25`) — under active development. Don't use this yet.**
|
|
3
3
|
>
|
|
4
4
|
> Install it deliberately: `npm install @byollm/server@alpha`.
|
|
5
5
|
>
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
> packages published and `@byollm/server` did not: a Sigstore
|
|
106
106
|
> transparency-log 409 on its provenance attestation. The workflow's
|
|
107
107
|
> "already published" guard correctly refuses to resume a partial publish,
|
|
108
|
-
> so `0.1.0-alpha.
|
|
108
|
+
> so `0.1.0-alpha.25` is that release, whole.
|
|
109
109
|
>
|
|
110
110
|
> If you run the Supabase adapter, `alpha.21` needs
|
|
111
111
|
> `20260819010000_completed_by_lease_id.sql`: alpha.19 shipped §3.6's
|
|
@@ -305,7 +305,12 @@ var ByollmHandlers = class {
|
|
|
305
305
|
owner: pairing.owner,
|
|
306
306
|
// Only on approval: a pending or denied poll learns nothing, so an
|
|
307
307
|
// unapproved code cannot be used to enumerate a site's keys.
|
|
308
|
-
|
|
308
|
+
//
|
|
309
|
+
// One entry, because a direct site *is* one site — the same shape a
|
|
310
|
+
// hub answers with rather than a special case (cloud_009 §5). The
|
|
311
|
+
// daemon's lookup is one map read on every lane, which is what keeps
|
|
312
|
+
// the two lanes one protocol.
|
|
313
|
+
sites: { [this.#siteKeyId]: publicIdentityOf2(this.#siteKeys) }
|
|
309
314
|
};
|
|
310
315
|
await this.#store.consumePairingToken(pairing.deviceCodeHash);
|
|
311
316
|
return ok(response);
|
|
@@ -384,7 +389,12 @@ var ByollmHandlers = class {
|
|
|
384
389
|
if (revoked) {
|
|
385
390
|
const held = await this.#store.listClaimedBy(runner.id);
|
|
386
391
|
const response2 = {
|
|
387
|
-
revoked: true
|
|
392
|
+
// Empty, which is what `revoked: true` used to say — cloud_008
|
|
393
|
+
// finding 59. A direct site has one site to withdraw, so revocation
|
|
394
|
+
// here is the whole set going; under a hub it is one entry leaving.
|
|
395
|
+
// One field, one fact, on both lanes.
|
|
396
|
+
sites: {},
|
|
397
|
+
awaitingConsent: [],
|
|
388
398
|
cancel: [],
|
|
389
399
|
lost: held.map((job) => job.id),
|
|
390
400
|
serverTime: now
|
|
@@ -406,7 +416,10 @@ var ByollmHandlers = class {
|
|
|
406
416
|
});
|
|
407
417
|
const cancel = await this.#store.listCancelRequests(runner.id);
|
|
408
418
|
const response = {
|
|
409
|
-
|
|
419
|
+
sites: { [this.#siteKeyId]: publicIdentityOf2(this.#siteKeys) },
|
|
420
|
+
// A direct site has no disclosure of its own to go stale: consent to it
|
|
421
|
+
// *is* the pairing, and withdrawing it empties the set above.
|
|
422
|
+
awaitingConsent: [],
|
|
410
423
|
cancel,
|
|
411
424
|
lost: [...lost],
|
|
412
425
|
serverTime: now
|
|
@@ -656,4 +669,4 @@ export {
|
|
|
656
669
|
signatureFrom,
|
|
657
670
|
createFetchHandler
|
|
658
671
|
};
|
|
659
|
-
//# sourceMappingURL=chunk-
|
|
672
|
+
//# sourceMappingURL=chunk-MXP5L5WO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ids.ts","../src/handlers.ts","../src/reseal.ts","../src/records.ts","../src/http.ts"],"sourcesContent":["import {\n createHash,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from \"node:crypto\";\n\n/**\n * Alphabet for the user-facing pairing code.\n *\n * Excludes `0/O`, `1/I/L`, `5/S` and `U/V` — a code is read aloud or copied\n * off a terminal into a browser, and a user who mistypes it gets a failure\n * they cannot diagnose. 27 symbols over 8 characters is ~38 bits, which is\n * ample for a code that lives ten minutes, is single-use, and is rate-limited.\n */\nconst USER_CODE_ALPHABET = \"ABCDEFGHJKMNPQRTWXYZ2346789\";\n\n/** A device code: the secret the daemon polls with. Never shown to a user. */\nexport function generateDeviceCode(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/** A runner id. */\nexport function generateRunnerId(): string {\n return `runner_${randomUUID()}`;\n}\n\n/** A job id. */\nexport function generateJobId(): string {\n // A bare UUID, not a prefixed one.\n //\n // The app mints this now, because byollm_009 §6 binds the job id into the\n // envelope's signature — so the id must exist before the row does. A\n // `job_`-prefixed string is not a `uuid`, and the Supabase adapter's column\n // is, so the prefix would have made every enqueue fail there while passing\n // in memory. Ids are opaque to the protocol; the prefix was only ever\n // decoration.\n return randomUUID();\n}\n\n/**\n * A short code the user reads and confirms, formatted `XXXX-XXXX`.\n * Drawn with rejection sampling so the alphabet stays uniform.\n */\nexport function generateUserCode(): string {\n const chars: string[] = [];\n while (chars.length < 8) {\n for (const byte of randomBytes(16)) {\n // 256 % 28 !== 0, so bytes at or above the largest whole multiple are\n // discarded rather than folded — folding would bias the low symbols.\n const limit = 256 - (256 % USER_CODE_ALPHABET.length);\n if (byte >= limit) continue;\n const symbol = USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length];\n if (symbol === undefined) continue;\n chars.push(symbol);\n if (chars.length === 8) break;\n }\n }\n return `${chars.slice(0, 4).join(\"\")}-${chars.slice(4).join(\"\")}`;\n}\n\n/** SHA-256, hex. Tokens and device codes are stored only as this. */\nexport function hashSecret(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\");\n}\n\n/**\n * Compare two hex digests without leaking their difference through timing.\n * Lengths are compared first because `timingSafeEqual` throws on a mismatch.\n */\nexport function secretsMatch(aHex: string, bHex: string): boolean {\n if (aHex.length !== bHex.length) return false;\n return timingSafeEqual(Buffer.from(aHex, \"hex\"), Buffer.from(bHex, \"hex\"));\n}\n\n/**\n * A fresh id for one lease grant.\n *\n * Not a secret and not guessed at — a daemon is told its lease id in the claim\n * response. It exists to distinguish *this* grant from the next one over the\n * same job by the same runner, which is what stops a replayed release landing\n * on a lease the sender never meant.\n */\nexport const generateLeaseId = (): string => randomUUID();\n","import {\n FetchRequest,\n SealedOutcome,\n keyId,\n open,\n publicIdentityOf,\n type FetchResponse,\n RequestSignature,\n verifyRequest,\n verifyPublicIdentity,\n type StoredKeys,\n ClaimRequest,\n type ClaimRequest as ClaimRequestType,\n type HeartbeatRequest as HeartbeatRequestType,\n type ReleaseRequest as ReleaseRequestType,\n type ResultRequest as ResultRequestType,\n ERROR_STATUS,\n HeartbeatRequest,\n PairRequest,\n PROTOCOL_VERSION,\n ReleaseRequest,\n ResultRequest,\n provenanceFor,\n type ClaimResponse,\n type Endpoint,\n type HeartbeatResponse,\n type PairPollResponse,\n type PairStartResponse,\n type ReleaseResponse,\n type ResultResponse,\n type WireErrorCode,\n} from \"@byollm/protocol\";\nimport { generateDeviceCode, generateUserCode, hashSecret } from \"./ids.js\";\nimport { resealForDevice } from \"./reseal.js\";\nimport { deadlineFor } from \"./records.js\";\nimport type { JobRecord, RunnerRecord } from \"./records.js\";\nimport type { ByollmStore } from \"./store.js\";\n\n/** Everything a mount needs to serve the protocol. */\n/**\n * What a transport must hand the handler to authenticate a call.\n *\n * `rawBody` is the exact bytes received, not a re-serialisation of the parsed\n * object: JSON.stringify does not round-trip byte-for-byte, and a signature\n * over re-serialised input verifies something the sender never signed.\n */\nexport interface AuthContext {\n readonly endpoint: string;\n readonly rawBody: string;\n readonly signature: unknown;\n}\n\nexport interface HandlerConfig {\n readonly store: ByollmStore;\n /**\n * Absolute URL of the page where a user approves a pairing. The device code\n * is *not* appended — the user types the short code into the app's own\n * authenticated page, which is what keeps pairing interactive.\n */\n readonly verificationUrl: string;\n /** How long a lease lasts. Default 60s — six heartbeats of headroom. */\n readonly leaseMs?: number;\n /** How long an unapproved pairing code lives. Default 10 minutes. */\n readonly pairingTtlMs?: number;\n /** How often a daemon may poll for pairing approval. Default 2s. */\n readonly pollIntervalMs?: number;\n /** Injectable clock, so tests can move time without sleeping. */\n readonly now?: () => number;\n /**\n * This site's keypairs (byollm_009 §5) — **supplied, never generated here.**\n *\n * A site is usually more than one process. Generating keys at startup would\n * work perfectly in development and fail only in production, silently: each\n * instance would have a different identity, a daemon would pin whichever\n * one approved its pairing, and every request routed to a different\n * instance would fail a signature check it had no way to explain. So this\n * is a required input, and there is a `keygen` script that produces one.\n */\n readonly siteKeys: StoredKeys;\n}\n\nconst DEFAULTS = {\n leaseMs: 60_000,\n pairingTtlMs: 10 * 60_000,\n pollIntervalMs: 2_000,\n} as const;\n\n/** A handled protocol call: a status and a JSON body. */\nexport interface HandlerResult {\n readonly status: number;\n readonly body: unknown;\n /** Set for `rate-limited` and `server-error`. */\n readonly retryAfterSeconds?: number;\n}\n\nfunction fail(\n error: WireErrorCode,\n message: string,\n retryAfterSeconds?: number,\n): HandlerResult {\n return {\n status: ERROR_STATUS[error],\n body: {\n error,\n message,\n ...(retryAfterSeconds === undefined\n ? {}\n : { retryAfter: retryAfterSeconds }),\n },\n ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),\n };\n}\n\nfunction ok(body: unknown): HandlerResult {\n return { status: 200, body };\n}\n\n/**\n * The five protocol endpoints, over any {@link ByollmStore}.\n *\n * Transport-free on purpose: a mount adapts `Request`/`Response` (or Express,\n * or whatever) onto {@link ByollmHandlers.handle}, and everything the\n * protocol actually specifies lives here where the conformance kit can reach\n * it without an HTTP server in the way.\n */\nexport class ByollmHandlers {\n readonly #store: ByollmStore;\n readonly #verificationUrl: string;\n readonly #leaseMs: number;\n readonly #pairingTtlMs: number;\n readonly #pollIntervalMs: number;\n readonly #now: () => number;\n readonly #siteKeys: StoredKeys;\n /** This site's identity key id — Amendment A's `stub.site`. Derived once. */\n readonly #siteKeyId: string;\n\n constructor(config: HandlerConfig) {\n this.#store = config.store;\n // Fail at construction, not at the first pairing. A site whose keys are\n // malformed should not start and then refuse its users one at a time.\n if (!verifyPublicIdentity(publicIdentityOf(config.siteKeys))) {\n throw new Error(\n \"siteKeys are not internally consistent: the encryption key is not \" +\n \"signed by the identity key. Generate a fresh pair with \" +\n \"`npx @byollm/server keygen`.\",\n );\n }\n this.#siteKeys = config.siteKeys;\n this.#siteKeyId = keyId(publicIdentityOf(config.siteKeys).identity);\n this.#verificationUrl = config.verificationUrl;\n this.#leaseMs = config.leaseMs ?? DEFAULTS.leaseMs;\n this.#pairingTtlMs = config.pairingTtlMs ?? DEFAULTS.pairingTtlMs;\n this.#pollIntervalMs = config.pollIntervalMs ?? DEFAULTS.pollIntervalMs;\n this.#now = config.now ?? Date.now;\n }\n\n /**\n * Dispatch one protocol call.\n *\n * @param endpoint - which of the five, already routed from the path\n * @param body - the parsed JSON request body, untrusted\n * @param auth - the signature and the exact bytes it covers\n */\n async handle(\n endpoint: Endpoint,\n body: unknown,\n auth: AuthContext,\n ): Promise<HandlerResult> {\n switch (endpoint) {\n case \"pair\":\n return this.#pair(body);\n case \"claim\":\n return this.#authed(auth, body, ClaimRequest, this.#claim.bind(this));\n case \"heartbeat\":\n // Heartbeat is the channel revocation travels on, so a revoked runner\n // must reach the handler and be told `revoked: true` rather than be\n // bounced with a 403 it would treat as a transport problem\n // ({@link MUSTS.REVOCATION_HONORED}).\n return this.#authed(\n auth,\n body,\n HeartbeatRequest,\n this.#heartbeat.bind(this),\n { allowRevoked: true },\n );\n case \"fetch\":\n return this.#authed(auth, body, FetchRequest, this.#fetch.bind(this));\n case \"result\":\n return this.#authed(auth, body, ResultRequest, this.#result.bind(this));\n case \"release\":\n return this.#authed(\n auth,\n body,\n ReleaseRequest,\n this.#release.bind(this),\n );\n }\n }\n\n /**\n * Shared preamble for the four authenticated endpoints: verify the\n * signature, reject a revoked runner, and parse the body.\n *\n * Authentication happens before schema validation so a stranger probing the\n * endpoint learns nothing about the wire format.\n */\n async #authed<T>(\n auth: AuthContext,\n body: unknown,\n schema: { safeParse: (v: unknown) => { success: boolean; data?: T } },\n run: (request: T, runner: RunnerRecord) => Promise<HandlerResult>,\n options: { allowRevoked?: boolean } = {},\n ): Promise<HandlerResult> {\n const signature = RequestSignature.safeParse(auth.signature);\n if (!signature.success) {\n return fail(\"unauthorized\", \"this request is not signed\");\n }\n\n const runner = await this.#store.getRunner(signature.data.runnerId);\n if (!runner) {\n return fail(\"unauthorized\", \"this runner is not recognised\");\n }\n\n // Verified against the identity pinned when the user approved this\n // machine — not against anything the request carries. A signature that\n // authenticates itself authenticates nothing.\n const failure = verifyRequest({\n identityPublic: runner.device.identity,\n endpoint: auth.endpoint,\n body: auth.rawBody,\n signature: signature.data,\n now: this.#now(),\n });\n if (failure !== null) {\n // Deliberately one message for both causes. Telling a caller whether\n // their clock or their key is wrong tells an attacker which half of a\n // forgery already works.\n return fail(\"unauthorized\", \"this request's signature is not valid\");\n }\n if (runner.revokedAt !== null && options.allowRevoked !== true) {\n // A distinct truth from \"unauthorized\": the daemon should stop and say\n // so, not retry or re-pair silently.\n return fail(\"revoked\", \"this runner has been revoked by its owner\");\n }\n\n const parsed = schema.safeParse(body);\n if (!parsed.success || parsed.data === undefined) {\n return fail(\"bad-request\", \"request body failed schema validation\");\n }\n return run(parsed.data, runner);\n }\n\n /**\n * Hand over the payload for a lease this runner holds — byollm_009 §6.\n *\n * The second half of claim-then-fetch. A claim answers with a stub, and the\n * work itself is collected separately by the device that took it, because a\n * payload can only be sealed once its recipient is known.\n *\n * Scoped to the lease, not the job: answering for whatever lease happens to\n * exist would hand the work to a runner whose grant had already been\n * superseded.\n */\n async #fetch(\n request: FetchRequest,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n const job = await this.#store.get(request.jobId);\n if (\n !job ||\n job.lease?.runnerId !== runner.id ||\n job.lease.id !== request.leaseId\n ) {\n // One answer for \"no such job\", \"not yours\" and \"a lease you no longer\n // hold\". A caller who is allowed to know already knows which.\n return fail(\"not-found\", \"no such lease on this job\");\n }\n // One implementation of open-and-reseal, shared with the cloud lane: the\n // deadline and key ids are bound into a signature, and two copies of a\n // bound value is the bug this codebase keeps finding.\n const resealed = await resealForDevice({\n siteKeys: this.#siteKeys,\n job: { id: job.id, envelope: job.envelope, createdAt: job.createdAt },\n device: runner.device,\n });\n if (!resealed.ok) {\n return fail(\"server-error\", \"this job's payload could not be opened\");\n }\n return ok({ envelope: resealed.envelope } satisfies FetchResponse);\n }\n\n // -- 1. pair --------------------------------------------------------------\n\n async #pair(body: unknown): Promise<HandlerResult> {\n const parsed = PairRequest.safeParse(body);\n if (!parsed.success) {\n return fail(\"bad-request\", \"pair request failed schema validation\");\n }\n const request = parsed.data;\n const now = this.#now();\n\n if (request.action === \"start\") {\n const deviceCode = generateDeviceCode();\n const userCode = generateUserCode();\n const expiresAt = now + this.#pairingTtlMs;\n\n // The machine must prove its encryption key belongs to the identity it\n // is presenting, before either is stored. Otherwise a caller could pair\n // a real identity with an encryption key it holds the secret for, and\n // read everything later sealed to that runner.\n if (!verifyPublicIdentity(request.device)) {\n return fail(\n \"bad-request\",\n \"the device's encryption key is not signed by the identity it was presented with\",\n );\n }\n\n await this.#store.createPairing({\n device: request.device,\n deviceCodeHash: hashSecret(deviceCode),\n userCode,\n state: \"pending\",\n owner: null,\n runnerId: null,\n collected: false,\n label: request.daemon.label,\n platform: request.daemon.platform,\n daemonVersion: request.daemon.version,\n capabilities: request.capabilities,\n expiresAt,\n createdAt: now,\n });\n\n const response: PairStartResponse = {\n deviceCode,\n userCode,\n verificationUrl: this.#verificationUrl,\n expiresAt,\n pollIntervalMs: this.#pollIntervalMs,\n };\n return ok(response);\n }\n\n // action === \"poll\"\n const pairing = await this.#store.getPairingByDeviceCodeHash(\n hashSecret(request.deviceCode),\n );\n if (!pairing) {\n return fail(\"not-found\", \"unknown device code\");\n }\n if (pairing.state === \"denied\") {\n return ok({ status: \"denied\" } satisfies PairPollResponse);\n }\n // Expiry is checked before approval state so a code approved after it\n // lapsed is still dead ({@link MUSTS.PAIR_CODE_EXPIRES}).\n if (pairing.expiresAt <= now && pairing.state === \"pending\") {\n return ok({ status: \"expired\" } satisfies PairPollResponse);\n }\n if (\n pairing.state === \"approved\" &&\n !pairing.collected &&\n pairing.runnerId !== null &&\n pairing.owner !== null\n ) {\n const response: PairPollResponse = {\n status: \"approved\",\n runnerId: pairing.runnerId,\n owner: pairing.owner,\n // Only on approval: a pending or denied poll learns nothing, so an\n // unapproved code cannot be used to enumerate a site's keys.\n //\n // One entry, because a direct site *is* one site — the same shape a\n // hub answers with rather than a special case (cloud_009 §5). The\n // daemon's lookup is one map read on every lane, which is what keeps\n // the two lanes one protocol.\n sites: { [this.#siteKeyId]: publicIdentityOf(this.#siteKeys) },\n };\n // Delivered exactly once — a replayed device code gets nothing.\n await this.#store.consumePairingToken(pairing.deviceCodeHash);\n return ok(response);\n }\n if (pairing.state === \"approved\") {\n return fail(\"not-found\", \"this pairing has already been collected\");\n }\n return ok({ status: \"pending\" } satisfies PairPollResponse);\n }\n\n // -- 2. claim -------------------------------------------------------------\n\n async #claim(\n request: ClaimRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n\n // Capabilities from *this* request, never the stored matrix — a daemon\n // that just lost a backend must not be handed work for it\n // ({@link MUSTS.CLAIM_REQUIRES_CAPABILITY}).\n const jobs = await this.#store.claim({\n runnerId: runner.id,\n runnerOwner: runner.owner,\n capabilities: request.capabilities,\n max: request.max,\n leaseMs: this.#leaseMs,\n now,\n });\n\n const response: ClaimResponse = {\n jobs: jobs.map((job) => ({\n id: job.id,\n kind: job.kind,\n audience: job.audience,\n owner: job.owner,\n // This site, named by its identity key id — Amendment A §A.3. The\n // daemon pinned this exact value at pairing, so it can check the stub\n // against the envelope it later opens rather than taking our word for\n // which site sent it. On this plane that is redundant, which is the\n // point: the direct and relayed stubs are the same shape, and a daemon\n // serving both cannot tell which upstream it is talking to.\n site: this.#siteKeyId,\n // Bucketed, not measured: an exact size is a stronger fingerprint\n // than routing needs (byollm_009 §6).\n sizeClass: job.sizeClass,\n // Reserved for byollm_006; no job declares it yet.\n streaming: false,\n // The stub's deadline bounds how long a captured envelope is worth\n // keeping, so it is always present — falling back to the TTL window\n // when the app named no absolute one.\n deadlineAt: deadlineFor(job, now),\n // `audienceAllow` is not sent — cloud_008 §0.2. The list stays on\n // `JobRecord`, where `claim` already filtered candidates with it; the\n // daemon's own allowlist is what decides `named` (byollm_001 Rev 1\n // §B) and always was.\n //\n // Removing it from `JobStub` did **not** make this line a type error.\n // A conditional spread is not excess-property-checked, so the field\n // would have gone on being sent to a daemon whose `.strict()` parse\n // now rejects the entire claim response — every daemon on the version\n // pair, refusing all work, for a field nobody read. Worth stating\n // where it happened: the schema is the contract, and the compiler\n // does not enforce it through a spread.\n // No fallback. A job returned from `claim` holds a lease by\n // definition, and synthesising one here would hand the daemon a lease\n // id the store has never heard of — every later release naming it\n // would silently match nothing. A store that returns an unleased job\n // has broken its contract, and this says so.\n lease: leaseOf(job),\n })),\n leaseMs: this.#leaseMs,\n };\n return ok(response);\n }\n\n // -- 3. heartbeat ---------------------------------------------------------\n\n async #heartbeat(\n request: HeartbeatRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n const revoked = runner.revokedAt !== null;\n\n if (revoked) {\n // Nothing is renewed for a revoked runner: every job it holds is\n // reported lost so it abandons the queue rather than finishing it.\n const held = await this.#store.listClaimedBy(runner.id);\n const response: HeartbeatResponse = {\n // Empty, which is what `revoked: true` used to say — cloud_008\n // finding 59. A direct site has one site to withdraw, so revocation\n // here is the whole set going; under a hub it is one entry leaving.\n // One field, one fact, on both lanes.\n sites: {},\n awaitingConsent: [],\n cancel: [],\n lost: held.map((job) => job.id),\n serverTime: now,\n };\n return ok(response);\n }\n\n await this.#store.touchRunner({\n runnerId: runner.id,\n capabilities: request.capabilities,\n daemonVersion: request.daemonVersion,\n paused: request.paused,\n now,\n });\n\n // `renewed` is not reported back — cloud_008 §1.4b. The grants are still\n // extended; the daemon simply never read the list, and `lost` is the\n // signal it acts on.\n const { lost } = await this.#store.renewLeases({\n runnerId: runner.id,\n leases: request.activeLeases,\n leaseMs: this.#leaseMs,\n now,\n });\n\n const cancel = await this.#store.listCancelRequests(runner.id);\n\n const response: HeartbeatResponse = {\n sites: { [this.#siteKeyId]: publicIdentityOf(this.#siteKeys) },\n // A direct site has no disclosure of its own to go stale: consent to it\n // *is* the pairing, and withdrawing it empties the set above.\n awaitingConsent: [],\n cancel,\n lost: [...lost],\n serverTime: now,\n };\n return ok(response);\n }\n\n // -- 4. result ------------------------------------------------------------\n\n async #result(\n request: ResultRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n const job = await this.#store.get(request.jobId);\n if (!job) return fail(\"not-found\", \"unknown job\");\n\n const outcome = await this.#openResult(request, runner);\n if (!outcome.ok) return outcome.failure;\n\n // Provenance is built here, from the job's audience and the authenticated\n // runner — never from anything the daemon asserted\n // ({@link MUSTS.PROVENANCE_NAMES_DEVICE}).\n const provenance = provenanceFor({\n audience: job.audience,\n runnerId: runner.id,\n runnerOwner: runner.owner,\n // From the envelope the device signed, not from the request beside it\n // — cloud_008 §2.5. A daemon can no longer seal one answer and declare\n // it came from a different model.\n backendClass: outcome.value.ran.backendClass,\n model: outcome.value.ran.model,\n });\n\n const {\n accepted,\n duplicate,\n job: updated,\n } = await this.#store.complete({\n jobId: request.jobId,\n // Who is asking, for the duplicate answer only — §3.6. Authorisation\n // is `holder`, below, and still is.\n runnerId: runner.id,\n // The grant, not the runner — cloud_008 §1.4a. `CompleteHolder`'s own\n // docstring already called the lease \"the more exact check anyway\";\n // this plane simply had no lease id to give it until now.\n holder: { by: \"lease\", leaseId: request.leaseId },\n outcome: outcome.value.outcome,\n provenance,\n now,\n });\n\n const response: ResultResponse = {\n accepted,\n // Only when true — cloud_008 §3.6. Absent means \"not a duplicate\", and\n // an optional field that is always present is a required one wearing a\n // question mark.\n ...(duplicate === true ? { duplicate: true } : {}),\n state: updated?.state ?? job.state,\n };\n return ok(response);\n }\n\n /**\n * Open a sealed result, or refuse it.\n *\n * The mirror of the daemon's `#openPayload`, and refuses for the same\n * reason: an outcome that does not verify against the device's pinned key is\n * an assertion by whoever relayed it, and storing it would let an\n * intermediary write answers into the app.\n *\n * The clear-text `disposition` is checked here rather than trusted. It is on\n * the wire so a relay can route without opening anything, which means the\n * one thing it must not be is authoritative — a daemon that sealed an error\n * and declared `ok` would otherwise have its declaration believed by\n * everything upstream of this line.\n */\n async #openResult(\n request: ResultRequestType,\n runner: RunnerRecord,\n ): Promise<\n { ok: true; value: SealedOutcome } | { ok: false; failure: HandlerResult }\n > {\n const refuse = (why: string) =>\n ({ ok: false as const, failure: fail(\"bad-request\", why) }) as const;\n\n const opened = await open({\n envelope: request.envelope,\n recipientKeys: this.#siteKeys,\n senderIdentityPublic: runner.device.identity,\n expected: {\n jobId: request.jobId,\n senderKeyId: keyId(runner.device.identity),\n recipientKeyId: keyId(publicIdentityOf(this.#siteKeys).identity),\n direction: \"result\",\n },\n });\n if (!opened.ok) {\n return refuse(\"the result did not verify as coming from this device\");\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(opened.plaintext);\n } catch {\n return refuse(\"the sealed result was not valid JSON\");\n }\n const sealed = SealedOutcome.safeParse(parsed);\n if (!sealed.success) return refuse(\"the sealed result was not an outcome\");\n\n if (sealed.data.outcome.outcome !== request.disposition) {\n return refuse(\"the declared disposition is not the one that was sealed\");\n }\n return { ok: true, value: sealed.data };\n }\n\n // -- 5. release -----------------------------------------------------------\n\n async #release(\n request: ReleaseRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const released = await this.#store.release({\n runnerId: runner.id,\n leases: request.leases,\n reason: request.reason,\n now: this.#now(),\n });\n const response: ReleaseResponse = { released };\n return ok(response);\n }\n}\n\n/** The protocol version this build speaks. */\nexport const SERVED_PROTOCOL_VERSION = PROTOCOL_VERSION;\n\n/** The lease a claimed job must have, or a loud failure. */\nfunction leaseOf(job: JobRecord): NonNullable<JobRecord[\"lease\"]> {\n if (!job.lease) {\n throw new Error(\n `store returned job ${job.id} from claim with no lease — the store ` +\n `contract requires a claimed job to hold one`,\n );\n }\n return job.lease;\n}\n","import {\n ENVELOPE_MAX_AGE_MS,\n keyId,\n open,\n publicIdentityOf,\n seal,\n type PublicIdentity,\n type SealedEnvelope,\n type StoredKeys,\n} from \"@byollm/protocol\";\n\n/**\n * Open this site's own at-rest envelope and re-seal it to a claiming device.\n *\n * The single operation that makes byollm_009 §6 work, and it now has two\n * callers: {@link ByollmHandlers} answering `fetch` on the direct plane, and\n * the cloud lane answering the relay's \"who claimed it\" poll. Both do exactly\n * this, and the reason it lives in one file is the reason everything else in\n * this codebase does: the deadline, the key ids and the direction are all\n * bound into a signature, and two implementations of a bound value is the same\n * bug as two clock readings — it works until they disagree, and then nothing\n * opens.\n *\n * The plaintext exists for one statement and never reaches a wire, a store, or\n * a log. That is the whole guarantee: the site is an endpoint, so it is\n * entitled to read its own work, and it is the only party between the app and\n * the device that is.\n */\n\ntype ResealFailure = \"unopenable\";\n\nexport type ResealResult =\n | { readonly ok: true; readonly envelope: SealedEnvelope }\n | { readonly ok: false; readonly reason: ResealFailure };\n\nexport async function resealForDevice(input: {\n siteKeys: StoredKeys;\n /** The job's identity and its at-rest ciphertext. */\n job: {\n readonly id: string;\n readonly envelope: SealedEnvelope;\n readonly createdAt: number;\n };\n /** The device that claimed it, as the upstream reported. */\n device: PublicIdentity;\n}): Promise<ResealResult> {\n const senderKeyId = keyId(publicIdentityOf(input.siteKeys).identity);\n\n const opened = await open({\n envelope: input.job.envelope,\n recipientKeys: input.siteKeys,\n senderIdentityPublic: input.siteKeys.identityPublic,\n expected: {\n jobId: input.job.id,\n senderKeyId,\n recipientKeyId: senderKeyId,\n direction: \"payload\",\n },\n });\n if (!opened.ok) {\n // The store holds something this site cannot open: rotated keys, a\n // corrupted row, or someone else's envelope. Not the device's problem and\n // not something a retry fixes.\n return { ok: false, reason: \"unopenable\" };\n }\n\n const envelope = await seal({\n plaintext: opened.plaintext,\n senderKeys: input.siteKeys,\n recipientEncryptionPublic: input.device.encryption,\n context: {\n jobId: input.job.id,\n senderKeyId,\n recipientKeyId: keyId(input.device.identity),\n // From the record, never recomputed from a fresh clock read — the\n // envelope's own deadline is what the signature bound.\n deadlineAt: input.job.createdAt + ENVELOPE_MAX_AGE_MS,\n direction: \"payload\",\n },\n });\n return { ok: true, envelope };\n}\n","import type {\n PublicIdentity,\n Audience,\n Capability,\n JobKind,\n JobOutcome,\n JobPayload,\n SealedEnvelope,\n SizeClass,\n JobState,\n Lease,\n ResultProvenance,\n} from \"@byollm/protocol\";\n\n/**\n * A job as the server stores it.\n *\n * Adapters map this shape onto their own storage; the field meanings are\n * normative because the conformance kit asserts behaviour that depends on\n * them (TTL clock start, dependency gating, refusal tracking).\n */\nexport interface JobRecord {\n readonly id: string;\n readonly kind: JobKind;\n /**\n * The work, sealed to this site's own encryption key (byollm_009 §10).\n *\n * The store never holds plaintext. The app sees plaintext at enqueue and at\n * result because the app *is* the endpoint; everything in between —\n * database, backups, log aggregators, a support engineer with read access —\n * sees ciphertext.\n *\n * This is not protection from the application the user deliberately sent\n * their work to. It is protection from everything the application's storage\n * touches, which is a longer list than most people picture.\n */\n readonly envelope: SealedEnvelope;\n /** Fixed at enqueue, where the plaintext is. */\n readonly sizeClass: SizeClass;\n readonly audience: Audience;\n /** The app's id for the user who enqueued it. */\n readonly owner: string;\n /** Server-side restriction on which runner owners may take a `named` job. */\n readonly audienceAllow: readonly string[] | undefined;\n /** Job ids that must all be `ok` before this becomes claimable. */\n readonly dependsOn: readonly string[];\n readonly state: JobState;\n readonly lease: Lease | null;\n /**\n * The grant that recorded this job's result — cloud_008 §3.6.\n *\n * Kept after `lease` is nulled, because \"who finished this\" outlives \"who\n * holds this\" and the two are asked for different reasons. It is what lets\n * a replay from the device that finished the job be answered *as a\n * duplicate* rather than as a stale lease — and lets a replay from any\n * other device be refused exactly as it would be for a job that is not\n * terminal, so a job id is not a terminality probe.\n */\n readonly completedByLeaseId: string | null;\n readonly createdAt: number;\n /**\n * When the job became claimable — enqueue time for a job with no\n * dependencies, or the moment its last dependency reached `ok`.\n *\n * **The TTL clock starts here, not at `createdAt`.** Starting it at enqueue\n * would expire a dependent job for the crime of waiting on a slow\n * dependency (byollm_001 Rev 1 §D, TTL clock resolved in build review).\n * `null` means still blocked.\n */\n readonly claimableAt: number | null;\n /** How long an unclaimed job may wait once claimable. */\n readonly ttlMs: number;\n /** Optional absolute deadline, independent of the TTL. */\n readonly deadlineAt: number | null;\n /**\n * Runners that released this job with reason `refused` — their local\n * allowlist declined it. Never offered to them again\n * ({@link MUSTS.REFUSAL_NOT_REOFFERED}).\n */\n readonly refusedBy: readonly string[];\n /** How many times this job has been claimed, including lease-expiry retries. */\n readonly attempts: number;\n readonly outcome: JobOutcome | null;\n readonly provenance: ResultProvenance | null;\n readonly updatedAt: number;\n}\n\n/** A paired daemon as the server stores it. */\nexport interface RunnerRecord {\n readonly id: string;\n /** The app's id for the user this runner is bound to — exactly one. */\n readonly owner: string;\n readonly label: string;\n readonly platform: \"darwin\" | \"linux\" | \"win32\";\n readonly daemonVersion: string;\n readonly capabilities: readonly Capability[];\n readonly paused: boolean;\n /** Set once; a revoked runner never un-revokes. */\n readonly revokedAt: number | null;\n readonly lastHeartbeatAt: number;\n readonly createdAt: number;\n /**\n * The device's pinned public keys. What later signatures verify against —\n * a runner id names a machine, this proves it.\n */\n readonly device: PublicIdentity;\n}\n\n/** An in-flight device-code pairing. */\nexport interface PairingRecord {\n /** SHA-256 of the device code. The code itself is never stored. */\n readonly deviceCodeHash: string;\n /** The short code the user reads. Unique among live pairings. */\n readonly userCode: string;\n readonly state: \"pending\" | \"approved\" | \"denied\";\n /** Set when approved — learned from the approving user's own session. */\n readonly owner: string | null;\n readonly runnerId: string | null;\n /**\n * Whether this approval has already been collected — cloud_008 §2.4.\n *\n * This was `runnerTokenOnce`, a bearer token held until the daemon's next\n * poll and then nulled. The token is gone (finding 37: minted, hashed,\n * written to two disks, never sent or compared), but the *deliver-once*\n * property it carried is real and separate: a replayed device code must get\n * nothing, or a code seen in a shell history is a second pairing.\n *\n * So the flag stays and the secret does not. Nulling a token to mean\n * \"collected\" was one field doing two jobs, and only one of them was load\n * bearing.\n */\n readonly collected: boolean;\n readonly label: string;\n readonly platform: \"darwin\" | \"linux\" | \"win32\";\n readonly daemonVersion: string;\n readonly capabilities: readonly Capability[];\n /**\n * The device's public keys, presented at pair start (byollm_009 §5).\n *\n * Kept on the pairing so the approving user is approving a *specific\n * machine*, not a code that any machine could later redeem. It is copied\n * onto the runner at approval.\n */\n readonly device: PublicIdentity;\n readonly expiresAt: number;\n readonly createdAt: number;\n}\n\n/** What the app supplies to enqueue a job. */\nexport interface EnqueueInput {\n readonly kind: JobKind;\n /** The work, in plaintext. The server seals it before it is stored. */\n readonly payload: JobPayload;\n readonly owner: string;\n /** Defaults to `self` — the safe direction. */\n readonly audience?: Audience;\n readonly audienceAllow?: readonly string[];\n readonly dependsOn?: readonly string[];\n /** Defaults to the server config's `defaultTtlMs`. */\n readonly ttlMs?: number;\n readonly deadlineAt?: number;\n /** Caller-supplied id, for idempotent enqueue. */\n readonly id?: string;\n}\n\n/**\n * What the *store* is given — the sealed form.\n *\n * Distinct from {@link EnqueueInput} because the two are genuinely different\n * things: an app hands over work in plaintext, and what gets written down is\n * sealed. Collapsing them into one type would mean a field that is sometimes\n * readable and sometimes not, which is the kind of ambiguity that ends with\n * plaintext in a database.\n */\nexport interface StoredJobInput extends Omit<EnqueueInput, \"payload\" | \"id\"> {\n readonly id: string;\n readonly envelope: SealedEnvelope;\n readonly sizeClass: SizeClass;\n}\n\n/**\n * When a job's ciphertext stops being worth carrying — cloud_008 §31.\n *\n * One function because it was two expressions. The direct plane computed\n * `job.deadlineAt ?? (job.claimableAt ?? now) + job.ttlMs`; the cloud lane\n * computed `record.deadlineAt ?? record.createdAt + <a local constant>`. The\n * first branch agreed and the fallback did not, so a job with no explicit\n * deadline got two different ones depending on which lane published it — and\n * the difference is largest exactly where it matters, for a job blocked on a\n * dependency, whose `claimableAt` may be hours after `createdAt`.\n *\n * The TTL clock starts when a job becomes *claimable*, which is the rule\n * `DEPENDS_ON_GATING` and `TTL_EXPIRY` already share: a dependent job must not\n * spend its life waiting for its dependency.\n */\nexport function deadlineFor(\n job: Pick<JobRecord, \"deadlineAt\" | \"claimableAt\" | \"ttlMs\">,\n now: number,\n): number {\n return job.deadlineAt ?? (job.claimableAt ?? now) + job.ttlMs;\n}\n","import {\n ENDPOINTS,\n ERROR_STATUS,\n PROTOCOL_PREFIX,\n checkProtocolVersion,\n type Endpoint,\n} from \"@byollm/protocol\";\nimport { ByollmHandlers, type HandlerConfig } from \"./handlers.js\";\n\n/**\n * Largest protocol request body accepted, before schema validation.\n *\n * A payload is capped at 4 MB of text by the protocol; this leaves room for\n * JSON overhead and a batch of results, and refuses anything wilder at the\n * door rather than after parsing it.\n */\nconst MAX_BODY_BYTES = 8 * 1024 * 1024;\n\n/**\n * Where the protocol endpoints are mounted.\n *\n * Defaults to {@link PROTOCOL_PREFIX}. Pass the real mount point when it is\n * anything else — a Next.js route at `app/api/byollm/[...route]/route.ts`\n * serves `/api/byollm/...`, so it needs `basePath: \"/api/byollm\"`.\n *\n * @throws if the path is not an absolute, single-segment-per-slash path. A\n * mount point is configuration, and a malformed one should fail at startup\n * rather than silently match nothing.\n */\nfunction normalizeBasePath(basePath: string): string {\n const trimmed = basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n if (!trimmed.startsWith(\"/\")) {\n throw new Error(`basePath must start with \"/\": got ${basePath}`);\n }\n if (trimmed.includes(\"//\") || /[?#*]/.test(trimmed)) {\n throw new Error(`basePath must be a plain path: got ${basePath}`);\n }\n return trimmed;\n}\n\n/**\n * Pull the endpoint name out of a URL path, or null if it isn't ours.\n *\n * The full path must match `<basePath>/<endpoint>` exactly. This used to\n * compare only the *last* segment, which meant `/anything/at/all/claim`\n * dispatched to `claim` and {@link PROTOCOL_PREFIX} was decorative — it\n * appeared in a 404 message and was never matched against. For the handler\n * that serves claim, result and heartbeat, dispatching on a suffix is a\n * looser rule than anyone reading the constant would assume, and loose\n * matching in a security surface should at least be a decision.\n *\n * The cost is that the mount point is now something a deployment has to state\n * rather than something that works by accident. That is the intended trade:\n * a 404 at startup naming the mount point beats a handler answering on paths\n * nobody meant to expose.\n */\nexport function routeEndpoint(\n pathname: string,\n basePath: string = PROTOCOL_PREFIX,\n): Endpoint | null {\n const base = normalizeBasePath(basePath);\n const path = pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n if (!path.startsWith(`${base}/`)) return null;\n const rest = path.slice(base.length + 1);\n return (ENDPOINTS as readonly string[]).includes(rest)\n ? (rest as Endpoint)\n : null;\n}\n\n/**\n * Read the request signature from headers (byollm_009 §4.2).\n *\n * In headers rather than the body so the signature covers the body whole,\n * with no field to exclude from its own hash — a scheme that signs a body\n * minus one field has to agree, byte for byte, on how that field is removed.\n */\nexport function signatureFrom(headers: Headers): unknown {\n const runnerId = headers.get(\"x-byollm-runner\");\n const rawIssuedAt = headers.get(\"x-byollm-issued-at\");\n const signature = headers.get(\"x-byollm-signature\");\n if (runnerId === null || signature === null || rawIssuedAt === null) {\n return undefined;\n }\n // Checked against null *before* Number(), because `Number(null)` is 0 —\n // finite, plausible-looking, and wrong. A missing timestamp would have\n // become a timestamp of the epoch, which the freshness check would then\n // reject for the wrong reason.\n const issuedAt = Number(rawIssuedAt);\n if (!Number.isFinite(issuedAt)) return undefined;\n return { runnerId, issuedAt, signature };\n}\n\n/**\n * A `Request` → `Response` handler for the whole protocol.\n *\n * Web-standard types, so this works unchanged in Next.js route handlers, Hono,\n * Bun, Deno, Cloudflare Workers, and anything else that speaks fetch.\n */\nexport function createFetchHandler(\n config: HandlerConfig & {\n /**\n * Where these endpoints are mounted. Defaults to\n * {@link PROTOCOL_PREFIX}; set it when the app serves them elsewhere.\n */\n readonly basePath?: string;\n },\n): (request: Request) => Promise<Response> {\n const handlers = new ByollmHandlers(config);\n // Validate once, at construction: a bad mount point is a deployment bug and\n // should surface when the server starts, not as a silent 404 per request.\n const basePath = normalizeBasePath(config.basePath ?? PROTOCOL_PREFIX);\n\n return async function handle(request: Request): Promise<Response> {\n if (request.method !== \"POST\") {\n return json(405, {\n error: \"bad-request\",\n message: \"protocol endpoints accept POST only\",\n });\n }\n\n const endpoint = routeEndpoint(new URL(request.url).pathname, basePath);\n if (endpoint === null) {\n return json(404, {\n error: \"not-found\",\n message: `not a ${basePath} endpoint`,\n });\n }\n\n const declared = request.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > MAX_BODY_BYTES) {\n return json(400, {\n error: \"bad-request\",\n message: \"request body too large\",\n });\n }\n\n let body: unknown;\n let rawBody: string;\n try {\n rawBody = await request.text();\n const text = rawBody;\n if (text.length > MAX_BODY_BYTES) {\n return json(400, {\n error: \"bad-request\",\n message: \"request body too large\",\n });\n }\n body = JSON.parse(text);\n } catch {\n // Deliberately not echoing the parse error: it would quote attacker\n // input back into a response an operator later reads in a terminal.\n return json(400, {\n error: \"bad-request\",\n message: \"request body is not valid JSON\",\n });\n }\n\n // byollm_009 §4: version before anything else. A mismatch must name the\n // disagreement and the fix, not surface as a generic bad-request from a\n // schema literal buried in an endpoint — which is what happened before,\n // and is why \"the connection is versionless\" was listed as a defect.\n const refusal = checkProtocolVersion(body);\n if (refusal) {\n return json(ERROR_STATUS[refusal.error], refusal);\n }\n\n const result = await handlers.handle(endpoint, body, {\n endpoint,\n // The bytes as received. Re-serialising the parsed object would verify\n // a signature over something the sender never sent.\n rawBody,\n signature: signatureFrom(request.headers),\n });\n\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n };\n if (result.retryAfterSeconds !== undefined) {\n headers[\"retry-after\"] = String(result.retryAfterSeconds);\n }\n return new Response(JSON.stringify(result.body), {\n status: result.status,\n headers,\n });\n };\n}\n\nfunction json(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n },\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP,IAAM,qBAAqB;AAGpB,SAAS,qBAA6B;AAC3C,SAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AAC7C;AAGO,SAAS,mBAA2B;AACzC,SAAO,UAAU,WAAW,CAAC;AAC/B;AAGO,SAAS,gBAAwB;AAStC,SAAO,WAAW;AACpB;AAMO,SAAS,mBAA2B;AACzC,QAAM,QAAkB,CAAC;AACzB,SAAO,MAAM,SAAS,GAAG;AACvB,eAAW,QAAQ,YAAY,EAAE,GAAG;AAGlC,YAAM,QAAQ,MAAO,MAAM,mBAAmB;AAC9C,UAAI,QAAQ,MAAO;AACnB,YAAM,SAAS,mBAAmB,OAAO,mBAAmB,MAAM;AAClE,UAAI,WAAW,OAAW;AAC1B,YAAM,KAAK,MAAM;AACjB,UAAI,MAAM,WAAW,EAAG;AAAA,IAC1B;AAAA,EACF;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;AACjE;AAGO,SAAS,WAAW,QAAwB;AACjD,SAAO,WA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,GAAG;AAAA,IACxC;AAAA,IACA,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,IACnB;AAAA,EACF,CAAC;AACH;","names":["keyId","open","publicIdentityOf","publicIdentityOf","keyId","response","open","ERROR_STATUS","ERROR_STATUS"]}
|
package/dist/index.js
CHANGED
package/dist/next.js
CHANGED
package/dist/supabase/index.js
CHANGED
|
@@ -146,7 +146,10 @@ function toPairing(row) {
|
|
|
146
146
|
state: row.state,
|
|
147
147
|
owner: row.owner,
|
|
148
148
|
runnerId: row.runner_id,
|
|
149
|
-
|
|
149
|
+
// Collected when it has a timestamp. This was `runner_token_once ===
|
|
150
|
+
// null` — a nulled token standing in for a fact about delivery, which is
|
|
151
|
+
// one field doing two jobs (cloud_008 §2.4a).
|
|
152
|
+
collected: row.collected_at !== null,
|
|
150
153
|
label: row.label,
|
|
151
154
|
platform: row.platform,
|
|
152
155
|
daemonVersion: row.daemon_version,
|
|
@@ -430,7 +433,7 @@ function supabaseStore(options) {
|
|
|
430
433
|
// renames it. Written as a constant rather than left null because
|
|
431
434
|
// `collected` reads `=== null`, and a schema change and a code
|
|
432
435
|
// change landing in one step is how a rollback strands rows.
|
|
433
|
-
|
|
436
|
+
collected_at: null
|
|
434
437
|
}).eq("device_code_hash", pairing.device_code_hash);
|
|
435
438
|
if (error) throw new Error(`supabase: ${error.message}`);
|
|
436
439
|
return toRunner(runner);
|
|
@@ -440,7 +443,7 @@ function supabaseStore(options) {
|
|
|
440
443
|
if (error) throw new Error(`supabase: ${error.message}`);
|
|
441
444
|
},
|
|
442
445
|
async consumePairingToken(deviceCodeHash) {
|
|
443
|
-
const { error } = await db.from("byollm_pairings").update({
|
|
446
|
+
const { error } = await db.from("byollm_pairings").update({ collected_at: "now()" }).eq("device_code_hash", deviceCodeHash);
|
|
444
447
|
if (error) throw new Error(`supabase: ${error.message}`);
|
|
445
448
|
},
|
|
446
449
|
async getRunner(runnerId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/supabase/realtime.ts","../../src/supabase/index.ts"],"sourcesContent":["import type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { DeliveredResult } from \"@byollm/protocol\";\nimport {\n NoRunnerAvailableError,\n ResultTimeoutError,\n type PollingDeliveryDeps,\n type ResultDelivery,\n type WaitOptions,\n} from \"../delivery.js\";\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n/**\n * How long a sustained no-runner signal must persist before it is believed.\n * A daemon restarting must not fail every job in flight.\n */\nconst NO_RUNNER_GRACE_MS = 10_000;\n\n/**\n * Realtime delivery: the app learns a job finished when Postgres says so.\n *\n * byollm_003 Rev 1 requires the server→app path be an explicit channel rather\n * than an implied in-request `await`. Polling is the portable default;\n * this is the one worth having when the app is already on Supabase, because\n * a result arrives in milliseconds instead of on the next poll tick.\n *\n * The no-runner watch still polls, deliberately: runner liveness is a\n * *derived* signal (nobody with matching capability has heartbeated lately),\n * and there is no row change to subscribe to for \"something stopped\n * happening\".\n */\nexport function supabaseRealtimeDelivery(\n client: SupabaseClient,\n): (deps: PollingDeliveryDeps) => ResultDelivery {\n return (deps) => new SupabaseRealtimeDelivery(client, deps);\n}\n\nclass SupabaseRealtimeDelivery implements ResultDelivery {\n readonly #client: SupabaseClient;\n readonly #deps: PollingDeliveryDeps;\n\n constructor(client: SupabaseClient, deps: PollingDeliveryDeps) {\n this.#client = client;\n this.#deps = deps;\n }\n\n async waitFor(\n jobId: string,\n options: WaitOptions = {},\n ): Promise<DeliveredResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n // Read first. The job may already be terminal, and subscribing to a\n // channel for an event that has already happened waits forever.\n const current = await this.#deps.read(jobId);\n if (current && isTerminal(current.state)) return current;\n\n // Declared before the subscription so the channel callback closes over a\n // `settled` that already exists. Every async path below routes its failure\n // here: a rejection that escapes this object becomes an unhandled\n // rejection, and an unhandled rejection ends the process.\n const settled = Promise.withResolvers<DeliveredResult>();\n this.#resolve = settled.resolve;\n\n const channel = this.#client.channel(`byollm_job_${jobId}`).on(\n \"postgres_changes\",\n {\n event: \"UPDATE\",\n schema: \"public\",\n table: \"byollm_jobs\",\n filter: `id=eq.${jobId}`,\n },\n () => {\n this.#check(jobId).catch(settled.reject);\n },\n );\n\n // `subscribe()` returns the channel, not a promise — awaiting it would be\n // a no-op that reads as if it waited for the subscription to be live.\n channel.subscribe();\n\n // A second read after subscribing closes the race where the job finished\n // between the first read and the subscription taking effect.\n this.#check(jobId).catch(settled.reject);\n\n const timer = setTimeout(() => {\n settled.reject(new ResultTimeoutError(jobId, timeoutMs));\n }, timeoutMs);\n\n const watcher = this.#watchAvailability(jobId, options, settled);\n const abort = (): void => {\n settled.reject(new Error(\"wait aborted\"));\n };\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n\n try {\n return await settled.promise;\n } finally {\n clearTimeout(timer);\n clearInterval(watcher);\n options.signal?.removeEventListener(\"abort\", abort);\n await this.#client.removeChannel(channel);\n }\n }\n\n #resolve: ((result: DeliveredResult) => void) | undefined;\n\n async #check(jobId: string): Promise<void> {\n const current = await this.#deps.read(jobId);\n if (current && isTerminal(current.state)) this.#resolve?.(current);\n }\n\n /** Poll runner liveness; there is no row event for \"nothing is happening\". */\n #watchAvailability(\n jobId: string,\n options: WaitOptions,\n settled: PromiseWithResolvers<DeliveredResult>,\n ): NodeJS.Timeout {\n let noRunnerSince: number | null = null;\n\n return setInterval(() => {\n // `.catch`, not `void`. Two things in here can reject — the store read\n // and the caller's own `onNoRunner` — and discarding either made a\n // transient store error, or an app whose fallback throws, terminate the\n // process. The caller is awaiting `result()`; that is where a failure\n // belongs, and it is what the polling channel already does by virtue of\n // running inside the awaited chain. A delivery adapter must not change\n // what a failure means.\n (async () => {\n const availability = await this.#deps.availability(jobId);\n if (availability.available || availability.blocked) {\n noRunnerSince = null;\n return;\n }\n noRunnerSince ??= Date.now();\n if (Date.now() - noRunnerSince < NO_RUNNER_GRACE_MS) return;\n\n const reason = availability.reason ?? \"no-runner-online\";\n const substitute = await options.onNoRunner?.(reason);\n if (substitute) {\n settled.resolve(substitute);\n } else {\n settled.reject(new NoRunnerAvailableError(jobId, reason));\n }\n })().catch(settled.reject);\n }, 2_000);\n }\n}\n\nfunction isTerminal(state: string): boolean {\n return (\n state === \"ok\" ||\n state === \"error\" ||\n state === \"canceled\" ||\n state === \"expired\"\n );\n}\n","import type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type {\n Capability,\n JobOutcome,\n JobState,\n PublicIdentity,\n} from \"@byollm/protocol\";\nimport type {\n StoredJobInput,\n JobRecord,\n PairingRecord,\n RunnerRecord,\n} from \"../records.js\";\nimport type {\n ApproveArgs,\n ByollmStore,\n ClaimArgs,\n AdoptArgs,\n CompleteArgs,\n CompleteResult,\n LeaseRef,\n ReleaseArgs,\n RenewArgs,\n RenewResult,\n TouchArgs,\n} from \"../store.js\";\n\n/**\n * `@byollm/server/supabase` — the first-party Supabase adapter.\n *\n * The piece the of-tomorrow-framework's runner module consumes verbatim.\n * Migrations ship in `supabase/migrations`; the atomic claim lives in a\n * `security definer` RPC using `FOR UPDATE SKIP LOCKED`, and the audience\n * rules are mirrored in SQL so the server refuses independently of the daemon\n * (byollm_003 §Server-side MUSTs).\n *\n * Requires the **service role** key: a runner authenticates with a bearer\n * token of its own, which is not a Supabase session, so the protocol handler\n * cannot run under RLS as the runner's user. RLS still governs everything the\n * *browser* does — the app-side policies in the migration are what protect\n * one user's jobs from another.\n *\n * @packageDocumentation\n */\n\n/** Row shape of `byollm_jobs`. */\ninterface JobRow {\n id: string;\n kind: string;\n envelope: unknown;\n size_class: \"small\" | \"medium\" | \"large\" | \"unbounded\";\n audience: \"self\" | \"named\" | \"public\";\n owner: string;\n audience_allow: string[] | null;\n depends_on: string[];\n state: JobState;\n lease_id: string | null;\n lease_runner: string | null;\n completed_by_lease_id: string | null;\n lease_expires_at: string | null;\n claimable_at: string | null;\n ttl_ms: number;\n deadline_at: string | null;\n refused_by: string[];\n attempts: number;\n outcome: JobOutcome | null;\n provenance: JobRecord[\"provenance\"];\n created_at: string;\n updated_at: string;\n}\n\n/** Row shape of `byollm_runners`. */\ninterface RunnerRow {\n id: string;\n owner: string;\n label: string;\n platform: \"darwin\" | \"linux\" | \"win32\";\n daemon_version: string;\n capabilities: Capability[];\n device: PublicIdentity;\n paused: boolean;\n revoked_at: string | null;\n last_heartbeat_at: string;\n created_at: string;\n}\n\n/** Row shape of `byollm_pairings`. */\ninterface PairingRow {\n device_code_hash: string;\n user_code: string;\n state: \"pending\" | \"approved\" | \"denied\";\n owner: string | null;\n runner_id: string | null;\n runner_token_once: string | null;\n label: string;\n platform: \"darwin\" | \"linux\" | \"win32\";\n daemon_version: string;\n capabilities: Capability[];\n device: PublicIdentity;\n expires_at: string;\n created_at: string;\n}\n\nconst ms = (iso: string | null): number | null =>\n iso === null ? null : Date.parse(iso);\n\nconst iso = (epochMs: number): string => new Date(epochMs).toISOString();\n\nfunction toJob(row: JobRow): JobRecord {\n const leaseExpires = ms(row.lease_expires_at);\n return {\n id: row.id,\n kind: row.kind as JobRecord[\"kind\"],\n envelope: row.envelope as JobRecord[\"envelope\"],\n sizeClass: row.size_class,\n audience: row.audience,\n owner: row.owner,\n audienceAllow: row.audience_allow ?? undefined,\n dependsOn: row.depends_on,\n state: row.state,\n completedByLeaseId: row.completed_by_lease_id ?? null,\n lease:\n // Keyed on the lease id, not the runner. A relayed grant has no runner\n // row to point at (see AdoptArgs), and reading the lease as absent\n // because `lease_runner` is null would make an actively-held job look\n // claimable — the exact bug `adopt` exists to prevent.\n leaseExpires !== null && row.lease_id !== null\n ? {\n id: row.lease_id,\n runnerId: row.lease_runner ?? \"\",\n expiresAt: leaseExpires,\n }\n : null,\n createdAt: Date.parse(row.created_at),\n claimableAt: ms(row.claimable_at),\n ttlMs: row.ttl_ms,\n deadlineAt: ms(row.deadline_at),\n refusedBy: row.refused_by,\n attempts: row.attempts,\n outcome: row.outcome,\n provenance: row.provenance,\n updatedAt: Date.parse(row.updated_at),\n };\n}\n\n/**\n * A PostgREST filter matching exactly these (job, lease) pairs.\n *\n * Not two `IN` lists: `id IN (…) AND lease_id IN (…)` is a cross product, and\n * while UUID uniqueness makes a mismatch improbable, \"improbable\" is not the\n * property a lease check should rest on. This says what it means.\n */\nconst leasePairs = (leases: readonly LeaseRef[]): string =>\n leases.map((l) => `and(id.eq.${l.jobId},lease_id.eq.${l.leaseId})`).join(\",\");\n\nfunction toRunner(row: RunnerRow): RunnerRecord {\n return {\n id: row.id,\n owner: row.owner,\n label: row.label,\n platform: row.platform,\n daemonVersion: row.daemon_version,\n capabilities: row.capabilities,\n device: row.device,\n paused: row.paused,\n revokedAt: ms(row.revoked_at),\n lastHeartbeatAt: Date.parse(row.last_heartbeat_at),\n createdAt: Date.parse(row.created_at),\n };\n}\n\nfunction toPairing(row: PairingRow): PairingRecord {\n return {\n deviceCodeHash: row.device_code_hash,\n userCode: row.user_code,\n state: row.state,\n owner: row.owner,\n runnerId: row.runner_id,\n collected: row.runner_token_once === null,\n label: row.label,\n platform: row.platform,\n daemonVersion: row.daemon_version,\n capabilities: row.capabilities,\n device: row.device,\n expiresAt: Date.parse(row.expires_at),\n createdAt: Date.parse(row.created_at),\n };\n}\n\nexport interface SupabaseStoreOptions {\n /** A client built with the **service role** key. */\n readonly client: SupabaseClient;\n /** Default TTL for a job once claimable. */\n readonly defaultTtlMs?: number;\n}\n\n/** Build the Supabase-backed store. */\nexport function supabaseStore(options: SupabaseStoreOptions): ByollmStore {\n const db = options.client;\n const defaultTtlMs = options.defaultTtlMs ?? 15 * 60_000;\n\n /**\n * Narrow one PostgREST response, or throw with the Postgres message.\n *\n * `supabase-js` types rows as `any` unless the project has generated\n * database types, so the assertion has to live somewhere. Confining it to\n * these two helpers — against the row interfaces declared above — keeps\n * every call site typed and leaves exactly one place to review.\n */\n /* eslint-disable @typescript-eslint/no-unnecessary-type-parameters --\n T appears only in the return type because these helpers *are* the cast.\n That is the point: one reviewable place where PostgREST's `any` becomes\n one of the row interfaces above. */\n function unwrap<T>(result: {\n data: unknown;\n error: { message: string } | null;\n }): T {\n if (result.error) throw new Error(`supabase: ${result.error.message}`);\n if (result.data === null || result.data === undefined) {\n throw new Error(\"supabase: no data returned\");\n }\n return result.data as T;\n }\n\n /** Same, but a missing row is a legitimate answer rather than an error. */\n function unwrapMaybe<T>(result: {\n data: unknown;\n error: { message: string } | null;\n }): T | null {\n if (result.error) throw new Error(`supabase: ${result.error.message}`);\n return (result.data ?? null) as T | null;\n }\n /* eslint-enable @typescript-eslint/no-unnecessary-type-parameters */\n\n return {\n // -- jobs ---------------------------------------------------------------\n\n async create(input: StoredJobInput, now: number): Promise<JobRecord> {\n const dependsOn = [...(input.dependsOn ?? [])];\n\n // A job with dependencies starts blocked; the trigger sets\n // `claimable_at` when the last one reaches `ok`, which is where its TTL\n // clock starts.\n let claimableAt: string | null = iso(now);\n if (dependsOn.length > 0) {\n const deps = unwrap<JobRow[]>(\n await db.from(\"byollm_jobs\").select(\"id,state\").in(\"id\", dependsOn),\n ) as { id: string; state: JobState }[];\n const allDone =\n deps.length === dependsOn.length &&\n deps.every((dep) => dep.state === \"ok\");\n claimableAt = allDone ? iso(now) : null;\n }\n\n const row = {\n id: input.id,\n kind: input.kind,\n envelope: input.envelope,\n size_class: input.sizeClass,\n audience: input.audience ?? \"self\",\n owner: input.owner,\n audience_allow: input.audienceAllow ? [...input.audienceAllow] : null,\n depends_on: dependsOn,\n claimable_at: claimableAt,\n ttl_ms: input.ttlMs ?? defaultTtlMs,\n deadline_at:\n input.deadlineAt === undefined ? null : iso(input.deadlineAt),\n };\n\n // Idempotent by caller-supplied id, matching the reference store: an\n // app's retry must not duplicate work.\n const inserted = unwrapMaybe<JobRow>(\n await db\n .from(\"byollm_jobs\")\n .upsert(row, { onConflict: \"id\", ignoreDuplicates: true })\n .select()\n .maybeSingle(),\n );\n\n if (inserted) return toJob(inserted);\n const existing = unwrap<JobRow>(\n await db.from(\"byollm_jobs\").select().eq(\"id\", input.id).single(),\n );\n return toJob(existing);\n },\n\n async get(jobId: string): Promise<JobRecord | null> {\n const row = unwrapMaybe<JobRow>(\n await db.from(\"byollm_jobs\").select().eq(\"id\", jobId).maybeSingle(),\n );\n return row === null ? null : toJob(row);\n },\n\n async claim(args: ClaimArgs): Promise<JobRecord[]> {\n // One RPC, one transaction, `FOR UPDATE SKIP LOCKED` inside\n // ({@link MUSTS.CLAIM_ATOMIC}).\n const rows = unwrap<JobRow[]>(\n await db.rpc(\"byollm_claim_jobs\", {\n p_runner_id: args.runnerId,\n p_capabilities: args.capabilities,\n p_max: args.max,\n p_lease_ms: args.leaseMs,\n }),\n );\n return rows.map(toJob);\n },\n\n async renewLeases(args: RenewArgs): Promise<RenewResult> {\n await db.rpc(\"byollm_expire_due\");\n if (args.leases.length === 0) return { renewed: [], lost: [] };\n\n const expiresAt = iso(args.now + args.leaseMs);\n const renewedRows = unwrap<JobRow[]>(\n await db\n .from(\"byollm_jobs\")\n .update({\n state: \"running\",\n lease_expires_at: expiresAt,\n updated_at: iso(args.now),\n })\n .eq(\"lease_runner\", args.runnerId)\n .or(leasePairs(args.leases))\n .in(\"state\", [\"claimed\", \"running\"])\n .select(\"id\"),\n );\n\n const renewedIds = new Set(renewedRows.map((row) => row.id));\n return {\n renewed: renewedRows.map((row) => ({\n jobId: row.id,\n expiresAt: args.now + args.leaseMs,\n })),\n // Anything the runner thinks it holds but did not renew is gone.\n lost: args.leases\n .map((l) => l.jobId)\n .filter((id) => !renewedIds.has(id)),\n };\n },\n\n async adopt(args: AdoptArgs): Promise<JobRecord | null> {\n // The predicates are the guard, evaluated in the database rather than\n // read-then-written here: `state in (queued, claimed)` is what makes\n // adopting a terminal or expired job impossible under concurrency.\n const rows = unwrap<JobRow[]>(\n await db\n .from(\"byollm_jobs\")\n .update({\n state: \"claimed\",\n lease_id: args.leaseId,\n // Left null on purpose: `lease_runner` is a foreign key into\n // `byollm_runners`, and a relayed device has no row there. See\n // AdoptArgs — the site records the grant, not a machine it has\n // no relationship with.\n lease_runner: null,\n lease_expires_at: iso(args.expiresAt),\n updated_at: iso(args.now),\n })\n .eq(\"id\", args.jobId)\n .in(\"state\", [\"queued\", \"claimed\"])\n .select(),\n );\n const written = rows[0];\n return written === undefined ? null : toJob(written);\n },\n\n async complete(args: CompleteArgs): Promise<CompleteResult> {\n const state: JobState =\n args.outcome.outcome === \"ok\"\n ? \"ok\"\n : args.outcome.outcome === \"canceled\"\n ? \"canceled\"\n : \"error\";\n\n // The `in('state', ...)` predicate is the idempotency guard: a job that\n // already reached a terminal state matches nothing, so the first\n // outcome wins ({@link MUSTS.RESULT_IDEMPOTENT}). The `lease_runner`\n // predicate is {@link MUSTS.LEASE_HONORED}.\n // The `in('state', ...)` predicate is the idempotency guard. The\n // second predicate is LEASE_HONORED, and which column carries it\n // depends on the plane: a direct runner is named by id, a relayed\n // grant only by its lease. Built as a query rather than branched into\n // two, so there is one update statement and no chance of the two\n // drifting.\n let update = db\n .from(\"byollm_jobs\")\n .update({\n state,\n lease_runner: null,\n lease_expires_at: null,\n // Which grant recorded it, kept after the lease is dropped — §3.6.\n completed_by_lease_id:\n args.holder.by === \"lease\" ? args.holder.leaseId : null,\n outcome: args.outcome,\n provenance: args.provenance,\n updated_at: iso(args.now),\n })\n .eq(\"id\", args.jobId)\n .in(\"state\", [\"claimed\", \"running\"]);\n update =\n args.holder.by === \"runner\"\n ? update.eq(\"lease_runner\", args.holder.runnerId)\n : update.eq(\"lease_id\", args.holder.leaseId);\n const rows = unwrap<JobRow[]>(await update.select());\n\n const written = rows[0];\n if (written === undefined) {\n const current = unwrapMaybe<JobRow>(\n await db\n .from(\"byollm_jobs\")\n .select()\n .eq(\"id\", args.jobId)\n .maybeSingle(),\n );\n const job = current === null ? null : toJob(current);\n // Terminal before holder — cloud_008 §3.6. The update above matched\n // nothing for one of two reasons, and the caller is owed the\n // difference: the device that already recorded this job hears\n // \"duplicate\", and anybody else hears the same refusal they would get\n // for a job that is not terminal, so a job id is not a terminality\n // probe.\n //\n // Decided on the row that is there rather than by a second predicate,\n // because the update is the atomic part and this is only a diagnosis\n // of why it matched nothing.\n const duplicate =\n job !== null &&\n job.provenance?.runnerId === args.runnerId &&\n (job.state === \"ok\" ||\n job.state === \"error\" ||\n job.state === \"canceled\") &&\n args.holder.by === \"lease\" &&\n job.completedByLeaseId !== null &&\n job.completedByLeaseId === args.holder.leaseId;\n return duplicate\n ? { accepted: false, duplicate: true, job }\n : { accepted: false, job };\n }\n return { accepted: true, job: toJob(written) };\n },\n\n async release(args: ReleaseArgs): Promise<string[]> {\n if (args.leases.length === 0) return [];\n\n const held = unwrap<{ id: string; refused_by: string[] }[]>(\n await db\n .from(\"byollm_jobs\")\n .select(\"id,refused_by\")\n .eq(\"lease_runner\", args.runnerId)\n .or(leasePairs(args.leases)),\n );\n\n const released: string[] = [];\n for (const row of held) {\n const refusedBy =\n args.reason === \"refused\"\n ? [...new Set([...row.refused_by, args.runnerId])]\n : row.refused_by;\n\n const { error } = await db\n .from(\"byollm_jobs\")\n .update({\n state: \"queued\",\n lease_id: null,\n lease_runner: null,\n lease_expires_at: null,\n // Newly available again, so the TTL clock restarts.\n claimable_at: iso(args.now),\n refused_by: refusedBy,\n updated_at: iso(args.now),\n })\n .eq(\"id\", row.id)\n .eq(\"lease_runner\", args.runnerId);\n if (error) throw new Error(`supabase: ${error.message}`);\n released.push(row.id);\n }\n return released;\n },\n\n async expireDue(_now: number): Promise<JobRecord[]> {\n // The sweep is a single idempotent SQL function; it reports a count\n // rather than rows, and the caller only needs to know it ran.\n const { error } = await db.rpc(\"byollm_expire_due\");\n if (error) throw new Error(`supabase: ${error.message}`);\n return [];\n },\n\n async cancel(jobId: string, now: number): Promise<JobRecord | null> {\n const current = unwrapMaybe<JobRow>(\n await db.from(\"byollm_jobs\").select().eq(\"id\", jobId).maybeSingle(),\n );\n if (current === null) return null;\n\n if (current.state === \"queued\") {\n const rows = unwrap<JobRow[]>(\n await db\n .from(\"byollm_jobs\")\n .update({ state: \"canceled\", updated_at: iso(now) })\n .eq(\"id\", jobId)\n .eq(\"state\", \"queued\")\n .select(),\n );\n const canceled = rows[0];\n return toJob(canceled ?? current);\n }\n\n if (current.state === \"claimed\" || current.state === \"running\") {\n // Held by a runner: the cancel travels on the next heartbeat and the\n // runner reports `canceled` itself.\n const { error } = await db\n .from(\"byollm_job_cancels\")\n .upsert({ job_id: jobId, requested_at: iso(now) });\n if (error) throw new Error(`supabase: ${error.message}`);\n }\n return toJob(current);\n },\n\n async listClaimedBy(runnerId: string): Promise<JobRecord[]> {\n const rows = unwrap<JobRow[]>(\n await db.from(\"byollm_jobs\").select().eq(\"lease_runner\", runnerId),\n );\n return rows.map(toJob);\n },\n\n async listCancelRequests(runnerId: string): Promise<string[]> {\n const rows = unwrap<{ job_id: string }[]>(\n await db\n .from(\"byollm_job_cancels\")\n .select(\"job_id, byollm_jobs!inner(lease_runner)\")\n .eq(\"byollm_jobs.lease_runner\", runnerId),\n ) as { job_id: string }[];\n return rows.map((row) => row.job_id);\n },\n\n // -- pairing and runners -------------------------------------------------\n\n /**\n * The push seam (byollm_009 §8.3), over Postgres Realtime.\n *\n * Native here, which is the point of requiring it of every adapter: the\n * backend that can push does, the one that cannot polls, and the\n * interface does not change again when streaming arrives.\n */\n subscribe(jobId: string, onChange: () => void): () => void {\n const channel = db\n .channel(`byollm_job_${jobId}`)\n .on(\n \"postgres_changes\",\n {\n event: \"UPDATE\",\n schema: \"public\",\n table: \"byollm_jobs\",\n filter: `id=eq.${jobId}`,\n },\n () => {\n onChange();\n },\n )\n .subscribe();\n\n let live = true;\n return () => {\n if (!live) return;\n live = false;\n // `removeChannel` is async and nothing awaits an unsubscribe, so the\n // rejection is routed rather than dropped — an unhandled one here\n // would end the process (see the Realtime delivery channel).\n void db.removeChannel(channel).catch(() => undefined);\n };\n },\n\n async createPairing(record: PairingRecord): Promise<void> {\n const { error } = await db.from(\"byollm_pairings\").insert({\n device_code_hash: record.deviceCodeHash,\n device: record.device,\n user_code: record.userCode,\n state: record.state,\n label: record.label,\n platform: record.platform,\n daemon_version: record.daemonVersion,\n capabilities: record.capabilities,\n expires_at: iso(record.expiresAt),\n });\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async getPairingByDeviceCodeHash(\n hash: string,\n ): Promise<PairingRecord | null> {\n const row = unwrapMaybe<PairingRow>(\n await db\n .from(\"byollm_pairings\")\n .select()\n .eq(\"device_code_hash\", hash)\n .maybeSingle(),\n );\n return row === null ? null : toPairing(row);\n },\n\n async getPairingByUserCode(\n userCode: string,\n ): Promise<PairingRecord | null> {\n const row = unwrapMaybe<PairingRow>(\n await db\n .from(\"byollm_pairings\")\n .select()\n .eq(\"user_code\", userCode)\n .maybeSingle(),\n );\n return row === null ? null : toPairing(row);\n },\n\n async approvePairing(args: ApproveArgs): Promise<RunnerRecord> {\n // Deliberately *not* the browser RPC: this path runs under the service\n // role with an `owner` the caller has already authenticated. Apps using\n // Supabase Auth in the browser should call `byollm_approve_pairing`\n // instead, which takes the owner from `auth.uid()` and cannot be told\n // who the user is.\n const pairing = unwrap<PairingRow>(\n await db\n .from(\"byollm_pairings\")\n .select()\n .eq(\"user_code\", args.userCode)\n .single(),\n );\n\n if (Date.parse(pairing.expires_at) <= args.now) {\n throw new Error(\"pairing code has expired\");\n }\n if (pairing.state !== \"pending\") {\n throw new Error(`pairing is already ${pairing.state}`);\n }\n\n const runner = unwrap<RunnerRow>(\n await db\n .from(\"byollm_runners\")\n .insert({\n owner: args.owner,\n label: pairing.label,\n platform: pairing.platform,\n daemon_version: pairing.daemon_version,\n capabilities: pairing.capabilities,\n // Carried from the pairing, exactly as the SQL RPC does. There\n // are two approval paths — this service-role one and\n // `byollm_approve_pairing` for browser callers — and a field\n // added to one and not the other produces a runner that is\n // correct through one door and broken through the other.\n device: pairing.device,\n })\n .select()\n .single(),\n );\n\n const { error } = await db\n .from(\"byollm_pairings\")\n .update({\n state: \"approved\",\n owner: args.owner,\n runner_id: runner.id,\n // Marks the approval collectable — cloud_008 §2.4. The column held\n // a bearer token; it now holds a marker, and the next migration\n // renames it. Written as a constant rather than left null because\n // `collected` reads `=== null`, and a schema change and a code\n // change landing in one step is how a rollback strands rows.\n runner_token_once: \"pending-collection\",\n })\n .eq(\"device_code_hash\", pairing.device_code_hash);\n if (error) throw new Error(`supabase: ${error.message}`);\n\n return toRunner(runner);\n },\n\n async denyPairing(userCode: string, _now: number): Promise<void> {\n const { error } = await db\n .from(\"byollm_pairings\")\n .update({ state: \"denied\" })\n .eq(\"user_code\", userCode);\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async consumePairingToken(deviceCodeHash: string): Promise<void> {\n const { error } = await db\n .from(\"byollm_pairings\")\n .update({ runner_token_once: null })\n .eq(\"device_code_hash\", deviceCodeHash);\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async getRunner(runnerId: string): Promise<RunnerRecord | null> {\n const row = unwrapMaybe<RunnerRow>(\n await db\n .from(\"byollm_runners\")\n .select()\n .eq(\"id\", runnerId)\n .maybeSingle(),\n );\n return row === null ? null : toRunner(row);\n },\n\n async touchRunner(args: TouchArgs): Promise<RunnerRecord | null> {\n const row = unwrapMaybe<RunnerRow>(\n await db\n .from(\"byollm_runners\")\n .update({\n capabilities: args.capabilities,\n daemon_version: args.daemonVersion,\n paused: args.paused,\n last_heartbeat_at: iso(args.now),\n })\n .eq(\"id\", args.runnerId)\n .select()\n .maybeSingle(),\n );\n return row === null ? null : toRunner(row);\n },\n\n async revokeRunner(runnerId: string, now: number): Promise<void> {\n // `is('revoked_at', null)` keeps revocation one-way: an already-revoked\n // runner keeps its first revocation time.\n const { error } = await db\n .from(\"byollm_runners\")\n .update({ revoked_at: iso(now) })\n .eq(\"id\", runnerId)\n .is(\"revoked_at\", null);\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async listRunners(owner?: string): Promise<RunnerRecord[]> {\n const query = db.from(\"byollm_runners\").select();\n const rows = unwrap<RunnerRow[]>(\n owner === undefined ? await query : await query.eq(\"owner\", owner),\n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OAAO,EACP,GAAG,MAAM,QAAQ,EACjB,YAAY;AAAA,MACjB;AACA,aAAO,QAAQ,OAAO,OAAO,SAAS,GAAG;AAAA,IAC3C;AAAA,IAEA,MAAM,YAAY,MAA+C;AAC/D,YAAM,MAAM;AAAA,QACV,MAAM,GACH,KAAK,gBAAgB,EACrB,OAAO;AAAA,UACN,cAAc,KAAK;AAAA,UACnB,gBAAgB,KAAK;AAAA,UACrB,QAAQ,KAAK;AAAA,UACb,mBAAmB,IAAI,KAAK,GAAG;AAAA,QACjC,CAAC,EACA,GAAG,MAAM,KAAK,QAAQ,EACtB,OAAO,EACP,YAAY;AAAA,MACjB;AACA,aAAO,QAAQ,OAAO,OAAO,SAAS,GAAG;AAAA,IAC3C;AAAA,IAEA,MAAM,aAAa,UAAkB,KAA4B;AAG/D,YAAM,EAAE,MAAM,IAAI,MAAM,GACrB,KAAK,gBAAgB,EACrB,OAAO,EAAE,YAAY,IAAI,GAAG,EAAE,CAAC,EAC/B,GAAG,MAAM,QAAQ,EACjB,GAAG,cAAc,IAAI;AACxB,UAAI,MAAO,OAAM,IAAI,MAAM,aAAa,MAAM,OAAO,EAAE;AAAA,IACzD;AAAA,IAEA,MAAM,YAAY,OAAyC;AACzD,YAAM,QAAQ,GAAG,KAAK,gBAAgB,EAAE,OAAO;AAC/C,YAAM,OAAO;AAAA,QACX,UAAU,SAAY,MAAM,QAAQ,MAAM,MAAM,GAAG,SAAS,KAAK;AAAA,MACnE;AACA,aAAO,KAAK,IAAI,QAAQ;AAAA,IAC1B;AAAA,EACF;AACF;","names":["iso"]}
|
|
1
|
+
{"version":3,"sources":["../../src/supabase/realtime.ts","../../src/supabase/index.ts"],"sourcesContent":["import type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { DeliveredResult } from \"@byollm/protocol\";\nimport {\n NoRunnerAvailableError,\n ResultTimeoutError,\n type PollingDeliveryDeps,\n type ResultDelivery,\n type WaitOptions,\n} from \"../delivery.js\";\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n/**\n * How long a sustained no-runner signal must persist before it is believed.\n * A daemon restarting must not fail every job in flight.\n */\nconst NO_RUNNER_GRACE_MS = 10_000;\n\n/**\n * Realtime delivery: the app learns a job finished when Postgres says so.\n *\n * byollm_003 Rev 1 requires the server→app path be an explicit channel rather\n * than an implied in-request `await`. Polling is the portable default;\n * this is the one worth having when the app is already on Supabase, because\n * a result arrives in milliseconds instead of on the next poll tick.\n *\n * The no-runner watch still polls, deliberately: runner liveness is a\n * *derived* signal (nobody with matching capability has heartbeated lately),\n * and there is no row change to subscribe to for \"something stopped\n * happening\".\n */\nexport function supabaseRealtimeDelivery(\n client: SupabaseClient,\n): (deps: PollingDeliveryDeps) => ResultDelivery {\n return (deps) => new SupabaseRealtimeDelivery(client, deps);\n}\n\nclass SupabaseRealtimeDelivery implements ResultDelivery {\n readonly #client: SupabaseClient;\n readonly #deps: PollingDeliveryDeps;\n\n constructor(client: SupabaseClient, deps: PollingDeliveryDeps) {\n this.#client = client;\n this.#deps = deps;\n }\n\n async waitFor(\n jobId: string,\n options: WaitOptions = {},\n ): Promise<DeliveredResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n // Read first. The job may already be terminal, and subscribing to a\n // channel for an event that has already happened waits forever.\n const current = await this.#deps.read(jobId);\n if (current && isTerminal(current.state)) return current;\n\n // Declared before the subscription so the channel callback closes over a\n // `settled` that already exists. Every async path below routes its failure\n // here: a rejection that escapes this object becomes an unhandled\n // rejection, and an unhandled rejection ends the process.\n const settled = Promise.withResolvers<DeliveredResult>();\n this.#resolve = settled.resolve;\n\n const channel = this.#client.channel(`byollm_job_${jobId}`).on(\n \"postgres_changes\",\n {\n event: \"UPDATE\",\n schema: \"public\",\n table: \"byollm_jobs\",\n filter: `id=eq.${jobId}`,\n },\n () => {\n this.#check(jobId).catch(settled.reject);\n },\n );\n\n // `subscribe()` returns the channel, not a promise — awaiting it would be\n // a no-op that reads as if it waited for the subscription to be live.\n channel.subscribe();\n\n // A second read after subscribing closes the race where the job finished\n // between the first read and the subscription taking effect.\n this.#check(jobId).catch(settled.reject);\n\n const timer = setTimeout(() => {\n settled.reject(new ResultTimeoutError(jobId, timeoutMs));\n }, timeoutMs);\n\n const watcher = this.#watchAvailability(jobId, options, settled);\n const abort = (): void => {\n settled.reject(new Error(\"wait aborted\"));\n };\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n\n try {\n return await settled.promise;\n } finally {\n clearTimeout(timer);\n clearInterval(watcher);\n options.signal?.removeEventListener(\"abort\", abort);\n await this.#client.removeChannel(channel);\n }\n }\n\n #resolve: ((result: DeliveredResult) => void) | undefined;\n\n async #check(jobId: string): Promise<void> {\n const current = await this.#deps.read(jobId);\n if (current && isTerminal(current.state)) this.#resolve?.(current);\n }\n\n /** Poll runner liveness; there is no row event for \"nothing is happening\". */\n #watchAvailability(\n jobId: string,\n options: WaitOptions,\n settled: PromiseWithResolvers<DeliveredResult>,\n ): NodeJS.Timeout {\n let noRunnerSince: number | null = null;\n\n return setInterval(() => {\n // `.catch`, not `void`. Two things in here can reject — the store read\n // and the caller's own `onNoRunner` — and discarding either made a\n // transient store error, or an app whose fallback throws, terminate the\n // process. The caller is awaiting `result()`; that is where a failure\n // belongs, and it is what the polling channel already does by virtue of\n // running inside the awaited chain. A delivery adapter must not change\n // what a failure means.\n (async () => {\n const availability = await this.#deps.availability(jobId);\n if (availability.available || availability.blocked) {\n noRunnerSince = null;\n return;\n }\n noRunnerSince ??= Date.now();\n if (Date.now() - noRunnerSince < NO_RUNNER_GRACE_MS) return;\n\n const reason = availability.reason ?? \"no-runner-online\";\n const substitute = await options.onNoRunner?.(reason);\n if (substitute) {\n settled.resolve(substitute);\n } else {\n settled.reject(new NoRunnerAvailableError(jobId, reason));\n }\n })().catch(settled.reject);\n }, 2_000);\n }\n}\n\nfunction isTerminal(state: string): boolean {\n return (\n state === \"ok\" ||\n state === \"error\" ||\n state === \"canceled\" ||\n state === \"expired\"\n );\n}\n","import type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type {\n Capability,\n JobOutcome,\n JobState,\n PublicIdentity,\n} from \"@byollm/protocol\";\nimport type {\n StoredJobInput,\n JobRecord,\n PairingRecord,\n RunnerRecord,\n} from \"../records.js\";\nimport type {\n ApproveArgs,\n ByollmStore,\n ClaimArgs,\n AdoptArgs,\n CompleteArgs,\n CompleteResult,\n LeaseRef,\n ReleaseArgs,\n RenewArgs,\n RenewResult,\n TouchArgs,\n} from \"../store.js\";\n\n/**\n * `@byollm/server/supabase` — the first-party Supabase adapter.\n *\n * The piece the of-tomorrow-framework's runner module consumes verbatim.\n * Migrations ship in `supabase/migrations`; the atomic claim lives in a\n * `security definer` RPC using `FOR UPDATE SKIP LOCKED`, and the audience\n * rules are mirrored in SQL so the server refuses independently of the daemon\n * (byollm_003 §Server-side MUSTs).\n *\n * Requires the **service role** key: a runner authenticates with a bearer\n * token of its own, which is not a Supabase session, so the protocol handler\n * cannot run under RLS as the runner's user. RLS still governs everything the\n * *browser* does — the app-side policies in the migration are what protect\n * one user's jobs from another.\n *\n * @packageDocumentation\n */\n\n/** Row shape of `byollm_jobs`. */\ninterface JobRow {\n id: string;\n kind: string;\n envelope: unknown;\n size_class: \"small\" | \"medium\" | \"large\" | \"unbounded\";\n audience: \"self\" | \"named\" | \"public\";\n owner: string;\n audience_allow: string[] | null;\n depends_on: string[];\n state: JobState;\n lease_id: string | null;\n lease_runner: string | null;\n completed_by_lease_id: string | null;\n lease_expires_at: string | null;\n claimable_at: string | null;\n ttl_ms: number;\n deadline_at: string | null;\n refused_by: string[];\n attempts: number;\n outcome: JobOutcome | null;\n provenance: JobRecord[\"provenance\"];\n created_at: string;\n updated_at: string;\n}\n\n/** Row shape of `byollm_runners`. */\ninterface RunnerRow {\n id: string;\n owner: string;\n label: string;\n platform: \"darwin\" | \"linux\" | \"win32\";\n daemon_version: string;\n capabilities: Capability[];\n device: PublicIdentity;\n paused: boolean;\n revoked_at: string | null;\n last_heartbeat_at: string;\n created_at: string;\n}\n\n/** Row shape of `byollm_pairings`. */\ninterface PairingRow {\n device_code_hash: string;\n user_code: string;\n state: \"pending\" | \"approved\" | \"denied\";\n owner: string | null;\n runner_id: string | null;\n collected_at: string | null;\n label: string;\n platform: \"darwin\" | \"linux\" | \"win32\";\n daemon_version: string;\n capabilities: Capability[];\n device: PublicIdentity;\n expires_at: string;\n created_at: string;\n}\n\nconst ms = (iso: string | null): number | null =>\n iso === null ? null : Date.parse(iso);\n\nconst iso = (epochMs: number): string => new Date(epochMs).toISOString();\n\nfunction toJob(row: JobRow): JobRecord {\n const leaseExpires = ms(row.lease_expires_at);\n return {\n id: row.id,\n kind: row.kind as JobRecord[\"kind\"],\n envelope: row.envelope as JobRecord[\"envelope\"],\n sizeClass: row.size_class,\n audience: row.audience,\n owner: row.owner,\n audienceAllow: row.audience_allow ?? undefined,\n dependsOn: row.depends_on,\n state: row.state,\n completedByLeaseId: row.completed_by_lease_id ?? null,\n lease:\n // Keyed on the lease id, not the runner. A relayed grant has no runner\n // row to point at (see AdoptArgs), and reading the lease as absent\n // because `lease_runner` is null would make an actively-held job look\n // claimable — the exact bug `adopt` exists to prevent.\n leaseExpires !== null && row.lease_id !== null\n ? {\n id: row.lease_id,\n runnerId: row.lease_runner ?? \"\",\n expiresAt: leaseExpires,\n }\n : null,\n createdAt: Date.parse(row.created_at),\n claimableAt: ms(row.claimable_at),\n ttlMs: row.ttl_ms,\n deadlineAt: ms(row.deadline_at),\n refusedBy: row.refused_by,\n attempts: row.attempts,\n outcome: row.outcome,\n provenance: row.provenance,\n updatedAt: Date.parse(row.updated_at),\n };\n}\n\n/**\n * A PostgREST filter matching exactly these (job, lease) pairs.\n *\n * Not two `IN` lists: `id IN (…) AND lease_id IN (…)` is a cross product, and\n * while UUID uniqueness makes a mismatch improbable, \"improbable\" is not the\n * property a lease check should rest on. This says what it means.\n */\nconst leasePairs = (leases: readonly LeaseRef[]): string =>\n leases.map((l) => `and(id.eq.${l.jobId},lease_id.eq.${l.leaseId})`).join(\",\");\n\nfunction toRunner(row: RunnerRow): RunnerRecord {\n return {\n id: row.id,\n owner: row.owner,\n label: row.label,\n platform: row.platform,\n daemonVersion: row.daemon_version,\n capabilities: row.capabilities,\n device: row.device,\n paused: row.paused,\n revokedAt: ms(row.revoked_at),\n lastHeartbeatAt: Date.parse(row.last_heartbeat_at),\n createdAt: Date.parse(row.created_at),\n };\n}\n\nfunction toPairing(row: PairingRow): PairingRecord {\n return {\n deviceCodeHash: row.device_code_hash,\n userCode: row.user_code,\n state: row.state,\n owner: row.owner,\n runnerId: row.runner_id,\n // Collected when it has a timestamp. This was `runner_token_once ===\n // null` — a nulled token standing in for a fact about delivery, which is\n // one field doing two jobs (cloud_008 §2.4a).\n collected: row.collected_at !== null,\n label: row.label,\n platform: row.platform,\n daemonVersion: row.daemon_version,\n capabilities: row.capabilities,\n device: row.device,\n expiresAt: Date.parse(row.expires_at),\n createdAt: Date.parse(row.created_at),\n };\n}\n\nexport interface SupabaseStoreOptions {\n /** A client built with the **service role** key. */\n readonly client: SupabaseClient;\n /** Default TTL for a job once claimable. */\n readonly defaultTtlMs?: number;\n}\n\n/** Build the Supabase-backed store. */\nexport function supabaseStore(options: SupabaseStoreOptions): ByollmStore {\n const db = options.client;\n const defaultTtlMs = options.defaultTtlMs ?? 15 * 60_000;\n\n /**\n * Narrow one PostgREST response, or throw with the Postgres message.\n *\n * `supabase-js` types rows as `any` unless the project has generated\n * database types, so the assertion has to live somewhere. Confining it to\n * these two helpers — against the row interfaces declared above — keeps\n * every call site typed and leaves exactly one place to review.\n */\n /* eslint-disable @typescript-eslint/no-unnecessary-type-parameters --\n T appears only in the return type because these helpers *are* the cast.\n That is the point: one reviewable place where PostgREST's `any` becomes\n one of the row interfaces above. */\n function unwrap<T>(result: {\n data: unknown;\n error: { message: string } | null;\n }): T {\n if (result.error) throw new Error(`supabase: ${result.error.message}`);\n if (result.data === null || result.data === undefined) {\n throw new Error(\"supabase: no data returned\");\n }\n return result.data as T;\n }\n\n /** Same, but a missing row is a legitimate answer rather than an error. */\n function unwrapMaybe<T>(result: {\n data: unknown;\n error: { message: string } | null;\n }): T | null {\n if (result.error) throw new Error(`supabase: ${result.error.message}`);\n return (result.data ?? null) as T | null;\n }\n /* eslint-enable @typescript-eslint/no-unnecessary-type-parameters */\n\n return {\n // -- jobs ---------------------------------------------------------------\n\n async create(input: StoredJobInput, now: number): Promise<JobRecord> {\n const dependsOn = [...(input.dependsOn ?? [])];\n\n // A job with dependencies starts blocked; the trigger sets\n // `claimable_at` when the last one reaches `ok`, which is where its TTL\n // clock starts.\n let claimableAt: string | null = iso(now);\n if (dependsOn.length > 0) {\n const deps = unwrap<JobRow[]>(\n await db.from(\"byollm_jobs\").select(\"id,state\").in(\"id\", dependsOn),\n ) as { id: string; state: JobState }[];\n const allDone =\n deps.length === dependsOn.length &&\n deps.every((dep) => dep.state === \"ok\");\n claimableAt = allDone ? iso(now) : null;\n }\n\n const row = {\n id: input.id,\n kind: input.kind,\n envelope: input.envelope,\n size_class: input.sizeClass,\n audience: input.audience ?? \"self\",\n owner: input.owner,\n audience_allow: input.audienceAllow ? [...input.audienceAllow] : null,\n depends_on: dependsOn,\n claimable_at: claimableAt,\n ttl_ms: input.ttlMs ?? defaultTtlMs,\n deadline_at:\n input.deadlineAt === undefined ? null : iso(input.deadlineAt),\n };\n\n // Idempotent by caller-supplied id, matching the reference store: an\n // app's retry must not duplicate work.\n const inserted = unwrapMaybe<JobRow>(\n await db\n .from(\"byollm_jobs\")\n .upsert(row, { onConflict: \"id\", ignoreDuplicates: true })\n .select()\n .maybeSingle(),\n );\n\n if (inserted) return toJob(inserted);\n const existing = unwrap<JobRow>(\n await db.from(\"byollm_jobs\").select().eq(\"id\", input.id).single(),\n );\n return toJob(existing);\n },\n\n async get(jobId: string): Promise<JobRecord | null> {\n const row = unwrapMaybe<JobRow>(\n await db.from(\"byollm_jobs\").select().eq(\"id\", jobId).maybeSingle(),\n );\n return row === null ? null : toJob(row);\n },\n\n async claim(args: ClaimArgs): Promise<JobRecord[]> {\n // One RPC, one transaction, `FOR UPDATE SKIP LOCKED` inside\n // ({@link MUSTS.CLAIM_ATOMIC}).\n const rows = unwrap<JobRow[]>(\n await db.rpc(\"byollm_claim_jobs\", {\n p_runner_id: args.runnerId,\n p_capabilities: args.capabilities,\n p_max: args.max,\n p_lease_ms: args.leaseMs,\n }),\n );\n return rows.map(toJob);\n },\n\n async renewLeases(args: RenewArgs): Promise<RenewResult> {\n await db.rpc(\"byollm_expire_due\");\n if (args.leases.length === 0) return { renewed: [], lost: [] };\n\n const expiresAt = iso(args.now + args.leaseMs);\n const renewedRows = unwrap<JobRow[]>(\n await db\n .from(\"byollm_jobs\")\n .update({\n state: \"running\",\n lease_expires_at: expiresAt,\n updated_at: iso(args.now),\n })\n .eq(\"lease_runner\", args.runnerId)\n .or(leasePairs(args.leases))\n .in(\"state\", [\"claimed\", \"running\"])\n .select(\"id\"),\n );\n\n const renewedIds = new Set(renewedRows.map((row) => row.id));\n return {\n renewed: renewedRows.map((row) => ({\n jobId: row.id,\n expiresAt: args.now + args.leaseMs,\n })),\n // Anything the runner thinks it holds but did not renew is gone.\n lost: args.leases\n .map((l) => l.jobId)\n .filter((id) => !renewedIds.has(id)),\n };\n },\n\n async adopt(args: AdoptArgs): Promise<JobRecord | null> {\n // The predicates are the guard, evaluated in the database rather than\n // read-then-written here: `state in (queued, claimed)` is what makes\n // adopting a terminal or expired job impossible under concurrency.\n const rows = unwrap<JobRow[]>(\n await db\n .from(\"byollm_jobs\")\n .update({\n state: \"claimed\",\n lease_id: args.leaseId,\n // Left null on purpose: `lease_runner` is a foreign key into\n // `byollm_runners`, and a relayed device has no row there. See\n // AdoptArgs — the site records the grant, not a machine it has\n // no relationship with.\n lease_runner: null,\n lease_expires_at: iso(args.expiresAt),\n updated_at: iso(args.now),\n })\n .eq(\"id\", args.jobId)\n .in(\"state\", [\"queued\", \"claimed\"])\n .select(),\n );\n const written = rows[0];\n return written === undefined ? null : toJob(written);\n },\n\n async complete(args: CompleteArgs): Promise<CompleteResult> {\n const state: JobState =\n args.outcome.outcome === \"ok\"\n ? \"ok\"\n : args.outcome.outcome === \"canceled\"\n ? \"canceled\"\n : \"error\";\n\n // The `in('state', ...)` predicate is the idempotency guard: a job that\n // already reached a terminal state matches nothing, so the first\n // outcome wins ({@link MUSTS.RESULT_IDEMPOTENT}). The `lease_runner`\n // predicate is {@link MUSTS.LEASE_HONORED}.\n // The `in('state', ...)` predicate is the idempotency guard. The\n // second predicate is LEASE_HONORED, and which column carries it\n // depends on the plane: a direct runner is named by id, a relayed\n // grant only by its lease. Built as a query rather than branched into\n // two, so there is one update statement and no chance of the two\n // drifting.\n let update = db\n .from(\"byollm_jobs\")\n .update({\n state,\n lease_runner: null,\n lease_expires_at: null,\n // Which grant recorded it, kept after the lease is dropped — §3.6.\n completed_by_lease_id:\n args.holder.by === \"lease\" ? args.holder.leaseId : null,\n outcome: args.outcome,\n provenance: args.provenance,\n updated_at: iso(args.now),\n })\n .eq(\"id\", args.jobId)\n .in(\"state\", [\"claimed\", \"running\"]);\n update =\n args.holder.by === \"runner\"\n ? update.eq(\"lease_runner\", args.holder.runnerId)\n : update.eq(\"lease_id\", args.holder.leaseId);\n const rows = unwrap<JobRow[]>(await update.select());\n\n const written = rows[0];\n if (written === undefined) {\n const current = unwrapMaybe<JobRow>(\n await db\n .from(\"byollm_jobs\")\n .select()\n .eq(\"id\", args.jobId)\n .maybeSingle(),\n );\n const job = current === null ? null : toJob(current);\n // Terminal before holder — cloud_008 §3.6. The update above matched\n // nothing for one of two reasons, and the caller is owed the\n // difference: the device that already recorded this job hears\n // \"duplicate\", and anybody else hears the same refusal they would get\n // for a job that is not terminal, so a job id is not a terminality\n // probe.\n //\n // Decided on the row that is there rather than by a second predicate,\n // because the update is the atomic part and this is only a diagnosis\n // of why it matched nothing.\n const duplicate =\n job !== null &&\n job.provenance?.runnerId === args.runnerId &&\n (job.state === \"ok\" ||\n job.state === \"error\" ||\n job.state === \"canceled\") &&\n args.holder.by === \"lease\" &&\n job.completedByLeaseId !== null &&\n job.completedByLeaseId === args.holder.leaseId;\n return duplicate\n ? { accepted: false, duplicate: true, job }\n : { accepted: false, job };\n }\n return { accepted: true, job: toJob(written) };\n },\n\n async release(args: ReleaseArgs): Promise<string[]> {\n if (args.leases.length === 0) return [];\n\n const held = unwrap<{ id: string; refused_by: string[] }[]>(\n await db\n .from(\"byollm_jobs\")\n .select(\"id,refused_by\")\n .eq(\"lease_runner\", args.runnerId)\n .or(leasePairs(args.leases)),\n );\n\n const released: string[] = [];\n for (const row of held) {\n const refusedBy =\n args.reason === \"refused\"\n ? [...new Set([...row.refused_by, args.runnerId])]\n : row.refused_by;\n\n const { error } = await db\n .from(\"byollm_jobs\")\n .update({\n state: \"queued\",\n lease_id: null,\n lease_runner: null,\n lease_expires_at: null,\n // Newly available again, so the TTL clock restarts.\n claimable_at: iso(args.now),\n refused_by: refusedBy,\n updated_at: iso(args.now),\n })\n .eq(\"id\", row.id)\n .eq(\"lease_runner\", args.runnerId);\n if (error) throw new Error(`supabase: ${error.message}`);\n released.push(row.id);\n }\n return released;\n },\n\n async expireDue(_now: number): Promise<JobRecord[]> {\n // The sweep is a single idempotent SQL function; it reports a count\n // rather than rows, and the caller only needs to know it ran.\n const { error } = await db.rpc(\"byollm_expire_due\");\n if (error) throw new Error(`supabase: ${error.message}`);\n return [];\n },\n\n async cancel(jobId: string, now: number): Promise<JobRecord | null> {\n const current = unwrapMaybe<JobRow>(\n await db.from(\"byollm_jobs\").select().eq(\"id\", jobId).maybeSingle(),\n );\n if (current === null) return null;\n\n if (current.state === \"queued\") {\n const rows = unwrap<JobRow[]>(\n await db\n .from(\"byollm_jobs\")\n .update({ state: \"canceled\", updated_at: iso(now) })\n .eq(\"id\", jobId)\n .eq(\"state\", \"queued\")\n .select(),\n );\n const canceled = rows[0];\n return toJob(canceled ?? current);\n }\n\n if (current.state === \"claimed\" || current.state === \"running\") {\n // Held by a runner: the cancel travels on the next heartbeat and the\n // runner reports `canceled` itself.\n const { error } = await db\n .from(\"byollm_job_cancels\")\n .upsert({ job_id: jobId, requested_at: iso(now) });\n if (error) throw new Error(`supabase: ${error.message}`);\n }\n return toJob(current);\n },\n\n async listClaimedBy(runnerId: string): Promise<JobRecord[]> {\n const rows = unwrap<JobRow[]>(\n await db.from(\"byollm_jobs\").select().eq(\"lease_runner\", runnerId),\n );\n return rows.map(toJob);\n },\n\n async listCancelRequests(runnerId: string): Promise<string[]> {\n const rows = unwrap<{ job_id: string }[]>(\n await db\n .from(\"byollm_job_cancels\")\n .select(\"job_id, byollm_jobs!inner(lease_runner)\")\n .eq(\"byollm_jobs.lease_runner\", runnerId),\n ) as { job_id: string }[];\n return rows.map((row) => row.job_id);\n },\n\n // -- pairing and runners -------------------------------------------------\n\n /**\n * The push seam (byollm_009 §8.3), over Postgres Realtime.\n *\n * Native here, which is the point of requiring it of every adapter: the\n * backend that can push does, the one that cannot polls, and the\n * interface does not change again when streaming arrives.\n */\n subscribe(jobId: string, onChange: () => void): () => void {\n const channel = db\n .channel(`byollm_job_${jobId}`)\n .on(\n \"postgres_changes\",\n {\n event: \"UPDATE\",\n schema: \"public\",\n table: \"byollm_jobs\",\n filter: `id=eq.${jobId}`,\n },\n () => {\n onChange();\n },\n )\n .subscribe();\n\n let live = true;\n return () => {\n if (!live) return;\n live = false;\n // `removeChannel` is async and nothing awaits an unsubscribe, so the\n // rejection is routed rather than dropped — an unhandled one here\n // would end the process (see the Realtime delivery channel).\n void db.removeChannel(channel).catch(() => undefined);\n };\n },\n\n async createPairing(record: PairingRecord): Promise<void> {\n const { error } = await db.from(\"byollm_pairings\").insert({\n device_code_hash: record.deviceCodeHash,\n device: record.device,\n user_code: record.userCode,\n state: record.state,\n label: record.label,\n platform: record.platform,\n daemon_version: record.daemonVersion,\n capabilities: record.capabilities,\n expires_at: iso(record.expiresAt),\n });\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async getPairingByDeviceCodeHash(\n hash: string,\n ): Promise<PairingRecord | null> {\n const row = unwrapMaybe<PairingRow>(\n await db\n .from(\"byollm_pairings\")\n .select()\n .eq(\"device_code_hash\", hash)\n .maybeSingle(),\n );\n return row === null ? null : toPairing(row);\n },\n\n async getPairingByUserCode(\n userCode: string,\n ): Promise<PairingRecord | null> {\n const row = unwrapMaybe<PairingRow>(\n await db\n .from(\"byollm_pairings\")\n .select()\n .eq(\"user_code\", userCode)\n .maybeSingle(),\n );\n return row === null ? null : toPairing(row);\n },\n\n async approvePairing(args: ApproveArgs): Promise<RunnerRecord> {\n // Deliberately *not* the browser RPC: this path runs under the service\n // role with an `owner` the caller has already authenticated. Apps using\n // Supabase Auth in the browser should call `byollm_approve_pairing`\n // instead, which takes the owner from `auth.uid()` and cannot be told\n // who the user is.\n const pairing = unwrap<PairingRow>(\n await db\n .from(\"byollm_pairings\")\n .select()\n .eq(\"user_code\", args.userCode)\n .single(),\n );\n\n if (Date.parse(pairing.expires_at) <= args.now) {\n throw new Error(\"pairing code has expired\");\n }\n if (pairing.state !== \"pending\") {\n throw new Error(`pairing is already ${pairing.state}`);\n }\n\n const runner = unwrap<RunnerRow>(\n await db\n .from(\"byollm_runners\")\n .insert({\n owner: args.owner,\n label: pairing.label,\n platform: pairing.platform,\n daemon_version: pairing.daemon_version,\n capabilities: pairing.capabilities,\n // Carried from the pairing, exactly as the SQL RPC does. There\n // are two approval paths — this service-role one and\n // `byollm_approve_pairing` for browser callers — and a field\n // added to one and not the other produces a runner that is\n // correct through one door and broken through the other.\n device: pairing.device,\n })\n .select()\n .single(),\n );\n\n const { error } = await db\n .from(\"byollm_pairings\")\n .update({\n state: \"approved\",\n owner: args.owner,\n runner_id: runner.id,\n // Marks the approval collectable — cloud_008 §2.4. The column held\n // a bearer token; it now holds a marker, and the next migration\n // renames it. Written as a constant rather than left null because\n // `collected` reads `=== null`, and a schema change and a code\n // change landing in one step is how a rollback strands rows.\n collected_at: null,\n })\n .eq(\"device_code_hash\", pairing.device_code_hash);\n if (error) throw new Error(`supabase: ${error.message}`);\n\n return toRunner(runner);\n },\n\n async denyPairing(userCode: string, _now: number): Promise<void> {\n const { error } = await db\n .from(\"byollm_pairings\")\n .update({ state: \"denied\" })\n .eq(\"user_code\", userCode);\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async consumePairingToken(deviceCodeHash: string): Promise<void> {\n const { error } = await db\n .from(\"byollm_pairings\")\n // The database's clock, not this process's — the same rule the\n // relay's lease stamps follow: two writers measuring one fact against\n // two clocks is how a \"collected\" row looks uncollected.\n .update({ collected_at: \"now()\" })\n .eq(\"device_code_hash\", deviceCodeHash);\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async getRunner(runnerId: string): Promise<RunnerRecord | null> {\n const row = unwrapMaybe<RunnerRow>(\n await db\n .from(\"byollm_runners\")\n .select()\n .eq(\"id\", runnerId)\n .maybeSingle(),\n );\n return row === null ? null : toRunner(row);\n },\n\n async touchRunner(args: TouchArgs): Promise<RunnerRecord | null> {\n const row = unwrapMaybe<RunnerRow>(\n await db\n .from(\"byollm_runners\")\n .update({\n capabilities: args.capabilities,\n daemon_version: args.daemonVersion,\n paused: args.paused,\n last_heartbeat_at: iso(args.now),\n })\n .eq(\"id\", args.runnerId)\n .select()\n .maybeSingle(),\n );\n return row === null ? null : toRunner(row);\n },\n\n async revokeRunner(runnerId: string, now: number): Promise<void> {\n // `is('revoked_at', null)` keeps revocation one-way: an already-revoked\n // runner keeps its first revocation time.\n const { error } = await db\n .from(\"byollm_runners\")\n .update({ revoked_at: iso(now) })\n .eq(\"id\", runnerId)\n .is(\"revoked_at\", null);\n if (error) throw new Error(`supabase: ${error.message}`);\n },\n\n async listRunners(owner?: string): Promise<RunnerRecord[]> {\n const query = db.from(\"byollm_runners\").select();\n const rows = unwrap<RunnerRow[]>(\n owner === undefined ? await query : await query.eq(\"owner\", owner),\n );\n return rows.map(toRunner);\n },\n };\n}\n\nexport { supabaseRealtimeDelivery } from \"./realtime.js\";\n"],"mappings":";;;;;;A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,OAAO,OAAO,SAAS,GAAG;AAAA,IAC3C;AAAA,IAEA,MAAM,YAAY,MAA+C;AAC/D,YAAM,MAAM;AAAA,QACV,MAAM,GACH,KAAK,gBAAgB,EACrB,OAAO;AAAA,UACN,cAAc,KAAK;AAAA,UACnB,gBAAgB,KAAK;AAAA,UACrB,QAAQ,KAAK;AAAA,UACb,mBAAmB,IAAI,KAAK,GAAG;AAAA,QACjC,CAAC,EACA,GAAG,MAAM,KAAK,QAAQ,EACtB,OAAO,EACP,YAAY;AAAA,MACjB;AACA,aAAO,QAAQ,OAAO,OAAO,SAAS,GAAG;AAAA,IAC3C;AAAA,IAEA,MAAM,aAAa,UAAkB,KAA4B;AAG/D,YAAM,EAAE,MAAM,IAAI,MAAM,GACrB,KAAK,gBAAgB,EACrB,OAAO,EAAE,YAAY,IAAI,GAAG,EAAE,CAAC,EAC/B,GAAG,MAAM,QAAQ,EACjB,GAAG,cAAc,IAAI;AACxB,UAAI,MAAO,OAAM,IAAI,MAAM,aAAa,MAAM,OAAO,EAAE;AAAA,IACzD;AAAA,IAEA,MAAM,YAAY,OAAyC;AACzD,YAAM,QAAQ,GAAG,KAAK,gBAAgB,EAAE,OAAO;AAC/C,YAAM,OAAO;AAAA,QACX,UAAU,SAAY,MAAM,QAAQ,MAAM,MAAM,GAAG,SAAS,KAAK;AAAA,MACnE;AACA,aAAO,KAAK,IAAI,QAAQ;AAAA,IAC1B;AAAA,EACF;AACF;","names":["iso"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@byollm/server",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.25",
|
|
4
4
|
"description": "Framework-agnostic BYOLLM protocol handlers, a reference in-memory store, a Next.js mount, and a Supabase adapter.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"node": ">=22.14"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@byollm/protocol": "0.1.0-alpha.
|
|
33
|
+
"@byollm/protocol": "0.1.0-alpha.25"
|
|
34
34
|
},
|
|
35
35
|
"peerDependencies": {
|
|
36
36
|
"@supabase/supabase-js": "^2.58.0"
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
-- The deliver-once flag stops pretending to be a token — cloud_008 §2.4a.
|
|
2
|
+
--
|
|
3
|
+
-- `20260819000000_drop_runner_token` removed the bearer credential and left
|
|
4
|
+
-- `byollm_pairings.runner_token_once` carrying a marker string, with the
|
|
5
|
+
-- reason written down: *"Renaming a column and changing the code that reads
|
|
6
|
+
-- it in one step is how a rollback strands rows, so the rename waits for a
|
|
7
|
+
-- later release."*
|
|
8
|
+
--
|
|
9
|
+
-- This is that release. The rename lands with the code that reads it, in one
|
|
10
|
+
-- step, because the transitional shape exists to protect a party who has not
|
|
11
|
+
-- agreed to change — and pre-1.0, with one deployment and one operator, that
|
|
12
|
+
-- party is us. Carrying a column named after a secret it no longer holds is
|
|
13
|
+
-- a comment that has to be re-read by everybody who meets it.
|
|
14
|
+
--
|
|
15
|
+
-- The property is unchanged and is the reason the column survives at all: a
|
|
16
|
+
-- replayed device code must get nothing, or a code left in a shell history is
|
|
17
|
+
-- a second pairing. That was riding on a token's nullability, which was one
|
|
18
|
+
-- field doing two jobs — and only one of them load-bearing.
|
|
19
|
+
|
|
20
|
+
alter table byollm_pairings
|
|
21
|
+
rename column runner_token_once to collected_at;
|
|
22
|
+
|
|
23
|
+
-- A timestamp rather than a marker string. `'pending-collection'` was the
|
|
24
|
+
-- shape a nulled token left behind; what the flag actually records is *when*
|
|
25
|
+
-- the approval was handed over, which is worth having when somebody asks why
|
|
26
|
+
-- a pairing did not complete.
|
|
27
|
+
alter table byollm_pairings
|
|
28
|
+
alter column collected_at type timestamptz
|
|
29
|
+
using case when collected_at is null then now() else null end;
|
|
30
|
+
|
|
31
|
+
comment on column byollm_pairings.collected_at is
|
|
32
|
+
'When the approval was collected. Null until then — a replayed device code '
|
|
33
|
+
'gets nothing. cloud_008 §2.4a; this was runner_token_once.';
|
|
34
|
+
|
|
35
|
+
-- The approval function moves with the column it writes. Recreated whole
|
|
36
|
+
-- rather than patched, because two functions with one name is how a caller
|
|
37
|
+
-- ends up invoking the one nobody maintains — the argument the migration
|
|
38
|
+
-- before this one made when it replaced the old signature.
|
|
39
|
+
|
|
40
|
+
create or replace function byollm_approve_pairing(
|
|
41
|
+
p_user_code text
|
|
42
|
+
)
|
|
43
|
+
returns byollm_runners
|
|
44
|
+
language plpgsql
|
|
45
|
+
security definer
|
|
46
|
+
set search_path = public
|
|
47
|
+
as $$
|
|
48
|
+
declare
|
|
49
|
+
v_pairing byollm_pairings;
|
|
50
|
+
v_runner byollm_runners;
|
|
51
|
+
v_owner uuid := (select auth.uid());
|
|
52
|
+
begin
|
|
53
|
+
if v_owner is null then
|
|
54
|
+
raise exception 'approving a pairing requires an authenticated user';
|
|
55
|
+
end if;
|
|
56
|
+
|
|
57
|
+
select * into v_pairing from byollm_pairings
|
|
58
|
+
where user_code = p_user_code for update;
|
|
59
|
+
|
|
60
|
+
if v_pairing is null then
|
|
61
|
+
raise exception 'unknown pairing code';
|
|
62
|
+
end if;
|
|
63
|
+
if v_pairing.expires_at <= now() then
|
|
64
|
+
raise exception 'pairing code has expired';
|
|
65
|
+
end if;
|
|
66
|
+
if v_pairing.state <> 'pending' then
|
|
67
|
+
raise exception 'pairing is already %', v_pairing.state;
|
|
68
|
+
end if;
|
|
69
|
+
|
|
70
|
+
insert into byollm_runners (owner, label, platform,
|
|
71
|
+
daemon_version, capabilities, device)
|
|
72
|
+
values (v_owner, v_pairing.label, v_pairing.platform,
|
|
73
|
+
v_pairing.daemon_version, v_pairing.capabilities, v_pairing.device)
|
|
74
|
+
returning * into v_runner;
|
|
75
|
+
|
|
76
|
+
-- The marker, not a token: this is what makes a replayed device code get
|
|
77
|
+
-- nothing. The service-role path in `supabase/index.ts` writes the same
|
|
78
|
+
-- value, and the two approval doors have to agree — a field set by one and
|
|
79
|
+
-- not the other produces a runner that is correct through one and broken
|
|
80
|
+
-- through the other.
|
|
81
|
+
update byollm_pairings
|
|
82
|
+
set state = 'approved',
|
|
83
|
+
owner = v_owner,
|
|
84
|
+
runner_id = v_runner.id,
|
|
85
|
+
collected_at = null
|
|
86
|
+
where device_code_hash = v_pairing.device_code_hash;
|
|
87
|
+
|
|
88
|
+
return v_runner;
|
|
89
|
+
end;
|
|
90
|
+
$$;
|
|
91
|
+
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ids.ts","../src/handlers.ts","../src/reseal.ts","../src/records.ts","../src/http.ts"],"sourcesContent":["import {\n createHash,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from \"node:crypto\";\n\n/**\n * Alphabet for the user-facing pairing code.\n *\n * Excludes `0/O`, `1/I/L`, `5/S` and `U/V` — a code is read aloud or copied\n * off a terminal into a browser, and a user who mistypes it gets a failure\n * they cannot diagnose. 27 symbols over 8 characters is ~38 bits, which is\n * ample for a code that lives ten minutes, is single-use, and is rate-limited.\n */\nconst USER_CODE_ALPHABET = \"ABCDEFGHJKMNPQRTWXYZ2346789\";\n\n/** A device code: the secret the daemon polls with. Never shown to a user. */\nexport function generateDeviceCode(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/** A runner id. */\nexport function generateRunnerId(): string {\n return `runner_${randomUUID()}`;\n}\n\n/** A job id. */\nexport function generateJobId(): string {\n // A bare UUID, not a prefixed one.\n //\n // The app mints this now, because byollm_009 §6 binds the job id into the\n // envelope's signature — so the id must exist before the row does. A\n // `job_`-prefixed string is not a `uuid`, and the Supabase adapter's column\n // is, so the prefix would have made every enqueue fail there while passing\n // in memory. Ids are opaque to the protocol; the prefix was only ever\n // decoration.\n return randomUUID();\n}\n\n/**\n * A short code the user reads and confirms, formatted `XXXX-XXXX`.\n * Drawn with rejection sampling so the alphabet stays uniform.\n */\nexport function generateUserCode(): string {\n const chars: string[] = [];\n while (chars.length < 8) {\n for (const byte of randomBytes(16)) {\n // 256 % 28 !== 0, so bytes at or above the largest whole multiple are\n // discarded rather than folded — folding would bias the low symbols.\n const limit = 256 - (256 % USER_CODE_ALPHABET.length);\n if (byte >= limit) continue;\n const symbol = USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length];\n if (symbol === undefined) continue;\n chars.push(symbol);\n if (chars.length === 8) break;\n }\n }\n return `${chars.slice(0, 4).join(\"\")}-${chars.slice(4).join(\"\")}`;\n}\n\n/** SHA-256, hex. Tokens and device codes are stored only as this. */\nexport function hashSecret(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\");\n}\n\n/**\n * Compare two hex digests without leaking their difference through timing.\n * Lengths are compared first because `timingSafeEqual` throws on a mismatch.\n */\nexport function secretsMatch(aHex: string, bHex: string): boolean {\n if (aHex.length !== bHex.length) return false;\n return timingSafeEqual(Buffer.from(aHex, \"hex\"), Buffer.from(bHex, \"hex\"));\n}\n\n/**\n * A fresh id for one lease grant.\n *\n * Not a secret and not guessed at — a daemon is told its lease id in the claim\n * response. It exists to distinguish *this* grant from the next one over the\n * same job by the same runner, which is what stops a replayed release landing\n * on a lease the sender never meant.\n */\nexport const generateLeaseId = (): string => randomUUID();\n","import {\n FetchRequest,\n SealedOutcome,\n keyId,\n open,\n publicIdentityOf,\n type FetchResponse,\n RequestSignature,\n verifyRequest,\n verifyPublicIdentity,\n type StoredKeys,\n ClaimRequest,\n type ClaimRequest as ClaimRequestType,\n type HeartbeatRequest as HeartbeatRequestType,\n type ReleaseRequest as ReleaseRequestType,\n type ResultRequest as ResultRequestType,\n ERROR_STATUS,\n HeartbeatRequest,\n PairRequest,\n PROTOCOL_VERSION,\n ReleaseRequest,\n ResultRequest,\n provenanceFor,\n type ClaimResponse,\n type Endpoint,\n type HeartbeatResponse,\n type PairPollResponse,\n type PairStartResponse,\n type ReleaseResponse,\n type ResultResponse,\n type WireErrorCode,\n} from \"@byollm/protocol\";\nimport { generateDeviceCode, generateUserCode, hashSecret } from \"./ids.js\";\nimport { resealForDevice } from \"./reseal.js\";\nimport { deadlineFor } from \"./records.js\";\nimport type { JobRecord, RunnerRecord } from \"./records.js\";\nimport type { ByollmStore } from \"./store.js\";\n\n/** Everything a mount needs to serve the protocol. */\n/**\n * What a transport must hand the handler to authenticate a call.\n *\n * `rawBody` is the exact bytes received, not a re-serialisation of the parsed\n * object: JSON.stringify does not round-trip byte-for-byte, and a signature\n * over re-serialised input verifies something the sender never signed.\n */\nexport interface AuthContext {\n readonly endpoint: string;\n readonly rawBody: string;\n readonly signature: unknown;\n}\n\nexport interface HandlerConfig {\n readonly store: ByollmStore;\n /**\n * Absolute URL of the page where a user approves a pairing. The device code\n * is *not* appended — the user types the short code into the app's own\n * authenticated page, which is what keeps pairing interactive.\n */\n readonly verificationUrl: string;\n /** How long a lease lasts. Default 60s — six heartbeats of headroom. */\n readonly leaseMs?: number;\n /** How long an unapproved pairing code lives. Default 10 minutes. */\n readonly pairingTtlMs?: number;\n /** How often a daemon may poll for pairing approval. Default 2s. */\n readonly pollIntervalMs?: number;\n /** Injectable clock, so tests can move time without sleeping. */\n readonly now?: () => number;\n /**\n * This site's keypairs (byollm_009 §5) — **supplied, never generated here.**\n *\n * A site is usually more than one process. Generating keys at startup would\n * work perfectly in development and fail only in production, silently: each\n * instance would have a different identity, a daemon would pin whichever\n * one approved its pairing, and every request routed to a different\n * instance would fail a signature check it had no way to explain. So this\n * is a required input, and there is a `keygen` script that produces one.\n */\n readonly siteKeys: StoredKeys;\n}\n\nconst DEFAULTS = {\n leaseMs: 60_000,\n pairingTtlMs: 10 * 60_000,\n pollIntervalMs: 2_000,\n} as const;\n\n/** A handled protocol call: a status and a JSON body. */\nexport interface HandlerResult {\n readonly status: number;\n readonly body: unknown;\n /** Set for `rate-limited` and `server-error`. */\n readonly retryAfterSeconds?: number;\n}\n\nfunction fail(\n error: WireErrorCode,\n message: string,\n retryAfterSeconds?: number,\n): HandlerResult {\n return {\n status: ERROR_STATUS[error],\n body: {\n error,\n message,\n ...(retryAfterSeconds === undefined\n ? {}\n : { retryAfter: retryAfterSeconds }),\n },\n ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),\n };\n}\n\nfunction ok(body: unknown): HandlerResult {\n return { status: 200, body };\n}\n\n/**\n * The five protocol endpoints, over any {@link ByollmStore}.\n *\n * Transport-free on purpose: a mount adapts `Request`/`Response` (or Express,\n * or whatever) onto {@link ByollmHandlers.handle}, and everything the\n * protocol actually specifies lives here where the conformance kit can reach\n * it without an HTTP server in the way.\n */\nexport class ByollmHandlers {\n readonly #store: ByollmStore;\n readonly #verificationUrl: string;\n readonly #leaseMs: number;\n readonly #pairingTtlMs: number;\n readonly #pollIntervalMs: number;\n readonly #now: () => number;\n readonly #siteKeys: StoredKeys;\n /** This site's identity key id — Amendment A's `stub.site`. Derived once. */\n readonly #siteKeyId: string;\n\n constructor(config: HandlerConfig) {\n this.#store = config.store;\n // Fail at construction, not at the first pairing. A site whose keys are\n // malformed should not start and then refuse its users one at a time.\n if (!verifyPublicIdentity(publicIdentityOf(config.siteKeys))) {\n throw new Error(\n \"siteKeys are not internally consistent: the encryption key is not \" +\n \"signed by the identity key. Generate a fresh pair with \" +\n \"`npx @byollm/server keygen`.\",\n );\n }\n this.#siteKeys = config.siteKeys;\n this.#siteKeyId = keyId(publicIdentityOf(config.siteKeys).identity);\n this.#verificationUrl = config.verificationUrl;\n this.#leaseMs = config.leaseMs ?? DEFAULTS.leaseMs;\n this.#pairingTtlMs = config.pairingTtlMs ?? DEFAULTS.pairingTtlMs;\n this.#pollIntervalMs = config.pollIntervalMs ?? DEFAULTS.pollIntervalMs;\n this.#now = config.now ?? Date.now;\n }\n\n /**\n * Dispatch one protocol call.\n *\n * @param endpoint - which of the five, already routed from the path\n * @param body - the parsed JSON request body, untrusted\n * @param auth - the signature and the exact bytes it covers\n */\n async handle(\n endpoint: Endpoint,\n body: unknown,\n auth: AuthContext,\n ): Promise<HandlerResult> {\n switch (endpoint) {\n case \"pair\":\n return this.#pair(body);\n case \"claim\":\n return this.#authed(auth, body, ClaimRequest, this.#claim.bind(this));\n case \"heartbeat\":\n // Heartbeat is the channel revocation travels on, so a revoked runner\n // must reach the handler and be told `revoked: true` rather than be\n // bounced with a 403 it would treat as a transport problem\n // ({@link MUSTS.REVOCATION_HONORED}).\n return this.#authed(\n auth,\n body,\n HeartbeatRequest,\n this.#heartbeat.bind(this),\n { allowRevoked: true },\n );\n case \"fetch\":\n return this.#authed(auth, body, FetchRequest, this.#fetch.bind(this));\n case \"result\":\n return this.#authed(auth, body, ResultRequest, this.#result.bind(this));\n case \"release\":\n return this.#authed(\n auth,\n body,\n ReleaseRequest,\n this.#release.bind(this),\n );\n }\n }\n\n /**\n * Shared preamble for the four authenticated endpoints: verify the\n * signature, reject a revoked runner, and parse the body.\n *\n * Authentication happens before schema validation so a stranger probing the\n * endpoint learns nothing about the wire format.\n */\n async #authed<T>(\n auth: AuthContext,\n body: unknown,\n schema: { safeParse: (v: unknown) => { success: boolean; data?: T } },\n run: (request: T, runner: RunnerRecord) => Promise<HandlerResult>,\n options: { allowRevoked?: boolean } = {},\n ): Promise<HandlerResult> {\n const signature = RequestSignature.safeParse(auth.signature);\n if (!signature.success) {\n return fail(\"unauthorized\", \"this request is not signed\");\n }\n\n const runner = await this.#store.getRunner(signature.data.runnerId);\n if (!runner) {\n return fail(\"unauthorized\", \"this runner is not recognised\");\n }\n\n // Verified against the identity pinned when the user approved this\n // machine — not against anything the request carries. A signature that\n // authenticates itself authenticates nothing.\n const failure = verifyRequest({\n identityPublic: runner.device.identity,\n endpoint: auth.endpoint,\n body: auth.rawBody,\n signature: signature.data,\n now: this.#now(),\n });\n if (failure !== null) {\n // Deliberately one message for both causes. Telling a caller whether\n // their clock or their key is wrong tells an attacker which half of a\n // forgery already works.\n return fail(\"unauthorized\", \"this request's signature is not valid\");\n }\n if (runner.revokedAt !== null && options.allowRevoked !== true) {\n // A distinct truth from \"unauthorized\": the daemon should stop and say\n // so, not retry or re-pair silently.\n return fail(\"revoked\", \"this runner has been revoked by its owner\");\n }\n\n const parsed = schema.safeParse(body);\n if (!parsed.success || parsed.data === undefined) {\n return fail(\"bad-request\", \"request body failed schema validation\");\n }\n return run(parsed.data, runner);\n }\n\n /**\n * Hand over the payload for a lease this runner holds — byollm_009 §6.\n *\n * The second half of claim-then-fetch. A claim answers with a stub, and the\n * work itself is collected separately by the device that took it, because a\n * payload can only be sealed once its recipient is known.\n *\n * Scoped to the lease, not the job: answering for whatever lease happens to\n * exist would hand the work to a runner whose grant had already been\n * superseded.\n */\n async #fetch(\n request: FetchRequest,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n const job = await this.#store.get(request.jobId);\n if (\n !job ||\n job.lease?.runnerId !== runner.id ||\n job.lease.id !== request.leaseId\n ) {\n // One answer for \"no such job\", \"not yours\" and \"a lease you no longer\n // hold\". A caller who is allowed to know already knows which.\n return fail(\"not-found\", \"no such lease on this job\");\n }\n // One implementation of open-and-reseal, shared with the cloud lane: the\n // deadline and key ids are bound into a signature, and two copies of a\n // bound value is the bug this codebase keeps finding.\n const resealed = await resealForDevice({\n siteKeys: this.#siteKeys,\n job: { id: job.id, envelope: job.envelope, createdAt: job.createdAt },\n device: runner.device,\n });\n if (!resealed.ok) {\n return fail(\"server-error\", \"this job's payload could not be opened\");\n }\n return ok({ envelope: resealed.envelope } satisfies FetchResponse);\n }\n\n // -- 1. pair --------------------------------------------------------------\n\n async #pair(body: unknown): Promise<HandlerResult> {\n const parsed = PairRequest.safeParse(body);\n if (!parsed.success) {\n return fail(\"bad-request\", \"pair request failed schema validation\");\n }\n const request = parsed.data;\n const now = this.#now();\n\n if (request.action === \"start\") {\n const deviceCode = generateDeviceCode();\n const userCode = generateUserCode();\n const expiresAt = now + this.#pairingTtlMs;\n\n // The machine must prove its encryption key belongs to the identity it\n // is presenting, before either is stored. Otherwise a caller could pair\n // a real identity with an encryption key it holds the secret for, and\n // read everything later sealed to that runner.\n if (!verifyPublicIdentity(request.device)) {\n return fail(\n \"bad-request\",\n \"the device's encryption key is not signed by the identity it was presented with\",\n );\n }\n\n await this.#store.createPairing({\n device: request.device,\n deviceCodeHash: hashSecret(deviceCode),\n userCode,\n state: \"pending\",\n owner: null,\n runnerId: null,\n collected: false,\n label: request.daemon.label,\n platform: request.daemon.platform,\n daemonVersion: request.daemon.version,\n capabilities: request.capabilities,\n expiresAt,\n createdAt: now,\n });\n\n const response: PairStartResponse = {\n deviceCode,\n userCode,\n verificationUrl: this.#verificationUrl,\n expiresAt,\n pollIntervalMs: this.#pollIntervalMs,\n };\n return ok(response);\n }\n\n // action === \"poll\"\n const pairing = await this.#store.getPairingByDeviceCodeHash(\n hashSecret(request.deviceCode),\n );\n if (!pairing) {\n return fail(\"not-found\", \"unknown device code\");\n }\n if (pairing.state === \"denied\") {\n return ok({ status: \"denied\" } satisfies PairPollResponse);\n }\n // Expiry is checked before approval state so a code approved after it\n // lapsed is still dead ({@link MUSTS.PAIR_CODE_EXPIRES}).\n if (pairing.expiresAt <= now && pairing.state === \"pending\") {\n return ok({ status: \"expired\" } satisfies PairPollResponse);\n }\n if (\n pairing.state === \"approved\" &&\n !pairing.collected &&\n pairing.runnerId !== null &&\n pairing.owner !== null\n ) {\n const response: PairPollResponse = {\n status: \"approved\",\n runnerId: pairing.runnerId,\n owner: pairing.owner,\n // Only on approval: a pending or denied poll learns nothing, so an\n // unapproved code cannot be used to enumerate a site's keys.\n site: publicIdentityOf(this.#siteKeys),\n };\n // Delivered exactly once — a replayed device code gets nothing.\n await this.#store.consumePairingToken(pairing.deviceCodeHash);\n return ok(response);\n }\n if (pairing.state === \"approved\") {\n return fail(\"not-found\", \"this pairing has already been collected\");\n }\n return ok({ status: \"pending\" } satisfies PairPollResponse);\n }\n\n // -- 2. claim -------------------------------------------------------------\n\n async #claim(\n request: ClaimRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n\n // Capabilities from *this* request, never the stored matrix — a daemon\n // that just lost a backend must not be handed work for it\n // ({@link MUSTS.CLAIM_REQUIRES_CAPABILITY}).\n const jobs = await this.#store.claim({\n runnerId: runner.id,\n runnerOwner: runner.owner,\n capabilities: request.capabilities,\n max: request.max,\n leaseMs: this.#leaseMs,\n now,\n });\n\n const response: ClaimResponse = {\n jobs: jobs.map((job) => ({\n id: job.id,\n kind: job.kind,\n audience: job.audience,\n owner: job.owner,\n // This site, named by its identity key id — Amendment A §A.3. The\n // daemon pinned this exact value at pairing, so it can check the stub\n // against the envelope it later opens rather than taking our word for\n // which site sent it. On this plane that is redundant, which is the\n // point: the direct and relayed stubs are the same shape, and a daemon\n // serving both cannot tell which upstream it is talking to.\n site: this.#siteKeyId,\n // Bucketed, not measured: an exact size is a stronger fingerprint\n // than routing needs (byollm_009 §6).\n sizeClass: job.sizeClass,\n // Reserved for byollm_006; no job declares it yet.\n streaming: false,\n // The stub's deadline bounds how long a captured envelope is worth\n // keeping, so it is always present — falling back to the TTL window\n // when the app named no absolute one.\n deadlineAt: deadlineFor(job, now),\n // `audienceAllow` is not sent — cloud_008 §0.2. The list stays on\n // `JobRecord`, where `claim` already filtered candidates with it; the\n // daemon's own allowlist is what decides `named` (byollm_001 Rev 1\n // §B) and always was.\n //\n // Removing it from `JobStub` did **not** make this line a type error.\n // A conditional spread is not excess-property-checked, so the field\n // would have gone on being sent to a daemon whose `.strict()` parse\n // now rejects the entire claim response — every daemon on the version\n // pair, refusing all work, for a field nobody read. Worth stating\n // where it happened: the schema is the contract, and the compiler\n // does not enforce it through a spread.\n // No fallback. A job returned from `claim` holds a lease by\n // definition, and synthesising one here would hand the daemon a lease\n // id the store has never heard of — every later release naming it\n // would silently match nothing. A store that returns an unleased job\n // has broken its contract, and this says so.\n lease: leaseOf(job),\n })),\n leaseMs: this.#leaseMs,\n };\n return ok(response);\n }\n\n // -- 3. heartbeat ---------------------------------------------------------\n\n async #heartbeat(\n request: HeartbeatRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n const revoked = runner.revokedAt !== null;\n\n if (revoked) {\n // Nothing is renewed for a revoked runner: every job it holds is\n // reported lost so it abandons the queue rather than finishing it.\n const held = await this.#store.listClaimedBy(runner.id);\n const response: HeartbeatResponse = {\n revoked: true,\n cancel: [],\n lost: held.map((job) => job.id),\n serverTime: now,\n };\n return ok(response);\n }\n\n await this.#store.touchRunner({\n runnerId: runner.id,\n capabilities: request.capabilities,\n daemonVersion: request.daemonVersion,\n paused: request.paused,\n now,\n });\n\n // `renewed` is not reported back — cloud_008 §1.4b. The grants are still\n // extended; the daemon simply never read the list, and `lost` is the\n // signal it acts on.\n const { lost } = await this.#store.renewLeases({\n runnerId: runner.id,\n leases: request.activeLeases,\n leaseMs: this.#leaseMs,\n now,\n });\n\n const cancel = await this.#store.listCancelRequests(runner.id);\n\n const response: HeartbeatResponse = {\n revoked: false,\n cancel,\n lost: [...lost],\n serverTime: now,\n };\n return ok(response);\n }\n\n // -- 4. result ------------------------------------------------------------\n\n async #result(\n request: ResultRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n const job = await this.#store.get(request.jobId);\n if (!job) return fail(\"not-found\", \"unknown job\");\n\n const outcome = await this.#openResult(request, runner);\n if (!outcome.ok) return outcome.failure;\n\n // Provenance is built here, from the job's audience and the authenticated\n // runner — never from anything the daemon asserted\n // ({@link MUSTS.PROVENANCE_NAMES_DEVICE}).\n const provenance = provenanceFor({\n audience: job.audience,\n runnerId: runner.id,\n runnerOwner: runner.owner,\n // From the envelope the device signed, not from the request beside it\n // — cloud_008 §2.5. A daemon can no longer seal one answer and declare\n // it came from a different model.\n backendClass: outcome.value.ran.backendClass,\n model: outcome.value.ran.model,\n });\n\n const {\n accepted,\n duplicate,\n job: updated,\n } = await this.#store.complete({\n jobId: request.jobId,\n // Who is asking, for the duplicate answer only — §3.6. Authorisation\n // is `holder`, below, and still is.\n runnerId: runner.id,\n // The grant, not the runner — cloud_008 §1.4a. `CompleteHolder`'s own\n // docstring already called the lease \"the more exact check anyway\";\n // this plane simply had no lease id to give it until now.\n holder: { by: \"lease\", leaseId: request.leaseId },\n outcome: outcome.value.outcome,\n provenance,\n now,\n });\n\n const response: ResultResponse = {\n accepted,\n // Only when true — cloud_008 §3.6. Absent means \"not a duplicate\", and\n // an optional field that is always present is a required one wearing a\n // question mark.\n ...(duplicate === true ? { duplicate: true } : {}),\n state: updated?.state ?? job.state,\n };\n return ok(response);\n }\n\n /**\n * Open a sealed result, or refuse it.\n *\n * The mirror of the daemon's `#openPayload`, and refuses for the same\n * reason: an outcome that does not verify against the device's pinned key is\n * an assertion by whoever relayed it, and storing it would let an\n * intermediary write answers into the app.\n *\n * The clear-text `disposition` is checked here rather than trusted. It is on\n * the wire so a relay can route without opening anything, which means the\n * one thing it must not be is authoritative — a daemon that sealed an error\n * and declared `ok` would otherwise have its declaration believed by\n * everything upstream of this line.\n */\n async #openResult(\n request: ResultRequestType,\n runner: RunnerRecord,\n ): Promise<\n { ok: true; value: SealedOutcome } | { ok: false; failure: HandlerResult }\n > {\n const refuse = (why: string) =>\n ({ ok: false as const, failure: fail(\"bad-request\", why) }) as const;\n\n const opened = await open({\n envelope: request.envelope,\n recipientKeys: this.#siteKeys,\n senderIdentityPublic: runner.device.identity,\n expected: {\n jobId: request.jobId,\n senderKeyId: keyId(runner.device.identity),\n recipientKeyId: keyId(publicIdentityOf(this.#siteKeys).identity),\n direction: \"result\",\n },\n });\n if (!opened.ok) {\n return refuse(\"the result did not verify as coming from this device\");\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(opened.plaintext);\n } catch {\n return refuse(\"the sealed result was not valid JSON\");\n }\n const sealed = SealedOutcome.safeParse(parsed);\n if (!sealed.success) return refuse(\"the sealed result was not an outcome\");\n\n if (sealed.data.outcome.outcome !== request.disposition) {\n return refuse(\"the declared disposition is not the one that was sealed\");\n }\n return { ok: true, value: sealed.data };\n }\n\n // -- 5. release -----------------------------------------------------------\n\n async #release(\n request: ReleaseRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const released = await this.#store.release({\n runnerId: runner.id,\n leases: request.leases,\n reason: request.reason,\n now: this.#now(),\n });\n const response: ReleaseResponse = { released };\n return ok(response);\n }\n}\n\n/** The protocol version this build speaks. */\nexport const SERVED_PROTOCOL_VERSION = PROTOCOL_VERSION;\n\n/** The lease a claimed job must have, or a loud failure. */\nfunction leaseOf(job: JobRecord): NonNullable<JobRecord[\"lease\"]> {\n if (!job.lease) {\n throw new Error(\n `store returned job ${job.id} from claim with no lease — the store ` +\n `contract requires a claimed job to hold one`,\n );\n }\n return job.lease;\n}\n","import {\n ENVELOPE_MAX_AGE_MS,\n keyId,\n open,\n publicIdentityOf,\n seal,\n type PublicIdentity,\n type SealedEnvelope,\n type StoredKeys,\n} from \"@byollm/protocol\";\n\n/**\n * Open this site's own at-rest envelope and re-seal it to a claiming device.\n *\n * The single operation that makes byollm_009 §6 work, and it now has two\n * callers: {@link ByollmHandlers} answering `fetch` on the direct plane, and\n * the cloud lane answering the relay's \"who claimed it\" poll. Both do exactly\n * this, and the reason it lives in one file is the reason everything else in\n * this codebase does: the deadline, the key ids and the direction are all\n * bound into a signature, and two implementations of a bound value is the same\n * bug as two clock readings — it works until they disagree, and then nothing\n * opens.\n *\n * The plaintext exists for one statement and never reaches a wire, a store, or\n * a log. That is the whole guarantee: the site is an endpoint, so it is\n * entitled to read its own work, and it is the only party between the app and\n * the device that is.\n */\n\ntype ResealFailure = \"unopenable\";\n\nexport type ResealResult =\n | { readonly ok: true; readonly envelope: SealedEnvelope }\n | { readonly ok: false; readonly reason: ResealFailure };\n\nexport async function resealForDevice(input: {\n siteKeys: StoredKeys;\n /** The job's identity and its at-rest ciphertext. */\n job: {\n readonly id: string;\n readonly envelope: SealedEnvelope;\n readonly createdAt: number;\n };\n /** The device that claimed it, as the upstream reported. */\n device: PublicIdentity;\n}): Promise<ResealResult> {\n const senderKeyId = keyId(publicIdentityOf(input.siteKeys).identity);\n\n const opened = await open({\n envelope: input.job.envelope,\n recipientKeys: input.siteKeys,\n senderIdentityPublic: input.siteKeys.identityPublic,\n expected: {\n jobId: input.job.id,\n senderKeyId,\n recipientKeyId: senderKeyId,\n direction: \"payload\",\n },\n });\n if (!opened.ok) {\n // The store holds something this site cannot open: rotated keys, a\n // corrupted row, or someone else's envelope. Not the device's problem and\n // not something a retry fixes.\n return { ok: false, reason: \"unopenable\" };\n }\n\n const envelope = await seal({\n plaintext: opened.plaintext,\n senderKeys: input.siteKeys,\n recipientEncryptionPublic: input.device.encryption,\n context: {\n jobId: input.job.id,\n senderKeyId,\n recipientKeyId: keyId(input.device.identity),\n // From the record, never recomputed from a fresh clock read — the\n // envelope's own deadline is what the signature bound.\n deadlineAt: input.job.createdAt + ENVELOPE_MAX_AGE_MS,\n direction: \"payload\",\n },\n });\n return { ok: true, envelope };\n}\n","import type {\n PublicIdentity,\n Audience,\n Capability,\n JobKind,\n JobOutcome,\n JobPayload,\n SealedEnvelope,\n SizeClass,\n JobState,\n Lease,\n ResultProvenance,\n} from \"@byollm/protocol\";\n\n/**\n * A job as the server stores it.\n *\n * Adapters map this shape onto their own storage; the field meanings are\n * normative because the conformance kit asserts behaviour that depends on\n * them (TTL clock start, dependency gating, refusal tracking).\n */\nexport interface JobRecord {\n readonly id: string;\n readonly kind: JobKind;\n /**\n * The work, sealed to this site's own encryption key (byollm_009 §10).\n *\n * The store never holds plaintext. The app sees plaintext at enqueue and at\n * result because the app *is* the endpoint; everything in between —\n * database, backups, log aggregators, a support engineer with read access —\n * sees ciphertext.\n *\n * This is not protection from the application the user deliberately sent\n * their work to. It is protection from everything the application's storage\n * touches, which is a longer list than most people picture.\n */\n readonly envelope: SealedEnvelope;\n /** Fixed at enqueue, where the plaintext is. */\n readonly sizeClass: SizeClass;\n readonly audience: Audience;\n /** The app's id for the user who enqueued it. */\n readonly owner: string;\n /** Server-side restriction on which runner owners may take a `named` job. */\n readonly audienceAllow: readonly string[] | undefined;\n /** Job ids that must all be `ok` before this becomes claimable. */\n readonly dependsOn: readonly string[];\n readonly state: JobState;\n readonly lease: Lease | null;\n /**\n * The grant that recorded this job's result — cloud_008 §3.6.\n *\n * Kept after `lease` is nulled, because \"who finished this\" outlives \"who\n * holds this\" and the two are asked for different reasons. It is what lets\n * a replay from the device that finished the job be answered *as a\n * duplicate* rather than as a stale lease — and lets a replay from any\n * other device be refused exactly as it would be for a job that is not\n * terminal, so a job id is not a terminality probe.\n */\n readonly completedByLeaseId: string | null;\n readonly createdAt: number;\n /**\n * When the job became claimable — enqueue time for a job with no\n * dependencies, or the moment its last dependency reached `ok`.\n *\n * **The TTL clock starts here, not at `createdAt`.** Starting it at enqueue\n * would expire a dependent job for the crime of waiting on a slow\n * dependency (byollm_001 Rev 1 §D, TTL clock resolved in build review).\n * `null` means still blocked.\n */\n readonly claimableAt: number | null;\n /** How long an unclaimed job may wait once claimable. */\n readonly ttlMs: number;\n /** Optional absolute deadline, independent of the TTL. */\n readonly deadlineAt: number | null;\n /**\n * Runners that released this job with reason `refused` — their local\n * allowlist declined it. Never offered to them again\n * ({@link MUSTS.REFUSAL_NOT_REOFFERED}).\n */\n readonly refusedBy: readonly string[];\n /** How many times this job has been claimed, including lease-expiry retries. */\n readonly attempts: number;\n readonly outcome: JobOutcome | null;\n readonly provenance: ResultProvenance | null;\n readonly updatedAt: number;\n}\n\n/** A paired daemon as the server stores it. */\nexport interface RunnerRecord {\n readonly id: string;\n /** The app's id for the user this runner is bound to — exactly one. */\n readonly owner: string;\n readonly label: string;\n readonly platform: \"darwin\" | \"linux\" | \"win32\";\n readonly daemonVersion: string;\n readonly capabilities: readonly Capability[];\n readonly paused: boolean;\n /** Set once; a revoked runner never un-revokes. */\n readonly revokedAt: number | null;\n readonly lastHeartbeatAt: number;\n readonly createdAt: number;\n /**\n * The device's pinned public keys. What later signatures verify against —\n * a runner id names a machine, this proves it.\n */\n readonly device: PublicIdentity;\n}\n\n/** An in-flight device-code pairing. */\nexport interface PairingRecord {\n /** SHA-256 of the device code. The code itself is never stored. */\n readonly deviceCodeHash: string;\n /** The short code the user reads. Unique among live pairings. */\n readonly userCode: string;\n readonly state: \"pending\" | \"approved\" | \"denied\";\n /** Set when approved — learned from the approving user's own session. */\n readonly owner: string | null;\n readonly runnerId: string | null;\n /**\n * Whether this approval has already been collected — cloud_008 §2.4.\n *\n * This was `runnerTokenOnce`, a bearer token held until the daemon's next\n * poll and then nulled. The token is gone (finding 37: minted, hashed,\n * written to two disks, never sent or compared), but the *deliver-once*\n * property it carried is real and separate: a replayed device code must get\n * nothing, or a code seen in a shell history is a second pairing.\n *\n * So the flag stays and the secret does not. Nulling a token to mean\n * \"collected\" was one field doing two jobs, and only one of them was load\n * bearing.\n */\n readonly collected: boolean;\n readonly label: string;\n readonly platform: \"darwin\" | \"linux\" | \"win32\";\n readonly daemonVersion: string;\n readonly capabilities: readonly Capability[];\n /**\n * The device's public keys, presented at pair start (byollm_009 §5).\n *\n * Kept on the pairing so the approving user is approving a *specific\n * machine*, not a code that any machine could later redeem. It is copied\n * onto the runner at approval.\n */\n readonly device: PublicIdentity;\n readonly expiresAt: number;\n readonly createdAt: number;\n}\n\n/** What the app supplies to enqueue a job. */\nexport interface EnqueueInput {\n readonly kind: JobKind;\n /** The work, in plaintext. The server seals it before it is stored. */\n readonly payload: JobPayload;\n readonly owner: string;\n /** Defaults to `self` — the safe direction. */\n readonly audience?: Audience;\n readonly audienceAllow?: readonly string[];\n readonly dependsOn?: readonly string[];\n /** Defaults to the server config's `defaultTtlMs`. */\n readonly ttlMs?: number;\n readonly deadlineAt?: number;\n /** Caller-supplied id, for idempotent enqueue. */\n readonly id?: string;\n}\n\n/**\n * What the *store* is given — the sealed form.\n *\n * Distinct from {@link EnqueueInput} because the two are genuinely different\n * things: an app hands over work in plaintext, and what gets written down is\n * sealed. Collapsing them into one type would mean a field that is sometimes\n * readable and sometimes not, which is the kind of ambiguity that ends with\n * plaintext in a database.\n */\nexport interface StoredJobInput extends Omit<EnqueueInput, \"payload\" | \"id\"> {\n readonly id: string;\n readonly envelope: SealedEnvelope;\n readonly sizeClass: SizeClass;\n}\n\n/**\n * When a job's ciphertext stops being worth carrying — cloud_008 §31.\n *\n * One function because it was two expressions. The direct plane computed\n * `job.deadlineAt ?? (job.claimableAt ?? now) + job.ttlMs`; the cloud lane\n * computed `record.deadlineAt ?? record.createdAt + <a local constant>`. The\n * first branch agreed and the fallback did not, so a job with no explicit\n * deadline got two different ones depending on which lane published it — and\n * the difference is largest exactly where it matters, for a job blocked on a\n * dependency, whose `claimableAt` may be hours after `createdAt`.\n *\n * The TTL clock starts when a job becomes *claimable*, which is the rule\n * `DEPENDS_ON_GATING` and `TTL_EXPIRY` already share: a dependent job must not\n * spend its life waiting for its dependency.\n */\nexport function deadlineFor(\n job: Pick<JobRecord, \"deadlineAt\" | \"claimableAt\" | \"ttlMs\">,\n now: number,\n): number {\n return job.deadlineAt ?? (job.claimableAt ?? now) + job.ttlMs;\n}\n","import {\n ENDPOINTS,\n ERROR_STATUS,\n PROTOCOL_PREFIX,\n checkProtocolVersion,\n type Endpoint,\n} from \"@byollm/protocol\";\nimport { ByollmHandlers, type HandlerConfig } from \"./handlers.js\";\n\n/**\n * Largest protocol request body accepted, before schema validation.\n *\n * A payload is capped at 4 MB of text by the protocol; this leaves room for\n * JSON overhead and a batch of results, and refuses anything wilder at the\n * door rather than after parsing it.\n */\nconst MAX_BODY_BYTES = 8 * 1024 * 1024;\n\n/**\n * Where the protocol endpoints are mounted.\n *\n * Defaults to {@link PROTOCOL_PREFIX}. Pass the real mount point when it is\n * anything else — a Next.js route at `app/api/byollm/[...route]/route.ts`\n * serves `/api/byollm/...`, so it needs `basePath: \"/api/byollm\"`.\n *\n * @throws if the path is not an absolute, single-segment-per-slash path. A\n * mount point is configuration, and a malformed one should fail at startup\n * rather than silently match nothing.\n */\nfunction normalizeBasePath(basePath: string): string {\n const trimmed = basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n if (!trimmed.startsWith(\"/\")) {\n throw new Error(`basePath must start with \"/\": got ${basePath}`);\n }\n if (trimmed.includes(\"//\") || /[?#*]/.test(trimmed)) {\n throw new Error(`basePath must be a plain path: got ${basePath}`);\n }\n return trimmed;\n}\n\n/**\n * Pull the endpoint name out of a URL path, or null if it isn't ours.\n *\n * The full path must match `<basePath>/<endpoint>` exactly. This used to\n * compare only the *last* segment, which meant `/anything/at/all/claim`\n * dispatched to `claim` and {@link PROTOCOL_PREFIX} was decorative — it\n * appeared in a 404 message and was never matched against. For the handler\n * that serves claim, result and heartbeat, dispatching on a suffix is a\n * looser rule than anyone reading the constant would assume, and loose\n * matching in a security surface should at least be a decision.\n *\n * The cost is that the mount point is now something a deployment has to state\n * rather than something that works by accident. That is the intended trade:\n * a 404 at startup naming the mount point beats a handler answering on paths\n * nobody meant to expose.\n */\nexport function routeEndpoint(\n pathname: string,\n basePath: string = PROTOCOL_PREFIX,\n): Endpoint | null {\n const base = normalizeBasePath(basePath);\n const path = pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n if (!path.startsWith(`${base}/`)) return null;\n const rest = path.slice(base.length + 1);\n return (ENDPOINTS as readonly string[]).includes(rest)\n ? (rest as Endpoint)\n : null;\n}\n\n/**\n * Read the request signature from headers (byollm_009 §4.2).\n *\n * In headers rather than the body so the signature covers the body whole,\n * with no field to exclude from its own hash — a scheme that signs a body\n * minus one field has to agree, byte for byte, on how that field is removed.\n */\nexport function signatureFrom(headers: Headers): unknown {\n const runnerId = headers.get(\"x-byollm-runner\");\n const rawIssuedAt = headers.get(\"x-byollm-issued-at\");\n const signature = headers.get(\"x-byollm-signature\");\n if (runnerId === null || signature === null || rawIssuedAt === null) {\n return undefined;\n }\n // Checked against null *before* Number(), because `Number(null)` is 0 —\n // finite, plausible-looking, and wrong. A missing timestamp would have\n // become a timestamp of the epoch, which the freshness check would then\n // reject for the wrong reason.\n const issuedAt = Number(rawIssuedAt);\n if (!Number.isFinite(issuedAt)) return undefined;\n return { runnerId, issuedAt, signature };\n}\n\n/**\n * A `Request` → `Response` handler for the whole protocol.\n *\n * Web-standard types, so this works unchanged in Next.js route handlers, Hono,\n * Bun, Deno, Cloudflare Workers, and anything else that speaks fetch.\n */\nexport function createFetchHandler(\n config: HandlerConfig & {\n /**\n * Where these endpoints are mounted. Defaults to\n * {@link PROTOCOL_PREFIX}; set it when the app serves them elsewhere.\n */\n readonly basePath?: string;\n },\n): (request: Request) => Promise<Response> {\n const handlers = new ByollmHandlers(config);\n // Validate once, at construction: a bad mount point is a deployment bug and\n // should surface when the server starts, not as a silent 404 per request.\n const basePath = normalizeBasePath(config.basePath ?? PROTOCOL_PREFIX);\n\n return async function handle(request: Request): Promise<Response> {\n if (request.method !== \"POST\") {\n return json(405, {\n error: \"bad-request\",\n message: \"protocol endpoints accept POST only\",\n });\n }\n\n const endpoint = routeEndpoint(new URL(request.url).pathname, basePath);\n if (endpoint === null) {\n return json(404, {\n error: \"not-found\",\n message: `not a ${basePath} endpoint`,\n });\n }\n\n const declared = request.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > MAX_BODY_BYTES) {\n return json(400, {\n error: \"bad-request\",\n message: \"request body too large\",\n });\n }\n\n let body: unknown;\n let rawBody: string;\n try {\n rawBody = await request.text();\n const text = rawBody;\n if (text.length > MAX_BODY_BYTES) {\n return json(400, {\n error: \"bad-request\",\n message: \"request body too large\",\n });\n }\n body = JSON.parse(text);\n } catch {\n // Deliberately not echoing the parse error: it would quote attacker\n // input back into a response an operator later reads in a terminal.\n return json(400, {\n error: \"bad-request\",\n message: \"request body is not valid JSON\",\n });\n }\n\n // byollm_009 §4: version before anything else. A mismatch must name the\n // disagreement and the fix, not surface as a generic bad-request from a\n // schema literal buried in an endpoint — which is what happened before,\n // and is why \"the connection is versionless\" was listed as a defect.\n const refusal = checkProtocolVersion(body);\n if (refusal) {\n return json(ERROR_STATUS[refusal.error], refusal);\n }\n\n const result = await handlers.handle(endpoint, body, {\n endpoint,\n // The bytes as received. Re-serialising the parsed object would verify\n // a signature over something the sender never sent.\n rawBody,\n signature: signatureFrom(request.headers),\n });\n\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n };\n if (result.retryAfterSeconds !== undefined) {\n headers[\"retry-after\"] = String(result.retryAfterSeconds);\n }\n return new Response(JSON.stringify(result.body), {\n status: result.status,\n headers,\n });\n };\n}\n\nfunction json(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n },\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP,IAAM,qBAAqB;AAGpB,SAAS,qBAA6B;AAC3C,SAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AAC7C;AAGO,SAAS,mBAA2B;AACzC,SAAO,UAAU,WAAW,CAAC;AAC/B;AAGO,SAAS,gBAAwB;AAStC,SAAO,WAAW;AACpB;AAMO,SAAS,mBAA2B;AACzC,QAAM,QAAkB,CAAC;AACzB,SAAO,MAAM,SAAS,GAAG;AACvB,eAAW,QAAQ,YAAY,EAAE,GAAG;AAGlC,YAAM,QAAQ,MAAO,MAAM,mBAAmB;AAC9C,UAAI,QAAQ,MAAO;AACnB,YAAM,SAAS,mBAAmB,OAAO,mBAAmB,MAAM;AAClE,UAAI,WAAW,OAAW;AAC1B,YAAM,KAAK,MAAM;AACjB,UAAI,MAAM,WAAW,EAAG;AAAA,IAC1B;AAAA,EACF;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,CAAC,EAAE,KAA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