@arbol-ai/maximus 7.4.0 → 8.0.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.
- package/README.md +36 -38
- package/bin/maximus.js +4 -0
- package/config/oxfmt.mjs +1 -0
- package/config/oxlint.mjs +10 -0
- package/dist/analytics/analytics.d.ts +21 -9
- package/dist/analytics/analytics.js +19 -5
- package/dist/body.d.ts +1 -1
- package/dist/body.js +2 -2
- package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
- package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
- package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
- package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
- package/dist/chunks/define-app-x7uY70_1.js +341 -0
- package/dist/chunks/{errors-D7zG9kx9.js → errors-C5w9WY1l.js} +10 -5
- package/dist/chunks/{execution-kVUJPy1A.js → execution-rOiLo8VG.js} +28 -15
- package/dist/chunks/generate-C-9FKW0o.js +197 -0
- package/dist/chunks/handler-iebR-urt.js +141 -0
- package/dist/chunks/http-layout-DS8DnPyu.js +128 -0
- package/dist/chunks/{http-paths-yKD6TSNJ.js → http-paths-DMBxwpp6.js} +50 -31
- package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
- package/dist/chunks/names-ncD7A3DV.js +280 -0
- package/dist/chunks/openapi-CeolxIqa.js +1588 -0
- package/dist/chunks/openapi-file-Bz9FRaE6.js +83 -0
- package/dist/chunks/pages-iZTvFs5a.js +14 -0
- package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
- package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
- package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
- package/dist/chunks/query-kind-CWKAXEME.js +40 -0
- package/dist/chunks/record-DQUDTpEA.js +10 -0
- package/dist/chunks/result-CKgZHrnj.js +56 -0
- package/dist/chunks/{runtime-DlqA7J38.js → runtime-D94vx21X.js} +50 -26
- package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
- package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
- package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
- package/dist/chunks/server-Bzf1Q1_4.js +410 -0
- package/dist/chunks/src-CPrJpbOM.js +573 -0
- package/dist/chunks/{standard-failures-CLjxS2ea.js → standard-failures-Lh4mSfwG.js} +1 -1
- package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
- package/dist/chunks/{types-DQdfRF3f.d.ts → types-DTIuIEJ-.d.ts} +1000 -342
- package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
- package/dist/chunks/workers-types-BRk_Xa_5.d.ts +143 -0
- package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
- package/dist/diagnostics.d.ts +6 -4
- package/dist/diagnostics.js +2 -2
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +2 -2
- package/dist/http-paths.d.ts +1 -1
- package/dist/http-paths.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -11
- package/dist/internals.d.ts +1 -1
- package/dist/internals.js +5 -4
- package/dist/mcp/index.d.ts +3 -2
- package/dist/mcp/index.js +5 -387
- package/dist/postgres/index.d.ts +25 -8
- package/dist/postgres/index.js +17 -8
- package/dist/project/config.d.ts +110 -72
- package/dist/project/config.js +161 -45
- package/dist/project/index.d.ts +17 -4
- package/dist/project/index.js +44 -9
- package/dist/projection.d.ts +14 -13
- package/dist/projection.js +8 -32
- package/dist/schemas.d.ts +1 -1
- package/dist/schemas.js +2 -2
- package/dist/standard-failures.d.ts +2 -89
- package/dist/standard-failures.js +1 -1
- package/dist/tooling/cli.js +149 -105
- package/dist/tooling/testing.js +2 -2
- package/dist/vite/cloudflare-workers.js +25 -0
- package/dist/vite/index.d.ts +157 -0
- package/dist/vite/index.js +1477 -0
- package/dist/webhooks.d.ts +12 -10
- package/dist/webhooks.js +26 -12
- package/dist/workers/runtime.d.ts +1 -1
- package/dist/workers/runtime.js +1 -1
- package/package.json +26 -22
- package/skills/maximus/SKILL.md +165 -68
- package/skills/maximus/references/deploying.md +73 -0
- package/skills/maximus/references/errors-and-results.md +114 -55
- package/skills/maximus/references/project.md +202 -0
- package/skills/maximus/references/routes-and-tools.md +256 -0
- package/skills/maximus/references/testing.md +137 -50
- package/skills/maximus/references/transports.md +113 -100
- package/skills/maximus/references/writing-code.md +84 -0
- package/templates/mcp/mcp/instructions.md.template +2 -0
- package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
- package/templates/mcp/tests/mcp.test.ts.template +36 -0
- package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
- package/templates/project/.github/workflows/ci.yml.template +4 -1
- package/templates/project/CLAUDE.md.template +41 -25
- package/templates/project/README.md.template +54 -48
- package/templates/project/middleware/10-response.ts.template +5 -2
- package/templates/project/package.json.template +13 -9
- package/templates/project/pages/index.ts.template +2 -4
- package/templates/project/routes/v1/greeting.get.ts.template +10 -0
- package/templates/project/routes/v1/greeting.post.ts.template +12 -0
- package/templates/project/tests/greeting.test.ts.template +45 -0
- package/templates/project/tsconfig.json.template +8 -6
- package/templates/project/vite.config.ts.template +15 -7
- package/templates/web/app/main.tsx.template +16 -0
- package/templates/web/app/root.tsx.template +17 -0
- package/templates/web/app/routes/index.tsx.template +9 -0
- package/templates/web/index.html.template +12 -0
- package/templates/web/package.json.template +12 -0
- package/templates/web/tsconfig.json.template +7 -0
- package/templates/web/vite.config.ts.template +22 -0
- package/dist/chunks/builder-BiXv7d2v.js +0 -100
- package/dist/chunks/define-app-DvD_1jUE.js +0 -625
- package/dist/chunks/prepare-project-CMyGSEtI.js +0 -236
- package/dist/chunks/prepare-project-MtS0-W_n.js +0 -3
- package/dist/chunks/record-DY-lX9w1.js +0 -34
- package/dist/chunks/src-N3oyx5QF.js +0 -1091
- package/dist/client/client.d.ts +0 -129
- package/dist/client/client.js +0 -321
- package/dist/tooling/vite.d.ts +0 -3
- package/dist/tooling/vite.js +0 -57
- package/skills/maximus/references/adding-an-operation.md +0 -179
- package/skills/maximus/references/building-a-service.md +0 -167
- package/skills/maximus/references/migration-from-v2.md +0 -62
- package/skills/maximus/references/migration-to-v5.md +0 -37
- package/skills/maximus/references/publishing-and-verification.md +0 -42
- package/templates/project/cloudflare.config.ts.template +0 -24
- package/templates/project/maximus.config.ts.template +0 -20
- package/templates/project/routes/v1/greeting.ts.template +0 -38
- package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
- package/templates/service/.github/workflows/ci.yml.template +0 -21
- package/templates/service/.gitignore.template +0 -9
- package/templates/service/CLAUDE.md.template +0 -5
- package/templates/service/README.md.template +0 -45
- package/templates/service/cloudflare.config.ts.template +0 -30
- package/templates/service/package.json.template +0 -36
- package/templates/service/src/app.ts.template +0 -30
- package/templates/service/src/index.ts.template +0 -13
- package/templates/service/tests/contract.test.ts.template +0 -12
- package/templates/service/tsconfig.json.template +0 -16
- package/templates/service/vite.config.ts.template +0 -13
- package/templates/service/vitest.config.ts.template +0 -10
|
@@ -0,0 +1,1588 @@
|
|
|
1
|
+
import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
|
|
2
|
+
import { S as wireInput, r as parseInput } from "./validation-fTohBT6R.js";
|
|
3
|
+
import { i as standardErrors } from "./errors-C5w9WY1l.js";
|
|
4
|
+
import { a as operationPathParameters } from "./http-paths-DMBxwpp6.js";
|
|
5
|
+
import { a as routeGroup, i as pathParameterSchemas, r as ok, t as err } from "./result-CKgZHrnj.js";
|
|
6
|
+
import { t as isRecord } from "./record-DQUDTpEA.js";
|
|
7
|
+
import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-p_aRcMC1.js";
|
|
8
|
+
import { t as queryKind } from "./query-kind-CWKAXEME.js";
|
|
9
|
+
import { Type } from "@sinclair/typebox";
|
|
10
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
11
|
+
|
|
12
|
+
// src/scopes.ts
|
|
13
|
+
/** `<namespace>:<resource>:<action>`, or deeper, in lowercase kebab-case segments. */
|
|
14
|
+
const SCOPE_NAME = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*){2,}$/;
|
|
15
|
+
/** Whether `scope` is a well-formed scope of the service whose namespace is `namespace`. */
|
|
16
|
+
function isNamespacedScope(scope, namespace) {
|
|
17
|
+
return scope.startsWith(`${namespace}:`) && SCOPE_NAME.test(scope);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Whether granted scopes admit a requirement: any one of the required scopes, or all of them with `all`.
|
|
21
|
+
* An empty requirement admits nobody.
|
|
22
|
+
*/
|
|
23
|
+
function matchesScopes(required, granted, match = "any") {
|
|
24
|
+
if (!required.length) return false;
|
|
25
|
+
const has = (scope) => granted.includes(scope);
|
|
26
|
+
return match === "all" ? required.every(has) : match === "any" && required.some(has);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/manifest.ts
|
|
30
|
+
/** Whether an operation belongs in public contracts: the OpenAPI document and the discovery metadata. */
|
|
31
|
+
function isPublicOperation(declaration) {
|
|
32
|
+
return declaration.visibility !== "internal";
|
|
33
|
+
}
|
|
34
|
+
/** The scopes of an operation as a list. */
|
|
35
|
+
function operationScopes(declaration) {
|
|
36
|
+
return typeof declaration.scope === "string" ? [declaration.scope] : declaration.scope;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Whether granted scopes admit an operation: any one of its scopes, or every one under `scopeMatch: 'all'`.
|
|
40
|
+
* HTTP admission, MCP listing and calls, and execution share it.
|
|
41
|
+
*/
|
|
42
|
+
function operationMatchesScopes(declaration, granted) {
|
|
43
|
+
return matchesScopes(operationScopes(declaration), granted, declaration.scopeMatch);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Declares one operation on its own, keeping its literal types. The builder's `.operation()` is the usual way
|
|
47
|
+
* to declare one. As there, `execute` receives the decoded input, `StaticDecode<typeof input>`.
|
|
48
|
+
*/
|
|
49
|
+
function operation(definition) {
|
|
50
|
+
return definition;
|
|
51
|
+
}
|
|
52
|
+
/** Where an operation is served, for a refusal that names it: its HTTP route, else its MCP tool. */
|
|
53
|
+
function servedAs(declared) {
|
|
54
|
+
if (declared?.http) return `${declared.http.method} ${declared.http.path}`;
|
|
55
|
+
return declared?.mcp && `the tool ${declared.mcp.name}`;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Merges groups of operations into one, never overwriting: a name two groups declare throws a TypeError,
|
|
59
|
+
* `Duplicate operation: <name>`, which names the route or tool of each when both have one.
|
|
60
|
+
*/
|
|
61
|
+
function composeOperations(...groups) {
|
|
62
|
+
const result = {};
|
|
63
|
+
for (const group of groups) for (const [name, op] of Object.entries(group)) {
|
|
64
|
+
if (Object.hasOwn(result, name)) {
|
|
65
|
+
const first = servedAs(result[name]);
|
|
66
|
+
const second = servedAs(op);
|
|
67
|
+
throw new TypeError(first && second ? `Duplicate operation: ${name} names both ${first} and ${second}; give one of them its own operationId.` : `Duplicate operation: ${name}`);
|
|
68
|
+
}
|
|
69
|
+
Object.defineProperty(result, name, {
|
|
70
|
+
value: op,
|
|
71
|
+
enumerable: true
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
/** The failure codes every operation may answer without declaring them. */
|
|
77
|
+
const STANDARD_CODES = new Set(Object.values(STANDARD_FAILURES).map(({ code }) => code));
|
|
78
|
+
/**
|
|
79
|
+
* The standard failures only routing and admission answer, before an operation runs: an unknown path or
|
|
80
|
+
* method, and a missing or refused token. An operation's context, middleware or handler never answers them.
|
|
81
|
+
*/
|
|
82
|
+
const ADMISSION_CODES = /* @__PURE__ */ new Set([
|
|
83
|
+
STANDARD_FAILURES.notFound.code,
|
|
84
|
+
STANDARD_FAILURES.methodNotAllowed.code,
|
|
85
|
+
STANDARD_FAILURES.unauthorized.code
|
|
86
|
+
]);
|
|
87
|
+
/**
|
|
88
|
+
* The standard failures of reading a request body: admission answers them for a JSON body, and a byte body's
|
|
89
|
+
* `read()` for the operation that reads one.
|
|
90
|
+
*/
|
|
91
|
+
const BODY_CODES = /* @__PURE__ */ new Set([STANDARD_FAILURES.tooLarge.code, STANDARD_FAILURES.unsupportedMedia.code]);
|
|
92
|
+
/** Default request body limit when neither the operation nor the application sets one. */
|
|
93
|
+
const DEFAULT_MAX_BODY_BYTES = 32768;
|
|
94
|
+
/** Default output limit when neither the operation nor the application sets one. */
|
|
95
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 262144;
|
|
96
|
+
/** Largest body limit an application or operation may declare: the body is buffered in memory. */
|
|
97
|
+
const MAX_BODY_BYTES_CEILING = 16777216;
|
|
98
|
+
/** The request body limit an operation is held to: its own, else the application's, else the default. */
|
|
99
|
+
function operationBodyLimit(application, declaration) {
|
|
100
|
+
return declaration.maxBodyBytes ?? application.maxBodyBytes ?? 32768;
|
|
101
|
+
}
|
|
102
|
+
/** The output limit an operation is held to: its own, else the application's, else the default. */
|
|
103
|
+
function operationOutputLimit(application, declaration) {
|
|
104
|
+
return declaration.maxOutputBytes ?? application.maxOutputBytes ?? 262144;
|
|
105
|
+
}
|
|
106
|
+
/** Whether an operation's MCP tool reaches outside the service: it does unless it declares otherwise. */
|
|
107
|
+
function mcpOpenWorld(tool) {
|
|
108
|
+
return tool.openWorld ?? true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/internal/claims.ts
|
|
112
|
+
/**
|
|
113
|
+
* Reading a verified token's claims, which token verification and Cloudflare Access share.
|
|
114
|
+
*/
|
|
115
|
+
/**
|
|
116
|
+
* A claim's own value under its name, else at a dotted path through object claims; undefined when absent.
|
|
117
|
+
* Only own properties are read, so no path reaches a prototype.
|
|
118
|
+
*/
|
|
119
|
+
function claimAt(claims, path) {
|
|
120
|
+
if (Object.hasOwn(claims, path)) return claims[path];
|
|
121
|
+
let value = claims;
|
|
122
|
+
for (const key of path.split(".")) {
|
|
123
|
+
if (!isRecord(value) || !Object.hasOwn(value, key)) return;
|
|
124
|
+
value = value[key];
|
|
125
|
+
}
|
|
126
|
+
return value;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/principal.ts
|
|
130
|
+
/**
|
|
131
|
+
* Who calls: the principal every operation receives, and what a verified token grants before admission adds
|
|
132
|
+
* the request id. Token verification (`tokens.ts`) and Cloudflare Access (`cloudflare-access.ts`) both answer
|
|
133
|
+
* a `TokenPrincipal`, parsed strictly against these schemas.
|
|
134
|
+
*/
|
|
135
|
+
/**
|
|
136
|
+
* Who calls, as every operation receives it: the actor, its kind, its verified organization and the request
|
|
137
|
+
* id.
|
|
138
|
+
*/
|
|
139
|
+
const PrincipalSchema = Type.Object({
|
|
140
|
+
actorId: Type.String({
|
|
141
|
+
minLength: 1,
|
|
142
|
+
maxLength: 255
|
|
143
|
+
}),
|
|
144
|
+
actorKind: Type.Union([Type.Literal("user"), Type.Literal("service")]),
|
|
145
|
+
organizationId: OrganizationIdSchema,
|
|
146
|
+
requestId: UuidSchema
|
|
147
|
+
}, { additionalProperties: false });
|
|
148
|
+
/**
|
|
149
|
+
* The OAuth client a token was issued to: its id and its class, `human`, `machine` or `dcr` (a dynamically
|
|
150
|
+
* registered client).
|
|
151
|
+
*/
|
|
152
|
+
const TokenClientSchema = Type.Object({
|
|
153
|
+
id: Type.String({
|
|
154
|
+
minLength: 1,
|
|
155
|
+
maxLength: 255
|
|
156
|
+
}),
|
|
157
|
+
class: Type.Union([
|
|
158
|
+
Type.Literal("human"),
|
|
159
|
+
Type.Literal("machine"),
|
|
160
|
+
Type.Literal("dcr")
|
|
161
|
+
])
|
|
162
|
+
}, { additionalProperties: false });
|
|
163
|
+
/**
|
|
164
|
+
* What a verified token grants: the principal without a request id, its scopes and, for an OAuth token, its
|
|
165
|
+
* client. A custom `tokens.resolve` returns this shape.
|
|
166
|
+
*/
|
|
167
|
+
const TokenPrincipalSchema = Type.Object({
|
|
168
|
+
...Type.Omit(PrincipalSchema, ["requestId"]).properties,
|
|
169
|
+
scopes: Type.Array(Type.String({ maxLength: 255 }), { maxItems: 1e3 }),
|
|
170
|
+
/** Custom resolvers must classify DCR from verified application policy, never request headers. */
|
|
171
|
+
client: Type.Optional(TokenClientSchema)
|
|
172
|
+
}, { additionalProperties: false });
|
|
173
|
+
|
|
174
|
+
// src/cloudflare-access.ts
|
|
175
|
+
/**
|
|
176
|
+
* Cloudflare Access application tokens: where a request presents one, what it grants and what a token policy
|
|
177
|
+
* must state to admit it. Access signs people and service tokens in at Cloudflare's edge, and sets the
|
|
178
|
+
* application token in `Cf-Access-Jwt-Assertion` on each request it lets through. A Worker cannot take that
|
|
179
|
+
* header's presence as proof: a request reaches it around Access at its `workers.dev` and preview URLs, at a
|
|
180
|
+
* path Access does not cover, or through a Service Binding. So every token is verified, its signature, issuer
|
|
181
|
+
* and audience, and nothing else Access sets, such as `Cf-Access-Authenticated-User-Email` or the
|
|
182
|
+
* `CF_Authorization` cookie, is read.
|
|
183
|
+
*/
|
|
184
|
+
/** The header Access sets the application token in: the only place a policy of its source reads one. */
|
|
185
|
+
const ACCESS_TOKEN_HEADER = "cf-access-jwt-assertion";
|
|
186
|
+
/** Whether a token policy admits Cloudflare Access application tokens, rather than bearer tokens. */
|
|
187
|
+
function usesCloudflareAccess(policy) {
|
|
188
|
+
return policy.source === "cloudflare-access";
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The principal a verified Access application token grants under `policy.access`. A person, whose token
|
|
192
|
+
* names them in `sub` and carries no `common_name`, acts as `sub` (never as their email) through a `human`
|
|
193
|
+
* client, the application's audience, and holds `access.people`. A service token, whose token has an empty
|
|
194
|
+
* `sub` and its client id as `common_name`, acts as that client id through a `machine` client of the same
|
|
195
|
+
* id, and holds what `access.services` lists under it, else nothing. Each acts in `access.organizationId`, or
|
|
196
|
+
* in the organization the claim `claims.organization` holds. Anything else is refused as `UNAUTHORIZED`: a
|
|
197
|
+
* token whose `type` is not `app` (an Access organization token, for one), a token that is neither a person's
|
|
198
|
+
* nor a service token's, an organization missing or malformed or named by both, and a policy without `access`.
|
|
199
|
+
*/
|
|
200
|
+
function projectAccessToken(claims, policy) {
|
|
201
|
+
const refused = err(standardErrors.unauthorized.create());
|
|
202
|
+
const { access } = policy;
|
|
203
|
+
if (access === void 0 || !isRecord(claims) || claims.type !== "app") return refused;
|
|
204
|
+
const audience = applicationAudience(claims.aud, policy.audience);
|
|
205
|
+
const caller = audience === void 0 ? null : accessCaller(claims, access, audience);
|
|
206
|
+
if (caller === null) return refused;
|
|
207
|
+
const principal = parseInput(TokenPrincipalSchema, {
|
|
208
|
+
...caller,
|
|
209
|
+
organizationId: accessOrganization(claims, access, policy.claims?.organization)
|
|
210
|
+
});
|
|
211
|
+
return principal.ok ? ok(principal.value) : refused;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* The application audience a token names: the first of the policy's audiences that its `aud`, a string or a
|
|
215
|
+
* list, carries; undefined when it carries none of them.
|
|
216
|
+
*/
|
|
217
|
+
function applicationAudience(named, audience) {
|
|
218
|
+
const carried = typeof named === "string" ? [named] : named;
|
|
219
|
+
if (!Array.isArray(carried)) return;
|
|
220
|
+
return (typeof audience === "string" ? [audience] : audience).find((candidate) => carried.includes(candidate));
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Who a token names: a person by a non-empty `sub` without `common_name`, or a service token by its
|
|
224
|
+
* `common_name` with an empty `sub`; null for a token of any other shape, such as one that carries both.
|
|
225
|
+
*/
|
|
226
|
+
function accessCaller(claims, access, audience) {
|
|
227
|
+
const { sub: subject, common_name: commonName } = claims;
|
|
228
|
+
if (typeof subject === "string" && subject !== "" && commonName === void 0) return {
|
|
229
|
+
actorId: subject,
|
|
230
|
+
actorKind: "user",
|
|
231
|
+
scopes: [...access.people],
|
|
232
|
+
client: {
|
|
233
|
+
id: audience,
|
|
234
|
+
class: "human"
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
if (subject === "" && typeof commonName === "string" && commonName !== "") return {
|
|
238
|
+
actorId: commonName,
|
|
239
|
+
actorKind: "service",
|
|
240
|
+
scopes: serviceScopes(access, commonName),
|
|
241
|
+
client: {
|
|
242
|
+
id: commonName,
|
|
243
|
+
class: "machine"
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The scopes `access.services` lists for a service token's client id, none when it lists none. Only its own
|
|
250
|
+
* entries are read, so no client id reaches a prototype's property.
|
|
251
|
+
*/
|
|
252
|
+
function serviceScopes(access, clientId) {
|
|
253
|
+
const { services = {} } = access;
|
|
254
|
+
return [...(Object.hasOwn(services, clientId) ? services[clientId] : void 0) ?? []];
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* The organization an Access caller acts in: `access.organizationId`, or the value of the claim `claim`
|
|
258
|
+
* names, such as `custom.org_id` for a custom OIDC claim Access passes on. Undefined, and so refused, unless
|
|
259
|
+
* exactly one of them is set.
|
|
260
|
+
*/
|
|
261
|
+
function accessOrganization(claims, access, claim) {
|
|
262
|
+
if (claim === void 0) return access.organizationId;
|
|
263
|
+
return access.organizationId === void 0 ? claimAt(claims, claim) : void 0;
|
|
264
|
+
}
|
|
265
|
+
/** The options of a token policy that only OAuth access tokens use, which Access application tokens are not. */
|
|
266
|
+
const OAUTH_OPTIONS = [
|
|
267
|
+
"scheme",
|
|
268
|
+
"resources",
|
|
269
|
+
"resourceMetadataUrl",
|
|
270
|
+
"authorizationEndpoint",
|
|
271
|
+
"tokenEndpoint"
|
|
272
|
+
];
|
|
273
|
+
/** The most scopes a principal holds, as `TokenPrincipalSchema` admits them. */
|
|
274
|
+
const MAX_SCOPES = 1e3;
|
|
275
|
+
/**
|
|
276
|
+
* Refuses, at construction, a policy of the `cloudflare-access` source that could never admit a caller, or
|
|
277
|
+
* that states what Access application tokens never carry: neither `access` nor `resolve`; any option only
|
|
278
|
+
* OAuth uses (`scheme`, `resources`, `resourceMetadataUrl` and the endpoints OpenAPI would publish); claims
|
|
279
|
+
* other than the organization; and, with `access`, an organization named twice, not at all or malformed, or
|
|
280
|
+
* scopes outside the application's namespace, more than 1000 of them, or listed under an empty client id.
|
|
281
|
+
*/
|
|
282
|
+
function checkAccessPolicy(policy, namespace) {
|
|
283
|
+
const { access, claims } = policy;
|
|
284
|
+
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.");
|
|
285
|
+
const oauth = OAUTH_OPTIONS.filter((option) => policy[option] !== void 0);
|
|
286
|
+
if (oauth.length) throw new TypeError(`Cloudflare Access application tokens are not OAuth access tokens: remove ${oauth.map((option) => `tokens.${option}`).join(", ")}.`);
|
|
287
|
+
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.");
|
|
288
|
+
if (access === void 0) return;
|
|
289
|
+
const { organizationId } = access;
|
|
290
|
+
const claim = claims?.organization;
|
|
291
|
+
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.");
|
|
292
|
+
/** Whether a list holds scopes of the application, at most as many and as long as a principal's. */
|
|
293
|
+
const ownScopes = (scopes) => Array.isArray(scopes) && scopes.length <= MAX_SCOPES && scopes.every((scope) => typeof scope === "string" && scope.length <= 255 && isNamespacedScope(scope, namespace));
|
|
294
|
+
const services = access.services ?? {};
|
|
295
|
+
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.`);
|
|
296
|
+
}
|
|
297
|
+
/** The methods that change nothing: another site's page may send them without consequence. */
|
|
298
|
+
const SAFE_METHODS = /* @__PURE__ */ new Set([
|
|
299
|
+
"GET",
|
|
300
|
+
"HEAD",
|
|
301
|
+
"OPTIONS"
|
|
302
|
+
]);
|
|
303
|
+
/**
|
|
304
|
+
* Whether a browser sent a write for another site's page: a method other than `GET`, `HEAD` and `OPTIONS`
|
|
305
|
+
* with `Sec-Fetch-Site: cross-site`, or with an `Origin` other than the request's own. A person's Access
|
|
306
|
+
* session travels in a cookie, which the browser attaches to such a request, and Access forwards it with
|
|
307
|
+
* the person's application token. A request with neither header, such as a service token's, is no browser's.
|
|
308
|
+
*/
|
|
309
|
+
function isCrossSiteWrite(request) {
|
|
310
|
+
if (SAFE_METHODS.has(request.method)) return false;
|
|
311
|
+
const origin = request.headers.get("origin");
|
|
312
|
+
return request.headers.get("sec-fetch-site") === "cross-site" || origin !== null && origin !== new URL(request.url).origin;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// src/internal/http-query.ts
|
|
316
|
+
/**
|
|
317
|
+
* The typed GET query codec: which input fields travel in the query string, and how each value is read as
|
|
318
|
+
* its kind.
|
|
319
|
+
*/
|
|
320
|
+
/** An integer as a query value: no leading zeros and at most 16 digits, so it stays exact. */
|
|
321
|
+
const INTEGER = /^-?(?:0|[1-9]\d{0,15})$/;
|
|
322
|
+
/** A decimal number as a query value, with an optional exponent. */
|
|
323
|
+
const NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
324
|
+
/** A GET's query fields and the kind each one is read as: every input field outside the path. */
|
|
325
|
+
function queryKinds(op) {
|
|
326
|
+
const path = new Set(op.http ? operationPathParameters(op.http.path) : []);
|
|
327
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
328
|
+
for (const [field, schema] of Object.entries(op.input.properties ?? {})) {
|
|
329
|
+
const kind = path.has(field) ? null : queryKind(schema);
|
|
330
|
+
if (kind) kinds.set(field, kind);
|
|
331
|
+
}
|
|
332
|
+
return kinds;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* A GET's input from its query string, each declared field read once as its kind:
|
|
336
|
+
* `?limit=2&active=true&tags=a,b` is `{ limit: 2, active: true, tags: ['a', 'b'] }`. A list is one
|
|
337
|
+
* comma-separated value, never a repeated key. A field the input does not declare stays a string for the
|
|
338
|
+
* schema to judge. Null when a field repeats, is named `__proto__` or does not read as its kind.
|
|
339
|
+
*/
|
|
340
|
+
function queryInput(kinds, params) {
|
|
341
|
+
const keys = [...params.keys()];
|
|
342
|
+
if (new Set(keys).size !== keys.length) return null;
|
|
343
|
+
const input = {};
|
|
344
|
+
for (const [key, text] of params) {
|
|
345
|
+
if (key === "__proto__") return null;
|
|
346
|
+
let value = text;
|
|
347
|
+
switch (kinds.get(key)) {
|
|
348
|
+
case "integer":
|
|
349
|
+
value = INTEGER.test(text) ? Number(text) : null;
|
|
350
|
+
break;
|
|
351
|
+
case "number":
|
|
352
|
+
value = NUMBER.test(text) && Number.isFinite(Number(text)) ? Number(text) : null;
|
|
353
|
+
break;
|
|
354
|
+
case "boolean":
|
|
355
|
+
value = text === "true" || text === "false" ? text === "true" : null;
|
|
356
|
+
break;
|
|
357
|
+
case "list": {
|
|
358
|
+
const items = text.split(",");
|
|
359
|
+
value = items.every(Boolean) ? items : null;
|
|
360
|
+
break;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (value === null) return null;
|
|
364
|
+
input[key] = value;
|
|
365
|
+
}
|
|
366
|
+
return input;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// src/schema-bundle.ts
|
|
370
|
+
/**
|
|
371
|
+
* Schema bundling: named schemas (`$id`) become shared components for an OpenAPI document, or are written
|
|
372
|
+
* in place for a reader without components, such as an MCP tool listing.
|
|
373
|
+
*/
|
|
374
|
+
/** Plain identifiers TypeBox uses for Recursive/Ref schemas; URLs and pointers are left untouched. */
|
|
375
|
+
const SCHEMA_ID = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
|
|
376
|
+
/** Use-site annotations: they describe one occurrence and do not change which values validate. */
|
|
377
|
+
const ANNOTATIONS = /* @__PURE__ */ new Set([
|
|
378
|
+
"description",
|
|
379
|
+
"title",
|
|
380
|
+
"examples",
|
|
381
|
+
"default",
|
|
382
|
+
"$comment",
|
|
383
|
+
"deprecated",
|
|
384
|
+
"readOnly",
|
|
385
|
+
"writeOnly"
|
|
386
|
+
]);
|
|
387
|
+
/** Marks a reference resolved only once every variant of its name is known. */
|
|
388
|
+
const PLACEHOLDER = "\0schema\0";
|
|
389
|
+
/** A reference outside any definition, resolved once every variant is known. */
|
|
390
|
+
function pending(id) {
|
|
391
|
+
return `${PLACEHOLDER}${id}`;
|
|
392
|
+
}
|
|
393
|
+
/** A value's JSON with sorted keys, so two equal schemas have one text. */
|
|
394
|
+
function canonical(value) {
|
|
395
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
396
|
+
if (value && typeof value === "object") return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`).join(",")}}`;
|
|
397
|
+
return JSON.stringify(value);
|
|
398
|
+
}
|
|
399
|
+
/** Adds every plain `$id` found in a value to `ids`. */
|
|
400
|
+
function collectIds(value, ids) {
|
|
401
|
+
if (Array.isArray(value)) {
|
|
402
|
+
for (const item of value) collectIds(item, ids);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
if (value && typeof value === "object") {
|
|
406
|
+
const id = value.$id;
|
|
407
|
+
if (typeof id === "string" && SCHEMA_ID.test(id)) ids.add(id);
|
|
408
|
+
for (const child of Object.values(value)) collectIds(child, ids);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/** Every plain `$id` the values name, which bundling makes components of. */
|
|
412
|
+
function schemaIds(values) {
|
|
413
|
+
const ids = /* @__PURE__ */ new Set();
|
|
414
|
+
for (const value of values) collectIds(value, ids);
|
|
415
|
+
return ids;
|
|
416
|
+
}
|
|
417
|
+
/** A copy of a value with every `$ref` passed through `replace`. */
|
|
418
|
+
function replaceReferences(value, replace) {
|
|
419
|
+
if (Array.isArray(value)) return value.map((item) => replaceReferences(item, replace));
|
|
420
|
+
if (!value || typeof value !== "object") return value;
|
|
421
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, key === "$ref" && typeof child === "string" ? replace(child) : replaceReferences(child, replace)]));
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Bundles `$id`-named schemas (TypeBox Recursive/Ref) into components so that every reference in an
|
|
425
|
+
* OpenAPI document is a local `#/components/schemas/<name>` pointer. A plain-name reference resolves
|
|
426
|
+
* against its enclosing `$id`, as in JSON Schema; structurally different definitions that share an
|
|
427
|
+
* `$id` (for example a normalized input projection and its output) become distinct components. A
|
|
428
|
+
* reference outside any definition must name exactly one variant. Use-site annotations stay beside
|
|
429
|
+
* the reference. The owner's runtime schemas are not changed.
|
|
430
|
+
*/
|
|
431
|
+
function bundleSchemas(sources, existing) {
|
|
432
|
+
const ids = schemaIds(sources);
|
|
433
|
+
const components = {};
|
|
434
|
+
const variants = /* @__PURE__ */ new Map();
|
|
435
|
+
const taken = new Set(Object.keys(existing));
|
|
436
|
+
/**
|
|
437
|
+
* A copy of a value with every `$id`-named schema replaced by a reference to its component, registering
|
|
438
|
+
* each distinct shape once, and references resolved against the enclosing names.
|
|
439
|
+
*/
|
|
440
|
+
function rewrite(value, scope) {
|
|
441
|
+
if (Array.isArray(value)) return value.map((item) => rewrite(item, scope));
|
|
442
|
+
if (!value || typeof value !== "object") return value;
|
|
443
|
+
const record = value;
|
|
444
|
+
if (typeof record.$id === "string" && ids.has(record.$id)) {
|
|
445
|
+
const { $id: id, ...rest } = record;
|
|
446
|
+
const definition = Object.fromEntries(Object.entries(rest).filter(([key]) => !ANNOTATIONS.has(key)));
|
|
447
|
+
const annotations = Object.fromEntries(Object.entries(rest).filter(([key]) => ANNOTATIONS.has(key)));
|
|
448
|
+
const self = `#/components/schemas/${PLACEHOLDER}self`;
|
|
449
|
+
const shaped = rewrite(definition, new Map([...scope, [id, self]]));
|
|
450
|
+
const shape = canonical(shaped);
|
|
451
|
+
const known = variants.get(id) ?? /* @__PURE__ */ new Map();
|
|
452
|
+
variants.set(id, known);
|
|
453
|
+
let name = known.get(shape);
|
|
454
|
+
if (!name) {
|
|
455
|
+
name = id;
|
|
456
|
+
for (let index = 2; taken.has(name); index += 1) name = `${id}_${index}`;
|
|
457
|
+
taken.add(name);
|
|
458
|
+
known.set(shape, name);
|
|
459
|
+
const target = `#/components/schemas/${name}`;
|
|
460
|
+
components[name] = replaceReferences(shaped, (reference) => reference === self ? target : reference);
|
|
461
|
+
}
|
|
462
|
+
return {
|
|
463
|
+
$ref: `#/components/schemas/${name}`,
|
|
464
|
+
...annotations
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
return Object.fromEntries(Object.entries(record).map(([key, child]) => {
|
|
468
|
+
if (key === "$ref" && typeof child === "string" && ids.has(child)) return [key, scope.get(child) ?? pending(child)];
|
|
469
|
+
return [key, rewrite(child, scope)];
|
|
470
|
+
}));
|
|
471
|
+
}
|
|
472
|
+
const rewritten = sources.map((source) => rewrite(source, /* @__PURE__ */ new Map()));
|
|
473
|
+
/**
|
|
474
|
+
* A pending reference as the one component its name has once every variant is known; refused when the name
|
|
475
|
+
* has several shapes or none.
|
|
476
|
+
*/
|
|
477
|
+
const resolve = (reference) => {
|
|
478
|
+
if (!reference.startsWith(PLACEHOLDER)) return reference;
|
|
479
|
+
const id = reference.slice(8);
|
|
480
|
+
const names = [...variants.get(id)?.values() ?? []];
|
|
481
|
+
if (names.length !== 1) throw new TypeError(`Schema reference "${id}" does not name exactly one definition.`);
|
|
482
|
+
return `#/components/schemas/${names[0]}`;
|
|
483
|
+
};
|
|
484
|
+
for (const [name, schema] of Object.entries(components)) components[name] = replaceReferences(schema, resolve);
|
|
485
|
+
return {
|
|
486
|
+
values: rewritten.map((value) => replaceReferences(value, resolve)),
|
|
487
|
+
components
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
/** Whether a value refers to a named schema (`$ref` to a plain `$id`) anywhere within it. */
|
|
491
|
+
function hasSchemaReferences(value) {
|
|
492
|
+
const references = /* @__PURE__ */ new Set();
|
|
493
|
+
collectReferences(value, references);
|
|
494
|
+
return [...references].some((reference) => SCHEMA_ID.test(reference));
|
|
495
|
+
}
|
|
496
|
+
/** Adds every `$ref` found in a value to `references`. */
|
|
497
|
+
function collectReferences(value, references) {
|
|
498
|
+
if (Array.isArray(value)) {
|
|
499
|
+
for (const item of value) collectReferences(item, references);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
if (value && typeof value === "object") for (const [key, child] of Object.entries(value)) if (key === "$ref" && typeof child === "string") references.add(child);
|
|
503
|
+
else collectReferences(child, references);
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* The schema with every `$id` nothing refers to removed, the definition left in place: what a reader
|
|
507
|
+
* that resolves no components meets, the same as before the schema was named. A definition a `$ref`
|
|
508
|
+
* names (TypeBox Recursive or Ref) keeps its `$id`, so the reference still resolves.
|
|
509
|
+
*/
|
|
510
|
+
function inlineSchemaNames(value) {
|
|
511
|
+
const references = /* @__PURE__ */ new Set();
|
|
512
|
+
collectReferences(value, references);
|
|
513
|
+
/** A copy of a node without the `$id`s nothing refers to. */
|
|
514
|
+
const strip = (node) => {
|
|
515
|
+
if (Array.isArray(node)) return node.map(strip);
|
|
516
|
+
if (!node || typeof node !== "object") return node;
|
|
517
|
+
return Object.fromEntries(Object.entries(node).filter(([key, child]) => !(key === "$id" && typeof child === "string" && SCHEMA_ID.test(child) && !references.has(child))).map(([key, child]) => [key, strip(child)]));
|
|
518
|
+
};
|
|
519
|
+
return strip(value);
|
|
520
|
+
}
|
|
521
|
+
/** Points each component reference at the schema's own `$defs`. */
|
|
522
|
+
function local(node) {
|
|
523
|
+
return replaceReferences(node, (reference) => reference.startsWith("#/components/schemas/") ? `#/$defs/${reference.slice(21)}` : reference);
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* A self-contained schema for a reader with no components, such as an MCP tool listing: no `$id`
|
|
527
|
+
* left, each named definition written where it is used, and the ones a `$ref` names bundled once
|
|
528
|
+
* under `$defs`. JSON Schema validators refuse a schema that declares one `$id` twice.
|
|
529
|
+
*/
|
|
530
|
+
function standaloneSchema(value) {
|
|
531
|
+
const { values, components } = bundleSchemas([inlineSchemaNames(value)], {});
|
|
532
|
+
if (!Object.keys(components).length) return values[0];
|
|
533
|
+
return {
|
|
534
|
+
...local(values[0]),
|
|
535
|
+
$defs: local(components)
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// src/internal/openapi-components.ts
|
|
540
|
+
/** A reference to the component schema `name`. */
|
|
541
|
+
function schemaReference(name) {
|
|
542
|
+
return { $ref: `#/components/schemas/${name}` };
|
|
543
|
+
}
|
|
544
|
+
/** A camelCase name or an uppercase code in PascalCase: `createNote` is `CreateNote`, `NOTE_NOT_FOUND` `NoteNotFound`. */
|
|
545
|
+
function pascalCase(name) {
|
|
546
|
+
return (/^[A-Z0-9_]+$/.test(name) ? name.toLowerCase().split("_") : [name]).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
547
|
+
}
|
|
548
|
+
/** The reason phrase of each HTTP status a failure may answer, in PascalCase, as RFC 9110 names it. */
|
|
549
|
+
const REASONS = {
|
|
550
|
+
400: "BadRequest",
|
|
551
|
+
401: "Unauthorized",
|
|
552
|
+
402: "PaymentRequired",
|
|
553
|
+
403: "Forbidden",
|
|
554
|
+
404: "NotFound",
|
|
555
|
+
405: "MethodNotAllowed",
|
|
556
|
+
406: "NotAcceptable",
|
|
557
|
+
408: "RequestTimeout",
|
|
558
|
+
409: "Conflict",
|
|
559
|
+
410: "Gone",
|
|
560
|
+
411: "LengthRequired",
|
|
561
|
+
412: "PreconditionFailed",
|
|
562
|
+
413: "ContentTooLarge",
|
|
563
|
+
415: "UnsupportedMediaType",
|
|
564
|
+
422: "UnprocessableContent",
|
|
565
|
+
423: "Locked",
|
|
566
|
+
424: "FailedDependency",
|
|
567
|
+
425: "TooEarly",
|
|
568
|
+
428: "PreconditionRequired",
|
|
569
|
+
429: "TooManyRequests",
|
|
570
|
+
451: "UnavailableForLegalReasons",
|
|
571
|
+
500: "InternalServerError",
|
|
572
|
+
501: "NotImplemented",
|
|
573
|
+
502: "BadGateway",
|
|
574
|
+
503: "ServiceUnavailable",
|
|
575
|
+
504: "GatewayTimeout",
|
|
576
|
+
507: "InsufficientStorage"
|
|
577
|
+
};
|
|
578
|
+
/** A status's reason phrase in PascalCase: 400 is `BadRequest`, and a status without one `Status499`. */
|
|
579
|
+
function statusReason(status) {
|
|
580
|
+
return REASONS[status] ?? `Status${status}`;
|
|
581
|
+
}
|
|
582
|
+
/** A failure code without the `_ERROR` its name would repeat: `INTERNAL_ERROR` is `INTERNAL`. */
|
|
583
|
+
function failureWords(code) {
|
|
584
|
+
return pascalCase(code.replace(/_ERROR$/, ""));
|
|
585
|
+
}
|
|
586
|
+
/** The component of one failure: `NOTE_NOT_FOUND` is `NoteNotFoundFailure`. */
|
|
587
|
+
function failureName(code) {
|
|
588
|
+
return `${failureWords(code)}Failure`;
|
|
589
|
+
}
|
|
590
|
+
/** The envelope of one failure, the answer's whole body: `NOTE_NOT_FOUND` is `NoteNotFoundError`. */
|
|
591
|
+
function failureEnvelopeName(code) {
|
|
592
|
+
return `${failureWords(code)}Error`;
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* The names a generator gives each operation's own types, which a component must not take: openapi-typescript
|
|
596
|
+
* and Hey API write `CreateNoteData`, `CreateNoteResponse` and `CreateNoteError`, and the OpenAPI Generator
|
|
597
|
+
* `CreateNoteRequest`.
|
|
598
|
+
*/
|
|
599
|
+
const GENERATED_SUFFIXES = [
|
|
600
|
+
"Data",
|
|
601
|
+
"Error",
|
|
602
|
+
"Errors",
|
|
603
|
+
"Response",
|
|
604
|
+
"Responses",
|
|
605
|
+
"Request"
|
|
606
|
+
];
|
|
607
|
+
/** The component names a generator writes for an operation's own types: `createNote`'s `CreateNoteResponse`. */
|
|
608
|
+
function generatedNames(operation) {
|
|
609
|
+
const name = pascalCase(operation);
|
|
610
|
+
return GENERATED_SUFFIXES.map((suffix) => `${name}${suffix}`);
|
|
611
|
+
}
|
|
612
|
+
/** The component schemas of a document, each name given to one schema only. */
|
|
613
|
+
var ComponentSchemas = class {
|
|
614
|
+
/** The schemas by name, in the order they were added. */
|
|
615
|
+
schemas = {};
|
|
616
|
+
/** Whether another schema than this one already has the name. */
|
|
617
|
+
holdsOther(name, schema) {
|
|
618
|
+
const existing = this.schemas[name];
|
|
619
|
+
return existing !== void 0 && canonical(existing) !== canonical(schema);
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Names a schema and answers a reference to it. The same schema under a name it already has is the same
|
|
623
|
+
* component; another schema under a taken name throws, since a reference would then name two shapes.
|
|
624
|
+
*/
|
|
625
|
+
add(name, schema) {
|
|
626
|
+
if (this.holdsOther(name, schema)) throw new TypeError(`Two different schemas claim the OpenAPI component ${name}.`);
|
|
627
|
+
this.schemas[name] = schema;
|
|
628
|
+
return schemaReference(name);
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
/** The JSON a field holds when the answer carries none: success has no error, a failure no data. */
|
|
632
|
+
const NONE = { const: null };
|
|
633
|
+
/** The metadata every answer carries, as the component `ResponseMetadata`. */
|
|
634
|
+
const RESPONSE_METADATA = {
|
|
635
|
+
type: "object",
|
|
636
|
+
description: "What every answer carries besides its data or error.",
|
|
637
|
+
additionalProperties: false,
|
|
638
|
+
required: ["requestId"],
|
|
639
|
+
properties: { requestId: {
|
|
640
|
+
type: "string",
|
|
641
|
+
description: "Request correlation identifier, also sent as X-Request-Id."
|
|
642
|
+
} }
|
|
643
|
+
};
|
|
644
|
+
/** The empty object, as the component `Empty`: the data of an answer, or of a failure, that carries none. */
|
|
645
|
+
const EMPTY_OBJECT = {
|
|
646
|
+
type: "object",
|
|
647
|
+
description: "No fields.",
|
|
648
|
+
additionalProperties: false,
|
|
649
|
+
properties: {}
|
|
650
|
+
};
|
|
651
|
+
/** The envelope of a successful answer: `success` is true, `data` the operation's output and `error` null. */
|
|
652
|
+
function successEnvelope(data) {
|
|
653
|
+
return {
|
|
654
|
+
type: "object",
|
|
655
|
+
description: "A successful answer.",
|
|
656
|
+
additionalProperties: false,
|
|
657
|
+
required: [
|
|
658
|
+
"success",
|
|
659
|
+
"data",
|
|
660
|
+
"error",
|
|
661
|
+
"metadata"
|
|
662
|
+
],
|
|
663
|
+
properties: {
|
|
664
|
+
success: {
|
|
665
|
+
type: "boolean",
|
|
666
|
+
enum: [true]
|
|
667
|
+
},
|
|
668
|
+
data,
|
|
669
|
+
error: NONE,
|
|
670
|
+
metadata: schemaReference("ResponseMetadata")
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
/** The envelope of a failed answer: `success` is false, `data` null and `error` the failure. */
|
|
675
|
+
function failureEnvelope(error) {
|
|
676
|
+
return {
|
|
677
|
+
type: "object",
|
|
678
|
+
description: "A failed answer.",
|
|
679
|
+
additionalProperties: false,
|
|
680
|
+
required: [
|
|
681
|
+
"success",
|
|
682
|
+
"data",
|
|
683
|
+
"error",
|
|
684
|
+
"metadata"
|
|
685
|
+
],
|
|
686
|
+
properties: {
|
|
687
|
+
success: {
|
|
688
|
+
type: "boolean",
|
|
689
|
+
enum: [false]
|
|
690
|
+
},
|
|
691
|
+
data: NONE,
|
|
692
|
+
error,
|
|
693
|
+
metadata: schemaReference("ResponseMetadata")
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* One failure as the component its code names: its code a one-value enum, which every generator reads as
|
|
699
|
+
* the literal, its retryability fixed and its data the schema its definition declares. Its message is a
|
|
700
|
+
* plain string: clients branch on the code, never on the text.
|
|
701
|
+
*/
|
|
702
|
+
function failureSchema(definition, data) {
|
|
703
|
+
return {
|
|
704
|
+
type: "object",
|
|
705
|
+
description: definition.message,
|
|
706
|
+
additionalProperties: false,
|
|
707
|
+
required: [
|
|
708
|
+
"code",
|
|
709
|
+
"message",
|
|
710
|
+
"retryable",
|
|
711
|
+
"data"
|
|
712
|
+
],
|
|
713
|
+
properties: {
|
|
714
|
+
code: {
|
|
715
|
+
type: "string",
|
|
716
|
+
enum: [definition.code],
|
|
717
|
+
description: "The failure code, stable across releases."
|
|
718
|
+
},
|
|
719
|
+
message: {
|
|
720
|
+
type: "string",
|
|
721
|
+
description: "What went wrong, for people; it never contains input values."
|
|
722
|
+
},
|
|
723
|
+
retryable: {
|
|
724
|
+
type: "boolean",
|
|
725
|
+
enum: [definition.retryable ?? false],
|
|
726
|
+
description: "Whether repeating the same request may succeed."
|
|
727
|
+
},
|
|
728
|
+
data
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
/** Several failures as one component, told apart by their `code`, as generators that read a discriminator expect. */
|
|
733
|
+
function failureUnion(codes) {
|
|
734
|
+
return {
|
|
735
|
+
oneOf: codes.map((code) => schemaReference(failureName(code))),
|
|
736
|
+
discriminator: {
|
|
737
|
+
propertyName: "code",
|
|
738
|
+
mapping: Object.fromEntries(codes.map((code) => [code, schemaReference(failureName(code)).$ref]))
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// src/internal/digest.ts
|
|
744
|
+
/**
|
|
745
|
+
* SHA-256 digests in hexadecimal, for rate limit keys, the development token's comparison and skill
|
|
746
|
+
* manifests.
|
|
747
|
+
*/
|
|
748
|
+
/** The SHA-256 digest of text or bytes, in lowercase hexadecimal. */
|
|
749
|
+
async function sha256Hex(value) {
|
|
750
|
+
const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
|
|
751
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
|
752
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// src/tokens.ts
|
|
756
|
+
/**
|
|
757
|
+
* Token verification: the principal every operation receives, the token policy, OAuth access token
|
|
758
|
+
* verification against the issuer's JWKS, claim projection, and request admission by scope. Cloudflare Access
|
|
759
|
+
* application tokens, which a policy of the `cloudflare-access` source admits, are `cloudflare-access.ts`'s.
|
|
760
|
+
*/
|
|
761
|
+
/** Every algorithm `TokenAlgorithm` names. */
|
|
762
|
+
const TOKEN_ALGORITHMS = /* @__PURE__ */ new Set([
|
|
763
|
+
"RS256",
|
|
764
|
+
"RS384",
|
|
765
|
+
"RS512",
|
|
766
|
+
"PS256",
|
|
767
|
+
"PS384",
|
|
768
|
+
"PS512",
|
|
769
|
+
"ES256",
|
|
770
|
+
"ES384",
|
|
771
|
+
"ES512",
|
|
772
|
+
"EdDSA"
|
|
773
|
+
]);
|
|
774
|
+
/** The sources a token policy may read tokens from. */
|
|
775
|
+
const TOKEN_SOURCES = /* @__PURE__ */ new Set(["authorization", "cloudflare-access"]);
|
|
776
|
+
/** The hosts only `vp dev`, or a test, reaches a Worker as: the internet never reaches a deployed Worker so. */
|
|
777
|
+
const LOCAL_HOSTS = /* @__PURE__ */ new Set([
|
|
778
|
+
"localhost",
|
|
779
|
+
"127.0.0.1",
|
|
780
|
+
"[::1]"
|
|
781
|
+
]);
|
|
782
|
+
/**
|
|
783
|
+
* Whether a token is the development token, presented to a local host. The digests have one length, so the
|
|
784
|
+
* comparison takes the same time however much of the token matches.
|
|
785
|
+
*/
|
|
786
|
+
async function isDevelopmentToken(development, token, request, env) {
|
|
787
|
+
const expected = isRecord(env) ? env[development.binding] : void 0;
|
|
788
|
+
return typeof expected === "string" && expected.length >= 32 && LOCAL_HOSTS.has(new URL(request.url).hostname) && await sha256Hex(token) === await sha256Hex(expected);
|
|
789
|
+
}
|
|
790
|
+
/** Whether the application issues its own bearer tokens instead of OAuth access tokens. */
|
|
791
|
+
function usesOwnBearer(policy) {
|
|
792
|
+
return policy.scheme?.type === "bearer";
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* A claim that lists values, such as scopes, permissions or grant types: a space-separated string or a list of
|
|
796
|
+
* strings, none when absent; null when malformed.
|
|
797
|
+
*/
|
|
798
|
+
function scopeList(value) {
|
|
799
|
+
if (value === void 0) return [];
|
|
800
|
+
if (typeof value === "string") return value.split(" ").filter(Boolean);
|
|
801
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : null;
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* The OAuth client a token names: the mapped claim, else `azp` or `client_id`, which must agree when both are
|
|
805
|
+
* present. Undefined when it names none; null when a client claim is malformed or the two disagree.
|
|
806
|
+
*/
|
|
807
|
+
function tokenClient(claims, path) {
|
|
808
|
+
const present = (path === void 0 ? [claims.azp, claims.client_id] : [claimAt(claims, path)]).filter((value) => value !== void 0);
|
|
809
|
+
if (present.some((value) => typeof value !== "string" || !value) || new Set(present).size > 1) return null;
|
|
810
|
+
return present[0];
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* The principal a verified access token grants, read where `mapping` says. A subject of the shape
|
|
814
|
+
* `mapping.machineSubject` names, `<client id>@clients` by default, is a machine; anyone else is a person,
|
|
815
|
+
* who holds only the granted scopes their permissions claim also lists. Malformed or inconsistent claims,
|
|
816
|
+
* such as a missing `sub`, a subject shaped like another client's, or a token of the client credentials grant
|
|
817
|
+
* (`gty: client-credentials`, as Auth0 names it) whose subject is not a machine's, are refused as
|
|
818
|
+
* `UNAUTHORIZED`.
|
|
819
|
+
*/
|
|
820
|
+
function projectToken(claims, mapping = {}) {
|
|
821
|
+
const refused = err(standardErrors.unauthorized.create());
|
|
822
|
+
if (!isRecord(claims) || typeof claims.sub !== "string") return refused;
|
|
823
|
+
const subject = claims.sub;
|
|
824
|
+
const client = tokenClient(claims, mapping.client);
|
|
825
|
+
const granted = scopeList(claimAt(claims, mapping.scopes ?? "scope"));
|
|
826
|
+
if (client === null || granted === null) return refused;
|
|
827
|
+
const clientsSuffix = mapping.machineSubject !== "{client}";
|
|
828
|
+
const machine = client !== void 0 && subject === (clientsSuffix ? `${client}@clients` : client);
|
|
829
|
+
if (clientsSuffix && !machine && subject.endsWith("@clients")) return refused;
|
|
830
|
+
const grants = scopeList(claimAt(claims, "gty"));
|
|
831
|
+
if (grants === null || grants.includes("client-credentials") && !machine) return refused;
|
|
832
|
+
let scopes = [...new Set(granted)];
|
|
833
|
+
const listed = mapping.permissions ?? "permissions";
|
|
834
|
+
if (!machine && listed !== false) {
|
|
835
|
+
const permissions = scopeList(claimAt(claims, listed));
|
|
836
|
+
if (permissions === null) return refused;
|
|
837
|
+
scopes = scopes.filter((scope) => permissions.includes(scope));
|
|
838
|
+
}
|
|
839
|
+
const principal = parseInput(TokenPrincipalSchema, {
|
|
840
|
+
organizationId: claimAt(claims, mapping.organization ?? "org_id"),
|
|
841
|
+
actorId: subject,
|
|
842
|
+
actorKind: machine ? "service" : "user",
|
|
843
|
+
scopes,
|
|
844
|
+
...client === void 0 ? {} : { client: {
|
|
845
|
+
id: client,
|
|
846
|
+
class: machine ? "machine" : "human"
|
|
847
|
+
} }
|
|
848
|
+
});
|
|
849
|
+
return principal.ok ? ok(principal.value) : refused;
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* The issuers a token may name as its `iss`, the canonical one first: the authorization server discovery
|
|
853
|
+
* names, and the one the JWKS and the endpoints resolve against. There is no default, so a deployment always
|
|
854
|
+
* names its own; a missing issuer, an empty one and a repeated one throw a TypeError.
|
|
855
|
+
*/
|
|
856
|
+
function tokenIssuers(policy) {
|
|
857
|
+
const listed = policy.issuer;
|
|
858
|
+
const issuers = Array.isArray(listed) ? listed : [listed];
|
|
859
|
+
const valid = issuers.filter((value) => typeof value === "string" && value !== "");
|
|
860
|
+
const [canonical, ...others] = valid;
|
|
861
|
+
if (canonical === void 0) throw new TypeError("tokens.issuer is required to verify or document OAuth access tokens.");
|
|
862
|
+
if (valid.length !== issuers.length || new Set(valid).size !== valid.length) throw new TypeError("tokens.issuer is one issuer, or a list of distinct issuers, the canonical one first.");
|
|
863
|
+
return [canonical, ...others];
|
|
864
|
+
}
|
|
865
|
+
/** The canonical OAuth authorization server, the first issuer; a policy without one throws a TypeError. */
|
|
866
|
+
function tokenIssuer(policy) {
|
|
867
|
+
return tokenIssuers(policy)[0];
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* The audiences a token may carry, the canonical one first: the `resource` OAuth discovery names.
|
|
871
|
+
* Refuses an empty list, an empty audience and a repeated one.
|
|
872
|
+
*/
|
|
873
|
+
function tokenAudiences(policy) {
|
|
874
|
+
const listed = policy.audience;
|
|
875
|
+
const audiences = Array.isArray(listed) ? listed : [listed];
|
|
876
|
+
const valid = audiences.filter((value) => typeof value === "string" && value !== "");
|
|
877
|
+
const [canonical, ...others] = valid;
|
|
878
|
+
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.");
|
|
879
|
+
return [canonical, ...others];
|
|
880
|
+
}
|
|
881
|
+
/** Whether a value, resolved against `base`, is an HTTPS URL. */
|
|
882
|
+
function httpsUrl(value, base) {
|
|
883
|
+
try {
|
|
884
|
+
return new URL(value, base).protocol === "https:";
|
|
885
|
+
} catch {
|
|
886
|
+
return false;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Refuses, at construction, a token policy that could never verify or document a token: a malformed
|
|
891
|
+
* `development`, an unknown `source`, `access` outside the `cloudflare-access` source, what that source
|
|
892
|
+
* refuses (see `checkAccessPolicy`, which checks its scopes against the application's `namespace`) and,
|
|
893
|
+
* unless the application issues its own bearer tokens or verifies Access tokens itself, an empty or unknown
|
|
894
|
+
* algorithm, a malformed claim mapping, a missing issuer, or an issuer or endpoint that is not an HTTPS URL.
|
|
895
|
+
* Verification is built on first use, so without this check such a policy would fail only at run time, as a
|
|
896
|
+
* 401 for every token and a 500 for the OpenAPI document. An application that issues its own bearer tokens
|
|
897
|
+
* names no authorization server.
|
|
898
|
+
*/
|
|
899
|
+
function checkTokenAuthority(policy, namespace) {
|
|
900
|
+
const { development } = policy;
|
|
901
|
+
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.");
|
|
902
|
+
if (policy.source !== void 0 && !TOKEN_SOURCES.has(policy.source)) throw new TypeError("tokens.source is authorization or cloudflare-access.");
|
|
903
|
+
const access = usesCloudflareAccess(policy);
|
|
904
|
+
if (policy.access !== void 0 && !access) throw new TypeError("tokens.access grants Cloudflare Access callers: set tokens.source to cloudflare-access.");
|
|
905
|
+
if (access) checkAccessPolicy(policy, namespace);
|
|
906
|
+
if (usesOwnBearer(policy) || access && policy.resolve !== void 0 && policy.issuer === void 0) return;
|
|
907
|
+
const { algorithms, claims } = policy;
|
|
908
|
+
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.");
|
|
909
|
+
if (claims !== void 0) {
|
|
910
|
+
const { permissions, machineSubject } = claims;
|
|
911
|
+
if ([
|
|
912
|
+
claims.organization,
|
|
913
|
+
claims.scopes,
|
|
914
|
+
claims.client,
|
|
915
|
+
permissions === false ? void 0 : permissions
|
|
916
|
+
].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}.");
|
|
917
|
+
}
|
|
918
|
+
const issuers = tokenIssuers(policy);
|
|
919
|
+
if (issuers.some((issuer) => !httpsUrl(issuer)) || [
|
|
920
|
+
policy.jwksUri,
|
|
921
|
+
policy.authorizationEndpoint,
|
|
922
|
+
policy.tokenEndpoint
|
|
923
|
+
].some((endpoint) => endpoint !== void 0 && !httpsUrl(endpoint, issuers[0]))) throw new TypeError("tokens.issuer, jwksUri, authorizationEndpoint and tokenEndpoint must be absolute HTTPS URLs, the last three resolved against the issuer.");
|
|
924
|
+
}
|
|
925
|
+
/** The authorization server's authorization and token endpoints, which OpenAPI publishes. */
|
|
926
|
+
function tokenEndpoints(policy) {
|
|
927
|
+
const issuer = tokenIssuer(policy);
|
|
928
|
+
return {
|
|
929
|
+
authorization: new URL(policy.authorizationEndpoint ?? "authorize", issuer).href,
|
|
930
|
+
token: new URL(policy.tokenEndpoint ?? "oauth/token", issuer).href
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Whether a token's `typ` header lets it be an access token: absent or `JWT`, a plain JWT, else RFC 9068's
|
|
935
|
+
* `at+jwt` (`application/at+jwt` in full), in any case. Any other type, such as `dpop+jwt` or `logout+jwt`,
|
|
936
|
+
* says the issuer's keys signed another kind of token.
|
|
937
|
+
*/
|
|
938
|
+
function accessTokenType(typ) {
|
|
939
|
+
if (typ === void 0) return true;
|
|
940
|
+
const type = typeof typ === "string" ? typ.toLowerCase().replace(/^application\//, "") : "";
|
|
941
|
+
return type === "jwt" || type === "at+jwt";
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Verifies OAuth access tokens against the issuer's JWKS and answers their claims, or throws for a token it
|
|
945
|
+
* refuses: the signature by one of the policy's algorithms (`RS256` by default), an `iss` that is one of the
|
|
946
|
+
* policy's issuers, an `aud` that names any one of the policy's audiences, `exp` and `sub`, with five seconds
|
|
947
|
+
* of clock tolerance, and a `typ` header, when the token has one, of a plain JWT or an RFC 9068 access token
|
|
948
|
+
* (`at+jwt`). The JWKS, at `jwksUri` resolved against the first issuer, is fetched within ten seconds and
|
|
949
|
+
* cached for ten minutes. An issuer or JWKS URL that is not HTTPS throws a TypeError at construction.
|
|
950
|
+
*/
|
|
951
|
+
function createTokenVerifier(policy) {
|
|
952
|
+
const issuers = tokenIssuers(policy);
|
|
953
|
+
const audience = tokenAudiences(policy);
|
|
954
|
+
const uri = new URL(policy.jwksUri ?? ".well-known/jwks.json", issuers[0]);
|
|
955
|
+
if (issuers.some((issuer) => new URL(issuer).protocol !== "https:") || uri.protocol !== "https:") throw new TypeError("Token authority must use HTTPS.");
|
|
956
|
+
const jwks = createRemoteJWKSet(uri, {
|
|
957
|
+
timeoutDuration: 1e4,
|
|
958
|
+
cacheMaxAge: 6e5,
|
|
959
|
+
cooldownDuration: 3e4
|
|
960
|
+
});
|
|
961
|
+
return async (token) => {
|
|
962
|
+
const { payload, protectedHeader } = await jwtVerify(token, jwks, {
|
|
963
|
+
issuer: issuers,
|
|
964
|
+
audience,
|
|
965
|
+
algorithms: [...policy.algorithms ?? ["RS256"]],
|
|
966
|
+
clockTolerance: 5,
|
|
967
|
+
requiredClaims: ["exp", "sub"]
|
|
968
|
+
});
|
|
969
|
+
if (!accessTokenType(protectedHeader.typ)) throw new Error("The token is typed as another kind of JWT than an access token.");
|
|
970
|
+
return payload;
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
/** The longest token admission reads; a longer one is refused unread. */
|
|
974
|
+
const MAX_TOKEN_LENGTH = 16384;
|
|
975
|
+
/** A compact JWS: three base64url segments separated by dots. */
|
|
976
|
+
const COMPACT_JWS = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
977
|
+
/** Any token: characters other than whitespace. */
|
|
978
|
+
const ANY_TOKEN = /^\S+$/;
|
|
979
|
+
/** The bearer token of a request's `Authorization` header, `Bearer <token>` in any case of the scheme. */
|
|
980
|
+
function bearerToken(request) {
|
|
981
|
+
return /^Bearer (\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* The token a request presents where the policy reads it: the bearer token of `Authorization` or, under the
|
|
985
|
+
* `cloudflare-access` source, the application token of `Cf-Access-Jwt-Assertion` and nothing else. Only a
|
|
986
|
+
* compact JWS is a token, unless the policy's own `resolve` verifies tokens, or, read from `Authorization`,
|
|
987
|
+
* the token may be the development token. Undefined when the request presents none, or one longer than 16384
|
|
988
|
+
* characters.
|
|
989
|
+
*/
|
|
990
|
+
function presentedToken(request, policy) {
|
|
991
|
+
const access = usesCloudflareAccess(policy);
|
|
992
|
+
const token = access ? request.headers.get(ACCESS_TOKEN_HEADER) : bearerToken(request);
|
|
993
|
+
const shape = policy.resolve || policy.development && !access ? ANY_TOKEN : COMPACT_JWS;
|
|
994
|
+
return token && token.length <= MAX_TOKEN_LENGTH && shape.test(token) ? token : void 0;
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Admits a request by its token: verifies it (the development token, a bearer token from a local host; else
|
|
998
|
+
* the policy's own `resolve` when it has one; else, for OAuth, against the issuer's JWKS, or for Cloudflare
|
|
999
|
+
* Access, against the team's keys, projected by `access`) and checks that its scopes admit the request. The
|
|
1000
|
+
* token is the bearer token of `Authorization`, or under the `cloudflare-access` source the application token
|
|
1001
|
+
* of `Cf-Access-Jwt-Assertion` alone. A request without a token, with one longer than 16384 characters, or
|
|
1002
|
+
* with an `x-api-key` header is refused; without `resolve` (or, for a bearer token, a development token), the
|
|
1003
|
+
* token must be a compact JWS. Refusals are `UNAUTHORIZED` or `FORBIDDEN` failures, never exceptions. `given`
|
|
1004
|
+
* stands in for the JWKS check in tests, answering a token's claims.
|
|
1005
|
+
*/
|
|
1006
|
+
function createTokenAuthorization(policy, given) {
|
|
1007
|
+
let verifier = given;
|
|
1008
|
+
/** Verifies an OAuth access token, building the verifier on first use. */
|
|
1009
|
+
const verify = (token) => {
|
|
1010
|
+
verifier ??= createTokenVerifier(policy);
|
|
1011
|
+
return verifier(token);
|
|
1012
|
+
};
|
|
1013
|
+
/** The principal a verified token's claims grant: Access's projection, or the OAuth claim mapping. */
|
|
1014
|
+
const project = (claims) => usesCloudflareAccess(policy) ? projectAccessToken(claims, policy) : projectToken(claims, policy.claims);
|
|
1015
|
+
/**
|
|
1016
|
+
* Admits the request when its token carries `scope` or, for a list, any one of them (every one with
|
|
1017
|
+
* `scopeMatch` `all`).
|
|
1018
|
+
*/
|
|
1019
|
+
return async (request, scope, context, scopeMatch = "any") => {
|
|
1020
|
+
const accepted = typeof scope === "string" ? [scope] : scope;
|
|
1021
|
+
/** Whether granted scopes admit the request. */
|
|
1022
|
+
const admits = (scopes) => matchesScopes(accepted, scopes, scopeMatch);
|
|
1023
|
+
if (request.headers.has("x-api-key")) return err(standardErrors.unauthorized.create());
|
|
1024
|
+
const bearer = bearerToken(request);
|
|
1025
|
+
if (policy.development && context && bearer && bearer.length <= MAX_TOKEN_LENGTH && await isDevelopmentToken(policy.development, bearer, request, context.env)) {
|
|
1026
|
+
const developer = {
|
|
1027
|
+
actorId: "local-developer",
|
|
1028
|
+
actorKind: "user",
|
|
1029
|
+
organizationId: policy.development.organizationId ?? "local-development",
|
|
1030
|
+
scopes: [...context.applicationScopes],
|
|
1031
|
+
client: {
|
|
1032
|
+
id: "local-development",
|
|
1033
|
+
class: "human"
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
return admits(developer.scopes) ? ok(developer) : err(standardErrors.forbidden.create());
|
|
1037
|
+
}
|
|
1038
|
+
const token = presentedToken(request, policy);
|
|
1039
|
+
if (!token) return err(standardErrors.unauthorized.create());
|
|
1040
|
+
if (policy.resolve) try {
|
|
1041
|
+
const outcome = await policy.resolve(token, context);
|
|
1042
|
+
if ("ok" in outcome && !outcome.ok) return err(outcome.error.code === "FORBIDDEN" ? standardErrors.forbidden.create() : standardErrors.unauthorized.create());
|
|
1043
|
+
const resolved = parseInput(TokenPrincipalSchema, "ok" in outcome ? outcome.value : outcome);
|
|
1044
|
+
if (!resolved.ok) return err(standardErrors.unauthorized.create());
|
|
1045
|
+
const { client } = resolved.value;
|
|
1046
|
+
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());
|
|
1047
|
+
return admits(resolved.value.scopes) ? ok(resolved.value) : err(standardErrors.forbidden.create());
|
|
1048
|
+
} catch {
|
|
1049
|
+
return err(standardErrors.unauthorized.create());
|
|
1050
|
+
}
|
|
1051
|
+
let claims;
|
|
1052
|
+
try {
|
|
1053
|
+
claims = await verify(token);
|
|
1054
|
+
} catch {
|
|
1055
|
+
return err(standardErrors.unauthorized.create());
|
|
1056
|
+
}
|
|
1057
|
+
const principal = project(claims);
|
|
1058
|
+
if (!principal.ok) return principal;
|
|
1059
|
+
return admits(principal.value.scopes) ? principal : err(standardErrors.forbidden.create());
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// src/openapi.ts
|
|
1064
|
+
/**
|
|
1065
|
+
* An application's OpenAPI 3.1 document, as its origin serves it and as SDK generators read it: one tag per
|
|
1066
|
+
* group of routes, and every request body, success envelope and failure a named component, so a generated
|
|
1067
|
+
* client reads `createNote(body: CreateNoteBody): NoteResponse`. The `x-*` extensions carry what OpenAPI
|
|
1068
|
+
* cannot say: scopes, effects, limits, MCP tools and native RPC.
|
|
1069
|
+
*/
|
|
1070
|
+
/** The standard failures only routing answers, before a request reaches any operation's route. */
|
|
1071
|
+
const ROUTING_CODES = /* @__PURE__ */ new Set(["NOT_FOUND", "HTTP_METHOD_NOT_ALLOWED"]);
|
|
1072
|
+
/** The headers every answer, and a failure that asks for a wait, carry, as the document's components. */
|
|
1073
|
+
const HEADERS = {
|
|
1074
|
+
RequestId: {
|
|
1075
|
+
description: "Request correlation identifier.",
|
|
1076
|
+
schema: { type: "string" }
|
|
1077
|
+
},
|
|
1078
|
+
RetryAfter: {
|
|
1079
|
+
description: "Seconds before another attempt.",
|
|
1080
|
+
schema: {
|
|
1081
|
+
type: "integer",
|
|
1082
|
+
minimum: 0
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
/** A reference to one of `HEADERS`. */
|
|
1087
|
+
function headerReference(name) {
|
|
1088
|
+
return { $ref: `#/components/headers/${name}` };
|
|
1089
|
+
}
|
|
1090
|
+
/** Whether an object schema holds no field at all, so that `{}` is its one value. */
|
|
1091
|
+
function isEmptyObject(schema) {
|
|
1092
|
+
return schema.type === "object" && Object.keys(schema.properties ?? {}).length === 0 && schema.patternProperties === void 0 && schema.additionalProperties === false;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* A request body without the fields its path carries, in each member of a union. An object that loses
|
|
1096
|
+
* fields is no longer the schema its `$id` names, so it loses the name, and its property counts lose the
|
|
1097
|
+
* path's fields.
|
|
1098
|
+
*/
|
|
1099
|
+
function bodyWithoutPathParameters(input, names) {
|
|
1100
|
+
if (input.type !== "object") {
|
|
1101
|
+
const { $id: _id, ...union } = input;
|
|
1102
|
+
return {
|
|
1103
|
+
...union,
|
|
1104
|
+
anyOf: input.anyOf.map((schema) => bodyWithoutPathParameters(schema, names))
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
const carried = Object.keys(input.properties ?? {}).filter((name) => names.has(name)).length;
|
|
1108
|
+
if (!carried) return input;
|
|
1109
|
+
const { $id: _id, minProperties, maxProperties, ...object } = input;
|
|
1110
|
+
return {
|
|
1111
|
+
...object,
|
|
1112
|
+
properties: Object.fromEntries(Object.entries(input.properties).filter(([name]) => !names.has(name))),
|
|
1113
|
+
required: (input.required ?? []).filter((name) => !names.has(name)),
|
|
1114
|
+
...typeof minProperties === "number" && minProperties > carried ? { minProperties: minProperties - carried } : {},
|
|
1115
|
+
...typeof maxProperties === "number" ? { maxProperties: maxProperties - carried } : {}
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* The document the origin serves at `/openapi.json`: every public operation that declares an HTTP route,
|
|
1120
|
+
* never an internal one, under one tag per group. Each request body, success envelope and failure is a named
|
|
1121
|
+
* component, which a generated client names its types after; each operation also carries its scopes,
|
|
1122
|
+
* effect, limits in force, MCP tool hints and native RPC as `x-*` extensions.
|
|
1123
|
+
*
|
|
1124
|
+
* Every schema reference in it is a local `#/components/schemas/<name>` pointer: the `$id`-named
|
|
1125
|
+
* schemas of its paths and components (TypeBox Recursive/Ref) become components, as `bundleSchemas`
|
|
1126
|
+
* describes. A schema `$id` that takes the name of a component the document writes itself, and a component
|
|
1127
|
+
* named as a generator names an operation's own types, such as `CreateNoteResponse`, throw a TypeError.
|
|
1128
|
+
*/
|
|
1129
|
+
function createOpenApi(manifest, options) {
|
|
1130
|
+
const document = openApiDocument(manifest, "http");
|
|
1131
|
+
if (options?.operationExtensions) {
|
|
1132
|
+
const paths = document.paths;
|
|
1133
|
+
for (const methods of Object.values(paths)) for (const declared of Object.values(methods)) {
|
|
1134
|
+
const name = String(declared.operationId);
|
|
1135
|
+
const operation = manifest.operations[name];
|
|
1136
|
+
if (!operation) throw new TypeError("The document names an undeclared operation.");
|
|
1137
|
+
const extensions = options.operationExtensions(name, operation);
|
|
1138
|
+
if (Object.keys(extensions).some((key) => !key.startsWith("x-"))) throw new TypeError("OpenAPI extensions must use x- names.");
|
|
1139
|
+
Object.assign(declared, extensions);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
return bundledDocument(document, manifest);
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* The document of the operations an application serves over native RPC, which another service binds to:
|
|
1146
|
+
* each operation that declares `rpc`, internal ones and tools included, as `POST /rpc/<name>` whose body is
|
|
1147
|
+
* the operation's whole input, with its answer and failures named as in the HTTP document. No HTTP route
|
|
1148
|
+
* answers these paths: each names a method of the Worker's `Service` entrypoint, which a Service Binding
|
|
1149
|
+
* calls with the caller's principal. `maximus openapi` writes it to `rpc.openapi.json`, and a caller's
|
|
1150
|
+
* `services` option types its binding from it.
|
|
1151
|
+
*/
|
|
1152
|
+
function createRpcOpenApi(manifest) {
|
|
1153
|
+
return bundledDocument(openApiDocument(manifest, "rpc"), manifest);
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* A document with its `$id`-named schemas bundled into components, every component in name order, after the
|
|
1157
|
+
* names it publishes are checked.
|
|
1158
|
+
*/
|
|
1159
|
+
function bundledDocument(document, manifest) {
|
|
1160
|
+
const own = Object.entries(document.components.schemas);
|
|
1161
|
+
const sources = [document.paths, ...own.map(([, schema]) => schema)];
|
|
1162
|
+
checkComponentNames(own.map(([name]) => name), schemaIds(sources), Object.keys(manifest.operations));
|
|
1163
|
+
const bundled = bundleSchemas(sources, document.components.schemas);
|
|
1164
|
+
const [paths, ...schemas] = bundled.values;
|
|
1165
|
+
const named = {
|
|
1166
|
+
...Object.fromEntries(own.map(([name], index) => [name, schemas[index]])),
|
|
1167
|
+
...bundled.components
|
|
1168
|
+
};
|
|
1169
|
+
return {
|
|
1170
|
+
...document,
|
|
1171
|
+
paths,
|
|
1172
|
+
components: {
|
|
1173
|
+
...document.components,
|
|
1174
|
+
schemas: Object.fromEntries(Object.entries(named).toSorted(([a], [b]) => a < b ? -1 : Number(a > b)))
|
|
1175
|
+
}
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Refuses the names a document cannot publish: a schema `$id` that takes the name of a component the document
|
|
1180
|
+
* writes itself, which bundling would otherwise rename, and a component a generator would name an operation's
|
|
1181
|
+
* own types after (`CreateNoteResponse` for `createNote`).
|
|
1182
|
+
*/
|
|
1183
|
+
function checkComponentNames(own, ids, operations) {
|
|
1184
|
+
const taken = new Set(own);
|
|
1185
|
+
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.`);
|
|
1186
|
+
const generated = new Map(operations.flatMap((operation) => generatedNames(operation).map((name) => [name, operation])));
|
|
1187
|
+
for (const name of [...own, ...ids]) {
|
|
1188
|
+
const operation = generated.get(name);
|
|
1189
|
+
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.`);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* The operations a document lists: for the HTTP document, each public operation that declares a route, at that
|
|
1194
|
+
* route; for the RPC document, each operation that declares `rpc`, at `POST /rpc/<name>`. Each keeps the group
|
|
1195
|
+
* its route gives it.
|
|
1196
|
+
*/
|
|
1197
|
+
function documentedOperations(manifest, kind) {
|
|
1198
|
+
return Object.entries(manifest.operations).flatMap(([name, op]) => {
|
|
1199
|
+
const group = op.group ?? (op.http ? routeGroup(op.http.path) : void 0) ?? manifest.title;
|
|
1200
|
+
if (kind === "rpc") return op.rpc ? [{
|
|
1201
|
+
name,
|
|
1202
|
+
op,
|
|
1203
|
+
http: {
|
|
1204
|
+
method: "POST",
|
|
1205
|
+
path: `/rpc/${name}`
|
|
1206
|
+
},
|
|
1207
|
+
group
|
|
1208
|
+
}] : [];
|
|
1209
|
+
return op.http && isPublicOperation(op) ? [{
|
|
1210
|
+
name,
|
|
1211
|
+
op,
|
|
1212
|
+
http: op.http,
|
|
1213
|
+
group
|
|
1214
|
+
}] : [];
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
/**
|
|
1218
|
+
* Refuses a description of a group no document lists: each name `groups` describes must be the group of a
|
|
1219
|
+
* public route or of an operation served over native RPC.
|
|
1220
|
+
*/
|
|
1221
|
+
function checkDescribedGroups(manifest) {
|
|
1222
|
+
const described = Object.keys(manifest.groups ?? {});
|
|
1223
|
+
if (!described.length) return;
|
|
1224
|
+
const listed = new Set([...documentedOperations(manifest, "http"), ...documentedOperations(manifest, "rpc")].map(({ group }) => group));
|
|
1225
|
+
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"}.`);
|
|
1226
|
+
}
|
|
1227
|
+
/** What an RPC document says about itself, in place of servers its paths do not have. */
|
|
1228
|
+
function rpcDescription(title) {
|
|
1229
|
+
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.`;
|
|
1230
|
+
}
|
|
1231
|
+
/** The document `createOpenApi` or `createRpcOpenApi` builds, before its `$id`-named schemas are bundled. */
|
|
1232
|
+
function openApiDocument(manifest, kind) {
|
|
1233
|
+
const entries = documentedOperations(manifest, kind);
|
|
1234
|
+
const rpc = kind === "rpc";
|
|
1235
|
+
const scopes = Object.fromEntries(entries.flatMap(({ op }) => [...operationScopes(op), ...op.conditionalScopes ?? []].map((scope) => [scope, scopeDescription(scope)])));
|
|
1236
|
+
const components = new ComponentSchemas();
|
|
1237
|
+
if (entries.length) components.add("ResponseMetadata", RESPONSE_METADATA);
|
|
1238
|
+
const headers = new Set(entries.length ? ["RequestId"] : []);
|
|
1239
|
+
const groups = [];
|
|
1240
|
+
const paths = {};
|
|
1241
|
+
for (const { name, op, http, group } of entries) {
|
|
1242
|
+
if (!groups.includes(group)) groups.push(group);
|
|
1243
|
+
const request = rpc ? rpcRequest(name, op, components) : requestContract(name, op, http, components);
|
|
1244
|
+
const failures = failureResponses(name, op, !rpc && "requestBody" in request, manifest.errors.definitions, components);
|
|
1245
|
+
if (Object.values(failures).some((response) => "Retry-After" in response.headers)) headers.add("RetryAfter");
|
|
1246
|
+
(paths[http.path] ??= {})[http.method.toLowerCase()] = {
|
|
1247
|
+
operationId: name,
|
|
1248
|
+
summary: op.title,
|
|
1249
|
+
...op.description ? { description: op.description } : {},
|
|
1250
|
+
tags: [group],
|
|
1251
|
+
...rpc ? rpcExtensions(manifest, op) : httpExtensions(manifest, op, http),
|
|
1252
|
+
...request,
|
|
1253
|
+
responses: {
|
|
1254
|
+
[http.successStatus ?? 200]: successResponse(name, op, http, components),
|
|
1255
|
+
...failures
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
checkDescribedGroups(manifest);
|
|
1260
|
+
return JSON.parse(JSON.stringify({
|
|
1261
|
+
openapi: "3.1.0",
|
|
1262
|
+
info: {
|
|
1263
|
+
title: manifest.title,
|
|
1264
|
+
version: manifest.version,
|
|
1265
|
+
...rpc ? { description: rpcDescription(manifest.title) } : {},
|
|
1266
|
+
...!rpc && manifest.description ? { description: manifest.description } : {}
|
|
1267
|
+
},
|
|
1268
|
+
...rpc ? {} : { servers: [{ url: manifest.origin }] },
|
|
1269
|
+
tags: groups.map((group) => {
|
|
1270
|
+
const description = manifest.groups?.[group];
|
|
1271
|
+
return description ? {
|
|
1272
|
+
name: group,
|
|
1273
|
+
description
|
|
1274
|
+
} : { name: group };
|
|
1275
|
+
}),
|
|
1276
|
+
paths,
|
|
1277
|
+
components: {
|
|
1278
|
+
schemas: components.schemas,
|
|
1279
|
+
...headers.size ? { headers: Object.fromEntries([...headers].map((name) => [name, HEADERS[name]])) } : {},
|
|
1280
|
+
...rpc || !entries.length ? {} : { securitySchemes: securitySchemes(manifest.tokens, scopes) }
|
|
1281
|
+
}
|
|
1282
|
+
}));
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* What an HTTP operation adds beside OpenAPI's own fields: the requirements that admit it, its scopes,
|
|
1286
|
+
* effect, MCP tool, native RPC and limits, and how its body and answer travel.
|
|
1287
|
+
*/
|
|
1288
|
+
function httpExtensions(manifest, op, http) {
|
|
1289
|
+
return {
|
|
1290
|
+
security: operationSecurity(op, manifest.tokens),
|
|
1291
|
+
"x-required-scopes": [...operationScopes(op)],
|
|
1292
|
+
...operationScopes(op).length > 1 ? { "x-scope-match": op.scopeMatch ?? "any" } : {},
|
|
1293
|
+
...op.conditionalScopes ? { "x-conditional-scopes": op.conditionalScopes } : {},
|
|
1294
|
+
"x-effect": op.effect,
|
|
1295
|
+
...op.mcp ? {
|
|
1296
|
+
"x-mcp-tool": op.mcp.name,
|
|
1297
|
+
"x-mcp-idempotent": op.mcp.idempotent,
|
|
1298
|
+
"x-mcp-open-world": mcpOpenWorld(op.mcp)
|
|
1299
|
+
} : {},
|
|
1300
|
+
"x-native-rpc": Boolean(op.rpc),
|
|
1301
|
+
"x-max-body-bytes": operationBodyLimit(manifest, op),
|
|
1302
|
+
"x-max-output-bytes": operationOutputLimit(manifest, op),
|
|
1303
|
+
...http.body ? {
|
|
1304
|
+
"x-body": http.body,
|
|
1305
|
+
"x-input-headers": http.headers ?? {}
|
|
1306
|
+
} : {},
|
|
1307
|
+
...http.response ? { "x-response": http.response } : {}
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* What a native RPC operation adds beside OpenAPI's own fields: its effect, the callers that may call it,
|
|
1312
|
+
* and the output limit in force. A Service Binding names its caller, so it has no security requirement.
|
|
1313
|
+
*/
|
|
1314
|
+
function rpcExtensions(manifest, op) {
|
|
1315
|
+
return {
|
|
1316
|
+
"x-effect": op.effect,
|
|
1317
|
+
"x-native-rpc": true,
|
|
1318
|
+
"x-rpc-callers": op.rpc === true ? [...manifest.rpc.callers] : [...op.rpc?.callers ?? []],
|
|
1319
|
+
"x-max-output-bytes": operationOutputLimit(manifest, op)
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
/** A scope as people read it: `notes:notes:read` reads notes, `notes:task-lists:write` writes task lists. */
|
|
1323
|
+
function scopeDescription(scope) {
|
|
1324
|
+
const [namespace, resource, action, ...deeper] = scope.split(":");
|
|
1325
|
+
if (namespace === void 0 || resource === void 0 || deeper.length) return scope;
|
|
1326
|
+
const words = resource.replaceAll("-", " ");
|
|
1327
|
+
if (action === "read") return `Read ${words}.`;
|
|
1328
|
+
if (action === "write") return `Create, change and delete ${words}.`;
|
|
1329
|
+
return scope;
|
|
1330
|
+
}
|
|
1331
|
+
/** Whether a body schema requires a field, so no empty body is valid: a union does when each member does. */
|
|
1332
|
+
function requiresField(schema) {
|
|
1333
|
+
const node = schema;
|
|
1334
|
+
return node.anyOf ? node.anyOf.every(requiresField) : (node.required ?? []).length > 0;
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* A parameter, described on the parameter itself, where generators read it: by its schema's description, or
|
|
1338
|
+
* else by its name in words (`noteId` is `The note id.`).
|
|
1339
|
+
*/
|
|
1340
|
+
function parameter(name, location, required, schema, style = {}) {
|
|
1341
|
+
const words = name.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2").replaceAll(/[_-]+/g, " ").toLowerCase();
|
|
1342
|
+
return {
|
|
1343
|
+
name,
|
|
1344
|
+
in: location,
|
|
1345
|
+
required,
|
|
1346
|
+
description: typeof schema.description === "string" ? schema.description : `The ${words}.`,
|
|
1347
|
+
...style,
|
|
1348
|
+
schema
|
|
1349
|
+
};
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* Where an operation's input travels: its path parameters, then a byte body's query and header
|
|
1353
|
+
* metadata, a GET's query, or a JSON body without the fields the path carries. A DELETE whose input the
|
|
1354
|
+
* path carries whole sends no body.
|
|
1355
|
+
*/
|
|
1356
|
+
function requestContract(name, op, http, components) {
|
|
1357
|
+
const input = wireInput(op.input);
|
|
1358
|
+
const parameterNames = operationPathParameters(http.path);
|
|
1359
|
+
const pathNames = new Set(parameterNames);
|
|
1360
|
+
const pathParameters = parameterNames.map((pathName) => {
|
|
1361
|
+
const schemas = pathParameterSchemas(input, pathName);
|
|
1362
|
+
return parameter(pathName, "path", true, schemas.length === 1 && schemas[0] ? schemas[0] : Type.Union(schemas));
|
|
1363
|
+
});
|
|
1364
|
+
const properties = input.properties ?? {};
|
|
1365
|
+
const required = input.required ?? [];
|
|
1366
|
+
const fields = Object.entries(properties).filter(([field]) => !pathNames.has(field));
|
|
1367
|
+
if (http.body === "bytes") return {
|
|
1368
|
+
parameters: [...pathParameters, ...fields.map(([field, schema]) => {
|
|
1369
|
+
const header = http.headers && Object.hasOwn(http.headers, field) ? http.headers[field] : void 0;
|
|
1370
|
+
return {
|
|
1371
|
+
...parameter(header ?? field, header ? "header" : "query", required.includes(field), schema),
|
|
1372
|
+
"x-input-field": field
|
|
1373
|
+
};
|
|
1374
|
+
})],
|
|
1375
|
+
requestBody: {
|
|
1376
|
+
required: true,
|
|
1377
|
+
content: { "application/octet-stream": { schema: {
|
|
1378
|
+
type: "string",
|
|
1379
|
+
format: "binary"
|
|
1380
|
+
} } }
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
if (http.method === "GET") {
|
|
1384
|
+
const kinds = queryKinds(op);
|
|
1385
|
+
return { parameters: [...pathParameters, ...fields.map(([field, schema]) => parameter(field, "query", required.includes(field), schema, kinds.get(field) === "list" ? {
|
|
1386
|
+
style: "form",
|
|
1387
|
+
explode: false
|
|
1388
|
+
} : {}))] };
|
|
1389
|
+
}
|
|
1390
|
+
const body = pathNames.size ? bodyWithoutPathParameters(input, pathNames) : input;
|
|
1391
|
+
const located = pathParameters.length ? { parameters: pathParameters } : {};
|
|
1392
|
+
if (http.method === "DELETE" && isEmptyObject(body)) return located;
|
|
1393
|
+
return {
|
|
1394
|
+
...located,
|
|
1395
|
+
requestBody: {
|
|
1396
|
+
required: http.method !== "DELETE" || requiresField(body),
|
|
1397
|
+
content: { "application/json": { schema: bodySchema(name, body, components) } }
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* The schema of a JSON request body: `Empty` for one without fields, which still travels as `{}`; the
|
|
1403
|
+
* input's own when it is named and the path carries none of it; else the component `<Operation>Body`, or
|
|
1404
|
+
* `<Operation>Input` for a native RPC method's whole input.
|
|
1405
|
+
*/
|
|
1406
|
+
function bodySchema(name, body, components, suffix = "Body") {
|
|
1407
|
+
if (isEmptyObject(body)) return components.add("Empty", EMPTY_OBJECT);
|
|
1408
|
+
if (typeof body.$id === "string") return body;
|
|
1409
|
+
return components.add(`${pascalCase(name)}${suffix}`, body);
|
|
1410
|
+
}
|
|
1411
|
+
/** A native RPC method's request: its whole input, as callers send it, which the method takes as one object. */
|
|
1412
|
+
function rpcRequest(name, op, components) {
|
|
1413
|
+
return { requestBody: {
|
|
1414
|
+
required: true,
|
|
1415
|
+
content: { "application/json": { schema: bodySchema(name, wireInput(op.input), components, "Input") } }
|
|
1416
|
+
} };
|
|
1417
|
+
}
|
|
1418
|
+
/** The success response: the JSON envelope, or a validated attachment's bytes and headers. */
|
|
1419
|
+
function successResponse(name, op, http, components) {
|
|
1420
|
+
const headers = { "X-Request-Id": headerReference("RequestId") };
|
|
1421
|
+
if (http.response !== "attachment") return {
|
|
1422
|
+
description: "Successful operation.",
|
|
1423
|
+
headers,
|
|
1424
|
+
content: { "application/json": { schema: successSchema(name, op.output, components) } }
|
|
1425
|
+
};
|
|
1426
|
+
return {
|
|
1427
|
+
description: "Successful operation.",
|
|
1428
|
+
content: { "application/octet-stream": { schema: {
|
|
1429
|
+
type: "string",
|
|
1430
|
+
format: "binary"
|
|
1431
|
+
} } },
|
|
1432
|
+
headers: {
|
|
1433
|
+
...headers,
|
|
1434
|
+
"Content-Type": {
|
|
1435
|
+
schema: { type: "string" },
|
|
1436
|
+
description: "Validated attachment media type."
|
|
1437
|
+
},
|
|
1438
|
+
"Content-Length": {
|
|
1439
|
+
schema: {
|
|
1440
|
+
type: "integer",
|
|
1441
|
+
minimum: 0
|
|
1442
|
+
},
|
|
1443
|
+
description: "Exact attachment byte length."
|
|
1444
|
+
},
|
|
1445
|
+
"Content-Disposition": {
|
|
1446
|
+
schema: { type: "string" },
|
|
1447
|
+
description: "Attachment filename in ASCII and RFC 5987 UTF-8 forms."
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* The component of a successful answer: named after its output's `$id` (`NoteResponse`, which every
|
|
1454
|
+
* operation that answers a note shares), `EmptyResponse` for an output without fields, and otherwise after
|
|
1455
|
+
* the operation, with its output as `<Operation>Result`.
|
|
1456
|
+
*/
|
|
1457
|
+
function successSchema(name, output, components) {
|
|
1458
|
+
if (isEmptyObject(output)) return components.add("EmptyResponse", successEnvelope(components.add("Empty", EMPTY_OBJECT)));
|
|
1459
|
+
const operation = pascalCase(name);
|
|
1460
|
+
if (typeof output.$id === "string") {
|
|
1461
|
+
const envelope = successEnvelope(output);
|
|
1462
|
+
const named = `${output.$id}Response`;
|
|
1463
|
+
return components.add(components.holdsOther(named, envelope) ? `${operation}ResultResponse` : named, envelope);
|
|
1464
|
+
}
|
|
1465
|
+
return components.add(`${operation}ResultResponse`, successEnvelope(components.add(`${operation}Result`, output)));
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* The failures an operation documents, one response per status, in catalog order: the standard failures
|
|
1469
|
+
* its route can meet, never routing's (an unknown path or method) and, when it sends no body, never a
|
|
1470
|
+
* body's; then the domain failures it declares, or every one when it declares none.
|
|
1471
|
+
*/
|
|
1472
|
+
function failureResponses(name, op, sendsBody, definitions, components) {
|
|
1473
|
+
const statuses = /* @__PURE__ */ new Map();
|
|
1474
|
+
for (const definition of Object.values(definitions)) if (documentsFailure(op, sendsBody, definition.code)) statuses.set(definition.status, [...statuses.get(definition.status) ?? [], definition]);
|
|
1475
|
+
return Object.fromEntries([...statuses].map(([status, failures]) => [status, failureResponse(name, status, failures, components)]));
|
|
1476
|
+
}
|
|
1477
|
+
/** Whether an operation's document lists a failure, as `failureResponses` describes. */
|
|
1478
|
+
function documentsFailure(op, sendsBody, code) {
|
|
1479
|
+
if (ROUTING_CODES.has(code)) return false;
|
|
1480
|
+
if (BODY_CODES.has(code)) return sendsBody;
|
|
1481
|
+
return STANDARD_CODES.has(code) || !op.failures || op.failures.includes(code);
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* One status an operation documents: each failure as its component, and the envelope of the answer, named
|
|
1485
|
+
* after its code when it is the status's only one (`NoteNotFoundError`), else after the operation and the
|
|
1486
|
+
* status (`ListNotesBadRequestError`), whose failures a discriminator on `code` tells apart.
|
|
1487
|
+
*/
|
|
1488
|
+
function failureResponse(name, status, failures, components) {
|
|
1489
|
+
for (const failure of failures) addFailure(failure, components);
|
|
1490
|
+
const codes = failures.map(({ code }) => code);
|
|
1491
|
+
const [only] = codes;
|
|
1492
|
+
const statusName = `${pascalCase(name)}${statusReason(status)}`;
|
|
1493
|
+
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))));
|
|
1494
|
+
const lines = failures.map((failure) => `\`${failure.code}\`: ${failure.message}`);
|
|
1495
|
+
return {
|
|
1496
|
+
description: lines.length === 1 && lines[0] !== void 0 ? lines[0] : lines.map((line) => `- ${line}`).join("\n"),
|
|
1497
|
+
headers: {
|
|
1498
|
+
"X-Request-Id": headerReference("RequestId"),
|
|
1499
|
+
...status === 429 || failures.some((failure) => failure.retryAfter) ? { "Retry-After": headerReference("RetryAfter") } : {}
|
|
1500
|
+
},
|
|
1501
|
+
"x-failure-codes": codes,
|
|
1502
|
+
content: { "application/json": { schema: envelope } }
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
/** A failure as its component, `<Code>Failure`, with its data: the schema its definition declares, else `Empty`. */
|
|
1506
|
+
function addFailure(definition, components) {
|
|
1507
|
+
const { dataSchema } = definition;
|
|
1508
|
+
let data;
|
|
1509
|
+
if (dataSchema === void 0 || isEmptyObject(dataSchema)) data = components.add("Empty", EMPTY_OBJECT);
|
|
1510
|
+
else if (typeof dataSchema.$id === "string") data = dataSchema;
|
|
1511
|
+
else data = components.add(`${failureName(definition.code)}Data`, dataSchema);
|
|
1512
|
+
components.add(failureName(definition.code), failureSchema(definition, data));
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* The security requirements that admit an operation, any one of which is enough: its scopes as
|
|
1516
|
+
* OAuth requirements (all of them in one requirement when it needs all), or the application's own
|
|
1517
|
+
* bearer tokens. With both schemes, users present OAuth tokens and services the application's own.
|
|
1518
|
+
* Behind Cloudflare Access, a client presents a service token's two headers together.
|
|
1519
|
+
*/
|
|
1520
|
+
function operationSecurity(op, tokens) {
|
|
1521
|
+
if (usesCloudflareAccess(tokens)) return [{
|
|
1522
|
+
accessClientId: [],
|
|
1523
|
+
accessClientSecret: []
|
|
1524
|
+
}];
|
|
1525
|
+
let security;
|
|
1526
|
+
if (tokens.scheme?.type === "bearer") security = [{ bearer: [] }];
|
|
1527
|
+
else if (op.scopeMatch === "all") security = [{ oauth2: [...operationScopes(op)] }];
|
|
1528
|
+
else security = operationScopes(op).map((scope) => ({ oauth2: [scope] }));
|
|
1529
|
+
if (tokens.scheme?.type === "oauth+bearer") {
|
|
1530
|
+
const actors = op.actorKinds ?? [];
|
|
1531
|
+
if (!actors.includes("user")) security = [];
|
|
1532
|
+
if (actors.includes("service")) security.push({ bearer: [] });
|
|
1533
|
+
}
|
|
1534
|
+
return security;
|
|
1535
|
+
}
|
|
1536
|
+
/**
|
|
1537
|
+
* How callers obtain a token: the OAuth 2.0 flows of the issuer (authorization code, and client
|
|
1538
|
+
* credentials unless services use the application's own tokens), the application's own bearer
|
|
1539
|
+
* tokens, or both. Behind Cloudflare Access, the headers of an Access service token, which Access
|
|
1540
|
+
* exchanges at the edge for the application token the API verifies; people sign in to Access in a
|
|
1541
|
+
* browser, which no scheme describes.
|
|
1542
|
+
*/
|
|
1543
|
+
function securitySchemes(tokens, scopes) {
|
|
1544
|
+
if (usesCloudflareAccess(tokens)) return {
|
|
1545
|
+
accessClientId: {
|
|
1546
|
+
type: "apiKey",
|
|
1547
|
+
in: "header",
|
|
1548
|
+
name: "CF-Access-Client-Id",
|
|
1549
|
+
description: "The Client ID of a Cloudflare Access service token, sent with its Client Secret."
|
|
1550
|
+
},
|
|
1551
|
+
accessClientSecret: {
|
|
1552
|
+
type: "apiKey",
|
|
1553
|
+
in: "header",
|
|
1554
|
+
name: "CF-Access-Client-Secret",
|
|
1555
|
+
description: "The Client Secret of the Cloudflare Access service token whose Client ID is sent."
|
|
1556
|
+
}
|
|
1557
|
+
};
|
|
1558
|
+
const { scheme } = tokens;
|
|
1559
|
+
if (scheme?.type === "bearer") return { bearer: {
|
|
1560
|
+
type: "http",
|
|
1561
|
+
scheme: "bearer",
|
|
1562
|
+
description: scheme.description
|
|
1563
|
+
} };
|
|
1564
|
+
const { authorization, token: tokenUrl } = tokenEndpoints(tokens);
|
|
1565
|
+
return {
|
|
1566
|
+
oauth2: {
|
|
1567
|
+
type: "oauth2",
|
|
1568
|
+
flows: {
|
|
1569
|
+
authorizationCode: {
|
|
1570
|
+
authorizationUrl: authorization,
|
|
1571
|
+
tokenUrl,
|
|
1572
|
+
scopes
|
|
1573
|
+
},
|
|
1574
|
+
...scheme?.type === "oauth+bearer" ? {} : { clientCredentials: {
|
|
1575
|
+
tokenUrl,
|
|
1576
|
+
scopes
|
|
1577
|
+
} }
|
|
1578
|
+
}
|
|
1579
|
+
},
|
|
1580
|
+
...scheme?.type === "oauth+bearer" ? { bearer: {
|
|
1581
|
+
type: "http",
|
|
1582
|
+
scheme: "bearer",
|
|
1583
|
+
description: scheme.description
|
|
1584
|
+
} } : {}
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
export { operationOutputLimit as A, MAX_BODY_BYTES_CEILING as C, mcpOpenWorld as D, isPublicOperation as E, isNamespacedScope as M, matchesScopes as N, operation as O, DEFAULT_MAX_BODY_BYTES as S, composeOperations as T, projectAccessToken as _, createTokenVerifier as a, ADMISSION_CODES as b, tokenIssuer as c, canonical as d, hasSchemaReferences as f, isCrossSiteWrite as g, queryKinds as h, createTokenAuthorization as i, operationScopes as j, operationMatchesScopes as k, usesOwnBearer as l, queryInput as m, createRpcOpenApi as n, projectToken as o, standaloneSchema as p, checkTokenAuthority as r, tokenAudiences as s, createOpenApi as t, sha256Hex as u, usesCloudflareAccess as v, STANDARD_CODES as w, BODY_CODES as x, PrincipalSchema as y };
|