@arbol-ai/maximus 0.0.0-stage → 7.0.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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -2
  3. package/config/oxfmt.d.mts +8 -0
  4. package/config/oxfmt.mjs +30 -0
  5. package/config/oxlint-plugin.mjs +41 -0
  6. package/config/oxlint.d.mts +8 -0
  7. package/config/oxlint.mjs +118 -0
  8. package/dist/analytics/analytics.d.ts +34 -0
  9. package/dist/analytics/analytics.js +62 -0
  10. package/dist/body.d.ts +2 -0
  11. package/dist/body.js +4 -0
  12. package/dist/chunks/body-BcMbreNd.js +106 -0
  13. package/dist/chunks/correlation-gaiEoMBr.js +45 -0
  14. package/dist/chunks/execution-qfZuMSIu.js +700 -0
  15. package/dist/chunks/json-Dwni3u4c.js +63 -0
  16. package/dist/chunks/record-D2H3cg8S.js +36 -0
  17. package/dist/chunks/schemas-q-51wBMQ.js +216 -0
  18. package/dist/chunks/src-Ph5KHCRP.js +1160 -0
  19. package/dist/chunks/telemetry-DvZgrzZn.js +220 -0
  20. package/dist/chunks/types-CGwAhnTE.d.ts +1630 -0
  21. package/dist/chunks/validation-DWxKk1Js.js +382 -0
  22. package/dist/client/client.d.ts +131 -0
  23. package/dist/client/client.js +325 -0
  24. package/dist/diagnostics.d.ts +41 -0
  25. package/dist/diagnostics.js +4 -0
  26. package/dist/errors.d.ts +2 -0
  27. package/dist/errors.js +128 -0
  28. package/dist/http-paths.d.ts +2 -0
  29. package/dist/http-paths.js +200 -0
  30. package/dist/index.d.ts +2 -0
  31. package/dist/index.js +11 -0
  32. package/dist/internals.d.ts +2 -0
  33. package/dist/internals.js +5 -0
  34. package/dist/mcp/index.d.ts +12 -0
  35. package/dist/mcp/index.js +406 -0
  36. package/dist/postgres/index.d.ts +81 -0
  37. package/dist/postgres/index.js +140 -0
  38. package/dist/schemas.d.ts +2 -0
  39. package/dist/schemas.js +4 -0
  40. package/dist/standard-failures.d.ts +91 -0
  41. package/dist/standard-failures.js +75 -0
  42. package/dist/tooling/cli.js +110 -0
  43. package/dist/tooling/testing.d.ts +7 -0
  44. package/dist/tooling/testing.js +21 -0
  45. package/dist/webhooks.d.ts +69 -0
  46. package/dist/webhooks.js +162 -0
  47. package/dist/workers/runtime.d.ts +112 -0
  48. package/dist/workers/runtime.js +228 -0
  49. package/package.json +153 -4
  50. package/skills/maximus/SKILL.md +89 -0
  51. package/skills/maximus/references/adding-an-operation.md +179 -0
  52. package/skills/maximus/references/building-a-service.md +158 -0
  53. package/skills/maximus/references/errors-and-results.md +77 -0
  54. package/skills/maximus/references/migration-from-v2.md +62 -0
  55. package/skills/maximus/references/migration-to-v5.md +37 -0
  56. package/skills/maximus/references/publishing-and-verification.md +39 -0
  57. package/skills/maximus/references/testing.md +73 -0
  58. package/skills/maximus/references/transports.md +119 -0
  59. package/templates/service/.agents/skills/project/SKILL.md.template +10 -0
  60. package/templates/service/.github/workflows/ci.yml.template +21 -0
  61. package/templates/service/.gitignore.template +8 -0
  62. package/templates/service/CLAUDE.md.template +3 -0
  63. package/templates/service/README.md.template +45 -0
  64. package/templates/service/cloudflare.config.ts.template +30 -0
  65. package/templates/service/oxfmt.config.ts.template +1 -0
  66. package/templates/service/oxlint.config.ts.template +1 -0
  67. package/templates/service/package.json.template +31 -0
  68. package/templates/service/src/app.ts.template +30 -0
  69. package/templates/service/src/index.ts.template +13 -0
  70. package/templates/service/tests/contract.test.ts.template +12 -0
  71. package/templates/service/tsconfig.json.template +16 -0
  72. package/templates/service/vite.config.ts.template +7 -0
  73. package/templates/service/vitest.config.ts.template +10 -0
