@byollm/server 0.1.0-alpha.2 → 0.1.0-alpha.22

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.
@@ -0,0 +1,659 @@
1
+ // src/ids.ts
2
+ import {
3
+ createHash,
4
+ randomBytes,
5
+ randomUUID,
6
+ timingSafeEqual
7
+ } from "crypto";
8
+ var USER_CODE_ALPHABET = "ABCDEFGHJKMNPQRTWXYZ2346789";
9
+ function generateDeviceCode() {
10
+ return randomBytes(32).toString("base64url");
11
+ }
12
+ function generateRunnerId() {
13
+ return `runner_${randomUUID()}`;
14
+ }
15
+ function generateJobId() {
16
+ return randomUUID();
17
+ }
18
+ function generateUserCode() {
19
+ const chars = [];
20
+ while (chars.length < 8) {
21
+ for (const byte of randomBytes(16)) {
22
+ const limit = 256 - 256 % USER_CODE_ALPHABET.length;
23
+ if (byte >= limit) continue;
24
+ const symbol = USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length];
25
+ if (symbol === void 0) continue;
26
+ chars.push(symbol);
27
+ if (chars.length === 8) break;
28
+ }
29
+ }
30
+ return `${chars.slice(0, 4).join("")}-${chars.slice(4).join("")}`;
31
+ }
32
+ function hashSecret(secret) {
33
+ return createHash("sha256").update(secret, "utf8").digest("hex");
34
+ }
35
+ function secretsMatch(aHex, bHex) {
36
+ if (aHex.length !== bHex.length) return false;
37
+ return timingSafeEqual(Buffer.from(aHex, "hex"), Buffer.from(bHex, "hex"));
38
+ }
39
+ var generateLeaseId = () => randomUUID();
40
+
41
+ // src/handlers.ts
42
+ import {
43
+ FetchRequest,
44
+ SealedOutcome,
45
+ keyId as keyId2,
46
+ open as open2,
47
+ publicIdentityOf as publicIdentityOf2,
48
+ RequestSignature,
49
+ verifyRequest,
50
+ verifyPublicIdentity,
51
+ ClaimRequest,
52
+ ERROR_STATUS,
53
+ HeartbeatRequest,
54
+ PairRequest,
55
+ PROTOCOL_VERSION,
56
+ ReleaseRequest,
57
+ ResultRequest,
58
+ provenanceFor
59
+ } from "@byollm/protocol";
60
+
61
+ // src/reseal.ts
62
+ import {
63
+ ENVELOPE_MAX_AGE_MS,
64
+ keyId,
65
+ open,
66
+ publicIdentityOf,
67
+ seal
68
+ } from "@byollm/protocol";
69
+ async function resealForDevice(input) {
70
+ const senderKeyId = keyId(publicIdentityOf(input.siteKeys).identity);
71
+ const opened = await open({
72
+ envelope: input.job.envelope,
73
+ recipientKeys: input.siteKeys,
74
+ senderIdentityPublic: input.siteKeys.identityPublic,
75
+ expected: {
76
+ jobId: input.job.id,
77
+ senderKeyId,
78
+ recipientKeyId: senderKeyId,
79
+ direction: "payload"
80
+ }
81
+ });
82
+ if (!opened.ok) {
83
+ return { ok: false, reason: "unopenable" };
84
+ }
85
+ const envelope = await seal({
86
+ plaintext: opened.plaintext,
87
+ senderKeys: input.siteKeys,
88
+ recipientEncryptionPublic: input.device.encryption,
89
+ context: {
90
+ jobId: input.job.id,
91
+ senderKeyId,
92
+ recipientKeyId: keyId(input.device.identity),
93
+ // From the record, never recomputed from a fresh clock read — the
94
+ // envelope's own deadline is what the signature bound.
95
+ deadlineAt: input.job.createdAt + ENVELOPE_MAX_AGE_MS,
96
+ direction: "payload"
97
+ }
98
+ });
99
+ return { ok: true, envelope };
100
+ }
101
+
102
+ // src/records.ts
103
+ function deadlineFor(job, now) {
104
+ return job.deadlineAt ?? (job.claimableAt ?? now) + job.ttlMs;
105
+ }
106
+
107
+ // src/handlers.ts
108
+ var DEFAULTS = {
109
+ leaseMs: 6e4,
110
+ pairingTtlMs: 10 * 6e4,
111
+ pollIntervalMs: 2e3
112
+ };
113
+ function fail(error, message, retryAfterSeconds) {
114
+ return {
115
+ status: ERROR_STATUS[error],
116
+ body: {
117
+ error,
118
+ message,
119
+ ...retryAfterSeconds === void 0 ? {} : { retryAfter: retryAfterSeconds }
120
+ },
121
+ ...retryAfterSeconds === void 0 ? {} : { retryAfterSeconds }
122
+ };
123
+ }
124
+ function ok(body) {
125
+ return { status: 200, body };
126
+ }
127
+ var ByollmHandlers = class {
128
+ #store;
129
+ #verificationUrl;
130
+ #leaseMs;
131
+ #pairingTtlMs;
132
+ #pollIntervalMs;
133
+ #now;
134
+ #siteKeys;
135
+ /** This site's identity key id — Amendment A's `stub.site`. Derived once. */
136
+ #siteKeyId;
137
+ constructor(config) {
138
+ this.#store = config.store;
139
+ if (!verifyPublicIdentity(publicIdentityOf2(config.siteKeys))) {
140
+ throw new Error(
141
+ "siteKeys are not internally consistent: the encryption key is not signed by the identity key. Generate a fresh pair with `npx @byollm/server keygen`."
142
+ );
143
+ }
144
+ this.#siteKeys = config.siteKeys;
145
+ this.#siteKeyId = keyId2(publicIdentityOf2(config.siteKeys).identity);
146
+ this.#verificationUrl = config.verificationUrl;
147
+ this.#leaseMs = config.leaseMs ?? DEFAULTS.leaseMs;
148
+ this.#pairingTtlMs = config.pairingTtlMs ?? DEFAULTS.pairingTtlMs;
149
+ this.#pollIntervalMs = config.pollIntervalMs ?? DEFAULTS.pollIntervalMs;
150
+ this.#now = config.now ?? Date.now;
151
+ }
152
+ /**
153
+ * Dispatch one protocol call.
154
+ *
155
+ * @param endpoint - which of the five, already routed from the path
156
+ * @param body - the parsed JSON request body, untrusted
157
+ * @param auth - the signature and the exact bytes it covers
158
+ */
159
+ async handle(endpoint, body, auth) {
160
+ switch (endpoint) {
161
+ case "pair":
162
+ return this.#pair(body);
163
+ case "claim":
164
+ return this.#authed(auth, body, ClaimRequest, this.#claim.bind(this));
165
+ case "heartbeat":
166
+ return this.#authed(
167
+ auth,
168
+ body,
169
+ HeartbeatRequest,
170
+ this.#heartbeat.bind(this),
171
+ { allowRevoked: true }
172
+ );
173
+ case "fetch":
174
+ return this.#authed(auth, body, FetchRequest, this.#fetch.bind(this));
175
+ case "result":
176
+ return this.#authed(auth, body, ResultRequest, this.#result.bind(this));
177
+ case "release":
178
+ return this.#authed(
179
+ auth,
180
+ body,
181
+ ReleaseRequest,
182
+ this.#release.bind(this)
183
+ );
184
+ }
185
+ }
186
+ /**
187
+ * Shared preamble for the four authenticated endpoints: verify the
188
+ * signature, reject a revoked runner, and parse the body.
189
+ *
190
+ * Authentication happens before schema validation so a stranger probing the
191
+ * endpoint learns nothing about the wire format.
192
+ */
193
+ async #authed(auth, body, schema, run, options = {}) {
194
+ const signature = RequestSignature.safeParse(auth.signature);
195
+ if (!signature.success) {
196
+ return fail("unauthorized", "this request is not signed");
197
+ }
198
+ const runner = await this.#store.getRunner(signature.data.runnerId);
199
+ if (!runner) {
200
+ return fail("unauthorized", "this runner is not recognised");
201
+ }
202
+ const failure = verifyRequest({
203
+ identityPublic: runner.device.identity,
204
+ endpoint: auth.endpoint,
205
+ body: auth.rawBody,
206
+ signature: signature.data,
207
+ now: this.#now()
208
+ });
209
+ if (failure !== null) {
210
+ return fail("unauthorized", "this request's signature is not valid");
211
+ }
212
+ if (runner.revokedAt !== null && options.allowRevoked !== true) {
213
+ return fail("revoked", "this runner has been revoked by its owner");
214
+ }
215
+ const parsed = schema.safeParse(body);
216
+ if (!parsed.success || parsed.data === void 0) {
217
+ return fail("bad-request", "request body failed schema validation");
218
+ }
219
+ return run(parsed.data, runner);
220
+ }
221
+ /**
222
+ * Hand over the payload for a lease this runner holds — byollm_009 §6.
223
+ *
224
+ * The second half of claim-then-fetch. A claim answers with a stub, and the
225
+ * work itself is collected separately by the device that took it, because a
226
+ * payload can only be sealed once its recipient is known.
227
+ *
228
+ * Scoped to the lease, not the job: answering for whatever lease happens to
229
+ * exist would hand the work to a runner whose grant had already been
230
+ * superseded.
231
+ */
232
+ async #fetch(request, runner) {
233
+ const job = await this.#store.get(request.jobId);
234
+ if (!job || job.lease?.runnerId !== runner.id || job.lease.id !== request.leaseId) {
235
+ return fail("not-found", "no such lease on this job");
236
+ }
237
+ const resealed = await resealForDevice({
238
+ siteKeys: this.#siteKeys,
239
+ job: { id: job.id, envelope: job.envelope, createdAt: job.createdAt },
240
+ device: runner.device
241
+ });
242
+ if (!resealed.ok) {
243
+ return fail("server-error", "this job's payload could not be opened");
244
+ }
245
+ return ok({ envelope: resealed.envelope });
246
+ }
247
+ // -- 1. pair --------------------------------------------------------------
248
+ async #pair(body) {
249
+ const parsed = PairRequest.safeParse(body);
250
+ if (!parsed.success) {
251
+ return fail("bad-request", "pair request failed schema validation");
252
+ }
253
+ const request = parsed.data;
254
+ const now = this.#now();
255
+ if (request.action === "start") {
256
+ const deviceCode = generateDeviceCode();
257
+ const userCode = generateUserCode();
258
+ const expiresAt = now + this.#pairingTtlMs;
259
+ if (!verifyPublicIdentity(request.device)) {
260
+ return fail(
261
+ "bad-request",
262
+ "the device's encryption key is not signed by the identity it was presented with"
263
+ );
264
+ }
265
+ await this.#store.createPairing({
266
+ device: request.device,
267
+ deviceCodeHash: hashSecret(deviceCode),
268
+ userCode,
269
+ state: "pending",
270
+ owner: null,
271
+ runnerId: null,
272
+ collected: false,
273
+ label: request.daemon.label,
274
+ platform: request.daemon.platform,
275
+ daemonVersion: request.daemon.version,
276
+ capabilities: request.capabilities,
277
+ expiresAt,
278
+ createdAt: now
279
+ });
280
+ const response = {
281
+ deviceCode,
282
+ userCode,
283
+ verificationUrl: this.#verificationUrl,
284
+ expiresAt,
285
+ pollIntervalMs: this.#pollIntervalMs
286
+ };
287
+ return ok(response);
288
+ }
289
+ const pairing = await this.#store.getPairingByDeviceCodeHash(
290
+ hashSecret(request.deviceCode)
291
+ );
292
+ if (!pairing) {
293
+ return fail("not-found", "unknown device code");
294
+ }
295
+ if (pairing.state === "denied") {
296
+ return ok({ status: "denied" });
297
+ }
298
+ if (pairing.expiresAt <= now && pairing.state === "pending") {
299
+ return ok({ status: "expired" });
300
+ }
301
+ if (pairing.state === "approved" && !pairing.collected && pairing.runnerId !== null && pairing.owner !== null) {
302
+ const response = {
303
+ status: "approved",
304
+ runnerId: pairing.runnerId,
305
+ owner: pairing.owner,
306
+ // Only on approval: a pending or denied poll learns nothing, so an
307
+ // unapproved code cannot be used to enumerate a site's keys.
308
+ site: publicIdentityOf2(this.#siteKeys)
309
+ };
310
+ await this.#store.consumePairingToken(pairing.deviceCodeHash);
311
+ return ok(response);
312
+ }
313
+ if (pairing.state === "approved") {
314
+ return fail("not-found", "this pairing has already been collected");
315
+ }
316
+ return ok({ status: "pending" });
317
+ }
318
+ // -- 2. claim -------------------------------------------------------------
319
+ async #claim(request, runner) {
320
+ if (request.runnerId !== runner.id) {
321
+ return fail("unauthorized", "runner id does not match the signing key");
322
+ }
323
+ const now = this.#now();
324
+ const jobs = await this.#store.claim({
325
+ runnerId: runner.id,
326
+ runnerOwner: runner.owner,
327
+ capabilities: request.capabilities,
328
+ max: request.max,
329
+ leaseMs: this.#leaseMs,
330
+ now
331
+ });
332
+ const response = {
333
+ jobs: jobs.map((job) => ({
334
+ id: job.id,
335
+ kind: job.kind,
336
+ audience: job.audience,
337
+ owner: job.owner,
338
+ // This site, named by its identity key id — Amendment A §A.3. The
339
+ // daemon pinned this exact value at pairing, so it can check the stub
340
+ // against the envelope it later opens rather than taking our word for
341
+ // which site sent it. On this plane that is redundant, which is the
342
+ // point: the direct and relayed stubs are the same shape, and a daemon
343
+ // serving both cannot tell which upstream it is talking to.
344
+ site: this.#siteKeyId,
345
+ // Bucketed, not measured: an exact size is a stronger fingerprint
346
+ // than routing needs (byollm_009 §6).
347
+ sizeClass: job.sizeClass,
348
+ // Reserved for byollm_006; no job declares it yet.
349
+ streaming: false,
350
+ // The stub's deadline bounds how long a captured envelope is worth
351
+ // keeping, so it is always present — falling back to the TTL window
352
+ // when the app named no absolute one.
353
+ deadlineAt: deadlineFor(job, now),
354
+ // `audienceAllow` is not sent — cloud_008 §0.2. The list stays on
355
+ // `JobRecord`, where `claim` already filtered candidates with it; the
356
+ // daemon's own allowlist is what decides `named` (byollm_001 Rev 1
357
+ // §B) and always was.
358
+ //
359
+ // Removing it from `JobStub` did **not** make this line a type error.
360
+ // A conditional spread is not excess-property-checked, so the field
361
+ // would have gone on being sent to a daemon whose `.strict()` parse
362
+ // now rejects the entire claim response — every daemon on the version
363
+ // pair, refusing all work, for a field nobody read. Worth stating
364
+ // where it happened: the schema is the contract, and the compiler
365
+ // does not enforce it through a spread.
366
+ // No fallback. A job returned from `claim` holds a lease by
367
+ // definition, and synthesising one here would hand the daemon a lease
368
+ // id the store has never heard of — every later release naming it
369
+ // would silently match nothing. A store that returns an unleased job
370
+ // has broken its contract, and this says so.
371
+ lease: leaseOf(job)
372
+ })),
373
+ leaseMs: this.#leaseMs
374
+ };
375
+ return ok(response);
376
+ }
377
+ // -- 3. heartbeat ---------------------------------------------------------
378
+ async #heartbeat(request, runner) {
379
+ if (request.runnerId !== runner.id) {
380
+ return fail("unauthorized", "runner id does not match the signing key");
381
+ }
382
+ const now = this.#now();
383
+ const revoked = runner.revokedAt !== null;
384
+ if (revoked) {
385
+ const held = await this.#store.listClaimedBy(runner.id);
386
+ const response2 = {
387
+ revoked: true,
388
+ cancel: [],
389
+ lost: held.map((job) => job.id),
390
+ serverTime: now
391
+ };
392
+ return ok(response2);
393
+ }
394
+ await this.#store.touchRunner({
395
+ runnerId: runner.id,
396
+ capabilities: request.capabilities,
397
+ daemonVersion: request.daemonVersion,
398
+ paused: request.paused,
399
+ now
400
+ });
401
+ const { lost } = await this.#store.renewLeases({
402
+ runnerId: runner.id,
403
+ leases: request.activeLeases,
404
+ leaseMs: this.#leaseMs,
405
+ now
406
+ });
407
+ const cancel = await this.#store.listCancelRequests(runner.id);
408
+ const response = {
409
+ revoked: false,
410
+ cancel,
411
+ lost: [...lost],
412
+ serverTime: now
413
+ };
414
+ return ok(response);
415
+ }
416
+ // -- 4. result ------------------------------------------------------------
417
+ async #result(request, runner) {
418
+ if (request.runnerId !== runner.id) {
419
+ return fail("unauthorized", "runner id does not match the signing key");
420
+ }
421
+ const now = this.#now();
422
+ const job = await this.#store.get(request.jobId);
423
+ if (!job) return fail("not-found", "unknown job");
424
+ const outcome = await this.#openResult(request, runner);
425
+ if (!outcome.ok) return outcome.failure;
426
+ const provenance = provenanceFor({
427
+ audience: job.audience,
428
+ runnerId: runner.id,
429
+ runnerOwner: runner.owner,
430
+ // From the envelope the device signed, not from the request beside it
431
+ // — cloud_008 §2.5. A daemon can no longer seal one answer and declare
432
+ // it came from a different model.
433
+ backendClass: outcome.value.ran.backendClass,
434
+ model: outcome.value.ran.model
435
+ });
436
+ const {
437
+ accepted,
438
+ duplicate,
439
+ job: updated
440
+ } = await this.#store.complete({
441
+ jobId: request.jobId,
442
+ // Who is asking, for the duplicate answer only — §3.6. Authorisation
443
+ // is `holder`, below, and still is.
444
+ runnerId: runner.id,
445
+ // The grant, not the runner — cloud_008 §1.4a. `CompleteHolder`'s own
446
+ // docstring already called the lease "the more exact check anyway";
447
+ // this plane simply had no lease id to give it until now.
448
+ holder: { by: "lease", leaseId: request.leaseId },
449
+ outcome: outcome.value.outcome,
450
+ provenance,
451
+ now
452
+ });
453
+ const response = {
454
+ accepted,
455
+ // Only when true — cloud_008 §3.6. Absent means "not a duplicate", and
456
+ // an optional field that is always present is a required one wearing a
457
+ // question mark.
458
+ ...duplicate === true ? { duplicate: true } : {},
459
+ state: updated?.state ?? job.state
460
+ };
461
+ return ok(response);
462
+ }
463
+ /**
464
+ * Open a sealed result, or refuse it.
465
+ *
466
+ * The mirror of the daemon's `#openPayload`, and refuses for the same
467
+ * reason: an outcome that does not verify against the device's pinned key is
468
+ * an assertion by whoever relayed it, and storing it would let an
469
+ * intermediary write answers into the app.
470
+ *
471
+ * The clear-text `disposition` is checked here rather than trusted. It is on
472
+ * the wire so a relay can route without opening anything, which means the
473
+ * one thing it must not be is authoritative — a daemon that sealed an error
474
+ * and declared `ok` would otherwise have its declaration believed by
475
+ * everything upstream of this line.
476
+ */
477
+ async #openResult(request, runner) {
478
+ const refuse = (why) => ({ ok: false, failure: fail("bad-request", why) });
479
+ const opened = await open2({
480
+ envelope: request.envelope,
481
+ recipientKeys: this.#siteKeys,
482
+ senderIdentityPublic: runner.device.identity,
483
+ expected: {
484
+ jobId: request.jobId,
485
+ senderKeyId: keyId2(runner.device.identity),
486
+ recipientKeyId: keyId2(publicIdentityOf2(this.#siteKeys).identity),
487
+ direction: "result"
488
+ }
489
+ });
490
+ if (!opened.ok) {
491
+ return refuse("the result did not verify as coming from this device");
492
+ }
493
+ let parsed;
494
+ try {
495
+ parsed = JSON.parse(opened.plaintext);
496
+ } catch {
497
+ return refuse("the sealed result was not valid JSON");
498
+ }
499
+ const sealed = SealedOutcome.safeParse(parsed);
500
+ if (!sealed.success) return refuse("the sealed result was not an outcome");
501
+ if (sealed.data.outcome.outcome !== request.disposition) {
502
+ return refuse("the declared disposition is not the one that was sealed");
503
+ }
504
+ return { ok: true, value: sealed.data };
505
+ }
506
+ // -- 5. release -----------------------------------------------------------
507
+ async #release(request, runner) {
508
+ if (request.runnerId !== runner.id) {
509
+ return fail("unauthorized", "runner id does not match the signing key");
510
+ }
511
+ const released = await this.#store.release({
512
+ runnerId: runner.id,
513
+ leases: request.leases,
514
+ reason: request.reason,
515
+ now: this.#now()
516
+ });
517
+ const response = { released };
518
+ return ok(response);
519
+ }
520
+ };
521
+ var SERVED_PROTOCOL_VERSION = PROTOCOL_VERSION;
522
+ function leaseOf(job) {
523
+ if (!job.lease) {
524
+ throw new Error(
525
+ `store returned job ${job.id} from claim with no lease \u2014 the store contract requires a claimed job to hold one`
526
+ );
527
+ }
528
+ return job.lease;
529
+ }
530
+
531
+ // src/http.ts
532
+ import {
533
+ ENDPOINTS,
534
+ ERROR_STATUS as ERROR_STATUS2,
535
+ PROTOCOL_PREFIX,
536
+ checkProtocolVersion
537
+ } from "@byollm/protocol";
538
+ var MAX_BODY_BYTES = 8 * 1024 * 1024;
539
+ function normalizeBasePath(basePath) {
540
+ const trimmed = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
541
+ if (!trimmed.startsWith("/")) {
542
+ throw new Error(`basePath must start with "/": got ${basePath}`);
543
+ }
544
+ if (trimmed.includes("//") || /[?#*]/.test(trimmed)) {
545
+ throw new Error(`basePath must be a plain path: got ${basePath}`);
546
+ }
547
+ return trimmed;
548
+ }
549
+ function routeEndpoint(pathname, basePath = PROTOCOL_PREFIX) {
550
+ const base = normalizeBasePath(basePath);
551
+ const path = pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
552
+ if (!path.startsWith(`${base}/`)) return null;
553
+ const rest = path.slice(base.length + 1);
554
+ return ENDPOINTS.includes(rest) ? rest : null;
555
+ }
556
+ function signatureFrom(headers) {
557
+ const runnerId = headers.get("x-byollm-runner");
558
+ const rawIssuedAt = headers.get("x-byollm-issued-at");
559
+ const signature = headers.get("x-byollm-signature");
560
+ if (runnerId === null || signature === null || rawIssuedAt === null) {
561
+ return void 0;
562
+ }
563
+ const issuedAt = Number(rawIssuedAt);
564
+ if (!Number.isFinite(issuedAt)) return void 0;
565
+ return { runnerId, issuedAt, signature };
566
+ }
567
+ function createFetchHandler(config) {
568
+ const handlers = new ByollmHandlers(config);
569
+ const basePath = normalizeBasePath(config.basePath ?? PROTOCOL_PREFIX);
570
+ return async function handle(request) {
571
+ if (request.method !== "POST") {
572
+ return json(405, {
573
+ error: "bad-request",
574
+ message: "protocol endpoints accept POST only"
575
+ });
576
+ }
577
+ const endpoint = routeEndpoint(new URL(request.url).pathname, basePath);
578
+ if (endpoint === null) {
579
+ return json(404, {
580
+ error: "not-found",
581
+ message: `not a ${basePath} endpoint`
582
+ });
583
+ }
584
+ const declared = request.headers.get("content-length");
585
+ if (declared !== null && Number(declared) > MAX_BODY_BYTES) {
586
+ return json(400, {
587
+ error: "bad-request",
588
+ message: "request body too large"
589
+ });
590
+ }
591
+ let body;
592
+ let rawBody;
593
+ try {
594
+ rawBody = await request.text();
595
+ const text = rawBody;
596
+ if (text.length > MAX_BODY_BYTES) {
597
+ return json(400, {
598
+ error: "bad-request",
599
+ message: "request body too large"
600
+ });
601
+ }
602
+ body = JSON.parse(text);
603
+ } catch {
604
+ return json(400, {
605
+ error: "bad-request",
606
+ message: "request body is not valid JSON"
607
+ });
608
+ }
609
+ const refusal = checkProtocolVersion(body);
610
+ if (refusal) {
611
+ return json(ERROR_STATUS2[refusal.error], refusal);
612
+ }
613
+ const result = await handlers.handle(endpoint, body, {
614
+ endpoint,
615
+ // The bytes as received. Re-serialising the parsed object would verify
616
+ // a signature over something the sender never sent.
617
+ rawBody,
618
+ signature: signatureFrom(request.headers)
619
+ });
620
+ const headers = {
621
+ "content-type": "application/json",
622
+ "cache-control": "no-store"
623
+ };
624
+ if (result.retryAfterSeconds !== void 0) {
625
+ headers["retry-after"] = String(result.retryAfterSeconds);
626
+ }
627
+ return new Response(JSON.stringify(result.body), {
628
+ status: result.status,
629
+ headers
630
+ });
631
+ };
632
+ }
633
+ function json(status, body) {
634
+ return new Response(JSON.stringify(body), {
635
+ status,
636
+ headers: {
637
+ "content-type": "application/json",
638
+ "cache-control": "no-store"
639
+ }
640
+ });
641
+ }
642
+
643
+ export {
644
+ generateDeviceCode,
645
+ generateRunnerId,
646
+ generateJobId,
647
+ generateUserCode,
648
+ hashSecret,
649
+ secretsMatch,
650
+ generateLeaseId,
651
+ deadlineFor,
652
+ resealForDevice,
653
+ ByollmHandlers,
654
+ SERVED_PROTOCOL_VERSION,
655
+ routeEndpoint,
656
+ signatureFrom,
657
+ createFetchHandler
658
+ };
659
+ //# sourceMappingURL=chunk-QTRX2LSF.js.map