@arbol-ai/maximus 8.4.0 → 8.5.1

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.
@@ -1,274 +1,13 @@
1
1
  import { i as parseInput } from "./validation-CpzAxj2_.js";
2
- import { L as wireInput, i as UuidSchema, n as OrganizationIdSchema, z as withoutSecretKeyword } from "./schemas-_UJcx_uY.js";
2
+ import { i as UuidSchema, n as OrganizationIdSchema, z as withoutSecretKeyword } from "./schemas-_UJcx_uY.js";
3
3
  import { t as isRecord } from "./record-DQUDTpEA.js";
4
4
  import { i as standardErrors } from "./errors-BoutSmiy.js";
5
- import { a as operationPathParameters } from "./http-paths-D043DkJv.js";
6
- import { n as routeGroup, t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
7
- import { S as matchesScopes, _ as operationBodyLimit, b as operationScopes, f as STANDARD_CODES, h as mcpOpenWorld, l as BODY_CODES, m as isPublicOperation, n as TASK_GROUP, r as TASK_GROUP_DESCRIPTION, x as isNamespacedScope, y as operationOutputLimit } from "./tasks-DYdY-dBI.js";
5
+ import { S as matchesScopes, x as isNamespacedScope } from "./tasks-DYdY-dBI.js";
8
6
  import { r as ok, t as err } from "./result-CF4OzG9O.js";
9
- import { t as queryKind } from "./query-kind-CWKAXEME.js";
10
7
  import { t as sha256Hex } from "./digest-C51F1bhA.js";
11
8
  import { Type } from "typebox";
12
9
  import { createRemoteJWKSet, jwtVerify } from "jose";
13
10
 
14
- // src/internal/claims.ts
15
- /**
16
- * Reading a verified token's claims, which token verification and Cloudflare Access share.
17
- */
18
- /**
19
- * A claim's own value under its name, else at a dotted path through object claims; undefined when absent.
20
- * Only own properties are read, so no path reaches a prototype.
21
- */
22
- function claimAt(claims, path) {
23
- if (Object.hasOwn(claims, path)) return claims[path];
24
- let value = claims;
25
- for (const key of path.split(".")) {
26
- if (!isRecord(value) || !Object.hasOwn(value, key)) return;
27
- value = value[key];
28
- }
29
- return value;
30
- }
31
-
32
- // src/principal.ts
33
- /**
34
- * Who calls: the principal every operation receives, and what a verified token grants before admission adds
35
- * the request id. Token verification (`tokens.ts`) and Cloudflare Access (`cloudflare-access.ts`) both answer
36
- * a `TokenPrincipal`, parsed strictly against these schemas.
37
- */
38
- /**
39
- * Who calls, as every operation receives it: the actor, its kind, its verified organization and the request
40
- * id.
41
- */
42
- const PrincipalSchema = Type.Object({
43
- actorId: Type.String({
44
- minLength: 1,
45
- maxLength: 255
46
- }),
47
- actorKind: Type.Union([Type.Literal("user"), Type.Literal("service")]),
48
- organizationId: OrganizationIdSchema,
49
- requestId: UuidSchema
50
- }, { additionalProperties: false });
51
- /**
52
- * The OAuth client a token was issued to: its id and its class, `human`, `machine` or `dcr` (a dynamically
53
- * registered client).
54
- */
55
- const TokenClientSchema = Type.Object({
56
- id: Type.String({
57
- minLength: 1,
58
- maxLength: 255
59
- }),
60
- class: Type.Union([
61
- Type.Literal("human"),
62
- Type.Literal("machine"),
63
- Type.Literal("dcr")
64
- ])
65
- }, { additionalProperties: false });
66
- /**
67
- * What a verified token grants: the principal without a request id, its scopes and, for an OAuth token, its
68
- * client. A custom `tokens.resolve` returns this shape.
69
- */
70
- const TokenPrincipalSchema = Type.Object({
71
- ...Type.Omit(PrincipalSchema, ["requestId"]).properties,
72
- scopes: Type.Array(Type.String({ maxLength: 255 }), { maxItems: 1e3 }),
73
- /** Custom resolvers must classify DCR from verified application policy, never request headers. */
74
- client: Type.Optional(TokenClientSchema)
75
- }, { additionalProperties: false });
76
-
77
- // src/cloudflare-access.ts
78
- /**
79
- * Cloudflare Access application tokens: where a request presents one, what it grants and what a token policy
80
- * must state to admit it. Access signs people and service tokens in at Cloudflare's edge, and sets the
81
- * application token in `Cf-Access-Jwt-Assertion` on each request it lets through. A Worker cannot take that
82
- * header's presence as proof: a request reaches it around Access at its `workers.dev` and preview URLs, at a
83
- * path Access does not cover, or through a Service Binding. So every token is verified, its signature, issuer
84
- * and audience, and nothing else Access sets, such as `Cf-Access-Authenticated-User-Email` or the
85
- * `CF_Authorization` cookie, is read.
86
- */
87
- /** The header Access sets the application token in: the only place a policy of its source reads one. */
88
- const ACCESS_TOKEN_HEADER = "cf-access-jwt-assertion";
89
- /** Whether a token policy admits Cloudflare Access application tokens, rather than bearer tokens. */
90
- function usesCloudflareAccess(policy) {
91
- return policy.source === "cloudflare-access";
92
- }
93
- /**
94
- * The principal a verified Access application token grants under `policy.access`. A person, whose token
95
- * names them in `sub` and carries no `common_name`, acts as `sub` (never as their email) through a `human`
96
- * client, the application's audience, and holds `access.people`. A service token, whose token has an empty
97
- * `sub` and its client id as `common_name`, acts as that client id through a `machine` client of the same
98
- * id, and holds what `access.services` lists under it, else nothing. Each acts in `access.organizationId`, or
99
- * in the organization the claim `claims.organization` holds. Anything else is refused as `UNAUTHORIZED`: a
100
- * token whose `type` is not `app` (an Access organization token, for one), a token that is neither a person's
101
- * nor a service token's, an organization missing or malformed or named by both, and a policy without `access`.
102
- */
103
- function projectAccessToken(claims, policy) {
104
- const refused = err(standardErrors.unauthorized.create());
105
- const { access } = policy;
106
- if (access === void 0 || !isRecord(claims) || claims.type !== "app") return refused;
107
- const audience = applicationAudience(claims.aud, policy.audience);
108
- const caller = audience === void 0 ? null : accessCaller(claims, access, audience);
109
- if (caller === null) return refused;
110
- const principal = parseInput(TokenPrincipalSchema, {
111
- ...caller,
112
- organizationId: accessOrganization(claims, access, policy.claims?.organization)
113
- });
114
- return principal.ok ? ok(principal.value) : refused;
115
- }
116
- /**
117
- * The application audience a token names: the first of the policy's audiences that its `aud`, a string or a
118
- * list, carries; undefined when it carries none of them.
119
- */
120
- function applicationAudience(named, audience) {
121
- const carried = typeof named === "string" ? [named] : named;
122
- if (!Array.isArray(carried)) return;
123
- return (typeof audience === "string" ? [audience] : audience).find((candidate) => carried.includes(candidate));
124
- }
125
- /**
126
- * Who a token names: a person by a non-empty `sub` without `common_name`, or a service token by its
127
- * `common_name` with an empty `sub`; null for a token of any other shape, such as one that carries both.
128
- */
129
- function accessCaller(claims, access, audience) {
130
- const { sub: subject, common_name: commonName } = claims;
131
- if (typeof subject === "string" && subject !== "" && commonName === void 0) return {
132
- actorId: subject,
133
- actorKind: "user",
134
- scopes: [...access.people],
135
- client: {
136
- id: audience,
137
- class: "human"
138
- }
139
- };
140
- if (subject === "" && typeof commonName === "string" && commonName !== "") return {
141
- actorId: commonName,
142
- actorKind: "service",
143
- scopes: serviceScopes(access, commonName),
144
- client: {
145
- id: commonName,
146
- class: "machine"
147
- }
148
- };
149
- return null;
150
- }
151
- /**
152
- * The scopes `access.services` lists for a service token's client id, none when it lists none. Only its own
153
- * entries are read, so no client id reaches a prototype's property.
154
- */
155
- function serviceScopes(access, clientId) {
156
- const { services = {} } = access;
157
- return [...(Object.hasOwn(services, clientId) ? services[clientId] : void 0) ?? []];
158
- }
159
- /**
160
- * The organization an Access caller acts in: `access.organizationId`, or the value of the claim `claim`
161
- * names, such as `custom.org_id` for a custom OIDC claim Access passes on. Undefined, and so refused, unless
162
- * exactly one of them is set.
163
- */
164
- function accessOrganization(claims, access, claim) {
165
- if (claim === void 0) return access.organizationId;
166
- return access.organizationId === void 0 ? claimAt(claims, claim) : void 0;
167
- }
168
- /** The options of a token policy that only OAuth access tokens use, which Access application tokens are not. */
169
- const OAUTH_OPTIONS = [
170
- "scheme",
171
- "resources",
172
- "resourceMetadataUrl",
173
- "authorizationEndpoint",
174
- "tokenEndpoint"
175
- ];
176
- /** The most scopes a principal holds, as `TokenPrincipalSchema` admits them. */
177
- const MAX_SCOPES = 1e3;
178
- /**
179
- * Refuses, at construction, a policy of the `cloudflare-access` source that could never admit a caller, or
180
- * that states what Access application tokens never carry: neither `access` nor `resolve`; any option only
181
- * OAuth uses (`scheme`, `resources`, `resourceMetadataUrl` and the endpoints OpenAPI would publish); claims
182
- * other than the organization; and, with `access`, an organization named twice, not at all or malformed, or
183
- * scopes outside the application's namespace, more than 1000 of them, or listed under an empty client id.
184
- */
185
- function checkAccessPolicy(policy, namespace) {
186
- const { access, claims } = policy;
187
- if (access === void 0 && policy.resolve === void 0) throw new TypeError("tokens.source cloudflare-access requires tokens.access, or tokens.resolve to verify Access tokens itself.");
188
- const oauth = OAUTH_OPTIONS.filter((option) => policy[option] !== void 0);
189
- if (oauth.length) throw new TypeError(`Cloudflare Access application tokens are not OAuth access tokens: remove ${oauth.map((option) => `tokens.${option}`).join(", ")}.`);
190
- if (claims !== void 0 && Object.entries(claims).some(([name, value]) => name !== "organization" && value !== void 0)) throw new TypeError("Under Cloudflare Access, tokens.claims names the organization alone: tokens.access grants the scopes.");
191
- if (access === void 0) return;
192
- const { organizationId } = access;
193
- const claim = claims?.organization;
194
- if (!(claim === void 0 ? parseInput(OrganizationIdSchema, organizationId).ok : organizationId === void 0 && typeof claim === "string" && claim !== "")) throw new TypeError("Under Cloudflare Access, name a valid organization once: tokens.access.organizationId or tokens.claims.organization.");
195
- /** Whether a list holds scopes of the application, at most as many and as long as a principal's. */
196
- const ownScopes = (scopes) => Array.isArray(scopes) && scopes.length <= MAX_SCOPES && scopes.every((scope) => typeof scope === "string" && scope.length <= 255 && isNamespacedScope(scope, namespace));
197
- const services = access.services ?? {};
198
- if (!ownScopes(access.people) || !isRecord(services) || Object.entries(services).some(([clientId, scopes]) => !clientId || clientId.length > 255 || !ownScopes(scopes))) throw new TypeError(`tokens.access grants scopes of ${namespace}:<resource>:<action>, at most ${MAX_SCOPES} to people and to each service token, by its client id.`);
199
- }
200
- /** The methods that change nothing: another site's page may send them without consequence. */
201
- const SAFE_METHODS = /* @__PURE__ */ new Set([
202
- "GET",
203
- "HEAD",
204
- "OPTIONS"
205
- ]);
206
- /**
207
- * Whether a browser sent a write for another site's page: a method other than `GET`, `HEAD` and `OPTIONS`
208
- * with `Sec-Fetch-Site: cross-site`, or with an `Origin` other than the request's own. A person's Access
209
- * session travels in a cookie, which the browser attaches to such a request, and Access forwards it with
210
- * the person's application token. A request with neither header, such as a service token's, is no browser's.
211
- */
212
- function isCrossSiteWrite(request) {
213
- if (SAFE_METHODS.has(request.method)) return false;
214
- const origin = request.headers.get("origin");
215
- return request.headers.get("sec-fetch-site") === "cross-site" || origin !== null && origin !== new URL(request.url).origin;
216
- }
217
-
218
- // src/internal/http-query.ts
219
- /**
220
- * The typed GET query codec: which input fields travel in the query string, and how each value is read as
221
- * its kind.
222
- */
223
- /** An integer as a query value: no leading zeros and at most 16 digits, so it stays exact. */
224
- const INTEGER = /^-?(?:0|[1-9]\d{0,15})$/;
225
- /** A decimal number as a query value, with an optional exponent. */
226
- const NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
227
- /** A GET's query fields and the kind each one is read as: every input field outside the path. */
228
- function queryKinds(op) {
229
- const path = new Set(op.http ? operationPathParameters(op.http.path) : []);
230
- const kinds = /* @__PURE__ */ new Map();
231
- for (const [field, schema] of Object.entries(op.input.properties ?? {})) {
232
- const kind = path.has(field) ? null : queryKind(schema);
233
- if (kind) kinds.set(field, kind);
234
- }
235
- return kinds;
236
- }
237
- /**
238
- * A GET's input from its query string, each declared field read once as its kind:
239
- * `?limit=2&active=true&tags=a,b` is `{ limit: 2, active: true, tags: ['a', 'b'] }`. A list is one
240
- * comma-separated value, never a repeated key. A field the input does not declare stays a string for the
241
- * schema to judge. Null when a field repeats, is named `__proto__` or does not read as its kind.
242
- */
243
- function queryInput(kinds, params) {
244
- const keys = [...params.keys()];
245
- if (new Set(keys).size !== keys.length) return null;
246
- const input = {};
247
- for (const [key, text] of params) {
248
- if (key === "__proto__") return null;
249
- let value = text;
250
- switch (kinds.get(key)) {
251
- case "integer":
252
- value = INTEGER.test(text) ? Number(text) : null;
253
- break;
254
- case "number":
255
- value = NUMBER.test(text) && Number.isFinite(Number(text)) ? Number(text) : null;
256
- break;
257
- case "boolean":
258
- value = text === "true" || text === "false" ? text === "true" : null;
259
- break;
260
- case "list": {
261
- const items = text.split(",");
262
- value = items.every(Boolean) ? items : null;
263
- break;
264
- }
265
- }
266
- if (value === null) return null;
267
- input[key] = value;
268
- }
269
- return input;
270
- }
271
-
272
11
  // src/schema-bundle.ts
273
12
  /**
274
13
  * Schema bundling: named schemas (`$id`) become shared components for an OpenAPI document, or are written
@@ -437,221 +176,221 @@ function local(node) {
437
176
  return replaceReferences(node, (reference) => reference.startsWith("#/components/schemas/") ? `#/$defs/${reference.slice(21)}` : reference);
438
177
  }
439
178
  /**
440
- * A self-contained schema for a reader with no components, such as an MCP tool listing: no `$id`
441
- * left, each named definition written where it is used, and the ones a `$ref` names bundled once
442
- * under `$defs`. JSON Schema validators refuse a schema that declares one `$id` twice.
179
+ * A self-contained schema for a reader with no components, such as an MCP tool listing: no `$id`
180
+ * left, each named definition written where it is used, and the ones a `$ref` names bundled once
181
+ * under `$defs`. JSON Schema validators refuse a schema that declares one `$id` twice.
182
+ */
183
+ function standaloneSchema(value) {
184
+ const { values, components } = bundleSchemas([inlineSchemaNames(value)], {});
185
+ if (!Object.keys(components).length) return values[0];
186
+ return {
187
+ ...local(values[0]),
188
+ $defs: local(components)
189
+ };
190
+ }
191
+
192
+ // src/internal/claims.ts
193
+ /**
194
+ * Reading a verified token's claims, which token verification and Cloudflare Access share.
195
+ */
196
+ /**
197
+ * A claim's own value under its name, else at a dotted path through object claims; undefined when absent.
198
+ * Only own properties are read, so no path reaches a prototype.
199
+ */
200
+ function claimAt(claims, path) {
201
+ if (Object.hasOwn(claims, path)) return claims[path];
202
+ let value = claims;
203
+ for (const key of path.split(".")) {
204
+ if (!isRecord(value) || !Object.hasOwn(value, key)) return;
205
+ value = value[key];
206
+ }
207
+ return value;
208
+ }
209
+
210
+ // src/principal.ts
211
+ /**
212
+ * Who calls: the principal every operation receives, and what a verified token grants before admission adds
213
+ * the request id. Token verification (`tokens.ts`) and Cloudflare Access (`cloudflare-access.ts`) both answer
214
+ * a `TokenPrincipal`, parsed strictly against these schemas.
215
+ */
216
+ /**
217
+ * Who calls, as every operation receives it: the actor, its kind, its verified organization and the request
218
+ * id.
219
+ */
220
+ const PrincipalSchema = Type.Object({
221
+ actorId: Type.String({
222
+ minLength: 1,
223
+ maxLength: 255
224
+ }),
225
+ actorKind: Type.Union([Type.Literal("user"), Type.Literal("service")]),
226
+ organizationId: OrganizationIdSchema,
227
+ requestId: UuidSchema
228
+ }, { additionalProperties: false });
229
+ /**
230
+ * The OAuth client a token was issued to: its id and its class, `human`, `machine` or `dcr` (a dynamically
231
+ * registered client).
232
+ */
233
+ const TokenClientSchema = Type.Object({
234
+ id: Type.String({
235
+ minLength: 1,
236
+ maxLength: 255
237
+ }),
238
+ class: Type.Union([
239
+ Type.Literal("human"),
240
+ Type.Literal("machine"),
241
+ Type.Literal("dcr")
242
+ ])
243
+ }, { additionalProperties: false });
244
+ /**
245
+ * What a verified token grants: the principal without a request id, its scopes and, for an OAuth token, its
246
+ * client. A custom `tokens.resolve` returns this shape.
247
+ */
248
+ const TokenPrincipalSchema = Type.Object({
249
+ ...Type.Omit(PrincipalSchema, ["requestId"]).properties,
250
+ scopes: Type.Array(Type.String({ maxLength: 255 }), { maxItems: 1e3 }),
251
+ /** Custom resolvers must classify DCR from verified application policy, never request headers. */
252
+ client: Type.Optional(TokenClientSchema)
253
+ }, { additionalProperties: false });
254
+
255
+ // src/cloudflare-access.ts
256
+ /**
257
+ * Cloudflare Access application tokens: where a request presents one, what it grants and what a token policy
258
+ * must state to admit it. Access signs people and service tokens in at Cloudflare's edge, and sets the
259
+ * application token in `Cf-Access-Jwt-Assertion` on each request it lets through. A Worker cannot take that
260
+ * header's presence as proof: a request reaches it around Access at its `workers.dev` and preview URLs, at a
261
+ * path Access does not cover, or through a Service Binding. So every token is verified, its signature, issuer
262
+ * and audience, and nothing else Access sets, such as `Cf-Access-Authenticated-User-Email` or the
263
+ * `CF_Authorization` cookie, is read.
264
+ */
265
+ /** The header Access sets the application token in: the only place a policy of its source reads one. */
266
+ const ACCESS_TOKEN_HEADER = "cf-access-jwt-assertion";
267
+ /** Whether a token policy admits Cloudflare Access application tokens, rather than bearer tokens. */
268
+ function usesCloudflareAccess(policy) {
269
+ return policy.source === "cloudflare-access";
270
+ }
271
+ /**
272
+ * The principal a verified Access application token grants under `policy.access`. A person, whose token
273
+ * names them in `sub` and carries no `common_name`, acts as `sub` (never as their email) through a `human`
274
+ * client, the application's audience, and holds `access.people`. A service token, whose token has an empty
275
+ * `sub` and its client id as `common_name`, acts as that client id through a `machine` client of the same
276
+ * id, and holds what `access.services` lists under it, else nothing. Each acts in `access.organizationId`, or
277
+ * in the organization the claim `claims.organization` holds. Anything else is refused as `UNAUTHORIZED`: a
278
+ * token whose `type` is not `app` (an Access organization token, for one), a token that is neither a person's
279
+ * nor a service token's, an organization missing or malformed or named by both, and a policy without `access`.
443
280
  */
444
- function standaloneSchema(value) {
445
- const { values, components } = bundleSchemas([inlineSchemaNames(value)], {});
446
- if (!Object.keys(components).length) return values[0];
447
- return {
448
- ...local(values[0]),
449
- $defs: local(components)
450
- };
451
- }
452
-
453
- // src/internal/openapi-components.ts
454
- /** A reference to the component schema `name`. */
455
- function schemaReference(name) {
456
- return { $ref: `#/components/schemas/${name}` };
457
- }
458
- /** A camelCase name or an uppercase code in PascalCase: `createNote` is `CreateNote`, `NOTE_NOT_FOUND` `NoteNotFound`. */
459
- function pascalCase(name) {
460
- return (/^[A-Z0-9_]+$/.test(name) ? name.toLowerCase().split("_") : [name]).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
461
- }
462
- /** The reason phrase of each HTTP status a failure may answer, in PascalCase, as RFC 9110 names it. */
463
- const REASONS = {
464
- 400: "BadRequest",
465
- 401: "Unauthorized",
466
- 402: "PaymentRequired",
467
- 403: "Forbidden",
468
- 404: "NotFound",
469
- 405: "MethodNotAllowed",
470
- 406: "NotAcceptable",
471
- 408: "RequestTimeout",
472
- 409: "Conflict",
473
- 410: "Gone",
474
- 411: "LengthRequired",
475
- 412: "PreconditionFailed",
476
- 413: "ContentTooLarge",
477
- 415: "UnsupportedMediaType",
478
- 422: "UnprocessableContent",
479
- 423: "Locked",
480
- 424: "FailedDependency",
481
- 425: "TooEarly",
482
- 428: "PreconditionRequired",
483
- 429: "TooManyRequests",
484
- 451: "UnavailableForLegalReasons",
485
- 500: "InternalServerError",
486
- 501: "NotImplemented",
487
- 502: "BadGateway",
488
- 503: "ServiceUnavailable",
489
- 504: "GatewayTimeout",
490
- 507: "InsufficientStorage"
491
- };
492
- /** A status's reason phrase in PascalCase: 400 is `BadRequest`, and a status without one `Status499`. */
493
- function statusReason(status) {
494
- return REASONS[status] ?? `Status${status}`;
495
- }
496
- /** A failure code without the `_ERROR` its name would repeat: `INTERNAL_ERROR` is `INTERNAL`. */
497
- function failureWords(code) {
498
- return pascalCase(code.replace(/_ERROR$/, ""));
499
- }
500
- /** The component of one failure: `NOTE_NOT_FOUND` is `NoteNotFoundFailure`. */
501
- function failureName(code) {
502
- return `${failureWords(code)}Failure`;
503
- }
504
- /** The envelope of one failure, the answer's whole body: `NOTE_NOT_FOUND` is `NoteNotFoundError`. */
505
- function failureEnvelopeName(code) {
506
- return `${failureWords(code)}Error`;
281
+ function projectAccessToken(claims, policy) {
282
+ const refused = err(standardErrors.unauthorized.create());
283
+ const { access } = policy;
284
+ if (access === void 0 || !isRecord(claims) || claims.type !== "app") return refused;
285
+ const audience = applicationAudience(claims.aud, policy.audience);
286
+ const caller = audience === void 0 ? null : accessCaller(claims, access, audience);
287
+ if (caller === null) return refused;
288
+ const principal = parseInput(TokenPrincipalSchema, {
289
+ ...caller,
290
+ organizationId: accessOrganization(claims, access, policy.claims?.organization)
291
+ });
292
+ return principal.ok ? ok(principal.value) : refused;
507
293
  }
508
294
  /**
509
- * The names a generator gives each operation's own types, which a component must not take: openapi-typescript
510
- * and Hey API write `CreateNoteData`, `CreateNoteResponse` and `CreateNoteError`, and the OpenAPI Generator
511
- * `CreateNoteRequest`.
295
+ * The application audience a token names: the first of the policy's audiences that its `aud`, a string or a
296
+ * list, carries; undefined when it carries none of them.
512
297
  */
513
- const GENERATED_SUFFIXES = [
514
- "Data",
515
- "Error",
516
- "Errors",
517
- "Response",
518
- "Responses",
519
- "Request"
520
- ];
521
- /** The component names a generator writes for an operation's own types: `createNote`'s `CreateNoteResponse`. */
522
- function generatedNames(operation) {
523
- const name = pascalCase(operation);
524
- return GENERATED_SUFFIXES.map((suffix) => `${name}${suffix}`);
298
+ function applicationAudience(named, audience) {
299
+ const carried = typeof named === "string" ? [named] : named;
300
+ if (!Array.isArray(carried)) return;
301
+ return (typeof audience === "string" ? [audience] : audience).find((candidate) => carried.includes(candidate));
525
302
  }
526
- /** The component schemas of a document, each name given to one schema only. */
527
- var ComponentSchemas = class {
528
- /** The schemas by name, in the order they were added. */
529
- schemas = {};
530
- /** Whether another schema than this one already has the name. */
531
- holdsOther(name, schema) {
532
- const existing = this.schemas[name];
533
- return existing !== void 0 && canonical(existing) !== canonical(schema);
534
- }
535
- /**
536
- * Names a schema and answers a reference to it. The same schema under a name it already has is the same
537
- * component; another schema under a taken name throws, since a reference would then name two shapes.
538
- */
539
- add(name, schema) {
540
- if (this.holdsOther(name, schema)) throw new TypeError(`Two different schemas claim the OpenAPI component ${name}.`);
541
- this.schemas[name] = schema;
542
- return schemaReference(name);
543
- }
544
- };
545
- /** The JSON a field holds when the answer carries none: success has no error, a failure no data. */
546
- const NONE = { const: null };
547
- /** The metadata every answer carries, as the component `ResponseMetadata`. */
548
- const RESPONSE_METADATA = {
549
- type: "object",
550
- description: "What every answer carries besides its data or error.",
551
- additionalProperties: false,
552
- required: ["requestId"],
553
- properties: { requestId: {
554
- type: "string",
555
- description: "Request correlation identifier, also sent as X-Request-Id."
556
- } }
557
- };
558
- /** The empty object, as the component `Empty`: the data of an answer, or of a failure, that carries none. */
559
- const EMPTY_OBJECT = {
560
- type: "object",
561
- description: "No fields.",
562
- additionalProperties: false,
563
- properties: {}
564
- };
565
- /** The envelope of a successful answer: `success` is true, `data` the operation's output and `error` null. */
566
- function successEnvelope(data) {
567
- return {
568
- type: "object",
569
- description: "A successful answer.",
570
- additionalProperties: false,
571
- required: [
572
- "success",
573
- "data",
574
- "error",
575
- "metadata"
576
- ],
577
- properties: {
578
- success: {
579
- type: "boolean",
580
- enum: [true]
581
- },
582
- data,
583
- error: NONE,
584
- metadata: schemaReference("ResponseMetadata")
303
+ /**
304
+ * Who a token names: a person by a non-empty `sub` without `common_name`, or a service token by its
305
+ * `common_name` with an empty `sub`; null for a token of any other shape, such as one that carries both.
306
+ */
307
+ function accessCaller(claims, access, audience) {
308
+ const { sub: subject, common_name: commonName } = claims;
309
+ if (typeof subject === "string" && subject !== "" && commonName === void 0) return {
310
+ actorId: subject,
311
+ actorKind: "user",
312
+ scopes: [...access.people],
313
+ client: {
314
+ id: audience,
315
+ class: "human"
585
316
  }
586
317
  };
587
- }
588
- /** The envelope of a failed answer: `success` is false, `data` null and `error` the failure. */
589
- function failureEnvelope(error) {
590
- return {
591
- type: "object",
592
- description: "A failed answer.",
593
- additionalProperties: false,
594
- required: [
595
- "success",
596
- "data",
597
- "error",
598
- "metadata"
599
- ],
600
- properties: {
601
- success: {
602
- type: "boolean",
603
- enum: [false]
604
- },
605
- data: NONE,
606
- error,
607
- metadata: schemaReference("ResponseMetadata")
318
+ if (subject === "" && typeof commonName === "string" && commonName !== "") return {
319
+ actorId: commonName,
320
+ actorKind: "service",
321
+ scopes: serviceScopes(access, commonName),
322
+ client: {
323
+ id: commonName,
324
+ class: "machine"
608
325
  }
609
326
  };
327
+ return null;
610
328
  }
611
329
  /**
612
- * One failure as the component its code names: its code a one-value enum, which every generator reads as
613
- * the literal, its retryability fixed and its data the schema its definition declares. Its message is a
614
- * plain string: clients branch on the code, never on the text.
330
+ * The scopes `access.services` lists for a service token's client id, none when it lists none. Only its own
331
+ * entries are read, so no client id reaches a prototype's property.
615
332
  */
616
- function failureSchema(definition, data) {
617
- return {
618
- type: "object",
619
- description: definition.message,
620
- additionalProperties: false,
621
- required: [
622
- "code",
623
- "message",
624
- "retryable",
625
- "data"
626
- ],
627
- properties: {
628
- code: {
629
- type: "string",
630
- enum: [definition.code],
631
- description: "The failure code, stable across releases."
632
- },
633
- message: {
634
- type: "string",
635
- description: "What went wrong, for people; it never contains input values."
636
- },
637
- retryable: {
638
- type: "boolean",
639
- enum: [definition.retryable ?? false],
640
- description: "Whether repeating the same request may succeed."
641
- },
642
- data
643
- }
644
- };
333
+ function serviceScopes(access, clientId) {
334
+ const { services = {} } = access;
335
+ return [...(Object.hasOwn(services, clientId) ? services[clientId] : void 0) ?? []];
645
336
  }
646
- /** Several failures as one component, told apart by their `code`, as generators that read a discriminator expect. */
647
- function failureUnion(codes) {
648
- return {
649
- oneOf: codes.map((code) => schemaReference(failureName(code))),
650
- discriminator: {
651
- propertyName: "code",
652
- mapping: Object.fromEntries(codes.map((code) => [code, schemaReference(failureName(code)).$ref]))
653
- }
654
- };
337
+ /**
338
+ * The organization an Access caller acts in: `access.organizationId`, or the value of the claim `claim`
339
+ * names, such as `custom.org_id` for a custom OIDC claim Access passes on. Undefined, and so refused, unless
340
+ * exactly one of them is set.
341
+ */
342
+ function accessOrganization(claims, access, claim) {
343
+ if (claim === void 0) return access.organizationId;
344
+ return access.organizationId === void 0 ? claimAt(claims, claim) : void 0;
345
+ }
346
+ /** The options of a token policy that only OAuth access tokens use, which Access application tokens are not. */
347
+ const OAUTH_OPTIONS = [
348
+ "scheme",
349
+ "resources",
350
+ "resourceMetadataUrl",
351
+ "authorizationEndpoint",
352
+ "tokenEndpoint"
353
+ ];
354
+ /** The most scopes a principal holds, as `TokenPrincipalSchema` admits them. */
355
+ const MAX_SCOPES = 1e3;
356
+ /**
357
+ * Refuses, at construction, a policy of the `cloudflare-access` source that could never admit a caller, or
358
+ * that states what Access application tokens never carry: neither `access` nor `resolve`; any option only
359
+ * OAuth uses (`scheme`, `resources`, `resourceMetadataUrl` and the endpoints OpenAPI would publish); claims
360
+ * other than the organization; and, with `access`, an organization named twice, not at all or malformed, or
361
+ * scopes outside the application's namespace, more than 1000 of them, or listed under an empty client id.
362
+ */
363
+ function checkAccessPolicy(policy, namespace) {
364
+ const { access, claims } = policy;
365
+ if (access === void 0 && policy.resolve === void 0) throw new TypeError("tokens.source cloudflare-access requires tokens.access, or tokens.resolve to verify Access tokens itself.");
366
+ const oauth = OAUTH_OPTIONS.filter((option) => policy[option] !== void 0);
367
+ if (oauth.length) throw new TypeError(`Cloudflare Access application tokens are not OAuth access tokens: remove ${oauth.map((option) => `tokens.${option}`).join(", ")}.`);
368
+ if (claims !== void 0 && Object.entries(claims).some(([name, value]) => name !== "organization" && value !== void 0)) throw new TypeError("Under Cloudflare Access, tokens.claims names the organization alone: tokens.access grants the scopes.");
369
+ if (access === void 0) return;
370
+ const { organizationId } = access;
371
+ const claim = claims?.organization;
372
+ if (!(claim === void 0 ? parseInput(OrganizationIdSchema, organizationId).ok : organizationId === void 0 && typeof claim === "string" && claim !== "")) throw new TypeError("Under Cloudflare Access, name a valid organization once: tokens.access.organizationId or tokens.claims.organization.");
373
+ /** Whether a list holds scopes of the application, at most as many and as long as a principal's. */
374
+ const ownScopes = (scopes) => Array.isArray(scopes) && scopes.length <= MAX_SCOPES && scopes.every((scope) => typeof scope === "string" && scope.length <= 255 && isNamespacedScope(scope, namespace));
375
+ const services = access.services ?? {};
376
+ if (!ownScopes(access.people) || !isRecord(services) || Object.entries(services).some(([clientId, scopes]) => !clientId || clientId.length > 255 || !ownScopes(scopes))) throw new TypeError(`tokens.access grants scopes of ${namespace}:<resource>:<action>, at most ${MAX_SCOPES} to people and to each service token, by its client id.`);
377
+ }
378
+ /** The methods that change nothing: another site's page may send them without consequence. */
379
+ const SAFE_METHODS = /* @__PURE__ */ new Set([
380
+ "GET",
381
+ "HEAD",
382
+ "OPTIONS"
383
+ ]);
384
+ /**
385
+ * Whether a browser sent a write for another site's page: a method other than `GET`, `HEAD` and `OPTIONS`
386
+ * with `Sec-Fetch-Site: cross-site`, or with an `Origin` other than the request's own. A person's Access
387
+ * session travels in a cookie, which the browser attaches to such a request, and Access forwards it with
388
+ * the person's application token. A request with neither header, such as a service token's, is no browser's.
389
+ */
390
+ function isCrossSiteWrite(request) {
391
+ if (SAFE_METHODS.has(request.method)) return false;
392
+ const origin = request.headers.get("origin");
393
+ return request.headers.get("sec-fetch-site") === "cross-site" || origin !== null && origin !== new URL(request.url).origin;
655
394
  }
656
395
 
657
396
  // src/tokens.ts
@@ -962,529 +701,4 @@ function createTokenAuthorization(policy, given) {
962
701
  };
963
702
  }
964
703
 
965
- // src/openapi.ts
966
- /**
967
- * An application's OpenAPI 3.1 document, as its origin serves it and as SDK generators read it: one tag per
968
- * group of routes, and every request body, success envelope and failure a named component, so a generated
969
- * client reads `createNote(body: CreateNoteBody): NoteResponse`. The `x-*` extensions carry what OpenAPI
970
- * cannot say: scopes, effects, limits, MCP tools and native RPC.
971
- */
972
- /** The standard failures only routing answers, before a request reaches any operation's route. */
973
- const ROUTING_CODES = /* @__PURE__ */ new Set(["NOT_FOUND", "HTTP_METHOD_NOT_ALLOWED"]);
974
- /** The headers every answer, and a failure that asks for a wait, carry, as the document's components. */
975
- const HEADERS = {
976
- RequestId: {
977
- description: "Request correlation identifier.",
978
- schema: { type: "string" }
979
- },
980
- RetryAfter: {
981
- description: "Seconds before another attempt.",
982
- schema: {
983
- type: "integer",
984
- minimum: 0
985
- }
986
- }
987
- };
988
- /** A reference to one of `HEADERS`. */
989
- function headerReference(name) {
990
- return { $ref: `#/components/headers/${name}` };
991
- }
992
- /** Whether an object schema holds no field at all, so that `{}` is its one value. */
993
- function isEmptyObject(schema) {
994
- return schema.type === "object" && Object.keys(schema.properties ?? {}).length === 0 && schema.patternProperties === void 0 && schema.additionalProperties === false;
995
- }
996
- /**
997
- * A request body without the fields its path carries, in each member of a union. An object that loses
998
- * fields is no longer the schema its `$id` names, so it loses the name, and its property counts lose the
999
- * path's fields.
1000
- */
1001
- function bodyWithoutPathParameters(input, names) {
1002
- if (input.type !== "object") {
1003
- const { $id: _id, ...union } = input;
1004
- return {
1005
- ...union,
1006
- anyOf: (input.anyOf ?? []).map((schema) => bodyWithoutPathParameters(schema, names))
1007
- };
1008
- }
1009
- const carried = Object.keys(input.properties ?? {}).filter((name) => names.has(name)).length;
1010
- if (!carried) return input;
1011
- const { $id: _id, minProperties, maxProperties, ...object } = input;
1012
- return {
1013
- ...object,
1014
- properties: Object.fromEntries(Object.entries(input.properties ?? {}).filter(([name]) => !names.has(name))),
1015
- required: (input.required ?? []).filter((name) => !names.has(name)),
1016
- ...typeof minProperties === "number" && minProperties > carried ? { minProperties: minProperties - carried } : {},
1017
- ...typeof maxProperties === "number" ? { maxProperties: maxProperties - carried } : {}
1018
- };
1019
- }
1020
- /**
1021
- * The document the origin serves at `/openapi.json`: every public operation that declares an HTTP route,
1022
- * never an internal one, under one tag per group. Each request body, success envelope and failure is a named
1023
- * component, which a generated client names its types after; each operation also carries its scopes,
1024
- * effect, limits in force, MCP tool hints and native RPC as `x-*` extensions.
1025
- *
1026
- * Every schema reference in it is a local `#/components/schemas/<name>` pointer: the `$id`-named
1027
- * schemas of its paths and components (TypeBox Cyclic/Ref) become components, as `bundleSchemas`
1028
- * describes. A schema `$id` that takes the name of a component the document writes itself, and a component
1029
- * named as a generator names an operation's own types, such as `CreateNoteResponse`, throw a TypeError.
1030
- */
1031
- function createOpenApi(manifest, options) {
1032
- const document = openApiDocument(manifest, "http");
1033
- if (options?.operationExtensions) {
1034
- const paths = document.paths;
1035
- for (const methods of Object.values(paths)) for (const declared of Object.values(methods)) {
1036
- const name = String(declared.operationId);
1037
- const operation = manifest.operations[name];
1038
- if (!operation) throw new TypeError("The document names an undeclared operation.");
1039
- const extensions = options.operationExtensions(name, operation);
1040
- if (Object.keys(extensions).some((key) => !key.startsWith("x-"))) throw new TypeError("OpenAPI extensions must use x- names.");
1041
- Object.assign(declared, extensions);
1042
- }
1043
- }
1044
- return bundledDocument(document, manifest);
1045
- }
1046
- /**
1047
- * The document of the operations an application serves over native RPC, which another service binds to:
1048
- * each operation that declares `rpc`, internal ones and tools included, as `POST /rpc/<name>` whose body is
1049
- * the operation's whole input, with its answer and failures named as in the HTTP document. No HTTP route
1050
- * answers these paths: each names a method of the Worker's `Service` entrypoint, which a Service Binding
1051
- * calls with the caller's principal. `maximus openapi` writes it to `rpc.openapi.json`, and a caller's
1052
- * `services` option types its binding from it.
1053
- */
1054
- function createRpcOpenApi(manifest) {
1055
- return bundledDocument(openApiDocument(manifest, "rpc"), manifest);
1056
- }
1057
- /**
1058
- * A document with its `$id`-named schemas bundled into components, every component in name order, after the
1059
- * names it publishes are checked.
1060
- */
1061
- function bundledDocument(document, manifest) {
1062
- const own = Object.entries(document.components.schemas);
1063
- const sources = [document.paths, ...own.map(([, schema]) => schema)];
1064
- checkComponentNames(own.map(([name]) => name), schemaIds(sources), Object.keys(manifest.operations));
1065
- const bundled = bundleSchemas(sources, document.components.schemas);
1066
- const [paths, ...schemas] = bundled.values;
1067
- const named = {
1068
- ...Object.fromEntries(own.map(([name], index) => [name, schemas[index]])),
1069
- ...bundled.components
1070
- };
1071
- return {
1072
- ...document,
1073
- paths,
1074
- components: {
1075
- ...document.components,
1076
- schemas: Object.fromEntries(Object.entries(named).toSorted(([a], [b]) => a < b ? -1 : Number(a > b)))
1077
- }
1078
- };
1079
- }
1080
- /**
1081
- * Refuses the names a document cannot publish: a schema `$id` that takes the name of a component the document
1082
- * writes itself, which bundling would otherwise rename, and a component a generator would name an operation's
1083
- * own types after (`CreateNoteResponse` for `createNote`).
1084
- */
1085
- function checkComponentNames(own, ids, operations) {
1086
- const taken = new Set(own);
1087
- for (const id of ids) if (taken.has(id)) throw new TypeError(`The schema $id "${id}" is the name of a component the OpenAPI document writes for its bodies, answers or failures; rename the schema.`);
1088
- const generated = new Map(operations.flatMap((operation) => generatedNames(operation).map((name) => [name, operation])));
1089
- for (const name of [...own, ...ids]) {
1090
- const operation = generated.get(name);
1091
- if (operation) throw new TypeError(`The OpenAPI component ${name} takes the name a generated client gives operation "${operation}"'s own types; rename the schema or the operation.`);
1092
- }
1093
- }
1094
- /**
1095
- * The operations a document lists: for the HTTP document, each public operation that declares a route, at that
1096
- * route; for the RPC document, each operation that declares `rpc`, at `POST /rpc/<name>`. Each keeps the group
1097
- * its route gives it.
1098
- */
1099
- function documentedOperations(manifest, kind) {
1100
- return Object.entries(manifest.operations).flatMap(([name, op]) => {
1101
- const group = op.group ?? (op.http ? routeGroup(op.http.path) : void 0) ?? manifest.title;
1102
- if (kind === "rpc") return op.rpc ? [{
1103
- name,
1104
- op,
1105
- http: {
1106
- method: "POST",
1107
- path: `/rpc/${name}`
1108
- },
1109
- group
1110
- }] : [];
1111
- return op.http && isPublicOperation(op) ? [{
1112
- name,
1113
- op,
1114
- http: op.http,
1115
- group
1116
- }] : [];
1117
- });
1118
- }
1119
- /**
1120
- * Refuses a description of a group no document lists: each name `groups` describes must be the group of a
1121
- * public route or of an operation served over native RPC.
1122
- */
1123
- function checkDescribedGroups(manifest) {
1124
- const described = Object.keys(manifest.groups ?? {});
1125
- if (!described.length) return;
1126
- const listed = new Set([...documentedOperations(manifest, "http"), ...documentedOperations(manifest, "rpc")].map(({ group }) => group));
1127
- for (const group of described) if (!listed.has(group)) throw new TypeError(`groups describes "${group}", which no public route or RPC method has as its group; the groups are ${[...listed].join(", ") || "none"}.`);
1128
- }
1129
- /** What an RPC document says about itself, in place of servers its paths do not have. */
1130
- function rpcDescription(title) {
1131
- return `The operations ${title} serves over native RPC, to the Workers its rpc.callers name, through a Service Binding to its Service entrypoint. No HTTP route answers these paths: each names a method, called with the caller's principal and the operation's whole input.`;
1132
- }
1133
- /** The document `createOpenApi` or `createRpcOpenApi` builds, before its `$id`-named schemas are bundled. */
1134
- function openApiDocument(manifest, kind) {
1135
- const entries = documentedOperations(manifest, kind);
1136
- const rpc = kind === "rpc";
1137
- const scopes = Object.fromEntries(entries.flatMap(({ op }) => [...operationScopes(op), ...op.conditionalScopes ?? []].map((scope) => [scope, scopeDescription(scope)])));
1138
- const components = new ComponentSchemas();
1139
- if (entries.length) components.add("ResponseMetadata", RESPONSE_METADATA);
1140
- const headers = new Set(entries.length ? ["RequestId"] : []);
1141
- const groups = [];
1142
- const paths = {};
1143
- for (const { name, op, http, group } of entries) {
1144
- if (!groups.includes(group)) groups.push(group);
1145
- const request = rpc ? rpcRequest(name, op, components) : requestContract(name, op, http, components);
1146
- const failures = failureResponses(name, op, !rpc && "requestBody" in request, manifest.errors.definitions, components);
1147
- if (Object.values(failures).some((response) => "Retry-After" in response.headers)) headers.add("RetryAfter");
1148
- (paths[http.path] ??= {})[http.method.toLowerCase()] = {
1149
- operationId: name,
1150
- summary: op.title,
1151
- ...op.description ? { description: op.description } : {},
1152
- tags: [group],
1153
- ...rpc ? rpcExtensions(manifest, op) : httpExtensions(manifest, op, http),
1154
- ...request,
1155
- responses: {
1156
- [http.successStatus ?? 200]: successResponse(name, op, http, components),
1157
- ...failures
1158
- }
1159
- };
1160
- }
1161
- checkDescribedGroups(manifest);
1162
- return JSON.parse(JSON.stringify({
1163
- openapi: "3.1.0",
1164
- info: {
1165
- title: manifest.title,
1166
- version: manifest.version,
1167
- ...rpc ? { description: rpcDescription(manifest.title) } : {},
1168
- ...!rpc && manifest.description ? { description: manifest.description } : {}
1169
- },
1170
- ...rpc ? {} : { servers: [{ url: manifest.origin }] },
1171
- tags: groups.map((group) => {
1172
- const description = manifest.groups?.[group] ?? (group === "Operation tasks" ? "The tasks of operations that answer before they finish: read one you started, or cancel one that has not started running." : void 0);
1173
- return description ? {
1174
- name: group,
1175
- description
1176
- } : { name: group };
1177
- }),
1178
- paths,
1179
- components: {
1180
- schemas: components.schemas,
1181
- ...headers.size ? { headers: Object.fromEntries([...headers].map((name) => [name, HEADERS[name]])) } : {},
1182
- ...rpc || !entries.length ? {} : { securitySchemes: securitySchemes(manifest.tokens, scopes) }
1183
- }
1184
- }));
1185
- }
1186
- /**
1187
- * What an HTTP operation adds beside OpenAPI's own fields: the requirements that admit it, its scopes,
1188
- * effect, MCP tool, native RPC and limits, and how its body and answer travel.
1189
- */
1190
- function httpExtensions(manifest, op, http) {
1191
- return {
1192
- security: operationSecurity(op, manifest.tokens),
1193
- "x-required-scopes": [...operationScopes(op)],
1194
- ...operationScopes(op).length > 1 ? { "x-scope-match": op.scopeMatch ?? "any" } : {},
1195
- ...op.conditionalScopes ? { "x-conditional-scopes": op.conditionalScopes } : {},
1196
- "x-effect": op.effect,
1197
- ...op.mcp ? {
1198
- "x-mcp-tool": op.mcp.name,
1199
- "x-mcp-idempotent": op.mcp.idempotent,
1200
- "x-mcp-open-world": mcpOpenWorld(op.mcp)
1201
- } : {},
1202
- "x-native-rpc": Boolean(op.rpc),
1203
- "x-max-body-bytes": operationBodyLimit(manifest, op),
1204
- "x-max-output-bytes": operationOutputLimit(manifest, op),
1205
- ...http.body ? {
1206
- "x-body": http.body,
1207
- "x-input-headers": http.headers ?? {}
1208
- } : {},
1209
- ...http.response ? { "x-response": http.response } : {}
1210
- };
1211
- }
1212
- /**
1213
- * What a native RPC operation adds beside OpenAPI's own fields: its effect, the callers that may call it,
1214
- * and the output limit in force. A Service Binding names its caller, so it has no security requirement.
1215
- */
1216
- function rpcExtensions(manifest, op) {
1217
- return {
1218
- "x-effect": op.effect,
1219
- "x-native-rpc": true,
1220
- "x-rpc-callers": op.rpc === true ? [...manifest.rpc.callers] : [...op.rpc?.callers ?? []],
1221
- "x-max-output-bytes": operationOutputLimit(manifest, op)
1222
- };
1223
- }
1224
- /** A scope as people read it: `notes:notes:read` reads notes, `notes:task-lists:write` writes task lists. */
1225
- function scopeDescription(scope) {
1226
- const [namespace, resource, action, ...deeper] = scope.split(":");
1227
- if (namespace === void 0 || resource === void 0 || deeper.length) return scope;
1228
- const words = resource.replaceAll("-", " ");
1229
- if (action === "read") return `Read ${words}.`;
1230
- if (action === "write") return `Create, change and delete ${words}.`;
1231
- return scope;
1232
- }
1233
- /** Whether a body schema requires a field, so no empty body is valid: a union does when each member does. */
1234
- function requiresField(schema) {
1235
- const node = schema;
1236
- return node.anyOf ? node.anyOf.every(requiresField) : (node.required ?? []).length > 0;
1237
- }
1238
- /**
1239
- * A parameter, described on the parameter itself, where generators read it: by its schema's description, or
1240
- * else by its name in words (`noteId` is `The note id.`).
1241
- */
1242
- function parameter(name, location, required, schema, style = {}) {
1243
- const words = name.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2").replaceAll(/[_-]+/g, " ").toLowerCase();
1244
- return {
1245
- name,
1246
- in: location,
1247
- required,
1248
- description: typeof schema.description === "string" ? schema.description : `The ${words}.`,
1249
- ...style,
1250
- schema
1251
- };
1252
- }
1253
- /**
1254
- * Where an operation's input travels: its path parameters, then a byte body's query and header
1255
- * metadata, a GET's query, or a JSON body without the fields the path carries. A DELETE whose input the
1256
- * path carries whole sends no body.
1257
- */
1258
- function requestContract(name, op, http, components) {
1259
- const input = wireInput(op.input);
1260
- const parameterNames = operationPathParameters(http.path);
1261
- const pathNames = new Set(parameterNames);
1262
- const pathParameters = parameterNames.map((pathName) => {
1263
- const schemas = pathParameterSchemas(input, pathName);
1264
- return parameter(pathName, "path", true, schemas.length === 1 && schemas[0] ? schemas[0] : Type.Union(schemas));
1265
- });
1266
- const properties = input.properties ?? {};
1267
- const required = input.required ?? [];
1268
- const fields = Object.entries(properties).filter(([field]) => !pathNames.has(field));
1269
- if (http.body === "bytes") return {
1270
- parameters: [...pathParameters, ...fields.map(([field, schema]) => {
1271
- const header = http.headers && Object.hasOwn(http.headers, field) ? http.headers[field] : void 0;
1272
- return {
1273
- ...parameter(header ?? field, header ? "header" : "query", required.includes(field), schema),
1274
- "x-input-field": field
1275
- };
1276
- })],
1277
- requestBody: {
1278
- required: true,
1279
- content: { "application/octet-stream": { schema: {
1280
- type: "string",
1281
- format: "binary"
1282
- } } }
1283
- }
1284
- };
1285
- if (http.method === "GET") {
1286
- const kinds = queryKinds(op);
1287
- return { parameters: [...pathParameters, ...fields.map(([field, schema]) => parameter(field, "query", required.includes(field), schema, kinds.get(field) === "list" ? {
1288
- style: "form",
1289
- explode: false
1290
- } : {}))] };
1291
- }
1292
- const body = pathNames.size ? bodyWithoutPathParameters(input, pathNames) : input;
1293
- const located = pathParameters.length ? { parameters: pathParameters } : {};
1294
- if (http.method === "DELETE" && isEmptyObject(body)) return located;
1295
- return {
1296
- ...located,
1297
- requestBody: {
1298
- required: http.method !== "DELETE" || requiresField(body),
1299
- content: { "application/json": { schema: bodySchema(name, body, components) } }
1300
- }
1301
- };
1302
- }
1303
- /**
1304
- * The schema of a JSON request body: `Empty` for one without fields, which still travels as `{}`; the
1305
- * input's own when it is named and the path carries none of it; else the component `<Operation>Body`, or
1306
- * `<Operation>Input` for a native RPC method's whole input.
1307
- */
1308
- function bodySchema(name, body, components, suffix = "Body") {
1309
- if (isEmptyObject(body)) return components.add("Empty", EMPTY_OBJECT);
1310
- if (typeof body.$id === "string") return body;
1311
- return components.add(`${pascalCase(name)}${suffix}`, body);
1312
- }
1313
- /** A native RPC method's request: its whole input, as callers send it, which the method takes as one object. */
1314
- function rpcRequest(name, op, components) {
1315
- return { requestBody: {
1316
- required: true,
1317
- content: { "application/json": { schema: bodySchema(name, wireInput(op.input), components, "Input") } }
1318
- } };
1319
- }
1320
- /** The success response: the JSON envelope, or a validated attachment's bytes and headers. */
1321
- function successResponse(name, op, http, components) {
1322
- const headers = { "X-Request-Id": headerReference("RequestId") };
1323
- if (http.response !== "attachment") return {
1324
- description: "Successful operation.",
1325
- headers,
1326
- content: { "application/json": { schema: successSchema(name, op.output, components) } }
1327
- };
1328
- return {
1329
- description: "Successful operation.",
1330
- content: { "application/octet-stream": { schema: {
1331
- type: "string",
1332
- format: "binary"
1333
- } } },
1334
- headers: {
1335
- ...headers,
1336
- "Content-Type": {
1337
- schema: { type: "string" },
1338
- description: "Validated attachment media type."
1339
- },
1340
- "Content-Length": {
1341
- schema: {
1342
- type: "integer",
1343
- minimum: 0
1344
- },
1345
- description: "Exact attachment byte length."
1346
- },
1347
- "Content-Disposition": {
1348
- schema: { type: "string" },
1349
- description: "Attachment filename in ASCII and RFC 5987 UTF-8 forms."
1350
- }
1351
- }
1352
- };
1353
- }
1354
- /**
1355
- * The component of a successful answer: named after its output's `$id` (`NoteResponse`, which every
1356
- * operation that answers a note shares), `EmptyResponse` for an output without fields, and otherwise after
1357
- * the operation, with its output as `<Operation>Result`.
1358
- */
1359
- function successSchema(name, output, components) {
1360
- if (isEmptyObject(output)) return components.add("EmptyResponse", successEnvelope(components.add("Empty", EMPTY_OBJECT)));
1361
- const operation = pascalCase(name);
1362
- if (typeof output.$id === "string") {
1363
- const envelope = successEnvelope(output);
1364
- const named = `${output.$id}Response`;
1365
- return components.add(components.holdsOther(named, envelope) ? `${operation}ResultResponse` : named, envelope);
1366
- }
1367
- return components.add(`${operation}ResultResponse`, successEnvelope(components.add(`${operation}Result`, output)));
1368
- }
1369
- /**
1370
- * The failures an operation documents, one response per status, in catalog order: the standard failures
1371
- * its route can meet, never routing's (an unknown path or method) and, when it sends no body, never a
1372
- * body's; then the domain failures it declares, or every one when it declares none.
1373
- */
1374
- function failureResponses(name, op, sendsBody, definitions, components) {
1375
- const statuses = /* @__PURE__ */ new Map();
1376
- for (const definition of Object.values(definitions)) if (documentsFailure(op, sendsBody, definition.code)) statuses.set(definition.status, [...statuses.get(definition.status) ?? [], definition]);
1377
- return Object.fromEntries([...statuses].map(([status, failures]) => [status, failureResponse(name, status, failures, components)]));
1378
- }
1379
- /** Whether an operation's document lists a failure, as `failureResponses` describes. */
1380
- function documentsFailure(op, sendsBody, code) {
1381
- if (ROUTING_CODES.has(code)) return false;
1382
- if (BODY_CODES.has(code)) return sendsBody;
1383
- return STANDARD_CODES.has(code) || !op.failures || op.failures.includes(code);
1384
- }
1385
- /**
1386
- * One status an operation documents: each failure as its component, and the envelope of the answer, named
1387
- * after its code when it is the status's only one (`NoteNotFoundError`), else after the operation and the
1388
- * status (`ListNotesBadRequestError`), whose failures a discriminator on `code` tells apart.
1389
- */
1390
- function failureResponse(name, status, failures, components) {
1391
- for (const failure of failures) addFailure(failure, components);
1392
- const codes = failures.map(({ code }) => code);
1393
- const [only] = codes;
1394
- const statusName = `${pascalCase(name)}${statusReason(status)}`;
1395
- const envelope = codes.length === 1 && only !== void 0 ? components.add(failureEnvelopeName(only), failureEnvelope(schemaReference(failureName(only)))) : components.add(`${statusName}Error`, failureEnvelope(components.add(`${statusName}Failure`, failureUnion(codes))));
1396
- const lines = failures.map((failure) => `\`${failure.code}\`: ${failure.message}`);
1397
- return {
1398
- description: lines.length === 1 && lines[0] !== void 0 ? lines[0] : lines.map((line) => `- ${line}`).join("\n"),
1399
- headers: {
1400
- "X-Request-Id": headerReference("RequestId"),
1401
- ...status === 429 || failures.some((failure) => failure.retryAfter) ? { "Retry-After": headerReference("RetryAfter") } : {}
1402
- },
1403
- "x-failure-codes": codes,
1404
- content: { "application/json": { schema: envelope } }
1405
- };
1406
- }
1407
- /** A failure as its component, `<Code>Failure`, with its data: the schema its definition declares, else `Empty`. */
1408
- function addFailure(definition, components) {
1409
- const dataSchema = definition.dataSchema;
1410
- let data;
1411
- if (dataSchema === void 0 || isEmptyObject(dataSchema)) data = components.add("Empty", EMPTY_OBJECT);
1412
- else if (typeof dataSchema.$id === "string") data = dataSchema;
1413
- else data = components.add(`${failureName(definition.code)}Data`, dataSchema);
1414
- components.add(failureName(definition.code), failureSchema(definition, data));
1415
- }
1416
- /**
1417
- * The security requirements that admit an operation, any one of which is enough: its scopes as
1418
- * OAuth requirements (all of them in one requirement when it needs all), or the application's own
1419
- * bearer tokens. With both schemes, users present OAuth tokens and services the application's own.
1420
- * Behind Cloudflare Access, a client presents a service token's two headers together.
1421
- */
1422
- function operationSecurity(op, tokens) {
1423
- if (usesCloudflareAccess(tokens)) return [{
1424
- accessClientId: [],
1425
- accessClientSecret: []
1426
- }];
1427
- let security;
1428
- if (tokens.scheme?.type === "bearer") security = [{ bearer: [] }];
1429
- else if (op.scopeMatch === "all") security = [{ oauth2: [...operationScopes(op)] }];
1430
- else security = operationScopes(op).map((scope) => ({ oauth2: [scope] }));
1431
- if (tokens.scheme?.type === "oauth+bearer") {
1432
- const actors = op.actorKinds ?? [];
1433
- if (!actors.includes("user")) security = [];
1434
- if (actors.includes("service")) security.push({ bearer: [] });
1435
- }
1436
- return security;
1437
- }
1438
- /**
1439
- * How callers obtain a token: the OAuth 2.0 flows of the issuer (authorization code, and client
1440
- * credentials unless services use the application's own tokens), the application's own bearer
1441
- * tokens, or both. Behind Cloudflare Access, the headers of an Access service token, which Access
1442
- * exchanges at the edge for the application token the API verifies; people sign in to Access in a
1443
- * browser, which no scheme describes.
1444
- */
1445
- function securitySchemes(tokens, scopes) {
1446
- if (usesCloudflareAccess(tokens)) return {
1447
- accessClientId: {
1448
- type: "apiKey",
1449
- in: "header",
1450
- name: "CF-Access-Client-Id",
1451
- description: "The Client ID of a Cloudflare Access service token, sent with its Client Secret."
1452
- },
1453
- accessClientSecret: {
1454
- type: "apiKey",
1455
- in: "header",
1456
- name: "CF-Access-Client-Secret",
1457
- description: "The Client Secret of the Cloudflare Access service token whose Client ID is sent."
1458
- }
1459
- };
1460
- const { scheme } = tokens;
1461
- if (scheme?.type === "bearer") return { bearer: {
1462
- type: "http",
1463
- scheme: "bearer",
1464
- description: scheme.description
1465
- } };
1466
- const { authorization, token: tokenUrl } = tokenEndpoints(tokens);
1467
- return {
1468
- oauth2: {
1469
- type: "oauth2",
1470
- flows: {
1471
- authorizationCode: {
1472
- authorizationUrl: authorization,
1473
- tokenUrl,
1474
- scopes
1475
- },
1476
- ...scheme?.type === "oauth+bearer" ? {} : { clientCredentials: {
1477
- tokenUrl,
1478
- scopes
1479
- } }
1480
- }
1481
- },
1482
- ...scheme?.type === "oauth+bearer" ? { bearer: {
1483
- type: "http",
1484
- scheme: "bearer",
1485
- description: scheme.description
1486
- } } : {}
1487
- };
1488
- }
1489
-
1490
- export { projectAccessToken as _, createTokenVerifier as a, tokenAudiences as c, canonical as d, hasSchemaReferences as f, isCrossSiteWrite as g, queryKinds as h, createTokenAuthorization as i, tokenIssuer as l, queryInput as m, createRpcOpenApi as n, presentedToken as o, standaloneSchema as p, checkTokenAuthority as r, projectToken as s, createOpenApi as t, usesOwnBearer as u, usesCloudflareAccess as v, PrincipalSchema as y };
704
+ export { schemaIds as _, projectToken as a, tokenIssuer as c, projectAccessToken as d, usesCloudflareAccess as f, hasSchemaReferences as g, canonical as h, presentedToken as i, usesOwnBearer as l, bundleSchemas as m, createTokenAuthorization as n, tokenAudiences as o, PrincipalSchema as p, createTokenVerifier as r, tokenEndpoints as s, checkTokenAuthority as t, isCrossSiteWrite as u, standaloneSchema as v };