@substrat-run/control-plane-api 0.158.0 → 0.160.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +25 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +570 -55
- package/dist/api.js.map +1 -1
- package/dist/browser.d.ts +2 -2
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +2 -1
- package/dist/browser.js.map +1 -1
- package/dist/cf-observability.d.ts +30 -5
- package/dist/cf-observability.d.ts.map +1 -1
- package/dist/cf-observability.js +277 -92
- package/dist/cf-observability.js.map +1 -1
- package/dist/custom-hostnames.d.ts +30 -0
- package/dist/custom-hostnames.d.ts.map +1 -1
- package/dist/custom-hostnames.js +25 -2
- package/dist/custom-hostnames.js.map +1 -1
- package/dist/deploy.d.ts +3 -0
- package/dist/deploy.d.ts.map +1 -1
- package/dist/deploy.js.map +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/observability.d.ts +26 -2
- package/dist/observability.d.ts.map +1 -1
- package/dist/observability.js +6 -13
- package/dist/observability.js.map +1 -1
- package/dist/platform-drain.d.ts.map +1 -1
- package/dist/platform-drain.js +103 -40
- package/dist/platform-drain.js.map +1 -1
- package/dist/platform-entry.generated.d.ts +2 -2
- package/dist/platform-entry.generated.d.ts.map +1 -1
- package/dist/platform-entry.generated.js +5 -5
- package/dist/platform-entry.generated.js.map +1 -1
- package/dist/platform-wire.d.ts +51 -0
- package/dist/platform-wire.d.ts.map +1 -0
- package/dist/platform-wire.js +163 -0
- package/dist/platform-wire.js.map +1 -0
- package/dist/scope-copy-backfill.d.ts.map +1 -1
- package/dist/scope-copy-backfill.js +22 -9
- package/dist/scope-copy-backfill.js.map +1 -1
- package/dist/staff-client.d.ts +38 -2
- package/dist/staff-client.d.ts.map +1 -1
- package/dist/staff-client.js +24 -1
- package/dist/staff-client.js.map +1 -1
- package/dist/vertical-client.d.ts +59 -3
- package/dist/vertical-client.d.ts.map +1 -1
- package/dist/vertical-client.js +144 -6
- package/dist/vertical-client.js.map +1 -1
- package/dist/wire-upload.d.ts +74 -0
- package/dist/wire-upload.d.ts.map +1 -0
- package/dist/wire-upload.js +114 -0
- package/dist/wire-upload.js.map +1 -0
- package/package.json +10 -10
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
export declare const PLATFORM_ENTRY_MODULE = "substrat-platform-entry.js";
|
|
8
8
|
/** The import specifier the uploader replaces with `./<the bundle's entry>`. */
|
|
9
9
|
export declare const PLATFORM_ENTRY_PLACEHOLDER = "__SUBSTRAT_VERTICAL_ENTRY__";
|
|
10
|
-
/** The entry itself —
|
|
10
|
+
/** The entry itself — 48819 bytes of ESM. */
|
|
11
11
|
export declare const PLATFORM_ENTRY_SOURCE: string;
|
|
12
12
|
/**
|
|
13
13
|
* #2245: the entry's `node:async_hooks` import, as it appears in `PLATFORM_ENTRY_SOURCE`, and
|
|
@@ -22,6 +22,6 @@ export declare const PLATFORM_ENTRY_ALS_FALLBACK = "const AsyncLocalStorage = un
|
|
|
22
22
|
* re-exports its class, when a vertical declares schedules and brings no sweeper of its own.
|
|
23
23
|
*/
|
|
24
24
|
export declare const PLATFORM_SWEEPER_MODULE = "substrat-platform-sweeper.js";
|
|
25
|
-
/** The sweeper itself —
|
|
25
|
+
/** The sweeper itself — 11087 bytes of ESM. */
|
|
26
26
|
export declare const PLATFORM_SWEEPER_SOURCE: string;
|
|
27
27
|
//# sourceMappingURL=platform-entry.generated.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-entry.generated.d.ts","sourceRoot":"","sources":["../src/platform-entry.generated.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,+BAA+B,CAAC;AAElE,gFAAgF;AAChF,eAAO,MAAM,0BAA0B,gCAAgC,CAAC;AAExE,6CAA6C;AAC7C,eAAO,MAAM,qBAAqB,EAAE,
|
|
1
|
+
{"version":3,"file":"platform-entry.generated.d.ts","sourceRoot":"","sources":["../src/platform-entry.generated.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,+BAA+B,CAAC;AAElE,gFAAgF;AAChF,eAAO,MAAM,0BAA0B,gCAAgC,CAAC;AAExE,6CAA6C;AAC7C,eAAO,MAAM,qBAAqB,EAAE,MAA+rjD,CAAC;AAEpujD;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,4DAA4D,CAAC;AACnG,eAAO,MAAM,2BAA2B,yCAAyC,CAAC;AAElF;;;GAGG;AACH,eAAO,MAAM,uBAAuB,iCAAiC,CAAC;AAEtE,+CAA+C;AAC/C,eAAO,MAAM,uBAAuB,EAAE,MAAuqW,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// GENERATED by tools/platform-entry-emit.mts from packages/vertical-host/src/invocation-log.ts and packages/adapter-cloudflare/src/scope-sweeper-do.ts — do not edit by hand.
|
|
1
|
+
// GENERATED by tools/platform-entry-emit.mts from packages/vertical-host/src/invocation-log.ts, packages/control-plane-api/platform-entry/wire-gate.ts and packages/adapter-cloudflare/src/scope-sweeper-do.ts — do not edit by hand.
|
|
2
2
|
// Re-emit with `pnpm lint:platform-entry`; CI runs it with `--check`.
|
|
3
3
|
/**
|
|
4
4
|
* The platform's entry module (#1893): uploaded in front of a vertical's bundle and made its
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
export const PLATFORM_ENTRY_MODULE = 'substrat-platform-entry.js';
|
|
10
10
|
/** The import specifier the uploader replaces with `./<the bundle's entry>`. */
|
|
11
11
|
export const PLATFORM_ENTRY_PLACEHOLDER = '__SUBSTRAT_VERTICAL_ENTRY__';
|
|
12
|
-
/** The entry itself —
|
|
13
|
-
export const PLATFORM_ENTRY_SOURCE = "// substrat-platform-entry.ts\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n// packages/contracts/dist/invocation-record.js\nvar INVOCATION_RECORD_HEADER = \"x-substrat-invocation-record\";\nvar REQUEST_ID_HEADER = \"x-substrat-request-id\";\nvar INVOCATION_RECORD_FIELD_MAX = 128;\nvar FIELDS = [\"operation\", \"problemCode\", \"principalKind\"];\nfunction encodeInvocationRecord(record2) {\n const params = new URLSearchParams();\n for (const key of FIELDS) {\n const v = record2[key];\n if (typeof v === \"string\" && v !== \"\")\n params.set(key, v.slice(0, INVOCATION_RECORD_FIELD_MAX));\n }\n const value = params.toString();\n return value === \"\" ? null : value;\n}\nvar FIELD_COVERAGE_HEADER = \"x-substrat-field-coverage\";\nfunction invocationLevelOf(status, threw, problemCode) {\n if (threw || status === null || status >= 500)\n return \"error\";\n if (status >= 400)\n return \"warn\";\n if (problemCode)\n return \"warn\";\n return \"info\";\n}\n\n// packages/contracts/dist/trace-sink.js\nvar TRACE_SINK_KEY = /* @__PURE__ */ Symbol.for(\"substrat.trace-sink\");\nvar STARTS_KEY = /* @__PURE__ */ Symbol.for(\"substrat.trace-starts\");\nfunction starts() {\n const slots = globalThis;\n return slots[STARTS_KEY] ??= /* @__PURE__ */ new Map();\n}\nfunction markTraceStart(invocationId, at = performance.now()) {\n const map = starts();\n if (!map.has(invocationId))\n map.set(invocationId, at);\n}\nfunction forgetTraceStart(invocationId) {\n starts().delete(invocationId);\n}\nfunction installedTraceSink() {\n return globalThis[TRACE_SINK_KEY];\n}\n\n// packages/kernel/dist/invocation-line.js\nfunction invocationLine(f) {\n const emitted = f.emitted;\n return {\n substrat: \"invocation\",\n ...f.kind ? { kind: f.kind } : {},\n tenantId: f.tenantId,\n scopeId: f.scopeId,\n vertical: f.vertical ?? null,\n surface: f.surface ?? null,\n method: f.method ?? null,\n path: f.path ?? null,\n status: f.status ?? null,\n threw: f.threw,\n durationMs: f.durationMs,\n invocationId: f.invocationId,\n level: f.level,\n operation: f.operation ?? null,\n problemCode: f.problemCode ?? null,\n principalKind: f.principalKind ?? null,\n eventCount: emitted ? emitted.total : null,\n eventTypes: emitted ? distinct(emitted.events.map((e) => e.type)) : [],\n entities: emitted && f.withEntities !== false ? distinct(emitted.events.map((e) => e.entity)) : [],\n versionId: f.versionId ?? null,\n ...f.outputFields ? { outputFields: f.outputFields, ...f.fieldCoverageId ? { fieldCoverageId: f.fieldCoverageId } : {} } : {},\n ...f.storeCalls && f.storeCalls.length > 0 ? { storeCalls: f.storeCalls } : {},\n ...f.storeCallsDropped ? { storeCallsDropped: f.storeCallsDropped } : {},\n ...f.outboundCalls && f.outboundCalls.length > 0 ? { outboundCalls: f.outboundCalls } : {},\n ...f.outboundCallsDropped ? { outboundCallsDropped: f.outboundCallsDropped } : {},\n ...f.parentInvocationId ? { parentInvocationId: f.parentInvocationId, ...f.parentScopeId ? { parentScopeId: f.parentScopeId } : {} } : {},\n ...f.async ?? {}\n };\n}\nvar STORE_CALL_LOG_CAP = 16;\nfunction tallyStoreCall(tally, call) {\n const calls = tally.storeCalls ?? (tally.storeCalls = []);\n if (calls.length < STORE_CALL_LOG_CAP) {\n calls.push({ binding: call.binding, operation: call.operation, outcome: call.outcome, durationMs: call.durationMs });\n } else {\n tally.storeCallsDropped = (tally.storeCallsDropped ?? 0) + 1;\n }\n}\nvar OUTBOUND_CALL_LOG_CAP = 16;\nfunction tallyOutboundCall(tally, call) {\n const calls = tally.outboundCalls ?? (tally.outboundCalls = []);\n if (calls.length < OUTBOUND_CALL_LOG_CAP) {\n calls.push({\n host: call.host,\n path: call.path,\n method: call.method,\n status: call.status,\n outcome: call.outcome,\n durationMs: call.durationMs,\n atMs: call.atMs,\n ...call.reason !== void 0 ? { reason: call.reason } : {}\n });\n } else {\n tally.outboundCallsDropped = (tally.outboundCallsDropped ?? 0) + 1;\n }\n}\nvar STORE_CALL_SINK_KEY = \"substrat.store-call-sink\";\nfunction distinct(values) {\n return [...new Set(values)];\n}\n\n// packages/kernel/dist/ulid.js\nvar B32 = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nvar MAX_ULID_TIME = 2 ** 48 - 1;\nvar ULID_SHAPE = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nvar unencodable = (t) => `not an encodable ULID instant: ${t} (want 0..${MAX_ULID_TIME})`;\nfunction encodeTime(time) {\n let ts = \"\";\n let t = time;\n for (let i = 0; i < 10; i++) {\n ts = B32[t % 32] + ts;\n t = Math.floor(t / 32);\n }\n return ts;\n}\nfunction createUlid() {\n let lastTime = -1;\n const lastRand = new Array(16).fill(0);\n function freshRandom() {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n for (let i = 0; i < 16; i++)\n lastRand[i] = bytes[i] % 32;\n }\n function incrementRandom() {\n for (let i = 15; i >= 0; i--) {\n if (lastRand[i] < 31) {\n lastRand[i]++;\n return true;\n }\n lastRand[i] = 0;\n }\n return false;\n }\n const mint = ((now = Date.now()) => {\n if (!Number.isSafeInteger(now))\n throw new RangeError(unencodable(now));\n let time = now;\n if (time <= lastTime) {\n time = lastTime;\n if (!incrementRandom()) {\n time = lastTime + 1;\n freshRandom();\n }\n } else {\n freshRandom();\n }\n if (time < 0 || time > MAX_ULID_TIME)\n throw new RangeError(unencodable(time));\n lastTime = time;\n let r = \"\";\n for (const d of lastRand)\n r += B32[d];\n return encodeTime(time) + r;\n });\n mint.seedFrom = (id) => {\n const time = ulidTime(id);\n if (time < lastTime)\n return;\n const rand = [];\n for (const ch of id.slice(10))\n rand.push(B32.indexOf(ch));\n if (time === lastTime) {\n let ahead = false;\n for (let i = 0; i < 16; i++) {\n if (rand[i] !== lastRand[i]) {\n ahead = rand[i] > lastRand[i];\n break;\n }\n }\n if (!ahead)\n return;\n }\n lastTime = time;\n for (let i = 0; i < 16; i++)\n lastRand[i] = rand[i];\n };\n return mint;\n}\nvar processUlid = createUlid();\nfunction ulid(now = Date.now()) {\n return processUlid(now);\n}\nfunction ulidTime(id) {\n if (!ULID_SHAPE.test(id))\n throw new Error(`not a ULID: ${id}`);\n let t = 0;\n for (const ch of id.slice(0, 10))\n t = t * 32 + B32.indexOf(ch);\n if (t > MAX_ULID_TIME)\n throw new Error(`not a ULID: ${id}`);\n return t;\n}\n\n// packages/vertical-host/src/outbound-calls.ts\nvar EGRESS_REFUSAL_HEADER = \"x-substrat-egress\";\nvar STORE_CALL_HOST = \"store.substrat.internal\";\nvar REDACTED = \"[redacted]\";\nvar PATH_MAX = 200;\nvar WORDS = /^[a-z]{1,16}(?:[-_][a-z]{1,16}){0,3}$/;\nvar WORDS_WITH_EXTENSION = /^[a-z]{1,16}(?:[-_][a-z]{1,16}){0,3}\\.[a-z][a-z0-9]{0,4}$/;\nvar SEGMENT_MAX = 40;\nvar SMALL_INTEGER = /^[0-9]{1,10}$/;\nvar VERSION = /^v[0-9]{1,3}(?:\\.[0-9]{1,3}){0,2}$/;\nfunction keepsSegment(segment) {\n if (segment.length > SEGMENT_MAX) return false;\n return segment === \"\" || WORDS.test(segment) || WORDS_WITH_EXTENSION.test(segment) || SMALL_INTEGER.test(segment) || VERSION.test(segment);\n}\nfunction redactOutboundPath(pathname) {\n const path = pathname.split(\"/\").map((segment) => keepsSegment(segment) ? segment : REDACTED).join(\"/\");\n return path.length > PATH_MAX ? `${path.slice(0, PATH_MAX)}…` : path;\n}\nvar ERROR_CLASS = /^[A-Z][A-Za-z]{0,30}(?:Error|Exception)$/;\nfunction errorName(e) {\n const name = e?.name;\n return typeof name === \"string\" && ERROR_CLASS.test(name) ? name : \"Error\";\n}\nfunction answeredOutcome(response) {\n if (response.status === 403 && response.headers?.get?.(EGRESS_REFUSAL_HEADER) === \"refused\") return \"refused\";\n return response.status >= 400 ? \"http-error\" : \"ok\";\n}\nfunction rejectedOutcome(e) {\n const name = errorName(e);\n if (name === \"TimeoutError\") return { outcome: \"timeout\" };\n if (name === \"AbortError\") return { outcome: \"aborted\" };\n return { outcome: \"failed\", reason: name };\n}\nvar SINCE = /* @__PURE__ */ Symbol.for(\"substrat.outbound-since\");\nfunction sinceMap() {\n const g = globalThis;\n return g[SINCE] ??= /* @__PURE__ */ new WeakMap();\n}\nfunction markRequestStart(recording, started) {\n try {\n sinceMap().set(recording, started);\n } catch {\n }\n}\nfunction destinationOf(input, init) {\n const fromRequest = typeof input === \"object\" && input !== null && !(input instanceof URL);\n const raw = fromRequest ? input.url : input;\n let url;\n try {\n url = new URL(String(raw));\n } catch {\n return null;\n }\n const initMethod = init?.method;\n const requestMethod = fromRequest ? input.method : void 0;\n const method = typeof initMethod === \"string\" ? initMethod : typeof requestMethod === \"string\" ? requestMethod : \"GET\";\n return { url, method: method.toUpperCase().slice(0, 16) };\n}\nfunction record(recording, destination, startedAt, end) {\n try {\n const call = {\n host: destination.url.host.toLowerCase(),\n path: redactOutboundPath(destination.url.pathname),\n method: destination.method,\n status: end.status,\n outcome: end.outcome,\n durationMs: Math.max(0, Date.now() - startedAt),\n atMs: Math.max(0, startedAt - (sinceMap().get(recording) ?? startedAt)),\n ...end.reason !== void 0 ? { reason: end.reason } : {}\n };\n tallyOutboundCall(recording, call);\n } catch {\n }\n}\nvar WRAPPED = /* @__PURE__ */ Symbol.for(\"substrat.outbound-fetch\");\nvar IN_CALL = /* @__PURE__ */ Symbol.for(\"substrat.outbound-fetch.in-call\");\nfunction recordingFetch(original, current) {\n const wrapped = function fetch(input, init) {\n const g = globalThis;\n if (g[IN_CALL] === true) return original.call(globalThis, input, init);\n let recording;\n let destination = null;\n try {\n recording = current();\n if (recording) destination = destinationOf(input, init);\n } catch {\n recording = void 0;\n }\n if (!recording || !destination || destination.url.hostname.toLowerCase() === STORE_CALL_HOST) {\n return original.call(globalThis, input, init);\n }\n const rec = recording;\n const dest = destination;\n const startedAt = Date.now();\n let pending;\n g[IN_CALL] = true;\n try {\n pending = original.call(globalThis, input, init);\n } finally {\n g[IN_CALL] = false;\n }\n return pending.then(\n (response) => {\n let status = null;\n let outcome = \"failed\";\n try {\n status = response.status;\n outcome = answeredOutcome(response);\n } catch {\n }\n record(rec, dest, startedAt, { status, outcome });\n return response;\n },\n (e) => {\n let end = { outcome: \"failed\", reason: \"Error\" };\n try {\n end = rejectedOutcome(e);\n } catch {\n }\n record(rec, dest, startedAt, { status: null, ...end });\n throw e;\n }\n );\n };\n Object.defineProperty(wrapped, WRAPPED, { value: true });\n return wrapped;\n}\nfunction installOutboundRecorder(current) {\n try {\n const g = globalThis;\n const existing = g.fetch;\n if (typeof existing !== \"function\" || existing[WRAPPED]) return;\n g.fetch = recordingFetch(existing, current);\n } catch {\n }\n}\n\n// packages/contracts/dist/wire-auth.js\nfunction secretMatches(presented, expected) {\n const given = presented ?? \"\";\n let diff = given.length ^ expected.length | (given.length === 0 ? 1 : 0);\n for (let i = 0; i < expected.length; i++) {\n diff |= (i < given.length ? given.charCodeAt(i) : 0) ^ expected.charCodeAt(i);\n }\n return diff === 0;\n}\n\n// packages/vertical-host/src/routed-node.ts\nvar ROUTED_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nvar RouterAssertionError = class extends Error {\n};\nfunction readRoutedNode(headers, options = {}) {\n const rawTenant = headers.get(\"x-substrat-tenant\");\n const rawScope = headers.get(\"x-substrat-scope\");\n if (!rawTenant && !rawScope) return null;\n const { expectedSecret, allowUnsigned = false } = options;\n if (expectedSecret) {\n if (!secretMatches(headers.get(\"x-substrat-router\"), expectedSecret)) {\n throw new RouterAssertionError(\"router assertion is not signed by a known router\");\n }\n } else if (!allowUnsigned) {\n throw new RouterAssertionError(\n \"router assertion cannot be verified: this worker has no ROUTER_SECRET configured\"\n );\n }\n if (!rawTenant || !rawScope) {\n throw new RouterAssertionError(\"router assertion is incomplete\");\n }\n if (!ROUTED_ID.test(rawTenant) || !ROUTED_ID.test(rawScope)) {\n throw new RouterAssertionError(\"router assertion carries a malformed id\");\n }\n return {\n tenantId: rawTenant,\n scopeId: rawScope,\n surface: headers.get(\"x-substrat-surface\") ?? \"app\",\n verticalSlug: headers.get(\"x-substrat-vertical\")\n };\n}\n\n// packages/vertical-host/src/invocation-log.ts\nfunction builtinAsyncLocalStorage() {\n try {\n const proc = globalThis.process;\n const mod = proc?.getBuiltinModule?.(\"node:async_hooks\");\n return typeof mod?.AsyncLocalStorage === \"function\" ? mod.AsyncLocalStorage : void 0;\n } catch {\n return void 0;\n }\n}\nfunction storeCallSlot(provided) {\n try {\n const g = globalThis;\n const key = Symbol.for(STORE_CALL_SINK_KEY);\n const existing = g[key];\n if (typeof existing?.run === \"function\" && typeof existing.current === \"function\") return existing;\n const Als = provided ?? builtinAsyncLocalStorage();\n if (!Als) return void 0;\n const storage = new Als();\n const slot = {\n current() {\n const tally = storage.getStore()?.tally;\n return tally ? (call) => tallyStoreCall(tally, call) : void 0;\n },\n invocationId: () => storage.getStore()?.invocationId,\n run: (tally, fn, invocationId) => storage.run({ tally, invocationId }, fn),\n recording: () => storage.getStore()?.tally\n };\n g[key] = slot;\n return slot;\n } catch {\n return void 0;\n }\n}\nfunction currentRecording() {\n const slot = globalThis[Symbol.for(STORE_CALL_SINK_KEY)];\n return typeof slot?.recording === \"function\" ? slot.recording() : void 0;\n}\nfunction runRecording(stamp, started, provided, fn) {\n const slot = storeCallSlot(provided);\n if (!slot) return fn();\n markRequestStart(stamp.record, started);\n installOutboundRecorder(currentRecording);\n return slot.run(stamp.record, fn, stamp.invocationId);\n}\nfunction versionIdOf(env) {\n const v = env?.SUBSTRAT_VERSION_ID;\n return typeof v === \"string\" && v.length > 0 ? v : null;\n}\nvar UPLOAD_LINK_LOG_SECRET_PREFIX = \"sbup_\";\nvar UPLOAD_LINK_SECRET_SEGMENT = /^(\\/api\\/attachment-uploads\\/[^/]+\\/[^/]+\\/)[^/]+/;\nvar SECRET_SHAPED_SEGMENT = new RegExp(`(^|/)${UPLOAD_LINK_LOG_SECRET_PREFIX}[^/]*`, \"g\");\nvar redactUploadLinkSecret = (pathname) => pathname.replace(UPLOAD_LINK_SECRET_SEGMENT, \"$1[redacted]\").replace(SECRET_SHAPED_SEGMENT, \"$1[redacted]\");\nfunction pathOf(url) {\n try {\n return redactUploadLinkSecret(new URL(url).pathname);\n } catch {\n return \"/\";\n }\n}\nvar STAMPS = /* @__PURE__ */ Symbol.for(\"substrat.invocation-stamp\");\nfunction stamps() {\n const g = globalThis;\n return g[STAMPS] ??= /* @__PURE__ */ new WeakMap();\n}\nfunction invocationStampOf(request) {\n return stamps().get(request);\n}\nfunction withRequestId(response, id) {\n const headers = response?.headers;\n try {\n headers?.set?.(REQUEST_ID_HEADER, id);\n return response;\n } catch {\n }\n try {\n const r = response;\n if (r.status === 101) return response;\n const copy = new Response(r.body, r);\n copy.headers.set(REQUEST_ID_HEADER, id);\n return copy;\n } catch {\n return response;\n }\n}\nfunction beginStamp(request, env, options) {\n const stamp = { invocationId: ulid(), record: {} };\n if (installedTraceSink()) markTraceStart(stamp.invocationId);\n const fieldCoverageId = armedFieldCoverageId(request.headers, env, options);\n if (fieldCoverageId) stamp.fieldCoverageId = fieldCoverageId;\n stamps().set(request, stamp);\n return stamp;\n}\nfunction armedFieldCoverageId(headers, env, options) {\n let id;\n try {\n id = headers.get(FIELD_COVERAGE_HEADER);\n } catch {\n return void 0;\n }\n if (id === null || !ROUTED_ID.test(id)) return void 0;\n return routedNodeOrNull(headers, env, options) !== null ? id : void 0;\n}\nfunction writeInvocationLine(stamp, done, options) {\n traceRequest(stamp, done);\n try {\n writeLineOrThrow(stamp, done, options);\n } catch (e) {\n try {\n console.log(JSON.stringify({ substrat: \"invocation-log-fault\", detail: String(e) }));\n } catch {\n }\n }\n}\nfunction traceRequest(stamp, done) {\n const sink = installedTraceSink();\n if (!sink) return;\n try {\n const { record: record2, invocationId } = stamp;\n const durationMs = Date.now() - done.started;\n const line = invocationLine({\n tenantId: \"\",\n scopeId: null,\n vertical: null,\n surface: null,\n method: done.request.method,\n path: pathOf(done.request.url),\n status: done.status,\n threw: done.threw,\n durationMs,\n invocationId,\n level: invocationLevelOf(done.status, done.threw, record2.problemCode),\n operation: record2.operation,\n problemCode: record2.problemCode,\n principalKind: record2.principalKind,\n ...record2.emitted ? { emitted: record2.emitted } : {},\n versionId: versionIdOf(done.env)\n });\n sink.head(invocationId, {\n startedAt: new Date(done.started).toISOString(),\n method: line.method,\n path: line.path,\n status: line.status,\n threw: line.threw,\n durationMs: line.durationMs,\n level: line.level,\n operation: line.operation,\n problemCode: line.problemCode,\n principalKind: line.principalKind,\n eventCount: line.eventCount,\n eventTypes: line.eventTypes,\n entities: line.entities,\n versionId: line.versionId,\n // Calls the record kept no room for: a truncated list must read as truncated.\n ...record2.outboundCallsDropped ? { stepsDropped: record2.outboundCallsDropped } : {}\n });\n for (const call of record2.outboundCalls ?? []) {\n sink.step(invocationId, {\n type: \"outbound\",\n atMs: call.atMs,\n durationMs: call.durationMs,\n host: call.host,\n path: call.path,\n method: call.method,\n status: call.status,\n outcome: call.outcome,\n ...call.reason ? { reason: call.reason } : {}\n });\n }\n sink.end(invocationId);\n forgetTraceStart(invocationId);\n } catch {\n }\n}\nfunction writeLineOrThrow(stamp, done, options) {\n const node = routedNodeOrNull(done.request.headers, done.env, options);\n if (!node) return;\n const { record: record2, invocationId } = stamp;\n const line = invocationLine({\n tenantId: node.tenantId,\n scopeId: node.scopeId,\n vertical: node.verticalSlug,\n surface: node.surface,\n method: done.request.method,\n path: pathOf(done.request.url),\n status: done.status,\n threw: done.threw,\n durationMs: Date.now() - done.started,\n invocationId,\n level: invocationLevelOf(done.status, done.threw, record2.problemCode),\n operation: record2.operation,\n problemCode: record2.problemCode,\n principalKind: record2.principalKind,\n ...record2.emitted ? { emitted: record2.emitted } : {},\n versionId: versionIdOf(done.env),\n ...record2.outputFields ? { outputFields: record2.outputFields } : {},\n ...stamp.fieldCoverageId ? { fieldCoverageId: stamp.fieldCoverageId } : {},\n ...record2.storeCalls && record2.storeCalls.length > 0 ? { storeCalls: record2.storeCalls } : {},\n ...record2.storeCallsDropped ? { storeCallsDropped: record2.storeCallsDropped } : {},\n ...record2.outboundCalls && record2.outboundCalls.length > 0 ? { outboundCalls: record2.outboundCalls } : {},\n ...record2.outboundCallsDropped ? { outboundCallsDropped: record2.outboundCallsDropped } : {}\n });\n console.log(JSON.stringify(line));\n}\nvar OTHER_HANDLERS = [\"scheduled\", \"queue\", \"email\", \"tail\", \"trace\", \"alarm\", \"test\"];\nfunction withInvocationLog(worker, options = {}) {\n const inner = worker?.fetch;\n if (typeof inner !== \"function\") return worker;\n const wrapped = {\n async fetch(request, env, ctx) {\n if (invocationStampOf(request)) return inner.call(worker, request, env, ctx);\n const started = Date.now();\n const stamp = beginStamp(request, env, options);\n let status = null;\n let threw = false;\n try {\n const response = withRequestId(\n await runRecording(stamp, started, options.asyncLocalStorage, () => inner.call(worker, request, env, ctx)),\n stamp.invocationId\n );\n status = response.status;\n handRecordToRouter(response, stamp.record, request, env, options);\n return response;\n } catch (e) {\n threw = true;\n throw e;\n } finally {\n writeInvocationLine(stamp, { request, env, status, threw, started }, options);\n }\n }\n };\n for (const name of OTHER_HANDLERS) {\n const h = worker[name];\n if (typeof h === \"function\") wrapped[name] = h.bind(worker);\n }\n return wrapped;\n}\nfunction handRecordToRouter(response, record2, request, env, options) {\n try {\n const value = encodeInvocationRecord(record2);\n if (value === null || !routedNodeOrNull(request.headers, env, options)) return;\n response.headers?.set?.(\n INVOCATION_RECORD_HEADER,\n value\n );\n } catch {\n }\n}\nfunction routedNodeOrNull(headers, env, options) {\n try {\n return readRoutedNode(headers, {\n expectedSecret: options.routerSecret?.(env),\n allowUnsigned: options.allowUnsigned?.(env) ?? false\n });\n } catch (e) {\n if (!(e instanceof RouterAssertionError)) console.log(JSON.stringify({ substrat: \"invocation-log-fault\", detail: String(e) }));\n return null;\n }\n}\n\n// substrat-platform-entry.ts\nimport * as vertical from \"__SUBSTRAT_VERTICAL_ENTRY__\";\nexport * from \"__SUBSTRAT_VERTICAL_ENTRY__\";\nvar substrat_platform_entry_default = withInvocationLog(vertical.default, {\n routerSecret: (env) => env.ROUTER_SECRET,\n allowUnsigned: (env) => env.ALLOW_DEV_NODE === \"true\",\n asyncLocalStorage: AsyncLocalStorage\n});\nexport {\n substrat_platform_entry_default as default\n};\n";
|
|
12
|
+
/** The entry itself — 48819 bytes of ESM. */
|
|
13
|
+
export const PLATFORM_ENTRY_SOURCE = "// substrat-platform-entry.ts\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n// packages/contracts/dist/auth-diagnostics.js\nvar AUTH_CHECK_STAGES = [\"bearer\", \"session\", \"mcp-audience\", \"mcp-caller\"];\nvar AUTH_CHECK_OUTCOMES = [\"accepted\", \"refused\", \"absent\", \"error\"];\nvar AUTH_CHECK_REASONS = [\n \"verified\",\n \"session-invalid\",\n \"credential-missing\",\n \"discovery-failed\",\n \"key-resolution-failed\",\n \"token-expired\",\n \"token-not-active\",\n \"issuer-invalid\",\n \"audience-invalid\",\n \"claims-invalid\",\n \"signature-invalid\",\n \"token-invalid\",\n \"verification-failed\",\n \"subject-missing\",\n \"assertion-not-access-token\",\n \"delegation-refused\",\n \"token-not-for-app\",\n \"resource-mismatch\",\n \"caller-resolved\",\n \"caller-refused\",\n \"caller-error\"\n];\nvar AUTH_CHECK_CAP = 16;\nvar AUTH_DIAGNOSTICS_KEY = /* @__PURE__ */ Symbol.for(\"substrat.auth-diagnostics\");\nfunction authCheckOf(value) {\n if (!value || typeof value !== \"object\")\n return void 0;\n const v = value;\n if (!AUTH_CHECK_STAGES.includes(v.stage) || !AUTH_CHECK_OUTCOMES.includes(v.outcome) || !AUTH_CHECK_REASONS.includes(v.reason))\n return void 0;\n return { stage: v.stage, outcome: v.outcome, reason: v.reason };\n}\nfunction tallyAuthCheck(record2, value) {\n const check = authCheckOf(value);\n if (!check)\n return;\n const checks = record2.authChecks ??= [];\n if (checks.length < AUTH_CHECK_CAP)\n checks.push(check);\n else\n record2.authChecksDropped = (record2.authChecksDropped ?? 0) + 1;\n}\n\n// packages/contracts/dist/invocation-record.js\nvar INVOCATION_RECORD_HEADER = \"x-substrat-invocation-record\";\nvar REQUEST_ID_HEADER = \"x-substrat-request-id\";\nvar PARENT_REQUEST_ID_HEADER = \"x-substrat-parent-request-id\";\nvar REQUEST_ID_SHAPE = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nfunction parentRequestIdOf(value) {\n return typeof value === \"string\" && REQUEST_ID_SHAPE.test(value) ? value : void 0;\n}\nvar INVOCATION_RECORD_FIELD_MAX = 128;\nvar FIELDS = [\"operation\", \"problemCode\", \"principalKind\"];\nfunction encodeInvocationRecord(record2) {\n const params = new URLSearchParams();\n for (const key of FIELDS) {\n const v = record2[key];\n if (typeof v === \"string\" && v !== \"\")\n params.set(key, v.slice(0, INVOCATION_RECORD_FIELD_MAX));\n }\n const value = params.toString();\n return value === \"\" ? null : value;\n}\nvar FIELD_COVERAGE_HEADER = \"x-substrat-field-coverage\";\nfunction invocationLevelOf(status, threw, problemCode) {\n if (threw || status === null || status >= 500)\n return \"error\";\n if (status >= 400)\n return \"warn\";\n if (problemCode)\n return \"warn\";\n return \"info\";\n}\n\n// packages/contracts/dist/trace-sink.js\nvar TRACE_SINK_KEY = /* @__PURE__ */ Symbol.for(\"substrat.trace-sink\");\nvar STARTS_KEY = /* @__PURE__ */ Symbol.for(\"substrat.trace-starts\");\nfunction starts() {\n const slots = globalThis;\n return slots[STARTS_KEY] ??= /* @__PURE__ */ new Map();\n}\nfunction markTraceStart(invocationId, at = performance.now()) {\n const map = starts();\n if (!map.has(invocationId))\n map.set(invocationId, at);\n}\nfunction forgetTraceStart(invocationId) {\n starts().delete(invocationId);\n}\nfunction installedTraceSink() {\n return globalThis[TRACE_SINK_KEY];\n}\n\n// packages/kernel/dist/invocation-line.js\nfunction invocationLine(f) {\n const emitted = f.emitted;\n return {\n substrat: \"invocation\",\n ...f.kind ? { kind: f.kind } : {},\n tenantId: f.tenantId,\n scopeId: f.scopeId,\n vertical: f.vertical ?? null,\n surface: f.surface ?? null,\n method: f.method ?? null,\n path: f.path ?? null,\n status: f.status ?? null,\n threw: f.threw,\n durationMs: f.durationMs,\n invocationId: f.invocationId,\n level: f.level,\n operation: f.operation ?? null,\n problemCode: f.problemCode ?? null,\n principalKind: f.principalKind ?? null,\n eventCount: emitted ? emitted.total : null,\n eventTypes: emitted ? distinct(emitted.events.map((e) => e.type)) : [],\n entities: emitted && f.withEntities !== false ? distinct(emitted.events.map((e) => e.entity)) : [],\n versionId: f.versionId ?? null,\n ...f.outputFields ? { outputFields: f.outputFields, ...f.fieldCoverageId ? { fieldCoverageId: f.fieldCoverageId } : {} } : {},\n ...f.storeCalls && f.storeCalls.length > 0 ? { storeCalls: f.storeCalls } : {},\n ...f.storeCallsDropped ? { storeCallsDropped: f.storeCallsDropped } : {},\n ...f.outboundCalls && f.outboundCalls.length > 0 ? { outboundCalls: f.outboundCalls } : {},\n ...f.outboundCallsDropped ? { outboundCallsDropped: f.outboundCallsDropped } : {},\n ...f.authChecks?.length ? { authChecks: f.authChecks } : {},\n ...f.authChecksDropped ? { authChecksDropped: f.authChecksDropped } : {},\n ...f.parentInvocationId ? { parentInvocationId: f.parentInvocationId, ...f.parentScopeId ? { parentScopeId: f.parentScopeId } : {} } : {},\n ...f.async ?? {}\n };\n}\nvar STORE_CALL_LOG_CAP = 16;\nfunction tallyStoreCall(tally, call) {\n const calls = tally.storeCalls ?? (tally.storeCalls = []);\n if (calls.length < STORE_CALL_LOG_CAP) {\n calls.push({ binding: call.binding, operation: call.operation, outcome: call.outcome, durationMs: call.durationMs });\n } else {\n tally.storeCallsDropped = (tally.storeCallsDropped ?? 0) + 1;\n }\n}\nvar OUTBOUND_CALL_LOG_CAP = 16;\nfunction tallyOutboundCall(tally, call) {\n const calls = tally.outboundCalls ?? (tally.outboundCalls = []);\n if (calls.length < OUTBOUND_CALL_LOG_CAP) {\n calls.push({\n host: call.host,\n path: call.path,\n method: call.method,\n status: call.status,\n outcome: call.outcome,\n durationMs: call.durationMs,\n atMs: call.atMs,\n ...call.reason !== void 0 ? { reason: call.reason } : {}\n });\n } else {\n tally.outboundCallsDropped = (tally.outboundCallsDropped ?? 0) + 1;\n }\n}\nvar STORE_CALL_SINK_KEY = \"substrat.store-call-sink\";\nfunction distinct(values) {\n return [...new Set(values)];\n}\n\n// packages/kernel/dist/ulid.js\nvar B32 = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nvar MAX_ULID_TIME = 2 ** 48 - 1;\nvar ULID_SHAPE = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nvar unencodable = (t) => `not an encodable ULID instant: ${t} (want 0..${MAX_ULID_TIME})`;\nfunction encodeTime(time) {\n let ts = \"\";\n let t = time;\n for (let i = 0; i < 10; i++) {\n ts = B32[t % 32] + ts;\n t = Math.floor(t / 32);\n }\n return ts;\n}\nfunction createUlid() {\n let lastTime = -1;\n const lastRand = new Array(16).fill(0);\n function freshRandom() {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n for (let i = 0; i < 16; i++)\n lastRand[i] = bytes[i] % 32;\n }\n function incrementRandom() {\n for (let i = 15; i >= 0; i--) {\n if (lastRand[i] < 31) {\n lastRand[i]++;\n return true;\n }\n lastRand[i] = 0;\n }\n return false;\n }\n const mint = ((now = Date.now()) => {\n if (!Number.isSafeInteger(now))\n throw new RangeError(unencodable(now));\n let time = now;\n if (time <= lastTime) {\n time = lastTime;\n if (!incrementRandom()) {\n time = lastTime + 1;\n freshRandom();\n }\n } else {\n freshRandom();\n }\n if (time < 0 || time > MAX_ULID_TIME)\n throw new RangeError(unencodable(time));\n lastTime = time;\n let r = \"\";\n for (const d of lastRand)\n r += B32[d];\n return encodeTime(time) + r;\n });\n mint.seedFrom = (id) => {\n const time = ulidTime(id);\n if (time < lastTime)\n return;\n const rand = [];\n for (const ch of id.slice(10))\n rand.push(B32.indexOf(ch));\n if (time === lastTime) {\n let ahead = false;\n for (let i = 0; i < 16; i++) {\n if (rand[i] !== lastRand[i]) {\n ahead = rand[i] > lastRand[i];\n break;\n }\n }\n if (!ahead)\n return;\n }\n lastTime = time;\n for (let i = 0; i < 16; i++)\n lastRand[i] = rand[i];\n };\n return mint;\n}\nvar processUlid = createUlid();\nfunction ulid(now = Date.now()) {\n return processUlid(now);\n}\nfunction ulidTime(id) {\n if (!ULID_SHAPE.test(id))\n throw new Error(`not a ULID: ${id}`);\n let t = 0;\n for (const ch of id.slice(0, 10))\n t = t * 32 + B32.indexOf(ch);\n if (t > MAX_ULID_TIME)\n throw new Error(`not a ULID: ${id}`);\n return t;\n}\n\n// packages/vertical-host/src/outbound-calls.ts\nvar EGRESS_REFUSAL_HEADER = \"x-substrat-egress\";\nvar STORE_CALL_HOST = \"store.substrat.internal\";\nvar REDACTED = \"[redacted]\";\nvar PATH_MAX = 200;\nvar WORDS = /^[a-z]{1,16}(?:[-_][a-z]{1,16}){0,3}$/;\nvar WORDS_WITH_EXTENSION = /^[a-z]{1,16}(?:[-_][a-z]{1,16}){0,3}\\.[a-z][a-z0-9]{0,4}$/;\nvar SEGMENT_MAX = 40;\nvar SMALL_INTEGER = /^[0-9]{1,10}$/;\nvar VERSION = /^v[0-9]{1,3}(?:\\.[0-9]{1,3}){0,2}$/;\nfunction keepsSegment(segment) {\n if (segment.length > SEGMENT_MAX) return false;\n return segment === \"\" || WORDS.test(segment) || WORDS_WITH_EXTENSION.test(segment) || SMALL_INTEGER.test(segment) || VERSION.test(segment);\n}\nfunction redactOutboundPath(pathname) {\n const path = pathname.split(\"/\").map((segment) => keepsSegment(segment) ? segment : REDACTED).join(\"/\");\n return path.length > PATH_MAX ? `${path.slice(0, PATH_MAX)}…` : path;\n}\nvar ERROR_CLASS = /^[A-Z][A-Za-z]{0,30}(?:Error|Exception)$/;\nfunction errorName(e) {\n const name = e?.name;\n return typeof name === \"string\" && ERROR_CLASS.test(name) ? name : \"Error\";\n}\nfunction answeredOutcome(response) {\n if (response.status === 403 && response.headers?.get?.(EGRESS_REFUSAL_HEADER) === \"refused\") return \"refused\";\n return response.status >= 400 ? \"http-error\" : \"ok\";\n}\nfunction rejectedOutcome(e) {\n const name = errorName(e);\n if (name === \"TimeoutError\") return { outcome: \"timeout\" };\n if (name === \"AbortError\") return { outcome: \"aborted\" };\n return { outcome: \"failed\", reason: name };\n}\nvar SINCE = /* @__PURE__ */ Symbol.for(\"substrat.outbound-since\");\nfunction sinceMap() {\n const g = globalThis;\n return g[SINCE] ??= /* @__PURE__ */ new WeakMap();\n}\nfunction markRequestStart(recording, started) {\n try {\n sinceMap().set(recording, started);\n } catch {\n }\n}\nfunction destinationOf(input, init) {\n const fromRequest = typeof input === \"object\" && input !== null && !(input instanceof URL);\n const raw = fromRequest ? input.url : input;\n let url;\n try {\n url = new URL(String(raw));\n } catch {\n return null;\n }\n const initMethod = init?.method;\n const requestMethod = fromRequest ? input.method : void 0;\n const method = typeof initMethod === \"string\" ? initMethod : typeof requestMethod === \"string\" ? requestMethod : \"GET\";\n return { url, method: method.toUpperCase().slice(0, 16) };\n}\nfunction record(recording, destination, startedAt, end) {\n try {\n const call = {\n host: destination.url.host.toLowerCase(),\n path: redactOutboundPath(destination.url.pathname),\n method: destination.method,\n status: end.status,\n outcome: end.outcome,\n durationMs: Math.max(0, Date.now() - startedAt),\n atMs: Math.max(0, startedAt - (sinceMap().get(recording) ?? startedAt)),\n ...end.reason !== void 0 ? { reason: end.reason } : {}\n };\n tallyOutboundCall(recording, call);\n } catch {\n }\n}\nvar WRAPPED = /* @__PURE__ */ Symbol.for(\"substrat.outbound-fetch\");\nvar IN_CALL = /* @__PURE__ */ Symbol.for(\"substrat.outbound-fetch.in-call\");\nfunction recordingFetch(original, current) {\n const wrapped = function fetch(input, init) {\n const g = globalThis;\n if (g[IN_CALL] === true) return original.call(globalThis, input, init);\n let recording;\n let destination = null;\n try {\n recording = current();\n if (recording) destination = destinationOf(input, init);\n } catch {\n recording = void 0;\n }\n if (!recording || !destination || destination.url.hostname.toLowerCase() === STORE_CALL_HOST) {\n return original.call(globalThis, input, init);\n }\n const rec = recording;\n const dest = destination;\n const startedAt = Date.now();\n let pending;\n g[IN_CALL] = true;\n try {\n pending = original.call(globalThis, input, init);\n } finally {\n g[IN_CALL] = false;\n }\n return pending.then(\n (response) => {\n let status = null;\n let outcome = \"failed\";\n try {\n status = response.status;\n outcome = answeredOutcome(response);\n } catch {\n }\n record(rec, dest, startedAt, { status, outcome });\n return response;\n },\n (e) => {\n let end = { outcome: \"failed\", reason: \"Error\" };\n try {\n end = rejectedOutcome(e);\n } catch {\n }\n record(rec, dest, startedAt, { status: null, ...end });\n throw e;\n }\n );\n };\n Object.defineProperty(wrapped, WRAPPED, { value: true });\n return wrapped;\n}\nfunction installOutboundRecorder(current) {\n try {\n const g = globalThis;\n const existing = g.fetch;\n if (typeof existing !== \"function\" || existing[WRAPPED]) return;\n g.fetch = recordingFetch(existing, current);\n } catch {\n }\n}\n\n// packages/contracts/dist/wire-headers.js\nvar PLATFORM_SECRET_HEADER = \"x-substrat-platform\";\nvar CONNECTOR_ATTACHMENT_META_MAX_BYTES = 8 * 1024;\n\n// packages/contracts/dist/wire-auth.js\nvar PlatformCallError = class extends Error {\n};\nfunction secretMatches(presented, expected) {\n const given = presented ?? \"\";\n let diff = given.length ^ expected.length | (given.length === 0 ? 1 : 0);\n for (let i = 0; i < expected.length; i++) {\n diff |= (i < given.length ? given.charCodeAt(i) : 0) ^ expected.charCodeAt(i);\n }\n return diff === 0;\n}\nfunction assertPlatformCall(headers, options = {}) {\n const { expectedSecret } = options;\n if (!expectedSecret) {\n throw new PlatformCallError(\"platform calls are not configured on this deployment\");\n }\n if (!secretMatches(headers.get(PLATFORM_SECRET_HEADER), expectedSecret)) {\n throw new PlatformCallError(\"not a platform call\");\n }\n}\n\n// packages/vertical-host/src/routed-node.ts\nvar ROUTED_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nvar RouterAssertionError = class extends Error {\n};\nfunction readRoutedNode(headers, options = {}) {\n const rawTenant = headers.get(\"x-substrat-tenant\");\n const rawScope = headers.get(\"x-substrat-scope\");\n if (!rawTenant && !rawScope) return null;\n const { expectedSecret, allowUnsigned: allowUnsigned2 = false } = options;\n if (expectedSecret) {\n if (!secretMatches(headers.get(\"x-substrat-router\"), expectedSecret)) {\n throw new RouterAssertionError(\"router assertion is not signed by a known router\");\n }\n } else if (!allowUnsigned2) {\n throw new RouterAssertionError(\n \"router assertion cannot be verified: this worker has no ROUTER_SECRET configured\"\n );\n }\n if (!rawTenant || !rawScope) {\n throw new RouterAssertionError(\"router assertion is incomplete\");\n }\n if (!ROUTED_ID.test(rawTenant) || !ROUTED_ID.test(rawScope)) {\n throw new RouterAssertionError(\"router assertion carries a malformed id\");\n }\n return {\n tenantId: rawTenant,\n scopeId: rawScope,\n surface: headers.get(\"x-substrat-surface\") ?? \"app\",\n verticalSlug: headers.get(\"x-substrat-vertical\")\n };\n}\n\n// packages/vertical-host/src/invocation-log.ts\nfunction builtinAsyncLocalStorage() {\n try {\n const proc = globalThis.process;\n const mod = proc?.getBuiltinModule?.(\"node:async_hooks\");\n return typeof mod?.AsyncLocalStorage === \"function\" ? mod.AsyncLocalStorage : void 0;\n } catch {\n return void 0;\n }\n}\nfunction storeCallSlot(provided) {\n try {\n const g = globalThis;\n const key = Symbol.for(STORE_CALL_SINK_KEY);\n const existing = g[key];\n if (typeof existing?.run === \"function\" && typeof existing.current === \"function\") return existing;\n const Als = provided ?? builtinAsyncLocalStorage();\n if (!Als) return void 0;\n const storage = new Als();\n const slot = {\n current() {\n const tally = storage.getStore()?.tally;\n return tally ? (call) => tallyStoreCall(tally, call) : void 0;\n },\n invocationId: () => storage.getStore()?.invocationId,\n run: (tally, fn, invocationId) => storage.run({ tally, invocationId }, fn),\n recording: () => storage.getStore()?.tally\n };\n g[key] = slot;\n return slot;\n } catch {\n return void 0;\n }\n}\nfunction currentRecording() {\n const slot = globalThis[Symbol.for(STORE_CALL_SINK_KEY)];\n return typeof slot?.recording === \"function\" ? slot.recording() : void 0;\n}\nfunction runRecording(stamp, started, provided, fn) {\n const slot = storeCallSlot(provided);\n if (!slot) return fn();\n try {\n const authSink = {\n record(check) {\n const record2 = currentRecording();\n if (record2) tallyAuthCheck(record2, check);\n }\n };\n globalThis[AUTH_DIAGNOSTICS_KEY] = authSink;\n } catch {\n }\n markRequestStart(stamp.record, started);\n installOutboundRecorder(currentRecording);\n return slot.run(stamp.record, fn, stamp.invocationId);\n}\nfunction versionIdOf(env) {\n const v = env?.SUBSTRAT_VERSION_ID;\n return typeof v === \"string\" && v.length > 0 ? v : null;\n}\nvar UPLOAD_LINK_LOG_SECRET_PREFIX = \"sbup_\";\nvar UPLOAD_LINK_SECRET_SEGMENT = /^(\\/api\\/attachment-uploads\\/[^/]+\\/[^/]+\\/)[^/]+/;\nvar SECRET_SHAPED_SEGMENT = new RegExp(`(^|/)${UPLOAD_LINK_LOG_SECRET_PREFIX}[^/]*`, \"g\");\nvar redactUploadLinkSecret = (pathname) => pathname.replace(UPLOAD_LINK_SECRET_SEGMENT, \"$1[redacted]\").replace(SECRET_SHAPED_SEGMENT, \"$1[redacted]\");\nfunction pathOf(url) {\n try {\n return redactUploadLinkSecret(new URL(url).pathname);\n } catch {\n return \"/\";\n }\n}\nvar STAMPS = /* @__PURE__ */ Symbol.for(\"substrat.invocation-stamp\");\nfunction stamps() {\n const g = globalThis;\n return g[STAMPS] ??= /* @__PURE__ */ new WeakMap();\n}\nfunction invocationStampOf(request) {\n return stamps().get(request);\n}\nfunction withRequestId(response, id) {\n const headers = response?.headers;\n try {\n headers?.set?.(REQUEST_ID_HEADER, id);\n return response;\n } catch {\n }\n try {\n const r = response;\n if (r.status === 101) return response;\n const copy = new Response(r.body, r);\n copy.headers.set(REQUEST_ID_HEADER, id);\n return copy;\n } catch {\n return response;\n }\n}\nfunction beginStamp(request, env, options) {\n const stamp = { invocationId: ulid(), record: {} };\n if (installedTraceSink()) markTraceStart(stamp.invocationId);\n const fieldCoverageId = armedFieldCoverageId(request.headers, env, options);\n if (fieldCoverageId) stamp.fieldCoverageId = fieldCoverageId;\n stamps().set(request, stamp);\n return stamp;\n}\nfunction armedFieldCoverageId(headers, env, options) {\n let id;\n try {\n id = headers.get(FIELD_COVERAGE_HEADER);\n } catch {\n return void 0;\n }\n if (id === null || !ROUTED_ID.test(id)) return void 0;\n return routedNodeOrNull(headers, env, options) !== null ? id : void 0;\n}\nfunction writeInvocationLine(stamp, done, options) {\n traceRequest(stamp, done);\n try {\n writeLineOrThrow(stamp, done, options);\n } catch (e) {\n try {\n console.log(JSON.stringify({ substrat: \"invocation-log-fault\", detail: String(e) }));\n } catch {\n }\n }\n}\nfunction traceRequest(stamp, done) {\n const sink = installedTraceSink();\n if (!sink) return;\n try {\n const { record: record2, invocationId } = stamp;\n const durationMs = Date.now() - done.started;\n const line = invocationLine({\n tenantId: \"\",\n scopeId: null,\n vertical: null,\n surface: null,\n method: done.request.method,\n path: pathOf(done.request.url),\n status: done.status,\n threw: done.threw,\n durationMs,\n invocationId,\n level: invocationLevelOf(done.status, done.threw, record2.problemCode),\n operation: record2.operation,\n problemCode: record2.problemCode,\n principalKind: record2.principalKind,\n ...record2.emitted ? { emitted: record2.emitted } : {},\n versionId: versionIdOf(done.env)\n });\n sink.head(invocationId, {\n startedAt: new Date(done.started).toISOString(),\n method: line.method,\n path: line.path,\n status: line.status,\n threw: line.threw,\n durationMs: line.durationMs,\n level: line.level,\n operation: line.operation,\n problemCode: line.problemCode,\n principalKind: line.principalKind,\n eventCount: line.eventCount,\n eventTypes: line.eventTypes,\n entities: line.entities,\n versionId: line.versionId,\n // Calls the record kept no room for: a truncated list must read as truncated.\n ...record2.outboundCallsDropped ? { stepsDropped: record2.outboundCallsDropped } : {}\n });\n for (const call of record2.outboundCalls ?? []) {\n sink.step(invocationId, {\n type: \"outbound\",\n atMs: call.atMs,\n durationMs: call.durationMs,\n host: call.host,\n path: call.path,\n method: call.method,\n status: call.status,\n outcome: call.outcome,\n ...call.reason ? { reason: call.reason } : {}\n });\n }\n for (const check of record2.authChecks ?? []) {\n sink.step(invocationId, { type: \"log\", atMs: durationMs, level: check.outcome === \"refused\" || check.outcome === \"error\" ? \"warn\" : \"info\", message: `auth ${check.stage}: ${check.outcome} (${check.reason})` });\n }\n if (record2.authChecksDropped) sink.head(invocationId, { stepsDropped: record2.authChecksDropped });\n sink.end(invocationId);\n forgetTraceStart(invocationId);\n } catch {\n }\n}\nfunction writeLineOrThrow(stamp, done, options) {\n const node = routedNodeOrNull(done.request.headers, done.env, options);\n if (!node) return;\n const { record: record2, invocationId } = stamp;\n const line = invocationLine({\n tenantId: node.tenantId,\n scopeId: node.scopeId,\n vertical: node.verticalSlug,\n surface: node.surface,\n method: done.request.method,\n path: pathOf(done.request.url),\n status: done.status,\n threw: done.threw,\n durationMs: Date.now() - done.started,\n invocationId,\n level: invocationLevelOf(done.status, done.threw, record2.problemCode),\n operation: record2.operation,\n problemCode: record2.problemCode,\n principalKind: record2.principalKind,\n ...record2.emitted ? { emitted: record2.emitted } : {},\n versionId: versionIdOf(done.env),\n ...record2.outputFields ? { outputFields: record2.outputFields } : {},\n ...stamp.fieldCoverageId ? { fieldCoverageId: stamp.fieldCoverageId } : {},\n ...record2.storeCalls && record2.storeCalls.length > 0 ? { storeCalls: record2.storeCalls } : {},\n ...record2.storeCallsDropped ? { storeCallsDropped: record2.storeCallsDropped } : {},\n ...record2.outboundCalls && record2.outboundCalls.length > 0 ? { outboundCalls: record2.outboundCalls } : {},\n ...record2.outboundCallsDropped ? { outboundCallsDropped: record2.outboundCallsDropped } : {},\n ...record2.authChecks?.length ? { authChecks: record2.authChecks } : {},\n ...record2.authChecksDropped ? { authChecksDropped: record2.authChecksDropped } : {}\n });\n console.log(JSON.stringify(line));\n}\nvar OTHER_HANDLERS = [\"scheduled\", \"queue\", \"email\", \"tail\", \"trace\", \"alarm\", \"test\"];\nfunction withInvocationLog(worker, options = {}) {\n const inner = worker?.fetch;\n if (typeof inner !== \"function\") return worker;\n const wrapped = {\n async fetch(request, env, ctx) {\n if (invocationStampOf(request)) return inner.call(worker, request, env, ctx);\n const started = Date.now();\n const stamp = beginStamp(request, env, options);\n let status = null;\n let threw = false;\n try {\n const response = withRequestId(\n await runRecording(stamp, started, options.asyncLocalStorage, () => inner.call(worker, request, env, ctx)),\n stamp.invocationId\n );\n status = response.status;\n handRecordToRouter(response, stamp.record, request, env, options);\n return response;\n } catch (e) {\n threw = true;\n throw e;\n } finally {\n writeInvocationLine(stamp, { request, env, status, threw, started }, options);\n }\n }\n };\n for (const name of OTHER_HANDLERS) {\n const h = worker[name];\n if (typeof h === \"function\") wrapped[name] = h.bind(worker);\n }\n return wrapped;\n}\nfunction handRecordToRouter(response, record2, request, env, options) {\n try {\n const value = encodeInvocationRecord(record2);\n if (value === null || !routedNodeOrNull(request.headers, env, options)) return;\n response.headers?.set?.(\n INVOCATION_RECORD_HEADER,\n value\n );\n } catch {\n }\n}\nfunction routedNodeOrNull(headers, env, options) {\n try {\n return readRoutedNode(headers, {\n expectedSecret: options.routerSecret?.(env),\n allowUnsigned: options.allowUnsigned?.(env) ?? false\n });\n } catch (e) {\n if (!(e instanceof RouterAssertionError)) console.log(JSON.stringify({ substrat: \"invocation-log-fault\", detail: String(e) }));\n return null;\n }\n}\n\n// packages/contracts/dist/scope-store-envelope.js\nfunction bytesToBase64Url(bytes) {\n let binary = \"\";\n for (const byte of bytes)\n binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\nfunction base64UrlToBytes(value) {\n if (!/^[A-Za-z0-9_-]+$/.test(value))\n return void 0;\n const padded = value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\") + \"=\".repeat((4 - value.length % 4) % 4);\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n } catch {\n return void 0;\n }\n}\nfunction copyBytes(bytes) {\n const copy = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(copy).set(bytes);\n return copy;\n}\nvar SMALL_ORDER_KEYS = [\n \"0000000000000000000000000000000000000000000000000000000000000000\",\n // y = 0, order 4\n \"0100000000000000000000000000000000000000000000000000000000000000\",\n // the identity, order 1\n \"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05\",\n // order 8\n \"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a\",\n // order 8\n \"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f\",\n // y = p - 1, order 2\n \"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f\",\n // y = p, a non-canonical 0\n \"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f\"\n // y = p + 1, a non-canonical identity\n];\nfunction isSmallOrderKey(bytes) {\n const unsigned = Uint8Array.from(bytes);\n unsigned[31] = unsigned[31] & 127;\n const hex = [...unsigned].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return SMALL_ORDER_KEYS.includes(hex);\n}\nasync function scopeStoreKeyId(publicKey) {\n const bytes = base64UrlToBytes(publicKey);\n if (!bytes || bytes.length !== 32)\n throw new Error(\"a store public key is not 32 bytes of base64url\");\n if (isSmallOrderKey(bytes))\n throw new Error(\"a store public key is a small-order point\");\n const hash = await crypto.subtle.digest(\"SHA-256\", copyBytes(bytes));\n return bytesToBase64Url(new Uint8Array(hash).slice(0, 8));\n}\nfunction scopeStorePublicKeyProblem(key) {\n if (key.length === 0)\n return \"empty\";\n const bytes = base64UrlToBytes(key);\n if (bytes?.length !== 32)\n return \"length\";\n if (isSmallOrderKey(bytes))\n return \"small-order\";\n if (bytesToBase64Url(bytes) !== key)\n return \"non-canonical\";\n return void 0;\n}\nvar PUBLIC_KEY_PROBLEM = {\n empty: \"a store public key list is empty or has an empty entry\",\n length: \"a store public key is not 32 bytes of base64url\",\n \"small-order\": \"a store public key is a small-order point\",\n \"non-canonical\": \"a store public key is not canonical base64url\"\n};\nfunction parseScopeStorePublicKeys(text) {\n const keys = text.split(\",\").map((key) => key.trim());\n if (keys.some((key) => key.length === 0))\n throw new Error(PUBLIC_KEY_PROBLEM.empty);\n const seen = /* @__PURE__ */ new Set();\n for (const key of keys) {\n const problem2 = scopeStorePublicKeyProblem(key);\n if (problem2)\n throw new Error(PUBLIC_KEY_PROBLEM[problem2]);\n if (seen.has(key))\n throw new Error(\"a store public key is listed twice\");\n seen.add(key);\n }\n return keys;\n}\nasync function verifyScopeStoreEnvelope(publicKey, canonical, signature) {\n const keyBytes = base64UrlToBytes(publicKey);\n const sigBytes = base64UrlToBytes(signature);\n if (!keyBytes || !sigBytes || sigBytes.length !== 64)\n return false;\n try {\n const key = await crypto.subtle.importKey(\"raw\", copyBytes(keyBytes), { name: \"Ed25519\" }, false, [\"verify\"]);\n return await crypto.subtle.verify(\"Ed25519\", key, copyBytes(sigBytes), new TextEncoder().encode(canonical));\n } catch {\n return false;\n }\n}\n\n// packages/contracts/dist/wire-signing.js\nvar WIRE_ENVELOPE_VERSION = 1;\nvar WIRE_ENVELOPE_TAG = `substrat-wire/${WIRE_ENVELOPE_VERSION}`;\nvar WIRE_ENVELOPE_HEADER = \"x-substrat-wire-envelope\";\nvar WIRE_SIGNATURE_HEADER = \"x-substrat-wire-signature\";\nvar WIRE_ENVELOPE_MAX_LIFETIME_SECONDS = 120;\nvar WIRE_CLOCK_SKEW_SECONDS = 30;\nvar SHAPES = {\n router: {\n // An end user's request the router resolved: always a tenant, a scope and a surface. The\n // body is a stream the router does not buffer, so a route binds none.\n route: { scope: \"required\", surface: \"required\", vertical: \"optional\", body: \"absent\" },\n // An internal call the router makes itself, such as a peer invocation.\n call: { scope: \"optional\", surface: \"absent\", vertical: \"optional\", body: \"required\" }\n },\n platform: {\n call: { scope: \"optional\", surface: \"absent\", vertical: \"absent\", body: \"required\" }\n }\n};\nfunction wireEnvelopeShape(iss, kind) {\n const byKind = Object.hasOwn(SHAPES, iss) ? SHAPES[iss] : void 0;\n return byKind && Object.hasOwn(byKind, kind) ? byKind[kind] : void 0;\n}\nvar LINES = 15;\nvar ULID = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nvar METHOD = /^[!#$%&'*+.^_`|~0-9A-Z-]{1,32}$/;\nvar DIGEST = /^[0-9a-f]{64}$/;\nvar SECONDS = /^(0|[1-9]\\d{0,14})$/;\nvar CONTROL = /[\\u0000-\\u001f\\u007f]/;\nvar LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/;\nvar MAX_TEXT = 255;\nvar isText = (value) => value.length <= MAX_TEXT && !CONTROL.test(value) && !LONE_SURROGATE.test(value);\nvar isWireAudience = (value) => value !== \"\" && isText(value);\nfunction isCanonicalBase64Url(text, length) {\n const bytes = base64UrlToBytes(text);\n return bytes?.length === length && bytesToBase64Url(bytes) === text;\n}\nfunction admits(presence, value, valid) {\n if (value === \"\")\n return presence !== \"required\";\n return presence !== \"absent\" && valid(value);\n}\nfunction parseWireEnvelope(canonical) {\n const lines = canonical.split(\"\\n\");\n if (lines.length !== LINES)\n return void 0;\n const [tag, iss, kind, kid, aud, tenantId, scopeId, surface, vertical2, method, targetDigest, bodyDigest, iat, exp, nonce] = lines;\n if (tag !== WIRE_ENVELOPE_TAG)\n return void 0;\n const shape = wireEnvelopeShape(iss, kind);\n if (!shape)\n return void 0;\n if (!isCanonicalBase64Url(kid, 8) || !isCanonicalBase64Url(nonce, 16))\n return void 0;\n if (!isWireAudience(aud))\n return void 0;\n if (tenantId === \"\" !== (scopeId === \"\"))\n return void 0;\n if (!admits(shape.scope, tenantId, (id) => ULID.test(id)) || !admits(shape.scope, scopeId, (id) => ULID.test(id)))\n return void 0;\n if (!admits(shape.surface, surface, isText) || !admits(shape.vertical, vertical2, isText))\n return void 0;\n if (!METHOD.test(method) || !DIGEST.test(targetDigest) || !admits(shape.body, bodyDigest, (d) => DIGEST.test(d)))\n return void 0;\n if (!SECONDS.test(iat) || !SECONDS.test(exp))\n return void 0;\n const orNull = (value) => value === \"\" ? null : value;\n return {\n v: 1,\n iss,\n kind,\n kid,\n aud,\n tenantId: orNull(tenantId),\n scopeId: orNull(scopeId),\n surface: orNull(surface),\n vertical: orNull(vertical2),\n method,\n targetDigest,\n bodyDigest: orNull(bodyDigest),\n iat: Number(iat),\n exp: Number(exp),\n nonce\n };\n}\nfunction decodeWireEnvelope(header) {\n const bytes = base64UrlToBytes(header);\n if (!bytes)\n return void 0;\n let canonical;\n try {\n canonical = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(bytes);\n } catch {\n return void 0;\n }\n const claims = parseWireEnvelope(canonical);\n return claims ? { canonical, claims } : void 0;\n}\nfunction bytesOf(data) {\n if (typeof data === \"string\")\n return new TextEncoder().encode(data);\n const view = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);\n return view.buffer instanceof ArrayBuffer ? view : view.slice();\n}\nasync function wireDigest(data) {\n const hash = await crypto.subtle.digest(\"SHA-256\", bytesOf(data));\n return [...new Uint8Array(hash)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction wireRequestBinding(request) {\n const url = new URL(request.url);\n return { method: request.method.toUpperCase(), target: `${url.pathname}${url.search}` };\n}\nfunction lifetimeAdmitted(iat, exp) {\n return exp > iat && exp - iat <= WIRE_ENVELOPE_MAX_LIFETIME_SECONDS;\n}\nvar PREPARED = /* @__PURE__ */ new WeakMap();\nasync function wireVerificationKeys(config) {\n const listed = (text) => text?.trim() ? parseScopeStorePublicKeys(text) : [];\n const router = listed(config.router);\n const platform = listed(config.platform);\n if (router.some((key) => platform.includes(key)))\n throw new Error(\"a wire public key is listed for both issuers\");\n const byKid = async (keys2) => new Map(await Promise.all(keys2.map(async (key) => [await scopeStoreKeyId(key), key])));\n const own = Object.freeze({ router: await byKid(router), platform: await byKid(platform) });\n const keys = Object.freeze({ router: new Map(own.router), platform: new Map(own.platform) });\n PREPARED.set(keys, own);\n return keys;\n}\nvar WIRE_REFUSED = Object.freeze({ ok: false });\nasync function verifyWireEnvelope(input) {\n const refuse = (reason) => {\n try {\n void Promise.resolve(input.onRefusal?.(reason)).catch(() => {\n });\n } catch {\n }\n return WIRE_REFUSED;\n };\n const { expected, keys, nowSeconds } = input;\n const own = PREPARED.get(keys);\n if (!own)\n throw new TypeError(\"verifyWireEnvelope takes the key set wireVerificationKeys built\");\n const replay = expected.kind === \"call\" ? expected.replay : \"none\";\n if (replay !== \"none\" && typeof replay?.claim !== \"function\") {\n throw new TypeError(\"a call's expectation states its replay policy: 'none' or a nonce cache\");\n }\n if (replay !== \"none\" && expected.scopeId == null) {\n throw new TypeError(\"a call that keeps nonces pins the scope whose object holds them\");\n }\n if (replay !== \"none\" && typeof input.clockSeconds !== \"function\") {\n throw new TypeError(\"a call that keeps nonces takes a clockSeconds function to time its claim\");\n }\n const header = input.headers.get(WIRE_ENVELOPE_HEADER);\n const signature = input.headers.get(WIRE_SIGNATURE_HEADER);\n if (!header || !signature)\n return refuse(\"missing\");\n const decoded = decodeWireEnvelope(header);\n if (!decoded)\n return refuse(\"malformed\");\n const { canonical, claims } = decoded;\n if (claims.iss !== expected.iss)\n return refuse(\"issuer\");\n if (claims.kind !== expected.kind)\n return refuse(\"kind\");\n const publicKey = own[claims.iss].get(claims.kid);\n if (!publicKey)\n return refuse(\"kid\");\n if (!await verifyScopeStoreEnvelope(publicKey, canonical, signature))\n return refuse(\"signature\");\n if (claims.aud !== expected.aud)\n return refuse(\"audience\");\n if (!lifetimeAdmitted(claims.iat, claims.exp))\n return refuse(\"lifetime\");\n if (!(nowSeconds >= claims.iat - WIRE_CLOCK_SKEW_SECONDS))\n return refuse(\"not-yet-valid\");\n if (!(nowSeconds <= claims.exp + WIRE_CLOCK_SKEW_SECONDS))\n return refuse(\"expired\");\n if (claims.method !== expected.method)\n return refuse(\"method\");\n if (claims.targetDigest !== await wireDigest(expected.target))\n return refuse(\"target\");\n if (expected.kind === \"call\") {\n const body = typeof expected.body === \"function\" ? await expected.body() : expected.body;\n if (body == null || claims.bodyDigest !== await wireDigest(body))\n return refuse(\"body\");\n }\n if (expected.tenantId !== void 0 && claims.tenantId !== expected.tenantId)\n return refuse(\"scope\");\n if (expected.scopeId !== void 0 && claims.scopeId !== expected.scopeId)\n return refuse(\"scope\");\n if (replay !== \"none\") {\n const until = claims.exp + WIRE_CLOCK_SKEW_SECONDS;\n const claimedAt = input.clockSeconds();\n if (!Number.isFinite(claimedAt) || claimedAt < 0) {\n throw new TypeError(\"clockSeconds read something other than a time in seconds\");\n }\n if (!(claimedAt <= until))\n return refuse(\"claim-after-until\");\n if (await replay.claim(claims.nonce, until) !== true)\n return refuse(\"replay\");\n }\n return { ok: true, claims };\n}\nvar WIRE_ROUTER_KEYS_VAR = \"SUBSTRAT_WIRE_ROUTER_KEYS\";\nvar WIRE_PLATFORM_KEYS_VAR = \"SUBSTRAT_WIRE_PLATFORM_KEYS\";\nvar WIRE_AUDIENCE_VAR = \"SUBSTRAT_WIRE_AUDIENCE\";\nvar WIRE_STATE_VAR = \"SUBSTRAT_WIRE_STATE\";\nfunction wireStateOf(config) {\n const listed = (value) => typeof value === \"string\" && value.trim() !== \"\";\n if (!listed(config.routerKeys) && !listed(config.platformKeys))\n return \"legacy-only\";\n return config.state === \"legacy-only\" || config.state === \"signed-only\" ? config.state : \"dual\";\n}\nvar ROUTE_ENDPOINT = Object.freeze({ kind: \"route\", issuers: Object.freeze([\"router\"]) });\nvar CALL_ENDPOINT = Object.freeze({ kind: \"call\", issuers: Object.freeze([\"platform\"]) });\nvar PEER_INVOKE_ENDPOINT = Object.freeze({ kind: \"call\", issuers: Object.freeze([\"platform\", \"router\"]) });\nfunction tryDecode(path, decoder) {\n try {\n return decoder(path);\n } catch {\n return path.replace(/(?:%[0-9A-Fa-f]{2})+/g, (run) => {\n try {\n return decoder(run);\n } catch {\n return run;\n }\n });\n }\n}\nfunction collapsed(path) {\n const segments = [];\n for (const segment of path.split(\"/\")) {\n if (segment === \"..\")\n segments.pop();\n else if (segment !== \"\" && segment !== \".\")\n segments.push(segment);\n }\n return `/${segments.join(\"/\")}`;\n}\nvar INTERNAL = /^\\/internal(?:\\/|$)/i;\nfunction wireEndpoint(pathname) {\n const routed = tryDecode(pathname.includes(\"%25\") ? pathname.replace(/%25/g, \"%2525\") : pathname, decodeURI);\n const forms = [pathname, routed, tryDecode(pathname, decodeURIComponent)];\n if (!forms.some((form) => INTERNAL.test(form) || INTERNAL.test(collapsed(form))))\n return ROUTE_ENDPOINT;\n return pathname === \"/internal/vertical-invoke\" ? PEER_INVOKE_ENDPOINT : CALL_ENDPOINT;\n}\nvar WIRE_REPLAY_FREE_CALLS = Object.freeze([\n \"/internal/query\",\n \"/internal/redrain-count\",\n \"/internal/lifecycle-flow\",\n \"/internal/operation-series\",\n \"/internal/connector-grants\"\n]);\nvar SAFE_METHODS = /* @__PURE__ */ new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\nfunction wireReplayOf(method, pathname) {\n return SAFE_METHODS.has(method.toUpperCase()) || WIRE_REPLAY_FREE_CALLS.includes(pathname) ? \"none\" : \"nonce\";\n}\nvar UNSIGNED = Object.freeze([\n [FIELD_COVERAGE_HEADER, \"route\", (value) => ULID.test(value)],\n [PARENT_REQUEST_ID_HEADER, \"call\", (value) => parentRequestIdOf(value) !== void 0]\n]);\nvar WIRE_UNSIGNED_HEADERS = Object.freeze(Object.fromEntries(UNSIGNED.map(([name, kind]) => [name, kind])));\nfunction wireUnsignedHeadersOf(kind, headers) {\n const kept = [];\n for (const [name, on, valid] of UNSIGNED) {\n const value = on === kind ? headers.get(name) : null;\n if (value !== null && valid(value))\n kept.push([name, value]);\n }\n return kept;\n}\n\n// packages/control-plane-api/platform-entry/wire-gate.ts\nvar WIRE_CLAIM_TIMEOUT_MS = 1e3;\nvar WIRE_REFUSAL_BODY = '{\"type\":\"about:blank\",\"title\":\"Unauthorized\",\"status\":401,\"detail\":\"unauthorized\",\"error\":\"unauthorized\"}';\nvar WIRE_FAULT_BODY = '{\"type\":\"about:blank\",\"title\":\"Service unavailable\",\"status\":503,\"detail\":\"this request could not be verified\",\"error\":\"this request could not be verified\"}';\nvar problem = (body, status) => new Response(body, { status, headers: { \"content-type\": \"application/problem+json\" } });\nvar ASSERTED_PREFIX = \"x-substrat-\";\nvar TENANT = \"x-substrat-tenant\";\nvar SCOPE = \"x-substrat-scope\";\nvar SURFACE = \"x-substrat-surface\";\nvar VERTICAL = \"x-substrat-vertical\";\nvar ROUTER_CREDENTIAL = \"x-substrat-router\";\nvar GateFault = class extends Error {\n constructor(fault) {\n super(fault);\n this.fault = fault;\n }\n fault;\n};\nfunction claimedThrough(reach, timeoutMs) {\n return {\n async claim(nonce, until) {\n let cache;\n try {\n cache = reach();\n } catch {\n throw new GateFault(\"nonce-store\");\n }\n if (cache == null) throw new GateFault(\"no-nonce-store\");\n let timer;\n try {\n return await Promise.race([\n cache.claim(nonce, until),\n new Promise((_, reject) => {\n timer = setTimeout(() => reject(new Error(\"the nonce store did not answer in time\")), timeoutMs);\n })\n ]);\n } catch {\n throw new GateFault(\"nonce-store\");\n } finally {\n clearTimeout(timer);\n }\n }\n };\n}\nvar builtKeys;\nfunction keysFor(router, platform) {\n const text = `${router}\n${platform}`;\n if (builtKeys?.text !== text) builtKeys = { text, keys: wireVerificationKeys({ router, platform }) };\n return builtKeys.keys;\n}\nvar textOf = (value) => typeof value === \"string\" ? value : \"\";\nfunction stateOf(env) {\n const e = env ?? {};\n return wireStateOf({ routerKeys: e[WIRE_ROUTER_KEYS_VAR], platformKeys: e[WIRE_PLATFORM_KEYS_VAR], state: e[WIRE_STATE_VAR] });\n}\nfunction legacyOf(request, call, env, options) {\n if (call) {\n let credential = request.headers.has(PLATFORM_SECRET_HEADER) ? \"invalid\" : \"absent\";\n try {\n assertPlatformCall(request.headers, { expectedSecret: options.platformSecret(env) });\n credential = \"valid\";\n } catch {\n }\n return { credential, identity: null };\n }\n try {\n const node = options.routedNode(request.headers, env);\n return node ? { credential: \"valid\", identity: node } : { credential: \"absent\", identity: null };\n } catch {\n return { credential: \"invalid\", identity: null };\n }\n}\nvar sameIdentity = (legacy, claims) => legacy.tenantId === claims.tenantId && legacy.scopeId === claims.scopeId && legacy.surface === claims.surface && legacy.verticalSlug === claims.vertical;\nvar servedAs = (who) => ({\n tenantId: who?.tenantId ?? null,\n scopeId: who?.scopeId ?? null\n});\nfunction withWireGate(worker, options) {\n const inner = worker?.fetch;\n if (typeof inner !== \"function\") return worker;\n const clock = options.clock ?? Date.now;\n const seconds = () => Math.floor(clock() / 1e3);\n const timeoutMs = options.claimTimeoutMs ?? WIRE_CLAIM_TIMEOUT_MS;\n const log = options.log ?? ((line) => console.log(line));\n const serve = (request, env, ctx) => inner.call(worker, request, env, ctx);\n async function judged(request, env, ctx, state) {\n const nowSeconds = seconds();\n const e = env;\n const aud = textOf(e[WIRE_AUDIENCE_VAR]);\n const { method, target } = wireRequestBinding(request);\n const pathname = new URL(request.url).pathname;\n const endpoint = wireEndpoint(pathname);\n const call = endpoint.kind === \"call\";\n const claimed = call ? decodeWireEnvelope(request.headers.get(WIRE_ENVELOPE_HEADER) ?? \"\")?.claims : void 0;\n const issuer = claimed && endpoint.issuers.includes(claimed.iss) ? claimed.iss : endpoint.issuers[0];\n let claims;\n const line = (outcome, legacy2, extra = {}) => {\n const v = e[\"SUBSTRAT_VERSION_ID\"];\n const record2 = {\n substrat: \"wire\",\n state,\n issuer: claims?.iss ?? (endpoint.issuers.length === 1 ? endpoint.issuers[0] : null),\n kind: endpoint.kind,\n outcome,\n reason: null,\n fault: null,\n legacy: legacy2,\n tenantId: null,\n scopeId: null,\n versionId: typeof v === \"string\" && v.length > 0 ? v : null,\n ...extra\n };\n try {\n log(JSON.stringify(record2));\n } catch {\n }\n };\n const faulted = (fault, legacy2) => {\n line(\"fault\", legacy2, { fault });\n return problem(WIRE_FAULT_BODY, 503);\n };\n const legacy = legacyOf(request, call, env, options);\n let downstream = request;\n const staticFault = (fault, extra = {}) => {\n if (state !== \"dual\") return faulted(fault, legacy.credential);\n line(\"fault\", legacy.credential, { fault, ...extra });\n return serve(downstream, env, ctx);\n };\n let keys;\n try {\n keys = await keysFor(textOf(e[WIRE_ROUTER_KEYS_VAR]), textOf(e[WIRE_PLATFORM_KEYS_VAR]));\n } catch {\n return staticFault(\"keys\", servedAs(legacy.identity));\n }\n const readBody = async () => {\n if (request.body === null) return \"\";\n let body;\n try {\n body = await request.arrayBuffer();\n } catch {\n return null;\n }\n downstream = new Request(request, { body });\n return body;\n };\n const keepsNonces = call && wireReplayOf(method, pathname) === \"nonce\";\n const pinned = keepsNonces ? claimed?.scopeId ?? void 0 : void 0;\n const reach = options.nonceCache;\n const store = pinned !== void 0 && reach ? claimedThrough(() => reach(env, pinned), timeoutMs) : void 0;\n const expected = call ? {\n iss: issuer,\n kind: \"call\",\n aud,\n method,\n target,\n body: readBody,\n replay: store ?? \"none\",\n scopeId: store ? pinned : void 0\n } : { iss: \"router\", kind: \"route\", aud, method, target };\n let reason = null;\n let noStore = !store;\n try {\n const verdict = await verifyWireEnvelope({\n headers: request.headers,\n keys,\n expected,\n nowSeconds,\n clockSeconds: seconds,\n onRefusal: (why) => {\n reason = why;\n }\n });\n if (verdict.ok) claims = verdict.claims;\n } catch (error) {\n if (error instanceof GateFault && error.fault === \"no-nonce-store\") {\n claims = claimed;\n noStore = true;\n } else {\n return faulted(error instanceof GateFault ? error.fault : \"verifier\", legacy.credential);\n }\n }\n if (claims && keepsNonces && noStore) {\n return staticFault(\"no-nonce-store\", servedAs(legacy.identity ?? claims));\n }\n const mismatched = !!claims && !!legacy.identity && !sameIdentity(legacy.identity, claims);\n if (state === \"dual\" && legacy.credential === \"valid\") {\n const outcome = !claims ? \"legacy-accepted\" : mismatched ? \"dual-mismatch\" : \"signed-accepted\";\n line(outcome, \"valid\", { reason, ...servedAs(legacy.identity ?? claims ?? null) });\n return serve(downstream, env, ctx);\n }\n if (!claims) {\n line(\"refused\", legacy.credential, { reason });\n if (state === \"dual\") return serve(downstream, env, ctx);\n return problem(WIRE_REFUSAL_BODY, 401);\n }\n let proven;\n try {\n proven = provenAs(downstream, claims, env, options);\n } catch {\n return faulted(\"verifier\", legacy.credential);\n }\n line(mismatched ? \"dual-mismatch\" : \"signed-accepted\", legacy.credential, servedAs(claims));\n return serve(proven, env, ctx);\n }\n return {\n ...worker,\n fetch(request, env, ctx) {\n const state = stateOf(env);\n if (state === \"legacy-only\") return serve(request, env, ctx);\n return judged(request, env, ctx, state);\n }\n };\n}\nfunction provenAs(request, claims, env, options) {\n const headers = new Headers(request.headers);\n for (const name of [...headers.keys()]) if (name.startsWith(ASSERTED_PREFIX)) headers.delete(name);\n for (const [name, value] of wireUnsignedHeadersOf(claims.kind, request.headers)) headers.set(name, value);\n const put = (name, value) => {\n if (value) headers.set(name, value);\n };\n if (claims.kind === \"route\") {\n put(TENANT, claims.tenantId);\n put(SCOPE, claims.scopeId);\n put(SURFACE, claims.surface);\n put(VERTICAL, claims.vertical);\n put(ROUTER_CREDENTIAL, options.routerSecret(env));\n } else {\n put(VERTICAL, claims.vertical);\n put(PLATFORM_SECRET_HEADER, options.platformSecret(env));\n }\n return new Request(request, { headers });\n}\n\n// substrat-platform-entry.ts\nimport * as vertical from \"__SUBSTRAT_VERTICAL_ENTRY__\";\nexport * from \"__SUBSTRAT_VERTICAL_ENTRY__\";\nvar routerSecret = (env) => env.ROUTER_SECRET;\nvar allowUnsigned = (env) => env.ALLOW_DEV_NODE === \"true\";\nvar substrat_platform_entry_default = withWireGate(\n withInvocationLog(vertical.default, { routerSecret, allowUnsigned, asyncLocalStorage: AsyncLocalStorage }),\n {\n routedNode: (headers, env) => readRoutedNode(headers, { expectedSecret: routerSecret(env), allowUnsigned: allowUnsigned(env) }),\n routerSecret,\n platformSecret: (env) => env.PLATFORM_SECRET\n }\n);\nexport {\n substrat_platform_entry_default as default\n};\n";
|
|
14
14
|
/**
|
|
15
15
|
* #2245: the entry's `node:async_hooks` import, as it appears in `PLATFORM_ENTRY_SOURCE`, and
|
|
16
16
|
* the line the uploader puts in its place for a script that can have no `AsyncLocalStorage`
|
|
@@ -24,6 +24,6 @@ export const PLATFORM_ENTRY_ALS_FALLBACK = "const AsyncLocalStorage = undefined;
|
|
|
24
24
|
* re-exports its class, when a vertical declares schedules and brings no sweeper of its own.
|
|
25
25
|
*/
|
|
26
26
|
export const PLATFORM_SWEEPER_MODULE = 'substrat-platform-sweeper.js';
|
|
27
|
-
/** The sweeper itself —
|
|
28
|
-
export const PLATFORM_SWEEPER_SOURCE = "// packages/adapter-cloudflare/src/scope-sweeper-do.ts\nimport { DurableObject } from \"cloudflare:workers\";\n\n// packages/contracts/dist/wire-headers.js\nvar PLATFORM_SECRET_HEADER = \"x-substrat-platform\";\n\n// packages/adapter-cloudflare/src/scope-sweeper-do.ts\nvar SWEEPER_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nfunction parseId(value, what) {\n if (typeof value !== \"string\" || !SWEEPER_ID.test(value)) {\n throw new TypeError(`${what} must be a ULID, got ${JSON.stringify(value)}`);\n }\n return value;\n}\nvar ROSTER_PREFIX = \"scope:\";\nvar JOB_START_PREFIX = \"job-start:\";\nfunction defineScopeSweeperDO(config) {\n return class ScopeSweeperDO extends DurableObject {\n /** The in-flight pass, when one is running — the overlap guard. */\n #pass = null;\n async noteScope(tenantId, scopeId) {\n const t = parseId(tenantId, \"tenantId\");\n const s = parseId(scopeId, \"scopeId\");\n await this.ctx.storage.put(`${ROSTER_PREFIX}${s}`, t);\n await this.ensureArmed();\n return { scopes: await this.#rosterSize() };\n }\n async forgetScope(scopeId) {\n const s = parseId(scopeId, \"scopeId\");\n await this.ctx.storage.delete([`${ROSTER_PREFIX}${s}`, `${JOB_START_PREFIX}${s}`]);\n return { scopes: await this.#rosterSize() };\n }\n /**\n * Arm the loop if it is not armed. Idempotent: an already-set alarm is left\n * exactly where it is, so this is safe to call on every request.\n */\n async ensureArmed() {\n const existing = await this.ctx.storage.getAlarm();\n if (existing !== null) return { armed: false, alarmAt: existing };\n const alarmAt = Date.now() + config.intervalMs;\n await this.ctx.storage.setAlarm(alarmAt);\n return { armed: true, alarmAt };\n }\n /**\n * Run a pass NOW (a manual kick, a just-provisioned scope's first tick, a\n * test). Joins the in-flight pass if one is running — never a second one —\n * and re-arms afterwards while scopes remain.\n */\n async sweepNow() {\n return this.#run();\n }\n /** The loop: one pass, then re-arm. Never throws (see the class doc). */\n async alarm() {\n await this.#run();\n }\n async #rosterSize() {\n return (await this.ctx.storage.list({ prefix: ROSTER_PREFIX })).size;\n }\n async #run() {\n if (this.#pass) return this.#pass;\n this.#pass = (async () => {\n try {\n const report = await this.#sweep();\n config.onPass?.(report, this.env);\n return report;\n } catch (err) {\n const outcome = { error: err instanceof Error ? err.message : String(err) };\n config.onPass?.(outcome, this.env);\n return outcome;\n }\n })();\n try {\n return await this.#pass;\n } finally {\n this.#pass = null;\n if (await this.#rosterSize() > 0) {\n await this.ctx.storage.setAlarm(Date.now() + config.intervalMs);\n }\n }\n }\n /** One pass over the roster: drain + due schedules per scope, errors contained. */\n async #sweep() {\n const host = config.host(this.env);\n const roster = await this.ctx.storage.list({ prefix: ROSTER_PREFIX });\n const report = {\n scopes: roster.size,\n drainTotals: { attempted: 0, delivered: 0, retrying: 0, deadLettered: 0 },\n schedules: { scopes: 0, fired: 0, skipped: 0, failed: 0 },\n ...config.runJobs ? { jobs: { attempted: 0, advanced: 0, completed: 0, retrying: 0, failed: 0 } } : {},\n errors: []\n };\n const registrations = host.registeredSchedules().filter((r) => r.schedules.length > 0);\n const entries = [...roster].map(([key, tenant]) => ({\n scopeId: key.slice(ROSTER_PREFIX.length),\n tenantId: tenant\n }));\n const concurrency = config.concurrency ?? 8;\n let next = 0;\n const worker = async () => {\n while (next < entries.length) {\n const { tenantId, scopeId } = entries[next++];\n if (host.lifecycleHeld) {\n try {\n if (await host.lifecycleHeld(scopeId)) {\n report.held = (report.held ?? 0) + 1;\n continue;\n }\n } catch (err) {\n report.errors.push({ kind: \"lifecycle\", id: scopeId, error: message(err) });\n continue;\n }\n }\n if (config.drainRetries !== false) {\n try {\n const r = await host.drainDue(tenantId, scopeId);\n report.drainTotals.attempted += r.attempted;\n report.drainTotals.delivered += r.delivered;\n report.drainTotals.retrying += r.retrying;\n report.drainTotals.deadLettered += r.deadLettered;\n } catch (err) {\n report.errors.push({ kind: \"drain\", id: scopeId, error: message(err) });\n }\n }\n if (config.runJobs) {\n if (config.startJobs) {\n try {\n const key = `${JOB_START_PREFIX}${scopeId}`;\n const last = await this.ctx.storage.get(key);\n const now = Date.now();\n if (last === void 0 || now - last >= (config.jobStartIntervalMs ?? config.intervalMs)) {\n await config.startJobs(host, tenantId, scopeId);\n await this.ctx.storage.put(key, now);\n }\n } catch (err) {\n report.errors.push({ kind: \"job\", id: `${scopeId}:start`, error: message(err) });\n }\n }\n try {\n const r = await host.runDueJobs(tenantId, scopeId);\n const totals = report.jobs;\n totals.attempted += r.attempted;\n totals.advanced += r.advanced;\n totals.completed += r.completed;\n totals.retrying += r.retrying;\n totals.failed += r.failed;\n for (const error of r.errors) {\n report.errors.push({ kind: \"job\", id: `${scopeId}:${error.runId}`, error: error.error });\n }\n } catch (err) {\n report.errors.push({ kind: \"job\", id: scopeId, error: message(err) });\n }\n }\n let touched = false;\n let needsPlatformDrain = false;\n const passAt = (/* @__PURE__ */ new Date()).toISOString();\n const passRuns = [];\n for (const reg of registrations) {\n try {\n const r = await host.runDueSchedules(reg.moduleId, tenantId, scopeId);\n if (r.fired > 0 || r.failed > 0) touched = true;\n report.schedules.fired += r.fired;\n report.schedules.skipped += r.skipped;\n report.schedules.failed += r.failed;\n if (r.platformRequests) {\n report.schedules.platformRequests = (report.schedules.platformRequests ?? 0) + r.platformRequests;\n needsPlatformDrain = true;\n }\n for (const e of r.errors) {\n report.errors.push({\n kind: \"schedule\",\n id: `${scopeId}:${e.operation}`,\n error: e.error\n });\n }\n for (const run of r.runs ?? []) {\n passRuns.push({\n kind: \"schedule\",\n operation: run.operation,\n outcome: run.outcome,\n at: passAt,\n ...run.outcome === \"failed\" ? { error: r.errors.find((e) => e.operation === run.operation)?.error ?? null } : {}\n });\n }\n } catch (err) {\n report.errors.push({\n kind: \"schedule\",\n id: `${scopeId}:${reg.moduleId}`,\n error: message(err)\n });\n }\n }\n if (touched) report.schedules.scopes += 1;\n if (host.registeredFreshness && host.checkFreshness) {\n const freshRegs = host.registeredFreshness().filter((r) => r.freshness.length > 0);\n if (freshRegs.length > 0) {\n try {\n const r = await host.checkFreshness(freshRegs[0].moduleId, tenantId, scopeId);\n for (const check of r.checks) {\n passRuns.push({\n kind: \"freshness\",\n eventType: check.eventType,\n outcome: check.outcome,\n at: passAt,\n observedAt: check.observedAt\n });\n }\n } catch (err) {\n report.errors.push({ kind: \"freshness\", id: scopeId, error: message(err) });\n }\n }\n }\n if (passRuns.length > 0 && host.enqueueSweepRuns) {\n try {\n await host.enqueueSweepRuns(scopeId, {\n version: config.versionId?.(this.env) ?? null,\n // The payload caps its batch; a pathological schedule count truncates\n // rather than refusing the whole report.\n entries: passRuns.slice(0, 64)\n });\n } catch {\n }\n }\n if (needsPlatformDrain) {\n this.ctx.waitUntil(Promise.resolve().then(() => kickPlatformDrain(this.env, tenantId, scopeId)).catch(() => {\n }));\n }\n }\n };\n await Promise.all(\n Array.from({ length: Math.max(1, Math.min(concurrency, entries.length)) }, worker)\n );\n return report;\n }\n };\n}\nvar message = (err) => err instanceof Error ? err.message : String(err);\nasync function kickPlatformDrain(env, tenantId, scopeId) {\n const platform = env;\n if (!platform.CONTROL_PLANE_URL || !platform.PLATFORM_SECRET) return;\n await fetch(new URL(\"/internal/drain-scope\", platform.CONTROL_PLANE_URL), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", [PLATFORM_SECRET_HEADER]: platform.PLATFORM_SECRET },\n body: JSON.stringify({ tenantId, scopeId, platformRequests: true, exports: false })\n });\n}\n\n// packages/vertical-host/src/scope-sweep-host.ts\nvar SCOPE_SWEEP_HOST_KEY = \"substrat.scope-sweep-host\";\nfunction slot() {\n return globalThis;\n}\nfunction registeredScopeSweepHost() {\n return slot()[Symbol.for(SCOPE_SWEEP_HOST_KEY)];\n}\n\n// substrat-platform-sweeper.ts\nvar SweeperDO = defineScopeSweeperDO({\n intervalMs: 12e4,\n versionId: (env) => env.SUBSTRAT_VERSION_ID ?? null,\n host(env) {\n const hostFor = registeredScopeSweepHost();\n if (!hostFor) {\n throw new Error(\"this bundle registered no scope host for the platform sweeper: mount mountPlatformSurface from a current @substrat-run/vertical-host\");\n }\n return hostFor(env);\n },\n onPass(outcome) {\n if (\"error\" in outcome || outcome.errors.length > 0) {\n console.error(JSON.stringify({ substrat: \"scope-sweep\", ...outcome }));\n }\n }\n});\nexport {\n SweeperDO\n};\n";
|
|
27
|
+
/** The sweeper itself — 11087 bytes of ESM. */
|
|
28
|
+
export const PLATFORM_SWEEPER_SOURCE = "// packages/adapter-cloudflare/src/scope-sweeper-do.ts\nimport { DurableObject } from \"cloudflare:workers\";\n\n// packages/contracts/dist/wire-headers.js\nvar PLATFORM_SECRET_HEADER = \"x-substrat-platform\";\nvar CONNECTOR_ATTACHMENT_META_MAX_BYTES = 8 * 1024;\n\n// packages/adapter-cloudflare/src/scope-sweeper-do.ts\nvar SWEEPER_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/;\nfunction parseId(value, what) {\n if (typeof value !== \"string\" || !SWEEPER_ID.test(value)) {\n throw new TypeError(`${what} must be a ULID, got ${JSON.stringify(value)}`);\n }\n return value;\n}\nvar ROSTER_PREFIX = \"scope:\";\nvar JOB_START_PREFIX = \"job-start:\";\nfunction defineScopeSweeperDO(config) {\n return class ScopeSweeperDO extends DurableObject {\n /** The in-flight pass, when one is running — the overlap guard. */\n #pass = null;\n async noteScope(tenantId, scopeId) {\n const t = parseId(tenantId, \"tenantId\");\n const s = parseId(scopeId, \"scopeId\");\n await this.ctx.storage.put(`${ROSTER_PREFIX}${s}`, t);\n await this.ensureArmed();\n return { scopes: await this.#rosterSize() };\n }\n async forgetScope(scopeId) {\n const s = parseId(scopeId, \"scopeId\");\n await this.ctx.storage.delete([`${ROSTER_PREFIX}${s}`, `${JOB_START_PREFIX}${s}`]);\n return { scopes: await this.#rosterSize() };\n }\n /**\n * Arm the loop if it is not armed. Idempotent: an already-set alarm is left\n * exactly where it is, so this is safe to call on every request.\n */\n async ensureArmed() {\n const existing = await this.ctx.storage.getAlarm();\n if (existing !== null) return { armed: false, alarmAt: existing };\n const alarmAt = Date.now() + config.intervalMs;\n await this.ctx.storage.setAlarm(alarmAt);\n return { armed: true, alarmAt };\n }\n /**\n * Run a pass NOW (a manual kick, a just-provisioned scope's first tick, a\n * test). Joins the in-flight pass if one is running — never a second one —\n * and re-arms afterwards while scopes remain.\n */\n async sweepNow() {\n return this.#run();\n }\n /** The loop: one pass, then re-arm. Never throws (see the class doc). */\n async alarm() {\n await this.#run();\n }\n async #rosterSize() {\n return (await this.ctx.storage.list({ prefix: ROSTER_PREFIX })).size;\n }\n async #run() {\n if (this.#pass) return this.#pass;\n this.#pass = (async () => {\n try {\n const report = await this.#sweep();\n config.onPass?.(report, this.env);\n return report;\n } catch (err) {\n const outcome = { error: err instanceof Error ? err.message : String(err) };\n config.onPass?.(outcome, this.env);\n return outcome;\n }\n })();\n try {\n return await this.#pass;\n } finally {\n this.#pass = null;\n if (await this.#rosterSize() > 0) {\n await this.ctx.storage.setAlarm(Date.now() + config.intervalMs);\n }\n }\n }\n /** One pass over the roster: drain + due schedules per scope, errors contained. */\n async #sweep() {\n const host = config.host(this.env);\n const roster = await this.ctx.storage.list({ prefix: ROSTER_PREFIX });\n const report = {\n scopes: roster.size,\n drainTotals: { attempted: 0, delivered: 0, retrying: 0, deadLettered: 0 },\n schedules: { scopes: 0, fired: 0, skipped: 0, failed: 0 },\n ...config.runJobs ? { jobs: { attempted: 0, advanced: 0, completed: 0, retrying: 0, failed: 0 } } : {},\n errors: []\n };\n const registrations = host.registeredSchedules().filter((r) => r.schedules.length > 0);\n const entries = [...roster].map(([key, tenant]) => ({\n scopeId: key.slice(ROSTER_PREFIX.length),\n tenantId: tenant\n }));\n const concurrency = config.concurrency ?? 8;\n let next = 0;\n const worker = async () => {\n while (next < entries.length) {\n const { tenantId, scopeId } = entries[next++];\n if (host.lifecycleHeld) {\n try {\n if (await host.lifecycleHeld(scopeId)) {\n report.held = (report.held ?? 0) + 1;\n continue;\n }\n } catch (err) {\n report.errors.push({ kind: \"lifecycle\", id: scopeId, error: message(err) });\n continue;\n }\n }\n if (config.drainRetries !== false) {\n try {\n const r = await host.drainDue(tenantId, scopeId);\n report.drainTotals.attempted += r.attempted;\n report.drainTotals.delivered += r.delivered;\n report.drainTotals.retrying += r.retrying;\n report.drainTotals.deadLettered += r.deadLettered;\n } catch (err) {\n report.errors.push({ kind: \"drain\", id: scopeId, error: message(err) });\n }\n }\n if (config.runJobs) {\n if (config.startJobs) {\n try {\n const key = `${JOB_START_PREFIX}${scopeId}`;\n const last = await this.ctx.storage.get(key);\n const now = Date.now();\n if (last === void 0 || now - last >= (config.jobStartIntervalMs ?? config.intervalMs)) {\n await config.startJobs(host, tenantId, scopeId);\n await this.ctx.storage.put(key, now);\n }\n } catch (err) {\n report.errors.push({ kind: \"job\", id: `${scopeId}:start`, error: message(err) });\n }\n }\n try {\n const r = await host.runDueJobs(tenantId, scopeId);\n const totals = report.jobs;\n totals.attempted += r.attempted;\n totals.advanced += r.advanced;\n totals.completed += r.completed;\n totals.retrying += r.retrying;\n totals.failed += r.failed;\n for (const error of r.errors) {\n report.errors.push({ kind: \"job\", id: `${scopeId}:${error.runId}`, error: error.error });\n }\n } catch (err) {\n report.errors.push({ kind: \"job\", id: scopeId, error: message(err) });\n }\n }\n let touched = false;\n let needsPlatformDrain = false;\n const passAt = (/* @__PURE__ */ new Date()).toISOString();\n const passRuns = [];\n let purgeRequests = 0;\n for (const reg of registrations) {\n try {\n const r = await host.runDueSchedules(reg.moduleId, tenantId, scopeId, { earlierPurgeRequests: purgeRequests });\n if (r.fired > 0 || r.failed > 0) touched = true;\n report.schedules.fired += r.fired;\n report.schedules.skipped += r.skipped;\n report.schedules.failed += r.failed;\n if (r.deferred) report.schedules.deferred = (report.schedules.deferred ?? 0) + r.deferred;\n purgeRequests += r.purgeRequests ?? 0;\n if (r.platformRequests) {\n report.schedules.platformRequests = (report.schedules.platformRequests ?? 0) + r.platformRequests;\n needsPlatformDrain = true;\n }\n for (const e of r.errors) {\n report.errors.push({\n kind: \"schedule\",\n id: `${scopeId}:${e.operation}`,\n error: e.error\n });\n }\n for (const run of r.runs ?? []) {\n passRuns.push({\n kind: \"schedule\",\n operation: run.operation,\n outcome: run.outcome,\n at: passAt,\n ...run.outcome === \"failed\" ? { error: r.errors.find((e) => e.operation === run.operation)?.error ?? null } : {}\n });\n }\n } catch (err) {\n report.errors.push({\n kind: \"schedule\",\n id: `${scopeId}:${reg.moduleId}`,\n error: message(err)\n });\n }\n }\n if (touched) report.schedules.scopes += 1;\n if (host.registeredFreshness && host.checkFreshness) {\n const freshRegs = host.registeredFreshness().filter((r) => r.freshness.length > 0);\n if (freshRegs.length > 0) {\n try {\n const r = await host.checkFreshness(freshRegs[0].moduleId, tenantId, scopeId);\n for (const check of r.checks) {\n passRuns.push({\n kind: \"freshness\",\n eventType: check.eventType,\n outcome: check.outcome,\n at: passAt,\n observedAt: check.observedAt\n });\n }\n } catch (err) {\n report.errors.push({ kind: \"freshness\", id: scopeId, error: message(err) });\n }\n }\n }\n if (passRuns.length > 0 && host.enqueueSweepRuns) {\n try {\n await host.enqueueSweepRuns(scopeId, {\n version: config.versionId?.(this.env) ?? null,\n // The payload caps its batch; a pathological schedule count truncates\n // rather than refusing the whole report.\n entries: passRuns.slice(0, 64)\n });\n } catch {\n }\n }\n if (needsPlatformDrain) {\n this.ctx.waitUntil(Promise.resolve().then(() => kickPlatformDrain(this.env, tenantId, scopeId)).catch(() => {\n }));\n }\n }\n };\n await Promise.all(\n Array.from({ length: Math.max(1, Math.min(concurrency, entries.length)) }, worker)\n );\n return report;\n }\n };\n}\nvar message = (err) => err instanceof Error ? err.message : String(err);\nasync function kickPlatformDrain(env, tenantId, scopeId) {\n const platform = env;\n if (!platform.CONTROL_PLANE_URL || !platform.PLATFORM_SECRET) return;\n await fetch(new URL(\"/internal/drain-scope\", platform.CONTROL_PLANE_URL), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", [PLATFORM_SECRET_HEADER]: platform.PLATFORM_SECRET },\n body: JSON.stringify({ tenantId, scopeId, platformRequests: true, exports: false })\n });\n}\n\n// packages/vertical-host/src/scope-sweep-host.ts\nvar SCOPE_SWEEP_HOST_KEY = \"substrat.scope-sweep-host\";\nfunction slot() {\n return globalThis;\n}\nfunction registeredScopeSweepHost() {\n return slot()[Symbol.for(SCOPE_SWEEP_HOST_KEY)];\n}\n\n// substrat-platform-sweeper.ts\nvar SweeperDO = defineScopeSweeperDO({\n intervalMs: 12e4,\n versionId: (env) => env.SUBSTRAT_VERSION_ID ?? null,\n host(env) {\n const hostFor = registeredScopeSweepHost();\n if (!hostFor) {\n throw new Error(\"this bundle registered no scope host for the platform sweeper: mount mountPlatformSurface from a current @substrat-run/vertical-host\");\n }\n return hostFor(env);\n },\n onPass(outcome) {\n if (\"error\" in outcome || outcome.errors.length > 0) {\n console.error(JSON.stringify({ substrat: \"scope-sweep\", ...outcome }));\n }\n }\n});\nexport {\n SweeperDO\n};\n";
|
|
29
29
|
//# sourceMappingURL=platform-entry.generated.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-entry.generated.js","sourceRoot":"","sources":["../src/platform-entry.generated.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"platform-entry.generated.js","sourceRoot":"","sources":["../src/platform-entry.generated.ts"],"names":[],"mappings":"AAAA,sOAAsO;AACtO,sEAAsE;AAEtE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,4BAA4B,CAAC;AAElE,gFAAgF;AAChF,MAAM,CAAC,MAAM,0BAA0B,GAAG,6BAA6B,CAAC;AAExE,6CAA6C;AAC7C,MAAM,CAAC,MAAM,qBAAqB,GAAW,srjDAAsrjD,CAAC;AAEpujD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,yDAAyD,CAAC;AACnG,MAAM,CAAC,MAAM,2BAA2B,GAAG,sCAAsC,CAAC;AAElF;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,8BAA8B,CAAC;AAEtE,+CAA+C;AAC/C,MAAM,CAAC,MAAM,uBAAuB,GAAW,8pWAA8pW,CAAC"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** The control plane's own signing settings, as its env holds them. */
|
|
2
|
+
export interface PlatformWireSettings {
|
|
3
|
+
/** The `sign` flag: `on`, or off. */
|
|
4
|
+
readonly sign?: string;
|
|
5
|
+
/** The issuer `platform` private key, PKCS8 Ed25519, base64url. */
|
|
6
|
+
readonly key?: string;
|
|
7
|
+
/** Where the signer's count goes, one line per call. `console.log` unless a test injects one. */
|
|
8
|
+
readonly log?: (line: string) => void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The top-level `tenantId` and `scopeId` of a JSON object, read from its UTF-8 bytes in one walk
|
|
12
|
+
* that decodes and parses nothing: it tracks depth, strings and their escapes, compares a top-level
|
|
13
|
+
* key's bytes with the two names, decodes a value only when it is a string of a ULID's length, and
|
|
14
|
+
* stops once both keys are seen. So a call's body, a copy or restore page of several MiB included,
|
|
15
|
+
* is never held a second time as a string or an object graph to name its scope. A key with a value
|
|
16
|
+
* that is not a string reads as `null`.
|
|
17
|
+
*
|
|
18
|
+
* It reads what `JSON.parse` would for every body the control plane sends, which `JSON.stringify`
|
|
19
|
+
* writes: no key twice, and no key's letters escaped. It does not validate the rest of the body, so a
|
|
20
|
+
* malformed one can name a pair a parse would refuse; the control plane writes none.
|
|
21
|
+
*
|
|
22
|
+
* So it assumes a body `JSON.stringify` wrote from an object the platform built: on a key repeated
|
|
23
|
+
* after both are seen the first wins, and a BOM or an escaped key is not read as a parse reads it. A
|
|
24
|
+
* caller that forwards raw bytes from outside the platform must not use it unchanged.
|
|
25
|
+
*/
|
|
26
|
+
export declare function topLevelIds(bytes: Uint8Array): {
|
|
27
|
+
tenantId?: unknown;
|
|
28
|
+
scopeId?: unknown;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* The tenant and scope a call names itself: its JSON body's top-level `tenantId` and `scopeId`
|
|
32
|
+
* ({@link topLevelIds}), else its query's, both or neither, each one ULID. The envelope names the pair
|
|
33
|
+
* (RFC §3.1: with the scope, or neither), and a call that changes state spends its nonce in that
|
|
34
|
+
* scope (§4). A call that names only a scope, or nothing, is signed naming neither: where its nonce
|
|
35
|
+
* is spent is follow-on 5's to decide.
|
|
36
|
+
*/
|
|
37
|
+
export declare function platformCallScope(request: Request, body: ArrayBuffer | undefined): {
|
|
38
|
+
tenantId: string;
|
|
39
|
+
scopeId: string;
|
|
40
|
+
} | null;
|
|
41
|
+
/**
|
|
42
|
+
* The `fetch` a client for the deployment the dispatch namespace knows as `aud` is given: `send`
|
|
43
|
+
* itself while the flag is off; on, `send` behind the signer, so every call, a retry included, is
|
|
44
|
+
* signed afresh for that deployment (RFC §4). The caller builds it for the same name it makes the
|
|
45
|
+
* dispatch stub from, so the envelope always names the script the call reaches. A signer that cannot
|
|
46
|
+
* sign never fails the call: it goes with its legacy header and its whole body, and the line says
|
|
47
|
+
* why, never a key. A streamed call is not signed and its body is not read: it goes exactly as
|
|
48
|
+
* given, counted `skipped`, which is a decision, not a failure.
|
|
49
|
+
*/
|
|
50
|
+
export declare function platformSignedFetch(settings: PlatformWireSettings, aud: string, send: typeof fetch): typeof fetch;
|
|
51
|
+
//# sourceMappingURL=platform-wire.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-wire.d.ts","sourceRoot":"","sources":["../src/platform-wire.ts"],"names":[],"mappings":"AAUA,uEAAuE;AACvE,MAAM,WAAW,oBAAoB;IACnC,qCAAqC;IACrC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,mEAAmE;IACnE,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,iGAAiG;IACjG,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACvC;AAoBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,CA6CxF;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,GAAG,SAAS,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAY/H;AAmBD;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,oBAAoB,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,KAAK,GAAG,OAAO,KAAK,CAejH"}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The control plane's wire signer (RFC wire-signing §5, §9 step 2): a `call` envelope, issuer
|
|
3
|
+
* `platform`, on every call the control plane makes to a deployment, beside the legacy header,
|
|
4
|
+
* which stays. Off by default: while the control plane's `sign` flag is off, the `fetch` a client is
|
|
5
|
+
* given is the very one it would have had, and every call goes out exactly as it did before signing
|
|
6
|
+
* existed.
|
|
7
|
+
*/
|
|
8
|
+
import { ULID_PATTERN } from '@substrat-run/contracts';
|
|
9
|
+
import { wireSignerOf } from '@substrat-run/contracts/wire-signing';
|
|
10
|
+
/** Bodies that are bytes rather than JSON (a multipart attachment, an octet stream) name no scope. */
|
|
11
|
+
const BYTES = /^(multipart\/|application\/octet-stream)/i;
|
|
12
|
+
const QUOTE = 0x22;
|
|
13
|
+
const BACKSLASH = 0x5c;
|
|
14
|
+
const COMMA = 0x2c;
|
|
15
|
+
const COLON = 0x3a;
|
|
16
|
+
const OPEN_OBJECT = 0x7b;
|
|
17
|
+
const OPENS = new Set([OPEN_OBJECT, 0x5b]);
|
|
18
|
+
const CLOSES = new Set([0x7d, 0x5d]);
|
|
19
|
+
const SPACE = new Set([0x20, 0x09, 0x0a, 0x0d]);
|
|
20
|
+
/** A ULID's length in bytes: a string value of any other length is not one, and is never decoded. */
|
|
21
|
+
const ULID_BYTES = 26;
|
|
22
|
+
const NAMED = [
|
|
23
|
+
['tenantId', new TextEncoder().encode('tenantId')],
|
|
24
|
+
['scopeId', new TextEncoder().encode('scopeId')],
|
|
25
|
+
];
|
|
26
|
+
/**
|
|
27
|
+
* The top-level `tenantId` and `scopeId` of a JSON object, read from its UTF-8 bytes in one walk
|
|
28
|
+
* that decodes and parses nothing: it tracks depth, strings and their escapes, compares a top-level
|
|
29
|
+
* key's bytes with the two names, decodes a value only when it is a string of a ULID's length, and
|
|
30
|
+
* stops once both keys are seen. So a call's body, a copy or restore page of several MiB included,
|
|
31
|
+
* is never held a second time as a string or an object graph to name its scope. A key with a value
|
|
32
|
+
* that is not a string reads as `null`.
|
|
33
|
+
*
|
|
34
|
+
* It reads what `JSON.parse` would for every body the control plane sends, which `JSON.stringify`
|
|
35
|
+
* writes: no key twice, and no key's letters escaped. It does not validate the rest of the body, so a
|
|
36
|
+
* malformed one can name a pair a parse would refuse; the control plane writes none.
|
|
37
|
+
*
|
|
38
|
+
* So it assumes a body `JSON.stringify` wrote from an object the platform built: on a key repeated
|
|
39
|
+
* after both are seen the first wins, and a BOM or an escaped key is not read as a parse reads it. A
|
|
40
|
+
* caller that forwards raw bytes from outside the platform must not use it unchanged.
|
|
41
|
+
*/
|
|
42
|
+
export function topLevelIds(bytes) {
|
|
43
|
+
const found = {};
|
|
44
|
+
let i = 0;
|
|
45
|
+
while (i < bytes.length && SPACE.has(bytes[i]))
|
|
46
|
+
i++;
|
|
47
|
+
if (bytes[i] !== OPEN_OBJECT)
|
|
48
|
+
return found;
|
|
49
|
+
let depth = 0;
|
|
50
|
+
let expectKey = false;
|
|
51
|
+
// The name whose value comes next, at depth 1: one of the two, or '' for any other key.
|
|
52
|
+
let pending = null;
|
|
53
|
+
const settle = (value) => {
|
|
54
|
+
if (pending)
|
|
55
|
+
found[pending] = value;
|
|
56
|
+
pending = null;
|
|
57
|
+
return 'tenantId' in found && 'scopeId' in found;
|
|
58
|
+
};
|
|
59
|
+
for (; i < bytes.length; i++) {
|
|
60
|
+
const b = bytes[i];
|
|
61
|
+
if (b === QUOTE) {
|
|
62
|
+
const start = i + 1;
|
|
63
|
+
i = start;
|
|
64
|
+
while (i < bytes.length && bytes[i] !== QUOTE)
|
|
65
|
+
i += bytes[i] === BACKSLASH ? 2 : 1;
|
|
66
|
+
if (i >= bytes.length)
|
|
67
|
+
return found;
|
|
68
|
+
// A string below the top level meets neither branch: a key is expected, and a value pending,
|
|
69
|
+
// only at depth 1, and a nested value settles what was pending as it opens.
|
|
70
|
+
if (expectKey) {
|
|
71
|
+
expectKey = false;
|
|
72
|
+
pending = NAMED.find(([, name]) => name.length === i - start && name.every((c, k) => bytes[start + k] === c))?.[0] ?? '';
|
|
73
|
+
}
|
|
74
|
+
else if (pending !== null) {
|
|
75
|
+
const text = i - start === ULID_BYTES ? new TextDecoder().decode(bytes.subarray(start, i)) : null;
|
|
76
|
+
if (settle(text))
|
|
77
|
+
return found;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
else if (OPENS.has(b)) {
|
|
81
|
+
// Only ever pending at depth 1, so a nested value settles the top-level key it is the value of.
|
|
82
|
+
if (pending !== null && settle(null))
|
|
83
|
+
return found;
|
|
84
|
+
depth++;
|
|
85
|
+
if (depth === 1)
|
|
86
|
+
expectKey = true;
|
|
87
|
+
}
|
|
88
|
+
else if (CLOSES.has(b)) {
|
|
89
|
+
depth--;
|
|
90
|
+
if (depth === 0)
|
|
91
|
+
return found;
|
|
92
|
+
}
|
|
93
|
+
else if (depth === 1) {
|
|
94
|
+
if (b === COMMA)
|
|
95
|
+
expectKey = true;
|
|
96
|
+
// A number, `true`, `false` or `null`: a value that is not a string.
|
|
97
|
+
else if (b !== COLON && !SPACE.has(b) && pending !== null && settle(null))
|
|
98
|
+
return found;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return found;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The tenant and scope a call names itself: its JSON body's top-level `tenantId` and `scopeId`
|
|
105
|
+
* ({@link topLevelIds}), else its query's, both or neither, each one ULID. The envelope names the pair
|
|
106
|
+
* (RFC §3.1: with the scope, or neither), and a call that changes state spends its nonce in that
|
|
107
|
+
* scope (§4). A call that names only a scope, or nothing, is signed naming neither: where its nonce
|
|
108
|
+
* is spent is follow-on 5's to decide.
|
|
109
|
+
*/
|
|
110
|
+
export function platformCallScope(request, body) {
|
|
111
|
+
const pair = (tenantId, scopeId) => typeof tenantId === 'string' && typeof scopeId === 'string' && ULID_PATTERN.test(tenantId) && ULID_PATTERN.test(scopeId)
|
|
112
|
+
? { tenantId, scopeId }
|
|
113
|
+
: null;
|
|
114
|
+
if (body !== undefined && body.byteLength > 0 && !BYTES.test(request.headers.get('content-type') ?? '')) {
|
|
115
|
+
const named = topLevelIds(new Uint8Array(body));
|
|
116
|
+
const fromBody = pair(named.tenantId, named.scopeId);
|
|
117
|
+
if (fromBody)
|
|
118
|
+
return fromBody;
|
|
119
|
+
}
|
|
120
|
+
const query = new URL(request.url).searchParams;
|
|
121
|
+
return pair(query.get('tenantId'), query.get('scopeId'));
|
|
122
|
+
}
|
|
123
|
+
/** A body sent as it is read rather than held. */
|
|
124
|
+
const isStream = (body) => body instanceof ReadableStream || typeof body?.getReader === 'function';
|
|
125
|
+
/**
|
|
126
|
+
* A call whose body is sent as it is read (a streamed attachment, #2498): binding it would mean
|
|
127
|
+
* holding all of it, which is what streaming it exists to avoid, so version 1 does not sign it
|
|
128
|
+
* (RFC §3.6, Q5). Judged on the body the call would send, whatever its call style: `init.body` when
|
|
129
|
+
* it gives one, else (a null `init.body` keeps it, as the Request constructor reads it) the body of a
|
|
130
|
+
* `Request` handed whole, which is a stream whatever it was built from, so it is never read to be
|
|
131
|
+
* bound either. Every client call today passes a URL and an `init`.
|
|
132
|
+
*/
|
|
133
|
+
function streamed(input, init) {
|
|
134
|
+
if (init?.body != null)
|
|
135
|
+
return isStream(init.body);
|
|
136
|
+
return input instanceof Request && input.body !== null;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The `fetch` a client for the deployment the dispatch namespace knows as `aud` is given: `send`
|
|
140
|
+
* itself while the flag is off; on, `send` behind the signer, so every call, a retry included, is
|
|
141
|
+
* signed afresh for that deployment (RFC §4). The caller builds it for the same name it makes the
|
|
142
|
+
* dispatch stub from, so the envelope always names the script the call reaches. A signer that cannot
|
|
143
|
+
* sign never fails the call: it goes with its legacy header and its whole body, and the line says
|
|
144
|
+
* why, never a key. A streamed call is not signed and its body is not read: it goes exactly as
|
|
145
|
+
* given, counted `skipped`, which is a decision, not a failure.
|
|
146
|
+
*/
|
|
147
|
+
export function platformSignedFetch(settings, aud, send) {
|
|
148
|
+
const signer = wireSignerOf(settings);
|
|
149
|
+
if (!signer)
|
|
150
|
+
return send;
|
|
151
|
+
const log = settings.log ?? ((line) => console.log(line));
|
|
152
|
+
const count = (outcome, reason) => log(JSON.stringify({ substrat: 'wire-sign', issuer: 'platform', aud, outcome, ...(reason ? { reason } : {}) }));
|
|
153
|
+
return (async (input, init) => {
|
|
154
|
+
if (streamed(input, init)) {
|
|
155
|
+
count('skipped', 'stream');
|
|
156
|
+
return send(input, init);
|
|
157
|
+
}
|
|
158
|
+
const result = await signer(new Request(input, init), { iss: 'platform', kind: 'call', aud }, platformCallScope);
|
|
159
|
+
count(result.outcome, result.outcome === 'failed' ? result.reason : undefined);
|
|
160
|
+
return send(result.request);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
//# sourceMappingURL=platform-wire.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-wire.js","sourceRo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AE,MAAM,CAAC;IACjB,OAAO,EAAE,iBAAiB,EAAE,CAAC;IAC7B,MAAM,EAAE,MAAM,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC;IAC5C;;;OAGG;IACH,YAAY,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE,EAAE,CAAC;CAC3E;AAsND,wBAAsB,yBAAyB,CAC7C,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GACzD,OAAO,CAAC,gBAAgB,CAAC,CA8F3B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BACKFILL_MOVE_ID } from '@substrat-run/kernel';
|
|
1
|
+
import { BACKFILL_MOVE_ID, withheldOpsFailure } from '@substrat-run/kernel';
|
|
2
2
|
import { hasCarriedAwayTombstone, listAllScopeScriptCopies, routeOfScope } from './scope-copy-cleanup.js';
|
|
3
3
|
/**
|
|
4
4
|
* The backfill of copies made before the directory's copy ledger existed (#1722).
|
|
@@ -270,11 +270,20 @@ export async function backfillScopeScriptCopies(input, opts) {
|
|
|
270
270
|
const entries = [];
|
|
271
271
|
const seen = new Map();
|
|
272
272
|
const unborn = new Set();
|
|
273
|
+
// #2554: a failure whose reason quotes what a store read threw, beside the reason without it. The
|
|
274
|
+
// page (staff's) carries the throw; the scope's tenant's row says only the reason, and staff's
|
|
275
|
+
// row the throw, under one reference (`withheldOpsFailure`).
|
|
276
|
+
const answeredReasons = new WeakMap();
|
|
273
277
|
for (const row of rows) {
|
|
274
278
|
const tenantId = row.tenantId;
|
|
275
279
|
const scopeId = row.scopeId;
|
|
276
280
|
const base = { fromLogId: row.id, tenantId, scopeId };
|
|
277
|
-
const failure = (scriptRef, reason) =>
|
|
281
|
+
const failure = (scriptRef, reason, thrown) => {
|
|
282
|
+
const entry = { ...base, scriptRef, outcome: 'failure', reason: thrown === undefined ? reason : `${reason} (${thrown})` };
|
|
283
|
+
entries.push(entry);
|
|
284
|
+
if (thrown !== undefined)
|
|
285
|
+
answeredReasons.set(entry, reason);
|
|
286
|
+
};
|
|
278
287
|
if (!tenantId || !scopeId) {
|
|
279
288
|
failure(null, 'the row names no tenant or scope');
|
|
280
289
|
continue;
|
|
@@ -322,7 +331,7 @@ export async function backfillScopeScriptCopies(input, opts) {
|
|
|
322
331
|
}
|
|
323
332
|
}
|
|
324
333
|
catch (e) {
|
|
325
|
-
failure(scriptRef,
|
|
334
|
+
failure(scriptRef, 'the store could not be read', e instanceof Error ? e.message : String(e));
|
|
326
335
|
continue;
|
|
327
336
|
}
|
|
328
337
|
const result = await admin.backfillScopeScriptCopy(actor, tenantId, scopeId, scriptRef, { fromLogId: row.id });
|
|
@@ -345,12 +354,16 @@ export async function backfillScopeScriptCopies(input, opts) {
|
|
|
345
354
|
.filter((s) => s.subjects.length > 0);
|
|
346
355
|
if (!opts.dryRun) {
|
|
347
356
|
await Promise.all([
|
|
348
|
-
...entries.filter((e) => e.outcome === 'failure').map((e) =>
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
357
|
+
...entries.filter((e) => e.outcome === 'failure').map((e) => {
|
|
358
|
+
const tenantId = e.tenantId;
|
|
359
|
+
const message = (reason) => `admin-log row ${e.fromLogId}${e.scriptRef ? ` (script '${e.scriptRef}')` : ''}: ${reason} — ` +
|
|
360
|
+
'a copy this may name is not in the copy ledger, so reap and erasure do not reach it (#1722)';
|
|
361
|
+
const at = { actor, operation: 'scope.copy-backfill', stage: 'unresolved', scopeId: e.scopeId };
|
|
362
|
+
const answered = answeredReasons.get(e);
|
|
363
|
+
return admin.recordOpsFailure(tenantId && answered !== undefined
|
|
364
|
+
? withheldOpsFailure({ ...at, tenantId }, message(e.reason), (reference) => `${message(answered)} (reference ${reference})`)
|
|
365
|
+
: { ...at, tenantId, message: message(e.reason) });
|
|
366
|
+
}),
|
|
354
367
|
...erasedBefore.map((s) => admin.recordOpsFailure({
|
|
355
368
|
actor, operation: 'scope.copy-backfill', stage: 'erased-before',
|
|
356
369
|
tenantId: s.tenantId, scopeId: s.scopeId,
|