@@ -0,0 +1,700 @@
1
+ import { STANDARD_FAILURES } from "../standard-failures.js";
2
+ import { l as hasUncompiledCodecs, r as parseInput, t as decodeInput } from "./validation-DWxKk1Js.js";
3
+ import { standardErrors } from "../errors.js";
4
+ import { n as readBodyBytes } from "./body-BcMbreNd.js";
5
+ import { n as exactLength, t as isRecord } from "./record-D2H3cg8S.js";
6
+ import { createHttpRouteResolver, isInputHeaderName, operationPathParameters } from "../http-paths.js";
7
+ import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-q-51wBMQ.js";
8
+ import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-DvZgrzZn.js";
9
+ import { Kind, Type } from "@sinclair/typebox";
10
+ import { Value } from "@sinclair/typebox/value";
11
+ import { createRemoteJWKSet, jwtVerify } from "jose";
12
+
13
+ //#region src/binary.ts
14
+ /**
15
+ * Byte bodies and file attachments over HTTP: the on-demand reader of a declared byte body, the checks an
16
+ * attachment output passes before anything is sent, and the exact-length response that serves it.
17
+ */
18
+ /** A request-local reader; constructing it never pulls bytes or records headers/content. */
19
+ function binaryBody(request, maxBytes) {
20
+ let reading;
21
+ return { read() {
22
+ reading ??= (async () => {
23
+ const encoding = request.headers.get("content-encoding");
24
+ if (encoding && encoding.toLowerCase() !== "identity") return {
25
+ ok: false,
26
+ error: standardErrors.unsupportedMedia.create()
27
+ };
28
+ const result = await readBodyBytes(request, {
29
+ maxBytes,
30
+ signal: request.signal
31
+ });
32
+ return result.ok ? result : {
33
+ ok: false,
34
+ error: result.error.data.reason === "too_large" ? standardErrors.tooLarge.create() : standardErrors.invalidInput.create()
35
+ };
36
+ })();
37
+ return reading;
38
+ } };
39
+ }
40
+ /** Whether an output schema is `AttachmentOutputSchema`. */
41
+ function isAttachmentSchema(schema) {
42
+ return schema[Kind] === "HttpAttachment";
43
+ }
44
+ /** Reject malformed output before exposing a body, filename or media type to HTTP. */
45
+ function validAttachment(value, maxBytes) {
46
+ if (!value || typeof value !== "object") return false;
47
+ const keys = Object.keys(value);
48
+ if (keys.length !== 4 || keys.some((key) => ![
49
+ "body",
50
+ "contentType",
51
+ "filename",
52
+ "byteLength"
53
+ ].includes(key))) return false;
54
+ const file = value;
55
+ if (!(file.body instanceof Uint8Array || file.body instanceof ReadableStream)) return false;
56
+ if (file.body instanceof ReadableStream && file.body.locked) return false;
57
+ if (!Number.isSafeInteger(file.byteLength) || file.byteLength < 0 || file.byteLength > maxBytes) return false;
58
+ if (file.body instanceof Uint8Array && file.body.byteLength !== file.byteLength) return false;
59
+ if (typeof file.contentType !== "string" || file.contentType.length > 255 || !/^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/u.test(file.contentType)) return false;
60
+ if (typeof file.filename !== "string" || !file.filename.length || file.filename.length > 512 || /[\p{Cc}/\\]/u.test(file.filename)) return false;
61
+ try {
62
+ encodeURIComponent(file.filename);
63
+ return true;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+ /** An exact-length stream prevents a handler from sending bytes beyond its validated attachment metadata. */
69
+ function attachmentResponse(file, status = 200) {
70
+ const encodedFilename = encodeURIComponent(file.filename).replaceAll(/[!'()*]/gu, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
71
+ const body = file.body instanceof Uint8Array ? file.body : exactLength(file.body, file.byteLength);
72
+ return new Response(body, {
73
+ status,
74
+ headers: {
75
+ "cache-control": "private, no-store",
76
+ "content-type": file.contentType,
77
+ "content-length": String(file.byteLength),
78
+ "content-disposition": `attachment; filename="${file.filename.replaceAll(/[^\u0020-\u007E]|["\\]/gu, "_")}"; filename*=UTF-8''${encodedFilename}`,
79
+ "content-security-policy": "default-src 'none'; sandbox",
80
+ "x-content-type-options": "nosniff"
81
+ }
82
+ });
83
+ }
84
+
85
+ //#endregion
86
+ //#region src/internal/http-routes.ts
87
+ /** Every body variant must declare its path authority as a required string field. */
88
+ function pathParameterSchemas(input, parameter) {
89
+ if (input.type === "object") {
90
+ const schema = input.properties?.[parameter];
91
+ if (!schema || schema.type !== "string" || !input.required?.includes(parameter)) throw new TypeError(`Path parameter "${parameter}" must be a required string input field.`);
92
+ return [schema];
93
+ }
94
+ if (Array.isArray(input.anyOf) && input.anyOf.length > 0) return input.anyOf.flatMap((schema) => pathParameterSchemas(schema, parameter));
95
+ throw new TypeError("Path parameters require object input contracts.");
96
+ }
97
+
98
+ //#endregion
99
+ //#region src/scopes.ts
100
+ /** `<namespace>:<resource>:<action>`, or deeper, in lowercase kebab-case segments. */
101
+ const SCOPE_NAME = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*){2,}$/;
102
+ /** Whether `scope` is a well-formed scope of the service whose namespace is `namespace`. */
103
+ function isNamespacedScope(scope, namespace) {
104
+ return scope.startsWith(`${namespace}:`) && SCOPE_NAME.test(scope);
105
+ }
106
+ /**
107
+ * Whether granted scopes admit a requirement: any one of the required scopes, or all of them with `all`.
108
+ * An empty requirement admits nobody.
109
+ */
110
+ function matchesScopes(required, granted, match = "any") {
111
+ if (!required.length) return false;
112
+ const has = (scope) => granted.includes(scope);
113
+ return match === "all" ? required.every(has) : match === "any" && required.some(has);
114
+ }
115
+
116
+ //#endregion
117
+ //#region src/manifest.ts
118
+ /** Whether an operation belongs in public contracts (OpenAPI, typed clients, discovery metadata). */
119
+ function isPublicOperation(declaration) {
120
+ return declaration.visibility !== "internal";
121
+ }
122
+ /** The scopes of an operation as a list; a caller needs any one of them. */
123
+ function operationScopes(declaration) {
124
+ return typeof declaration.scope === "string" ? [declaration.scope] : declaration.scope;
125
+ }
126
+ /** Shared by HTTP admission, MCP discovery and calls, and execution. */
127
+ function operationMatchesScopes(declaration, granted) {
128
+ return matchesScopes(operationScopes(declaration), granted, declaration.scopeMatch);
129
+ }
130
+ /**
131
+ * Declares one operation on its own, keeping its literal types. The builder's `.operation()` is the usual way
132
+ * to declare one. As there, `execute` receives the decoded input, `StaticDecode<typeof input>`.
133
+ */
134
+ function operation(definition) {
135
+ return definition;
136
+ }
137
+ /** Compose resource modules without silently overwriting a capability. */
138
+ function composeOperations(...groups) {
139
+ const result = {};
140
+ for (const group of groups) for (const [name, op] of Object.entries(group)) {
141
+ if (Object.hasOwn(result, name)) throw new TypeError(`Duplicate operation: ${name}`);
142
+ Object.defineProperty(result, name, {
143
+ value: op,
144
+ enumerable: true
145
+ });
146
+ }
147
+ return result;
148
+ }
149
+ /** The failure codes every operation may answer without declaring them. */
150
+ const STANDARD_CODES = new Set(Object.values(STANDARD_FAILURES).map(({ code }) => code));
151
+ /** Default request body limit when neither the operation nor the application sets one. */
152
+ const DEFAULT_MAX_BODY_BYTES = 32768;
153
+ /** Default output limit when neither the operation nor the application sets one. */
154
+ const DEFAULT_MAX_OUTPUT_BYTES = 262144;
155
+ /** Largest body limit an application or operation may declare: the body is buffered in memory. */
156
+ const MAX_BODY_BYTES_CEILING = 16777216;
157
+ /** The request body limit an operation is held to: its own, else the application's, else the default. */
158
+ function operationBodyLimit(application, declaration) {
159
+ return declaration.maxBodyBytes ?? application.maxBodyBytes ?? 32768;
160
+ }
161
+ /** The output limit an operation is held to: its own, else the application's, else the default. */
162
+ function operationOutputLimit(application, declaration) {
163
+ return declaration.maxOutputBytes ?? application.maxOutputBytes ?? 262144;
164
+ }
165
+ /** Whether an operation's MCP tool reaches outside the service: it does unless it declares otherwise. */
166
+ function mcpOpenWorld(tool) {
167
+ return tool.openWorld ?? true;
168
+ }
169
+
170
+ //#endregion
171
+ //#region src/internal/digest.ts
172
+ /**
173
+ * SHA-256 digests in hexadecimal, for rate limit keys and skill manifests.
174
+ */
175
+ /** The SHA-256 digest of text or bytes, in lowercase hexadecimal. */
176
+ async function sha256Hex(value) {
177
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
178
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
179
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/result.ts
184
+ /** A success carrying `value`. */
185
+ function ok(value) {
186
+ return {
187
+ ok: true,
188
+ value
189
+ };
190
+ }
191
+ /** A failure carrying `error`, usually `catalog.someFailure.create()`. */
192
+ function err(error) {
193
+ return {
194
+ ok: false,
195
+ error
196
+ };
197
+ }
198
+ /**
199
+ * Whether an untrusted answer (a Service Binding's, a stored one) is a Maximus Result: a success with
200
+ * its value, or a failure with a well-formed error. Anything else is not an answer at all.
201
+ */
202
+ function isResult(value) {
203
+ if (!isRecord(value)) return false;
204
+ if (value.ok === true) return "value" in value;
205
+ const { error } = value;
206
+ return value.ok === false && isRecord(error) && typeof error.code === "string" && typeof error.message === "string" && typeof error.retryable === "boolean" && isRecord(error.data);
207
+ }
208
+
209
+ //#endregion
210
+ //#region src/tokens.ts
211
+ /**
212
+ * Token verification: the principal every operation receives, the token policy, OAuth access token
213
+ * verification against the issuer's JWKS, claim projection, and request admission by scope.
214
+ */
215
+ /**
216
+ * Who calls, as every operation receives it: the actor, its kind, its verified organization and the request
217
+ * id.
218
+ */
219
+ const PrincipalSchema = Type.Object({
220
+ actorId: Type.String({
221
+ minLength: 1,
222
+ maxLength: 255
223
+ }),
224
+ actorKind: Type.Union([Type.Literal("user"), Type.Literal("service")]),
225
+ organizationId: OrganizationIdSchema,
226
+ requestId: UuidSchema
227
+ }, { additionalProperties: false });
228
+ /**
229
+ * The OAuth client a token was issued to: its id and its class, `human`, `machine` or `dcr` (a dynamically
230
+ * registered client).
231
+ */
232
+ const TokenClientSchema = Type.Object({
233
+ id: Type.String({
234
+ minLength: 1,
235
+ maxLength: 255
236
+ }),
237
+ class: Type.Union([
238
+ Type.Literal("human"),
239
+ Type.Literal("machine"),
240
+ Type.Literal("dcr")
241
+ ])
242
+ }, { additionalProperties: false });
243
+ /**
244
+ * What a verified token grants: the principal without a request id, its scopes and, for an OAuth token, its
245
+ * client. A custom `tokens.resolve` returns this shape.
246
+ */
247
+ const TokenPrincipalSchema = Type.Object({
248
+ ...Type.Omit(PrincipalSchema, ["requestId"]).properties,
249
+ scopes: Type.Array(Type.String({ maxLength: 255 }), { maxItems: 1e3 }),
250
+ /** Custom resolvers must classify DCR from verified application policy, never request headers. */
251
+ client: Type.Optional(TokenClientSchema)
252
+ }, { additionalProperties: false });
253
+ /** Every algorithm `TokenAlgorithm` names. */
254
+ const TOKEN_ALGORITHMS = /* @__PURE__ */ new Set([
255
+ "RS256",
256
+ "RS384",
257
+ "RS512",
258
+ "PS256",
259
+ "PS384",
260
+ "PS512",
261
+ "ES256",
262
+ "ES384",
263
+ "ES512",
264
+ "EdDSA"
265
+ ]);
266
+ /** The hosts only `cf dev`, or a test, reaches a Worker as: the internet never reaches a deployed Worker so. */
267
+ const LOCAL_HOSTS = /* @__PURE__ */ new Set([
268
+ "localhost",
269
+ "127.0.0.1",
270
+ "[::1]"
271
+ ]);
272
+ /**
273
+ * Whether a token is the development token, presented to a local host. The digests have one length, so the
274
+ * comparison takes the same time however much of the token matches.
275
+ */
276
+ async function isDevelopmentToken(development, token, request, env) {
277
+ const expected = isRecord(env) ? env[development.binding] : void 0;
278
+ return typeof expected === "string" && expected.length >= 32 && LOCAL_HOSTS.has(new URL(request.url).hostname) && await sha256Hex(token) === await sha256Hex(expected);
279
+ }
280
+ /** Whether the application issues its own bearer tokens instead of OAuth access tokens. */
281
+ function usesOwnBearer(policy) {
282
+ return policy.scheme?.type === "bearer";
283
+ }
284
+ /**
285
+ * A claim's own value under its name, else at a dotted path through object claims; undefined when absent.
286
+ * Only own properties are read, so no path reaches a prototype.
287
+ */
288
+ function claimAt(claims, path) {
289
+ if (Object.hasOwn(claims, path)) return claims[path];
290
+ let value = claims;
291
+ for (const key of path.split(".")) {
292
+ if (!isRecord(value) || !Object.hasOwn(value, key)) return;
293
+ value = value[key];
294
+ }
295
+ return value;
296
+ }
297
+ /** A claim's scopes: a space-separated string or a list of strings, none when absent; null when malformed. */
298
+ function scopeList(value) {
299
+ if (value === void 0) return [];
300
+ if (typeof value === "string") return value.split(" ").filter(Boolean);
301
+ return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : null;
302
+ }
303
+ /**
304
+ * The OAuth client a token names: the mapped claim, else `azp` or `client_id`, which must agree when both are
305
+ * present. Undefined when it names none; null when a client claim is malformed or the two disagree.
306
+ */
307
+ function tokenClient(claims, path) {
308
+ const present = (path === void 0 ? [claims.azp, claims.client_id] : [claimAt(claims, path)]).filter((value) => value !== void 0);
309
+ if (present.some((value) => typeof value !== "string" || !value) || new Set(present).size > 1) return null;
310
+ return present[0];
311
+ }
312
+ /**
313
+ * The principal a verified access token grants, read where `mapping` says. A subject of the shape
314
+ * `mapping.machineSubject` names, `<client id>@clients` by default, is a machine; anyone else is a person,
315
+ * who holds only the granted scopes their permissions claim also lists. Malformed or inconsistent claims
316
+ * are refused.
317
+ */
318
+ function projectToken(claims, mapping = {}) {
319
+ const refused = err(standardErrors.unauthorized.create());
320
+ if (!isRecord(claims) || typeof claims.sub !== "string") return refused;
321
+ const subject = claims.sub;
322
+ const client = tokenClient(claims, mapping.client);
323
+ const granted = scopeList(claimAt(claims, mapping.scopes ?? "scope"));
324
+ if (client === null || granted === null) return refused;
325
+ const clientsSuffix = mapping.machineSubject !== "{client}";
326
+ const machine = client !== void 0 && subject === (clientsSuffix ? `${client}@clients` : client);
327
+ if (clientsSuffix && !machine && subject.endsWith("@clients")) return refused;
328
+ let scopes = [...new Set(granted)];
329
+ const listed = mapping.permissions ?? "permissions";
330
+ if (!machine && listed !== false) {
331
+ const permissions = scopeList(claimAt(claims, listed));
332
+ if (permissions === null) return refused;
333
+ scopes = scopes.filter((scope) => permissions.includes(scope));
334
+ }
335
+ const principal = parseInput(TokenPrincipalSchema, {
336
+ organizationId: claimAt(claims, mapping.organization ?? "org_id"),
337
+ actorId: subject,
338
+ actorKind: machine ? "service" : "user",
339
+ scopes,
340
+ ...client === void 0 ? {} : { client: {
341
+ id: client,
342
+ class: machine ? "machine" : "human"
343
+ } }
344
+ });
345
+ return principal.ok ? ok(principal.value) : refused;
346
+ }
347
+ /** The OAuth authorization server; there is no default, so a deployment always names its own. */
348
+ function tokenIssuer(policy) {
349
+ if (!policy.issuer) throw new TypeError("tokens.issuer is required to verify or document OAuth access tokens.");
350
+ return policy.issuer;
351
+ }
352
+ /**
353
+ * The audiences a token may carry, the canonical one first: the `resource` OAuth discovery names.
354
+ * Refuses an empty list, an empty audience and a repeated one.
355
+ */
356
+ function tokenAudiences(policy) {
357
+ const listed = policy.audience;
358
+ const audiences = Array.isArray(listed) ? listed : [listed];
359
+ const valid = audiences.filter((value) => typeof value === "string" && value !== "");
360
+ const [canonical, ...others] = valid;
361
+ if (canonical === void 0 || valid.length !== audiences.length || new Set(valid).size !== valid.length) throw new TypeError("tokens.audience must be a non-empty string or a non-empty list of distinct non-empty strings.");
362
+ return [canonical, ...others];
363
+ }
364
+ /** Whether a value, resolved against `base`, is an HTTPS URL. */
365
+ function httpsUrl(value, base) {
366
+ try {
367
+ return new URL(value, base).protocol === "https:";
368
+ } catch {
369
+ return false;
370
+ }
371
+ }
372
+ /**
373
+ * Refuse, at construction, an OAuth policy that could never verify or document a token. Verification
374
+ * is built lazily, so without this check a missing issuer surfaced only at run time, as a 401 for
375
+ * every token and a 500 for the OpenAPI document. An application that issues its own bearer tokens
376
+ * names no authorization server.
377
+ */
378
+ function checkTokenAuthority(policy) {
379
+ const { development } = policy;
380
+ if (development !== void 0 && (typeof development.binding !== "string" || !development.binding || development.organizationId !== void 0 && !parseInput(OrganizationIdSchema, development.organizationId).ok)) throw new TypeError("tokens.development names the binding of its token and a valid organization id.");
381
+ if (usesOwnBearer(policy)) return;
382
+ const { algorithms, claims } = policy;
383
+ if (algorithms !== void 0 && (!algorithms.length || algorithms.some((name) => !TOKEN_ALGORITHMS.has(name)))) throw new TypeError("tokens.algorithms lists one or more asymmetric JWS algorithms.");
384
+ if (claims !== void 0) {
385
+ const { permissions, machineSubject } = claims;
386
+ if ([
387
+ claims.organization,
388
+ claims.scopes,
389
+ claims.client,
390
+ permissions === false ? void 0 : permissions
391
+ ].some((path) => path !== void 0 && (typeof path !== "string" || !path)) || machineSubject !== void 0 && !["{client}@clients", "{client}"].includes(machineSubject)) throw new TypeError("tokens.claims names each claim by a non-empty string (permissions may be false), and machineSubject is {client}@clients or {client}.");
392
+ }
393
+ const issuer = tokenIssuer(policy);
394
+ if (!httpsUrl(issuer) || [
395
+ policy.jwksUri,
396
+ policy.authorizationEndpoint,
397
+ policy.tokenEndpoint
398
+ ].some((endpoint) => endpoint !== void 0 && !httpsUrl(endpoint, issuer))) throw new TypeError("tokens.issuer, jwksUri, authorizationEndpoint and tokenEndpoint must be absolute HTTPS URLs, the last three resolved against the issuer.");
399
+ }
400
+ /** The authorization server's authorization and token endpoints, which OpenAPI publishes. */
401
+ function tokenEndpoints(policy) {
402
+ const issuer = tokenIssuer(policy);
403
+ return {
404
+ authorization: new URL(policy.authorizationEndpoint ?? "authorize", issuer).href,
405
+ token: new URL(policy.tokenEndpoint ?? "oauth/token", issuer).href
406
+ };
407
+ }
408
+ /** A token is accepted when its `aud` names any one of the policy's audiences. */
409
+ function createTokenVerifier(policy) {
410
+ const issuer = tokenIssuer(policy);
411
+ const audience = tokenAudiences(policy);
412
+ const uri = new URL(policy.jwksUri ?? ".well-known/jwks.json", issuer);
413
+ if (new URL(issuer).protocol !== "https:" || uri.protocol !== "https:") throw new TypeError("Token authority must use HTTPS.");
414
+ const jwks = createRemoteJWKSet(uri, {
415
+ timeoutDuration: 1e4,
416
+ cacheMaxAge: 6e5,
417
+ cooldownDuration: 3e4
418
+ });
419
+ return async (token) => {
420
+ const { payload } = await jwtVerify(token, jwks, {
421
+ issuer,
422
+ audience,
423
+ algorithms: [...policy.algorithms ?? ["RS256"]],
424
+ clockTolerance: 5,
425
+ requiredClaims: ["exp", "sub"]
426
+ });
427
+ return payload;
428
+ };
429
+ }
430
+ /**
431
+ * Admits a request by its bearer token: verifies it (OAuth by JWKS, or the policy's own `resolve`) and checks
432
+ * that it carries the required scope. Refusals are `UNAUTHORIZED` or `FORBIDDEN` failures, never exceptions.
433
+ */
434
+ function createTokenAuthorization(policy, given) {
435
+ let verifier = given;
436
+ /** Verifies an OAuth access token, building the verifier on first use. */
437
+ const verify = (token) => {
438
+ verifier ??= createTokenVerifier(policy);
439
+ return verifier(token);
440
+ };
441
+ /** Admit the request when its token carries `scope`, or any one of `scope` when it is a list. */
442
+ return async (request, scope, context, scopeMatch = "any") => {
443
+ const accepted = typeof scope === "string" ? [scope] : scope;
444
+ /** Whether granted scopes admit the request. */
445
+ const admits = (scopes) => matchesScopes(accepted, scopes, scopeMatch);
446
+ const token = (policy.resolve || policy.development ? /^Bearer (\S+)$/i : /^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/i).exec(request.headers.get("authorization") ?? "")?.[1];
447
+ if (!token || token.length > 16384 || request.headers.has("x-api-key")) return err(standardErrors.unauthorized.create());
448
+ if (policy.development && context && await isDevelopmentToken(policy.development, token, request, context.env)) {
449
+ const developer = {
450
+ actorId: "local-developer",
451
+ actorKind: "user",
452
+ organizationId: policy.development.organizationId ?? "local-development",
453
+ scopes: [...context.applicationScopes],
454
+ client: {
455
+ id: "local-development",
456
+ class: "human"
457
+ }
458
+ };
459
+ return admits(developer.scopes) ? ok(developer) : err(standardErrors.forbidden.create());
460
+ }
461
+ if (policy.resolve) try {
462
+ const outcome = await policy.resolve(token, context);
463
+ if ("ok" in outcome && !outcome.ok) return err(outcome.error.code === "FORBIDDEN" ? standardErrors.forbidden.create() : standardErrors.unauthorized.create());
464
+ const resolved = parseInput(TokenPrincipalSchema, "ok" in outcome ? outcome.value : outcome);
465
+ if (!resolved.ok) return err(standardErrors.unauthorized.create());
466
+ const { client } = resolved.value;
467
+ if (client && (client.class === "machine" !== (resolved.value.actorKind === "service") || policy.scheme?.type !== "oauth+bearer" && client.class === "machine" && resolved.value.actorId !== client.id && resolved.value.actorId !== `${client.id}@clients`)) return err(standardErrors.unauthorized.create());
468
+ return admits(resolved.value.scopes) ? ok(resolved.value) : err(standardErrors.forbidden.create());
469
+ } catch {
470
+ return err(standardErrors.unauthorized.create());
471
+ }
472
+ let claims;
473
+ try {
474
+ claims = await verify(token);
475
+ } catch {
476
+ return err(standardErrors.unauthorized.create());
477
+ }
478
+ const principal = projectToken(claims, policy.claims);
479
+ if (!principal.ok) return principal;
480
+ return admits(principal.value.scopes) ? principal : err(standardErrors.forbidden.create());
481
+ };
482
+ }
483
+
484
+ //#endregion
485
+ //#region src/define-app.ts
486
+ /** Names a Worker entrypoint already uses, or that would break a class or a promise. */
487
+ const RESERVED_NAMES = /* @__PURE__ */ new Set([
488
+ "fetch",
489
+ "connect",
490
+ "constructor",
491
+ "then",
492
+ "scheduled",
493
+ "queue",
494
+ "alarm",
495
+ "__proto__",
496
+ "prototype"
497
+ ]);
498
+ /** An MCP tool name: a letter, then up to 63 letters, digits and underscores. */
499
+ const TOOL_NAME = /^[a-z][A-Za-z0-9_]{0,63}$/;
500
+ /** Every field an operation has: any other, such as a misspelled or retired one, would do nothing. */
501
+ const OPERATION_FIELDS = new Set(Object.keys({
502
+ actorKinds: true,
503
+ http: true,
504
+ visibility: true,
505
+ mcp: true,
506
+ rpc: true,
507
+ scope: true,
508
+ scopeMatch: true,
509
+ conditionalScopes: true,
510
+ failures: true,
511
+ title: true,
512
+ description: true,
513
+ group: true,
514
+ effect: true,
515
+ input: true,
516
+ output: true,
517
+ maxBodyBytes: true,
518
+ maxOutputBytes: true,
519
+ execute: true,
520
+ pipeline: true
521
+ }));
522
+ /** Checks the application, then hands it back unchanged. */
523
+ function defineApp() {
524
+ return (manifest) => {
525
+ checkApplication(manifest);
526
+ return manifest;
527
+ };
528
+ }
529
+ /**
530
+ * Every rule, in the order they always ran, so an application that breaks several meets the same refusal
531
+ * first.
532
+ */
533
+ function checkApplication(manifest) {
534
+ if (!/^[a-z][a-z0-9-]{1,63}$/.test(manifest.namespace)) throw new TypeError("A scope namespace is required.");
535
+ checkDeclaredFailures(manifest.operations, manifest.errors);
536
+ const claimed = {
537
+ routes: /* @__PURE__ */ new Set(),
538
+ tools: /* @__PURE__ */ new Set()
539
+ };
540
+ for (const [name, op] of Object.entries(manifest.operations)) checkOperation(name, op, manifest, claimed);
541
+ createHttpRouteResolver(Object.values(manifest.operations));
542
+ checkGuides(manifest.mcp?.guides ?? []);
543
+ checkSkills(manifest.mcp?.skills ?? []);
544
+ checkSkillTool(manifest.mcp, claimed.tools);
545
+ if (!validBodyLimit(manifest.maxBodyBytes)) throw new TypeError("The application body limit is a positive integer up to 16 MiB.");
546
+ if (!validBodyLimit(manifest.maxOutputBytes)) throw new TypeError("The application output limit is a positive integer up to 16 MiB.");
547
+ if (new URL(manifest.origin).protocol !== "https:") throw new TypeError("Application origin must use HTTPS.");
548
+ checkTokenAuthority(manifest.tokens);
549
+ tokenAudiences(manifest.tokens);
550
+ if (Object.keys(manifest.tokens.resources ?? {}).length > 0 && manifest.tokens.resourceMetadataUrl === void 0) throw new TypeError("tokens.resources requires tokens.resourceMetadataUrl: name the metadata a 401 challenge points at.");
551
+ }
552
+ /** An operation's `failures` name domain codes of the catalog, each once. */
553
+ function checkDeclaredFailures(operations, errors) {
554
+ const domainCodes = new Set(Object.values(errors.definitions).map(({ code }) => code).filter((code) => !STANDARD_CODES.has(code)));
555
+ for (const [name, op] of Object.entries(operations)) if (op.failures && (new Set(op.failures).size !== op.failures.length || op.failures.some((code) => !domainCodes.has(code)))) throw new TypeError(`Operation "${name}": failures lists each domain failure code of the error catalog once; standard failures are always allowed.`);
556
+ }
557
+ /** Every rule one operation keeps, in the order a definition is usually written. */
558
+ function checkOperation(name, op, application, claimed) {
559
+ checkOperationContract(name, op, application.namespace);
560
+ checkHttpExposure(name, op, claimed.routes);
561
+ if (op.conditionalScopes && (!op.conditionalScopes.length || new Set(op.conditionalScopes).size !== op.conditionalScopes.length || op.conditionalScopes.some((scope) => operationScopes(op).includes(scope) || !isNamespacedScope(scope, application.namespace)))) throw new TypeError("Conditional scopes require unique namespaced declarations distinct from the admission scope.");
562
+ if (op.mcp) {
563
+ if (!TOOL_NAME.test(op.mcp.name) || claimed.tools.has(op.mcp.name)) throw new TypeError("MCP tools require unique safe names.");
564
+ claimed.tools.add(op.mcp.name);
565
+ }
566
+ if (op.rpc && op.rpc !== true && op.rpc.callers.some((caller) => !application.rpc.callers.includes(caller))) throw new TypeError("Operation RPC callers must be allowed by the application.");
567
+ }
568
+ /** The operation's fields, name, scopes, eligible actors and schemas. */
569
+ function checkOperationContract(name, op, namespace) {
570
+ const unknown = Object.keys(op).find((field) => !OPERATION_FIELDS.has(field));
571
+ if (unknown !== void 0) throw new TypeError(`Operation "${name}": "${unknown}" is not an operation field.`);
572
+ if (op.scopeMatch !== void 0 && op.scopeMatch !== "any" && op.scopeMatch !== "all") throw new TypeError(`Operation "${name}": scopeMatch must be any or all.`);
573
+ if (hasUncompiledCodecs(op.input)) throw new TypeError(`Operation "${name}": its input uses codecs (normalize, transform, inspect, refine, pipe or stripObject) that run only inside inputSchema(); wrap the input in inputSchema().`);
574
+ if (op.actorKinds && (!op.actorKinds.length || new Set(op.actorKinds).size !== op.actorKinds.length || op.actorKinds.some((kind) => kind !== "user" && kind !== "service"))) throw new TypeError(`Operation "${name}": actorKinds must explicitly name eligible users or services.`);
575
+ if (!/^[a-z][a-zA-Z0-9]*$/.test(name) || RESERVED_NAMES.has(name)) throw new TypeError(`Operation "${name}": use a camelCase name that is not a reserved Worker method. Use safe operation names, namespaced scopes and strict object schemas.`);
576
+ const scopes = operationScopes(op);
577
+ if (!scopes.length || new Set(scopes).size !== scopes.length || scopes.some((scope) => !isNamespacedScope(scope, namespace))) throw new TypeError(`Operation "${name}": every scope is "${namespace}:<resource>:<action>", listed once. Use safe operation names, namespaced scopes and strict object schemas.`);
578
+ if (!(strictObject(op.input, op.http?.method !== "GET") && (isAttachmentSchema(op.output) || strictObject(op.output, true)))) throw new TypeError(`Operation "${name}": input and output are strict objects or unions of strict objects; a GET input is one strict object (its query). Use safe operation names, namespaced scopes and strict object schemas.`);
579
+ }
580
+ /** Byte bodies, attachments, limits, header-sourced fields and the route itself. */
581
+ function checkHttpExposure(name, op, routes) {
582
+ if (op.http?.body !== void 0 && op.http.body !== "bytes" || op.http?.response !== void 0 && op.http.response !== "attachment") throw new TypeError("Unsupported HTTP binary contract.");
583
+ const binary = op.http?.body === "bytes";
584
+ const attachment = isAttachmentSchema(op.output);
585
+ if ((binary || attachment) && (!op.http || op.mcp || op.rpc)) throw new TypeError(`Operation "${name}": byte bodies and attachments are HTTP-only.`);
586
+ if (op.http?.response === "attachment" !== attachment || binary && op.http?.method === "GET") throw new TypeError(`Operation "${name}": declare matching attachment output and non-GET byte bodies.`);
587
+ if (!validBodyLimit(op.maxOutputBytes)) throw new TypeError("Invalid operation output byte limit.");
588
+ if (op.http?.successStatus !== void 0 && ![
589
+ 200,
590
+ 201,
591
+ 202
592
+ ].includes(op.http.successStatus)) throw new TypeError("Invalid operation success status.");
593
+ if (op.http?.headers) {
594
+ const pathFields = new Set(operationPathParameters(op.http.path));
595
+ const headers = Object.entries(op.http.headers);
596
+ if (!binary || op.input.type !== "object" || new Set(headers.map(([, wire]) => wire.toLowerCase())).size !== headers.length || headers.some(([field, wire]) => !Object.hasOwn(op.input.properties, field) || pathFields.has(field) || !isInputHeaderName(wire))) throw new TypeError("Byte operation headers must name unique, non-authority metadata fields.");
597
+ }
598
+ if (!validBodyLimit(op.maxBodyBytes) || op.maxBodyBytes !== void 0 && op.http?.method === "GET") throw new TypeError(`Operation "${name}": an operation body limit is a positive integer up to 16 MiB, on a non-GET route.`);
599
+ if (op.http) {
600
+ for (const parameter of operationPathParameters(op.http.path)) pathParameterSchemas(op.input, parameter);
601
+ const route = `${op.http.method} ${op.http.path}`;
602
+ if (routes.has(route) || op.effect !== "read" && op.http.method === "GET") throw new TypeError(`Operation "${name}": use unique versioned routes; mutations cannot use GET.`);
603
+ routes.add(route);
604
+ }
605
+ }
606
+ /** Guides are named resources and prompts: each name safe and unique. */
607
+ function checkGuides(guides) {
608
+ if (new Set(guides.map((guide) => guide.name)).size !== guides.length || guides.some((guide) => !/^[a-z][a-z0-9-]{0,63}$/.test(guide.name))) throw new TypeError("Guides require unique safe names.");
609
+ }
610
+ /** The MCP skills: unique Agent Skills names, one-line descriptions and instructions. */
611
+ function checkSkills(skills) {
612
+ if (new Set(skills.map((skill) => skill.name)).size !== skills.length || skills.some((skill) => skill.name.length > 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skill.name) || !skill.description.trim() || skill.description.length > 1024 || /[\r\n]/.test(skill.description) || !skill.text.trim())) throw new TypeError("Skills require unique Agent Skills names, a one-line description and instructions.");
613
+ }
614
+ /** The skill tool serves the MCP skills under a name no operation's tool takes. */
615
+ function checkSkillTool(mcp, tools) {
616
+ const skillTool = mcp?.skillTool;
617
+ if (skillTool !== void 0 && (!(mcp?.skills ?? []).length || !TOOL_NAME.test(skillTool) || tools.has(skillTool))) throw new TypeError("A skill tool requires skills and a safe name no operation uses.");
618
+ }
619
+ /** Whether a body or output limit is absent, or a positive integer up to 16 MiB. */
620
+ function validBodyLimit(value) {
621
+ return value === void 0 || Number.isInteger(value) && value > 0 && value <= 16777216;
622
+ }
623
+ /**
624
+ * A strict object (`additionalProperties: false`), or — when `unions` is true —
625
+ * a union whose every member is a strict object, so a request body or a result
626
+ * can be discriminated by a field (`{ channel: 'email', … } | { channel: 'sms', … }`).
627
+ */
628
+ function strictObject(schema, unions) {
629
+ if (schema.type === "object") return schema.additionalProperties === false;
630
+ const members = schema.anyOf;
631
+ return unions && Array.isArray(members) && members.length > 0 && members.every((member) => strictObject(member, false));
632
+ }
633
+
634
+ //#endregion
635
+ //#region src/execution.ts
636
+ /**
637
+ * The one execution path every transport calls: the caller's eligibility, input decoding, context
638
+ * preparation, middleware, the handler, and the checks on what it returns.
639
+ */
640
+ /**
641
+ * The execution path every transport shares: checks that the caller may run the operation, decodes the input,
642
+ * prepares the context, runs the middleware and the handler, then checks the result against the declared
643
+ * output and failures. An unexpected error becomes `INTERNAL_ERROR` and is reported, never thrown.
644
+ */
645
+ async function executeOperation(manifest, operation, env, principal, input, authority, background, body) {
646
+ if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
647
+ const admitted = decodeInput(operation.input, input);
648
+ if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
649
+ try {
650
+ const trustedAuthority = authority ? Object.freeze({
651
+ surface: authority.surface,
652
+ scopes: Object.freeze([...authority.scopes]),
653
+ client: Object.freeze({ ...authority.client }),
654
+ ...authority.token ? { token: authority.token } : {}
655
+ }) : void 0;
656
+ const invocation = {
657
+ env,
658
+ principal,
659
+ input: admitted.value,
660
+ ...body ? { body } : {},
661
+ ...background ? { background } : {},
662
+ ...trustedAuthority ? { authority: trustedAuthority } : {}
663
+ };
664
+ const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
665
+ if (!context.ok) return err(manifest.errors.validate(context.error));
666
+ const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
667
+ let latest = -1;
668
+ /**
669
+ * Runs the middleware at `index`, whose `next` runs the following one, until the handler; each `next`
670
+ * runs once.
671
+ */
672
+ const dispatch = async (index) => {
673
+ if (index <= latest) throw new Error("Middleware next() may be called only once.");
674
+ latest = index;
675
+ const middleware = chain[index];
676
+ return await (middleware ? middleware(context.value, () => dispatch(index + 1)) : operation.execute(context.value, admitted.value));
677
+ };
678
+ const result = await dispatch(0);
679
+ if (!result || typeof result.ok !== "boolean" || !Object.hasOwn(result, "ok") || Object.keys(result).length !== 2 || !Object.hasOwn(result, result.ok ? "value" : "error")) throw new TypeError("Invalid operation result");
680
+ if (!result.ok) {
681
+ const failure = manifest.errors.validate(result.error);
682
+ if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
683
+ return err(failure);
684
+ }
685
+ const maxOutputBytes = operationOutputLimit(manifest, operation);
686
+ if (isAttachmentSchema(operation.output)) {
687
+ if (!validAttachment(result.value, maxOutputBytes)) throw new TypeError("Invalid attachment output");
688
+ return result;
689
+ }
690
+ if (!Value.Check(operation.output, result.value)) throw new TypeError("Invalid operation output");
691
+ if (new TextEncoder().encode(JSON.stringify(result.value)).byteLength > maxOutputBytes) throw new TypeError("Operation output exceeds its limit");
692
+ return result;
693
+ } catch (error) {
694
+ if (telemetryEnabled(manifest.telemetry, env)) reportUnexpected(error, "operation", principal.requestId);
695
+ return err(standardErrors.internal.create());
696
+ }
697
+ }
698
+
699
+ //#endregion
700
+ export { operationMatchesScopes as C, pathParameterSchemas as D, matchesScopes as E, attachmentResponse as O, operationBodyLimit as S, operationScopes as T, STANDARD_CODES as _, createTokenVerifier as a, mcpOpenWorld as b, tokenEndpoints as c, err as d, isResult as f, MAX_BODY_BYTES_CEILING as g, DEFAULT_MAX_BODY_BYTES as h, createTokenAuthorization as i, binaryBody as k, tokenIssuer as l, sha256Hex as m, defineApp as n, projectToken as o, ok as p, PrincipalSchema as r, tokenAudiences as s, executeOperation as t, usesOwnBearer as u, composeOperations as v, operationOutputLimit as w, operation as x, isPublicOperation as y };