@byollm/server 0.1.0-alpha.1 → 0.1.0-alpha.100

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