@arbol-ai/maximus 7.3.1 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-CfVZBt7D.js +336 -0
- package/dist/chunks/errors-WfyKhiyk.js +131 -0
- package/dist/chunks/execution-CfZEx_JP.js +84 -0
- package/dist/chunks/generate-C-9FKW0o.js +197 -0
- package/dist/chunks/handler-DWTGoduQ.js +140 -0
- package/dist/chunks/http-layout-_h7xwgPC.js +128 -0
- package/dist/chunks/http-paths-DMBxwpp6.js +218 -0
- package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
- package/dist/chunks/names-ncD7A3DV.js +280 -0
- package/dist/chunks/openapi-CV0KmJpS.js +1588 -0
- package/dist/chunks/openapi-file-OjSs9mRv.js +83 -0
- package/dist/chunks/pages-DyC0m8Zb.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-BPnaa-NK.js → runtime-CVVf5hmp.js} +50 -25
- 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-CCc7fil4.js +410 -0
- package/dist/chunks/src--HZrH1U9.js +568 -0
- package/dist/chunks/standard-failures-CLjxS2ea.js +74 -0
- package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
- package/dist/chunks/{types-BWxDd3tY.d.ts → types-BQYB4Ads.d.ts} +998 -337
- package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
- package/dist/chunks/workers-types-iONp32T4.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 -125
- package/dist/http-paths.d.ts +1 -1
- package/dist/http-paths.js +1 -197
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -10
- package/dist/internals.d.ts +1 -1
- package/dist/internals.js +5 -3
- 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 +139 -0
- package/dist/project/config.js +196 -0
- 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 -72
- package/dist/tooling/cli.js +151 -107
- 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 +30 -22
- package/skills/maximus/SKILL.md +165 -69
- 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 -22
- package/templates/project/README.md.template +54 -47
- package/templates/project/middleware/10-response.ts.template +16 -0
- package/templates/project/package.json.template +16 -8
- 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 -5
- 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/execution-B-yy4C7N.js +0 -691
- package/dist/chunks/prepare-project-zi106pWF.js +0 -146
- package/dist/chunks/record-DY-lX9w1.js +0 -34
- package/dist/chunks/src-DPSpGNnT.js +0 -1164
- 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 -44
- 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 -39
- package/templates/project/cloudflare.config.ts.template +0 -24
- package/templates/project/routes/v1/greeting.ts.template +0 -22
- package/templates/project/src/app.ts.template +0 -2
- package/templates/project/src/application.ts.template +0 -26
- package/templates/project/src/index.ts.template +0 -3
- package/templates/project/src/worker.ts.template +0 -6
- 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,568 @@
|
|
|
1
|
+
import { i as standardErrors } from "./errors-WfyKhiyk.js";
|
|
2
|
+
import { r as readBodyText } from "./body-DOIHwIIl.js";
|
|
3
|
+
import { i as binaryBody, n as defineApp, r as attachmentResponse } from "./define-app-CfVZBt7D.js";
|
|
4
|
+
import { t as createHttpRouteResolver } from "./http-paths-DMBxwpp6.js";
|
|
5
|
+
import { r as ok, t as err } from "./result-CKgZHrnj.js";
|
|
6
|
+
import { E as isPublicOperation, S as DEFAULT_MAX_BODY_BYTES, T as composeOperations, c as tokenIssuer, g as isCrossSiteWrite, h as queryKinds, i as createTokenAuthorization, j as operationScopes, k as operationMatchesScopes, m as queryInput, s as tokenAudiences, t as createOpenApi, u as sha256Hex } from "./openapi-CV0KmJpS.js";
|
|
7
|
+
import { a as telemetryEnabled, i as reportUnexpected, n as recordAdmission, r as recordExecution, s as withTelemetry } from "./telemetry-C3LfZcOB.js";
|
|
8
|
+
import { t as executeOperation } from "./execution-CfZEx_JP.js";
|
|
9
|
+
import { a as ownsPrefix, i as nativePaths, n as composition, o as servesCloudflareAccess, r as httpTransports, s as servesOwnBearer, t as VERSIONED_PATH } from "./http-layout-_h7xwgPC.js";
|
|
10
|
+
import { n as mediaType } from "./json-B14evE6-.js";
|
|
11
|
+
import { t as toYaml } from "./yaml-Dk2L24yQ.js";
|
|
12
|
+
import { Type as Type$1, Type as t } from "@sinclair/typebox";
|
|
13
|
+
|
|
14
|
+
// src/builder.ts
|
|
15
|
+
/**
|
|
16
|
+
* An application under construction, as `maximus()` starts it. Every method returns a new builder and leaves
|
|
17
|
+
* this one unchanged, so resource modules built from one base share its inferred context without overwriting
|
|
18
|
+
* each other's operations.
|
|
19
|
+
*/
|
|
20
|
+
var ApplicationBuilder = class ApplicationBuilder {
|
|
21
|
+
/**
|
|
22
|
+
* The application declared so far: its configuration, context preparation, middleware and operations, which
|
|
23
|
+
* `.build()` checks.
|
|
24
|
+
*/
|
|
25
|
+
definition;
|
|
26
|
+
root;
|
|
27
|
+
/**
|
|
28
|
+
* Wraps `definition`. `root` identifies the application the builder descends from, and `.mount()` admits
|
|
29
|
+
* only modules of the same one. Start an application with `maximus()` instead.
|
|
30
|
+
*/
|
|
31
|
+
constructor(definition, root = definition) {
|
|
32
|
+
this.definition = definition;
|
|
33
|
+
this.root = root;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Declares an operation: a camelCase name no other operation uses, its definition (scope, words, effect,
|
|
37
|
+
* schemas and exposure) and its handler, which receives the prepared context and the decoded input and
|
|
38
|
+
* returns a Result. A name declared twice throws a TypeError, `Duplicate operation: <name>`.
|
|
39
|
+
*/
|
|
40
|
+
operation(name, definition, execute) {
|
|
41
|
+
const operations = composeOperations(this.definition.operations, { [name]: {
|
|
42
|
+
...definition,
|
|
43
|
+
execute,
|
|
44
|
+
pipeline: {
|
|
45
|
+
context: (invocation) => this.definition.context({
|
|
46
|
+
...invocation,
|
|
47
|
+
operation: name
|
|
48
|
+
}),
|
|
49
|
+
middleware: this.definition.middleware ?? []
|
|
50
|
+
}
|
|
51
|
+
} });
|
|
52
|
+
return new ApplicationBuilder({
|
|
53
|
+
...this.definition,
|
|
54
|
+
operations
|
|
55
|
+
}, this.root);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Adds what `resolve` returns to the context of every operation declared after it. It runs after admission
|
|
59
|
+
* and before the middleware; a failure it returns answers the call. Derive before declaring operations: on
|
|
60
|
+
* a builder that already has one, it throws a TypeError.
|
|
61
|
+
*/
|
|
62
|
+
derive(resolve) {
|
|
63
|
+
if (Object.keys(this.definition.operations).length) throw new TypeError("Derive context before declaring operations.");
|
|
64
|
+
const previous = this.definition.context;
|
|
65
|
+
return new ApplicationBuilder({
|
|
66
|
+
...this.definition,
|
|
67
|
+
context: async (invocation) => {
|
|
68
|
+
const context = await previous(invocation);
|
|
69
|
+
if (!context.ok) return context;
|
|
70
|
+
const derived = await resolve(context.value);
|
|
71
|
+
return derived.ok ? ok({
|
|
72
|
+
...context.value,
|
|
73
|
+
...derived.value
|
|
74
|
+
}) : derived;
|
|
75
|
+
}
|
|
76
|
+
}, this.root);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Wraps every operation declared after it, once the caller is admitted and the context prepared. The
|
|
80
|
+
* middleware calls `next` at most once.
|
|
81
|
+
*/
|
|
82
|
+
use(middleware) {
|
|
83
|
+
return new ApplicationBuilder({
|
|
84
|
+
...this.definition,
|
|
85
|
+
middleware: [...this.definition.middleware ?? [], middleware]
|
|
86
|
+
}, this.root);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Adds the operations of a resource module built from the same application; each keeps the context and
|
|
90
|
+
* middleware it was declared with. A module of another application, or one that declares an operation this
|
|
91
|
+
* builder has, throws a TypeError.
|
|
92
|
+
*/
|
|
93
|
+
mount(module) {
|
|
94
|
+
if (this.root !== module.root) throw new TypeError("Resource groups must derive from the same application.");
|
|
95
|
+
return new ApplicationBuilder({
|
|
96
|
+
...this.definition,
|
|
97
|
+
operations: composeOperations(this.definition.operations, module.definition.operations)
|
|
98
|
+
}, this.root);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Checks every rule the application must keep and returns it. A refusal is a TypeError whose message names
|
|
102
|
+
* the rule; most of the rules about one operation also name that operation.
|
|
103
|
+
*/
|
|
104
|
+
build() {
|
|
105
|
+
return defineApp()(this.definition);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Starts an application: its name, scope namespace, title, version, origin, token policy, error catalog and
|
|
110
|
+
* RPC callers, and its optional limits, rate limit, telemetry and MCP configuration. Chain `.derive()` and
|
|
111
|
+
* `.use()` to prepare each call, `.operation()` to declare operations, `.mount()` to compose resource modules
|
|
112
|
+
* that share this base, then `.build()`.
|
|
113
|
+
*/
|
|
114
|
+
function maximus(configuration) {
|
|
115
|
+
return new ApplicationBuilder({
|
|
116
|
+
...configuration,
|
|
117
|
+
operations: {},
|
|
118
|
+
context: (invocation) => Promise.resolve(ok(invocation))
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/oauth.ts
|
|
123
|
+
/** A scope token as RFC 6749 defines it: printable ASCII without spaces, quotes or backslashes. */
|
|
124
|
+
const SCOPE = /^[\u0021\u0023-\u005B\u005D-\u007E]+$/;
|
|
125
|
+
/** Whether a value is an HTTPS URL without credentials or a fragment, and, for an issuer, without a query. */
|
|
126
|
+
function httpsIdentifier(value, issuer) {
|
|
127
|
+
try {
|
|
128
|
+
const url = new URL(value);
|
|
129
|
+
return url.protocol === "https:" && !url.username && !url.password && !url.hash && (!issuer || !url.search);
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The RFC 9728 document of one resource: its `resource`, `authorization_servers`, `bearer_methods_supported`
|
|
136
|
+
* (`header`) and `scopes_supported`, read from configuration and the env, never from the request. It throws a
|
|
137
|
+
* TypeError when the audience or an issuer is not an HTTPS URL without credentials or a fragment (an issuer
|
|
138
|
+
* also without a query), when no issuer is named, or when a scope is malformed.
|
|
139
|
+
*/
|
|
140
|
+
function protectedResourceMetadata(resource, env) {
|
|
141
|
+
const audience = typeof resource.audience === "function" ? resource.audience(env) : resource.audience;
|
|
142
|
+
const servers = typeof resource.authorizationServers === "function" ? resource.authorizationServers(env) : resource.authorizationServers;
|
|
143
|
+
if (!httpsIdentifier(audience, false) || !servers.length || servers.some((server) => !httpsIdentifier(server, true)) || resource.scopes.some((scope) => !SCOPE.test(scope))) throw new TypeError("OAuth discovery requires HTTPS resource and issuer identifiers and valid scopes.");
|
|
144
|
+
return {
|
|
145
|
+
resource: audience,
|
|
146
|
+
authorization_servers: [...new Set(servers)],
|
|
147
|
+
bearer_methods_supported: ["header"],
|
|
148
|
+
scopes_supported: [...new Set(resource.scopes)]
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/http.ts
|
|
153
|
+
/**
|
|
154
|
+
* Serves an application over HTTP as one function, `(request, env, background?) => Promise<Response>`: its
|
|
155
|
+
* operations at their routes, the OpenAPI document as JSON and YAML, OAuth discovery, `/health`, transports
|
|
156
|
+
* such as MCP, plain routes and mounts. Every response but a protocol upgrade (101) carries `x-request-id`,
|
|
157
|
+
* `x-content-type-options: nosniff`, `server-timing` and `cache-control: private, no-store`, unless a plain
|
|
158
|
+
* route, mount, fallback or `before` hook sets its own `cache-control`. Construction throws a TypeError for a
|
|
159
|
+
* path two of them would claim, and for an option, token scheme or token source it cannot serve.
|
|
160
|
+
*/
|
|
161
|
+
function createHttpHandler(manifest, hooks = {}) {
|
|
162
|
+
if (hooks.origins && (!hooks.origins.length || hooks.origins.some((origin) => {
|
|
163
|
+
const url = new URL(origin);
|
|
164
|
+
return url.protocol !== "https:" || url.origin !== origin;
|
|
165
|
+
}))) throw new TypeError("HTTP origins must be exact HTTPS origins.");
|
|
166
|
+
for (const middleware of hooks.middleware ?? []) if (typeof middleware !== "function") throw new TypeError("Every HTTP middleware entry must be a function.");
|
|
167
|
+
const paths = nativePaths(manifest.tokens, hooks);
|
|
168
|
+
const authorize = createTokenAuthorization(manifest.tokens, hooks.verify);
|
|
169
|
+
const operations = Object.entries(manifest.operations);
|
|
170
|
+
const fallbackBodyBytes = manifest.maxBodyBytes ?? 32768;
|
|
171
|
+
const routes = createHttpRouteResolver(operations.map(([name, op]) => ({
|
|
172
|
+
name,
|
|
173
|
+
op,
|
|
174
|
+
http: op.http,
|
|
175
|
+
query: queryKinds(op)
|
|
176
|
+
})));
|
|
177
|
+
const transports = httpTransports(hooks.transports, manifest.mcp !== void 0);
|
|
178
|
+
const mcpTransport = transports.mcp;
|
|
179
|
+
/**
|
|
180
|
+
* The transport's operations a caller may run, those its scopes and actor kind admit: what sizes the body
|
|
181
|
+
* it may send, so no one else's large operation widens it.
|
|
182
|
+
*/
|
|
183
|
+
const runnableBy = (caller) => operations.filter(([, op]) => operationMatchesScopes(op, caller.scopes) && (!op.actorKinds || op.actorKinds.includes(caller.actorKind)));
|
|
184
|
+
const applicationScopes = Object.freeze([.../* @__PURE__ */ new Set([...operations.flatMap(([, op]) => [...operationScopes(op), ...op.conditionalScopes ?? []]), ...[...transports.byPath.values()].map((transport) => transport.scope(manifest.namespace))])]);
|
|
185
|
+
const ownBearer = servesOwnBearer(manifest.tokens, mcpTransport);
|
|
186
|
+
const access = servesCloudflareAccess(manifest.tokens, mcpTransport);
|
|
187
|
+
const oauth = !ownBearer && !access;
|
|
188
|
+
if (mcpTransport?.path === "/") paths.reserved.delete("/");
|
|
189
|
+
const composed = composition(paths, routes, transports, hooks);
|
|
190
|
+
let document;
|
|
191
|
+
/** The origin's OpenAPI document, built once on first use. */
|
|
192
|
+
const contract = () => {
|
|
193
|
+
document ??= createOpenApi(paths.base ? {
|
|
194
|
+
...manifest,
|
|
195
|
+
origin: `${manifest.origin}${paths.base}`
|
|
196
|
+
} : manifest);
|
|
197
|
+
return document;
|
|
198
|
+
};
|
|
199
|
+
/** The document's JSON and YAML texts, each serialized once on first use. */
|
|
200
|
+
const texts = {};
|
|
201
|
+
/** The origin's OpenAPI document as the text one of its URLs serves. */
|
|
202
|
+
const contractText = (format) => texts[format] ??= format === "json" ? JSON.stringify(contract()) : toYaml(contract());
|
|
203
|
+
/** The default RFC 9728 protected-resource metadata: the public scopes the origin serves. */
|
|
204
|
+
const metadata = () => ({
|
|
205
|
+
resource: tokenAudiences(manifest.tokens)[0],
|
|
206
|
+
resource_name: manifest.title,
|
|
207
|
+
authorization_servers: [tokenIssuer(manifest.tokens)],
|
|
208
|
+
bearer_methods_supported: ["header"],
|
|
209
|
+
scopes_supported: [.../* @__PURE__ */ new Set([...operations.filter(([, op]) => isPublicOperation(op) && (op.http || op.mcp && mcpTransport)).flatMap(([, op]) => operationScopes(op)), ...[...transports.byPath.values()].map((transport) => transport.scope(manifest.namespace))])],
|
|
210
|
+
resource_documentation: `${manifest.origin}${paths.mount("/openapi.json")}`
|
|
211
|
+
});
|
|
212
|
+
/** The failure envelope, with its status, its challenge and its Retry-After. */
|
|
213
|
+
function failure(value, requestId, context, suppliedHeaders) {
|
|
214
|
+
const error = manifest.errors.validate(value);
|
|
215
|
+
const headers = new Headers(suppliedHeaders);
|
|
216
|
+
headers.set("content-type", "application/json");
|
|
217
|
+
headers.set("cache-control", "private, no-store");
|
|
218
|
+
headers.set("x-content-type-options", "nosniff");
|
|
219
|
+
headers.set("x-request-id", requestId);
|
|
220
|
+
if (error.code === "UNAUTHORIZED" && !headers.has("www-authenticate")) {
|
|
221
|
+
const metadataUrl = oauth ? challengeMetadataUrl(context) : null;
|
|
222
|
+
headers.set("www-authenticate", metadataUrl === null ? "Bearer" : `Bearer resource_metadata="${metadataUrl}"`);
|
|
223
|
+
}
|
|
224
|
+
const retry = manifest.errors.retryAfter(error.code);
|
|
225
|
+
if (retry) headers.set("retry-after", String(error.code === "RATE_LIMITED" ? manifest.rateLimit?.retryAfter ?? retry : retry));
|
|
226
|
+
return Response.json({
|
|
227
|
+
success: false,
|
|
228
|
+
data: null,
|
|
229
|
+
error,
|
|
230
|
+
metadata: { requestId }
|
|
231
|
+
}, {
|
|
232
|
+
status: manifest.errors.status(error.code),
|
|
233
|
+
headers
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
/** The protected-resource metadata a 401 points at, or null when there is none to point at. */
|
|
237
|
+
function challengeMetadataUrl(context) {
|
|
238
|
+
const configured = manifest.tokens.resourceMetadataUrl;
|
|
239
|
+
if (typeof configured === "function") return configured(context);
|
|
240
|
+
if (configured !== void 0) return configured;
|
|
241
|
+
if (manifest.tokens.resources !== void 0 && paths.resources.size === 0) return null;
|
|
242
|
+
return `${manifest.origin}${paths.mount("/.well-known/oauth-protected-resource")}`;
|
|
243
|
+
}
|
|
244
|
+
/** The application's own GET documents: its index, its OpenAPI and its discovery metadata. */
|
|
245
|
+
function nativeDocument(nativePath, reject) {
|
|
246
|
+
switch (nativePath) {
|
|
247
|
+
case "/": return Response.json({
|
|
248
|
+
name: manifest.title,
|
|
249
|
+
openapi: paths.mount("/openapi.json"),
|
|
250
|
+
...mcpTransport ? { mcp: mcpTransport.path } : {}
|
|
251
|
+
});
|
|
252
|
+
case "/openapi.json": return new Response(contractText("json"), { headers: { "content-type": "application/json" } });
|
|
253
|
+
case "/openapi.yaml":
|
|
254
|
+
case "/openapi.yml": return new Response(contractText("yaml"), { headers: { "content-type": "application/yaml; charset=utf-8" } });
|
|
255
|
+
case "/.well-known/oauth-protected-resource":
|
|
256
|
+
case "/.well-known/oauth-protected-resource/mcp":
|
|
257
|
+
if (!oauth || manifest.tokens.resources !== void 0) return reject(standardErrors.notFound.create());
|
|
258
|
+
return Response.json(metadata(), { headers: { "access-control-allow-origin": "*" } });
|
|
259
|
+
default: return null;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/** Whether the rate limit binding still admits this caller; the key is a digest of who calls. */
|
|
263
|
+
async function withinRateLimit(env, caller) {
|
|
264
|
+
if (!manifest.rateLimit) return true;
|
|
265
|
+
const { success } = await env[manifest.rateLimit.binding].limit({ key: await sha256Hex(`${caller.organizationId}:${caller.actorId}`) });
|
|
266
|
+
return success;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Answers one request: dispatches it, turns an unexpected error into INTERNAL_ERROR, and sets the request
|
|
270
|
+
* id, cache and timing headers on every response.
|
|
271
|
+
*/
|
|
272
|
+
async function handle(incoming, env, background) {
|
|
273
|
+
const started = performance.now();
|
|
274
|
+
const requestId = crypto.randomUUID();
|
|
275
|
+
let principal = null;
|
|
276
|
+
let operation = null;
|
|
277
|
+
let surface = "http";
|
|
278
|
+
let plain = false;
|
|
279
|
+
let requestEnv = env;
|
|
280
|
+
const context = {
|
|
281
|
+
requestId,
|
|
282
|
+
fail: (error, headers) => failure(error, requestId, resolutionContext(), headers),
|
|
283
|
+
waitUntil: (promise) => {
|
|
284
|
+
if (background) background.waitUntil(promise);
|
|
285
|
+
else (async () => {
|
|
286
|
+
try {
|
|
287
|
+
await promise;
|
|
288
|
+
} catch (error) {
|
|
289
|
+
reportUnexpected(error, "route", requestId);
|
|
290
|
+
}
|
|
291
|
+
})();
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
/** What a token resolver and a challenge URL see of this request. */
|
|
295
|
+
const resolutionContext = () => ({
|
|
296
|
+
env: requestEnv,
|
|
297
|
+
request: incoming,
|
|
298
|
+
surface,
|
|
299
|
+
applicationScopes,
|
|
300
|
+
background
|
|
301
|
+
});
|
|
302
|
+
/** A refusal before execution, observed as a rejected admission. */
|
|
303
|
+
function reject(error) {
|
|
304
|
+
recordAdmission(manifest, requestEnv, background, {
|
|
305
|
+
principal,
|
|
306
|
+
operation,
|
|
307
|
+
surface,
|
|
308
|
+
requestId,
|
|
309
|
+
started,
|
|
310
|
+
errorCode: error.code
|
|
311
|
+
});
|
|
312
|
+
return failure(error, requestId, resolutionContext());
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Routes the request: origin pinning, the `before` hook, plain routes and mounts, liveness and discovery
|
|
316
|
+
* documents, then an operation or a transport, else the fallback or NOT_FOUND.
|
|
317
|
+
*/
|
|
318
|
+
async function dispatchNative() {
|
|
319
|
+
const url = new URL(incoming.url);
|
|
320
|
+
if (hooks.before) {
|
|
321
|
+
plain = true;
|
|
322
|
+
const response = await hooks.before(incoming, env, context);
|
|
323
|
+
if (response) return response;
|
|
324
|
+
plain = false;
|
|
325
|
+
}
|
|
326
|
+
const route = composed.routes.get(url.pathname) ?? composed.mounted(url.pathname);
|
|
327
|
+
if (route) {
|
|
328
|
+
plain = true;
|
|
329
|
+
return route(incoming, env, context);
|
|
330
|
+
}
|
|
331
|
+
const nativePath = paths.local(url.pathname);
|
|
332
|
+
const resource = paths.resources.get(url.pathname);
|
|
333
|
+
if (url.pathname === paths.health || resource) {
|
|
334
|
+
if (incoming.method !== "GET") return context.fail(standardErrors.methodNotAllowed.create(), { allow: "GET" });
|
|
335
|
+
return resource ? Response.json(protectedResourceMetadata(resource, env), { headers: { "access-control-allow-origin": "*" } }) : Response.json({
|
|
336
|
+
status: "ok",
|
|
337
|
+
service: manifest.name,
|
|
338
|
+
version: manifest.version
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
if (incoming.method === "GET" && !transports.byPath.has(url.pathname)) {
|
|
342
|
+
const native = nativeDocument(nativePath, reject);
|
|
343
|
+
if (native) return native;
|
|
344
|
+
}
|
|
345
|
+
const operationRoute = routes.match(incoming.method, nativePath ?? "");
|
|
346
|
+
const transport = transports.byPath.get(url.pathname);
|
|
347
|
+
operation = operationRoute?.definition.name ?? null;
|
|
348
|
+
surface = transport ? "mcp" : "http";
|
|
349
|
+
if (!operationRoute && !transport) {
|
|
350
|
+
const reserved = paths.base && nativePath !== null || ownsPrefix("/.well-known", url.pathname) || VERSIONED_PATH.test(url.pathname) || paths.reserved.has(url.pathname) || [...transports.byPath.keys()].some((prefix) => ownsPrefix(prefix, url.pathname));
|
|
351
|
+
if (hooks.fallback && !reserved) {
|
|
352
|
+
plain = true;
|
|
353
|
+
return hooks.fallback(incoming, env, context);
|
|
354
|
+
}
|
|
355
|
+
return reject(standardErrors.notFound.create());
|
|
356
|
+
}
|
|
357
|
+
let invoked = false;
|
|
358
|
+
/**
|
|
359
|
+
* Admits and runs the matched operation or transport with the env `aroundOperation` scoped: token, rate
|
|
360
|
+
* limit, bounded body, then input and execution.
|
|
361
|
+
*/
|
|
362
|
+
async function run(scopedEnv) {
|
|
363
|
+
if (invoked) throw new TypeError("An HTTP operation continuation may run only once.");
|
|
364
|
+
invoked = true;
|
|
365
|
+
requestEnv = scopedEnv;
|
|
366
|
+
if (access && isCrossSiteWrite(incoming)) return reject(standardErrors.forbidden.create());
|
|
367
|
+
const result = await authorize(incoming, operationRoute ? operationScopes(operationRoute.definition.op) : transport?.scope(manifest.namespace) ?? "", {
|
|
368
|
+
env: scopedEnv,
|
|
369
|
+
request: incoming,
|
|
370
|
+
surface,
|
|
371
|
+
applicationScopes,
|
|
372
|
+
background
|
|
373
|
+
}, operationRoute?.definition.op.scopeMatch);
|
|
374
|
+
if (!result.ok) return reject(result.error);
|
|
375
|
+
const authenticated = result.value;
|
|
376
|
+
const accessToken = oauth ? /^Bearer (\S+)$/i.exec(incoming.headers.get("authorization") ?? "")?.[1] : void 0;
|
|
377
|
+
const actor = {
|
|
378
|
+
actorId: authenticated.actorId,
|
|
379
|
+
actorKind: authenticated.actorKind,
|
|
380
|
+
organizationId: authenticated.organizationId,
|
|
381
|
+
requestId
|
|
382
|
+
};
|
|
383
|
+
principal = actor;
|
|
384
|
+
if (!await withinRateLimit(scopedEnv, authenticated)) return reject(standardErrors.rateLimited.create());
|
|
385
|
+
let request = incoming;
|
|
386
|
+
let bodyText = "";
|
|
387
|
+
const byteOperation = operationRoute?.definition.op.http?.body === "bytes";
|
|
388
|
+
const type = request.headers.get("content-type");
|
|
389
|
+
if (operationRoute && !byteOperation && request.method !== "GET" && (type === null ? request.body !== null && request.method !== "DELETE" : mediaType(type) !== "application/json")) return reject(standardErrors.unsupportedMedia.create());
|
|
390
|
+
if (request.body && !byteOperation) {
|
|
391
|
+
const maxBytes = operationRoute ? operationRoute.definition.op.maxBodyBytes ?? fallbackBodyBytes : transport?.maxBodyBytes?.(runnableBy(authenticated), fallbackBodyBytes) ?? fallbackBodyBytes;
|
|
392
|
+
const body = await readBodyText(request, { maxBytes });
|
|
393
|
+
if (!body.ok) return reject(body.error.data.reason === "too_large" ? standardErrors.tooLarge.create() : standardErrors.invalidInput.create());
|
|
394
|
+
bodyText = body.value;
|
|
395
|
+
request = new Request(request.url, {
|
|
396
|
+
method: request.method,
|
|
397
|
+
headers: request.headers,
|
|
398
|
+
body: bodyText,
|
|
399
|
+
signal: request.signal
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Admits the requests a transport's request carries beyond the first (a JSON-RPC batch over MCP),
|
|
404
|
+
* each passing the rate limit as a request of its own would, before any of them runs.
|
|
405
|
+
*/
|
|
406
|
+
async function admitCarried(requests) {
|
|
407
|
+
for (let admitted = 0; admitted < requests; admitted += 1) if (!await withinRateLimit(scopedEnv, authenticated)) return reject(standardErrors.rateLimited.create());
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Runs one operation through the shared execution path as the admitted caller, and records the call.
|
|
411
|
+
*/
|
|
412
|
+
async function invoke(name, op, input) {
|
|
413
|
+
if (transport && !operations.some(([selectedName, selected]) => selectedName === name && selected === op)) return {
|
|
414
|
+
ok: false,
|
|
415
|
+
error: standardErrors.notFound.create()
|
|
416
|
+
};
|
|
417
|
+
if (transport && !operationMatchesScopes(op, authenticated.scopes)) return {
|
|
418
|
+
ok: false,
|
|
419
|
+
error: standardErrors.forbidden.create()
|
|
420
|
+
};
|
|
421
|
+
if (telemetryEnabled(manifest.telemetry, scopedEnv)) hooks.annotate?.(name, requestId);
|
|
422
|
+
const invocationStarted = performance.now();
|
|
423
|
+
const output = await executeOperation(manifest, op, scopedEnv, actor, input, authenticated.client ? {
|
|
424
|
+
surface: transport ? "mcp" : "http",
|
|
425
|
+
scopes: authenticated.scopes,
|
|
426
|
+
client: authenticated.client,
|
|
427
|
+
...accessToken ? { token: accessToken } : {}
|
|
428
|
+
} : void 0, background, byteOperation ? binaryBody(incoming, op.maxBodyBytes ?? fallbackBodyBytes) : void 0);
|
|
429
|
+
recordExecution(manifest, scopedEnv, background, {
|
|
430
|
+
principal: actor,
|
|
431
|
+
operation: name,
|
|
432
|
+
surface: transport ? "mcp" : "http",
|
|
433
|
+
started: invocationStarted,
|
|
434
|
+
result: output
|
|
435
|
+
});
|
|
436
|
+
return output;
|
|
437
|
+
}
|
|
438
|
+
if (transport) return transport.handle({
|
|
439
|
+
request,
|
|
440
|
+
requestId,
|
|
441
|
+
authenticated,
|
|
442
|
+
application: manifest,
|
|
443
|
+
operations,
|
|
444
|
+
contract,
|
|
445
|
+
contractText,
|
|
446
|
+
url: (path) => `${manifest.origin}${paths.mount(path)}`,
|
|
447
|
+
invoke,
|
|
448
|
+
admitCarried,
|
|
449
|
+
refused: (error, name) => {
|
|
450
|
+
recordAdmission(manifest, scopedEnv, background, {
|
|
451
|
+
principal: actor,
|
|
452
|
+
operation: name ?? null,
|
|
453
|
+
surface,
|
|
454
|
+
requestId,
|
|
455
|
+
started,
|
|
456
|
+
errorCode: error.code
|
|
457
|
+
});
|
|
458
|
+
},
|
|
459
|
+
body: bodyText,
|
|
460
|
+
bodyLimit: (op) => op.maxBodyBytes ?? fallbackBodyBytes
|
|
461
|
+
});
|
|
462
|
+
if (!operationRoute) return reject(standardErrors.notFound.create());
|
|
463
|
+
const input = operationInput(operationRoute, incoming, url, bodyText);
|
|
464
|
+
if (!input.ok) return reject(input.error);
|
|
465
|
+
const output = await invoke(operationRoute.definition.name, operationRoute.definition.op, input.value);
|
|
466
|
+
if (!output.ok) return failure(output.error, requestId, resolutionContext());
|
|
467
|
+
const exposure = operationRoute.definition.op.http;
|
|
468
|
+
if (exposure?.response === "attachment") return attachmentResponse(output.value, exposure.successStatus ?? 200);
|
|
469
|
+
return Response.json({
|
|
470
|
+
success: true,
|
|
471
|
+
data: output.value,
|
|
472
|
+
error: null,
|
|
473
|
+
metadata: { requestId }
|
|
474
|
+
}, { status: exposure?.successStatus ?? 200 });
|
|
475
|
+
}
|
|
476
|
+
return operationRoute && hooks.aroundOperation ? hooks.aroundOperation(incoming, env, {
|
|
477
|
+
name: operationRoute.definition.name,
|
|
478
|
+
effect: operationRoute.definition.op.effect
|
|
479
|
+
}, run) : run(env);
|
|
480
|
+
}
|
|
481
|
+
let response;
|
|
482
|
+
try {
|
|
483
|
+
if (hooks.origins && !hooks.origins.includes(new URL(incoming.url).origin)) response = reject(standardErrors.notFound.create());
|
|
484
|
+
else {
|
|
485
|
+
const dispatch = async (index) => {
|
|
486
|
+
const middleware = hooks.middleware?.[index];
|
|
487
|
+
if (!middleware) return dispatchNative();
|
|
488
|
+
let invoked = false;
|
|
489
|
+
let active = true;
|
|
490
|
+
const requestView = new Request(incoming.url, {
|
|
491
|
+
method: incoming.method,
|
|
492
|
+
headers: new Headers(incoming.headers),
|
|
493
|
+
signal: incoming.signal
|
|
494
|
+
});
|
|
495
|
+
try {
|
|
496
|
+
return await middleware(requestView, env, context, () => {
|
|
497
|
+
if (invoked || !active) throw new TypeError("An HTTP middleware continuation may run only once before its wrapper settles.");
|
|
498
|
+
invoked = true;
|
|
499
|
+
return dispatch(index + 1);
|
|
500
|
+
});
|
|
501
|
+
} finally {
|
|
502
|
+
active = false;
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
response = await dispatch(0);
|
|
506
|
+
}
|
|
507
|
+
} catch (error) {
|
|
508
|
+
reportUnexpected(error, plain ? "route" : surface, requestId);
|
|
509
|
+
response = plain ? failure(standardErrors.internal.create(), requestId, resolutionContext()) : reject(standardErrors.internal.create());
|
|
510
|
+
}
|
|
511
|
+
if (response.status === 101) return response;
|
|
512
|
+
const headers = new Headers(response.headers);
|
|
513
|
+
headers.set("x-request-id", requestId);
|
|
514
|
+
if (!(plain && headers.has("cache-control"))) headers.set("cache-control", "private, no-store");
|
|
515
|
+
headers.set("x-content-type-options", "nosniff");
|
|
516
|
+
headers.set("server-timing", `total;dur=${(performance.now() - started).toFixed(1)}`);
|
|
517
|
+
return new Response(response.body, {
|
|
518
|
+
status: response.status,
|
|
519
|
+
statusText: response.statusText,
|
|
520
|
+
headers
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
return (request, env, background) => withTelemetry(manifest.telemetry, env, () => handle(request, env, background));
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* An operation's input from its HTTP request: a byte operation's query and header metadata, a GET's
|
|
527
|
+
* typed query, a DELETE's absent body or a JSON body, with the path parameters added. A path
|
|
528
|
+
* parameter may come only from the path, never also from the query or the body.
|
|
529
|
+
*/
|
|
530
|
+
function operationInput(route, request, url, bodyText) {
|
|
531
|
+
const { op, query } = route.definition;
|
|
532
|
+
let input;
|
|
533
|
+
if (op.http?.body === "bytes") {
|
|
534
|
+
const fields = [...url.searchParams.keys()];
|
|
535
|
+
if (new Set(fields).size !== fields.length) return err(standardErrors.invalidInput.create());
|
|
536
|
+
const inputMetadata = Object.fromEntries(url.searchParams);
|
|
537
|
+
for (const [field, header] of Object.entries(op.http.headers ?? {})) {
|
|
538
|
+
if (url.searchParams.has(field)) return err(standardErrors.invalidInput.create());
|
|
539
|
+
const value = request.headers.get(header);
|
|
540
|
+
if (value !== null) inputMetadata[field] = value;
|
|
541
|
+
}
|
|
542
|
+
input = inputMetadata;
|
|
543
|
+
} else if (request.method === "GET") {
|
|
544
|
+
const fields = queryInput(query, url.searchParams);
|
|
545
|
+
if (!fields) return err(standardErrors.invalidInput.create());
|
|
546
|
+
input = fields;
|
|
547
|
+
} else if (request.method === "DELETE" && bodyText === "" && !request.headers.has("content-type")) input = {};
|
|
548
|
+
else {
|
|
549
|
+
if (mediaType(request.headers.get("content-type")) !== "application/json") return err(standardErrors.unsupportedMedia.create());
|
|
550
|
+
try {
|
|
551
|
+
input = JSON.parse(bodyText);
|
|
552
|
+
} catch {
|
|
553
|
+
return err(standardErrors.invalidInput.create());
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const { parameters } = route;
|
|
557
|
+
if (Object.keys(parameters).some((name) => url.searchParams.has(name))) return err(standardErrors.invalidInput.create());
|
|
558
|
+
if (Object.keys(parameters).length === 0) return ok(input);
|
|
559
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) return err(standardErrors.invalidInput.create());
|
|
560
|
+
const body = input;
|
|
561
|
+
if (Object.keys(parameters).some((name) => Object.hasOwn(body, name))) return err(standardErrors.invalidInput.create());
|
|
562
|
+
return ok({
|
|
563
|
+
...body,
|
|
564
|
+
...parameters
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
export { maximus as a, protectedResourceMetadata as i, t as n, createHttpHandler as r, Type$1 as t };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// src/standard-failures.ts
|
|
2
|
+
/** The framework's own failures, by the name `standardErrors` gives each. */
|
|
3
|
+
const STANDARD_FAILURES = {
|
|
4
|
+
invalidInput: {
|
|
5
|
+
code: "INVALID_INPUT",
|
|
6
|
+
status: 400,
|
|
7
|
+
message: "The request does not match the published schema."
|
|
8
|
+
},
|
|
9
|
+
unauthorized: {
|
|
10
|
+
code: "UNAUTHORIZED",
|
|
11
|
+
status: 401,
|
|
12
|
+
message: "A valid access token is required."
|
|
13
|
+
},
|
|
14
|
+
forbidden: {
|
|
15
|
+
code: "FORBIDDEN",
|
|
16
|
+
status: 403,
|
|
17
|
+
message: "The token does not authorize this operation."
|
|
18
|
+
},
|
|
19
|
+
notFound: {
|
|
20
|
+
code: "NOT_FOUND",
|
|
21
|
+
status: 404,
|
|
22
|
+
message: "The requested operation does not exist."
|
|
23
|
+
},
|
|
24
|
+
methodNotAllowed: {
|
|
25
|
+
code: "HTTP_METHOD_NOT_ALLOWED",
|
|
26
|
+
status: 405,
|
|
27
|
+
message: "The HTTP method is not supported for this resource."
|
|
28
|
+
},
|
|
29
|
+
tooLarge: {
|
|
30
|
+
code: "REQUEST_TOO_LARGE",
|
|
31
|
+
status: 413,
|
|
32
|
+
message: "The request exceeds the allowed size."
|
|
33
|
+
},
|
|
34
|
+
unsupportedMedia: {
|
|
35
|
+
code: "UNSUPPORTED_MEDIA_TYPE",
|
|
36
|
+
status: 415,
|
|
37
|
+
message: "The request content type is not supported."
|
|
38
|
+
},
|
|
39
|
+
rateLimited: {
|
|
40
|
+
code: "RATE_LIMITED",
|
|
41
|
+
status: 429,
|
|
42
|
+
message: "The request rate limit was exceeded. Try again later.",
|
|
43
|
+
retryable: true,
|
|
44
|
+
retryAfter: 60
|
|
45
|
+
},
|
|
46
|
+
internal: {
|
|
47
|
+
code: "INTERNAL_ERROR",
|
|
48
|
+
status: 500,
|
|
49
|
+
message: "The service could not complete the operation."
|
|
50
|
+
},
|
|
51
|
+
upstreamUnavailable: {
|
|
52
|
+
code: "UPSTREAM_UNAVAILABLE",
|
|
53
|
+
status: 503,
|
|
54
|
+
message: "The upstream service could not complete the request.",
|
|
55
|
+
retryable: true
|
|
56
|
+
},
|
|
57
|
+
upstreamTimeout: {
|
|
58
|
+
code: "UPSTREAM_TIMEOUT",
|
|
59
|
+
status: 504,
|
|
60
|
+
message: "The upstream service did not respond before its deadline.",
|
|
61
|
+
retryable: true
|
|
62
|
+
},
|
|
63
|
+
/**
|
|
64
|
+
* A write may have been applied and its answer was lost. Never retried: the caller reconciles (reads
|
|
65
|
+
* the resource or polls the operation) before deciding to repeat anything.
|
|
66
|
+
*/
|
|
67
|
+
outcomeUnknown: {
|
|
68
|
+
code: "OUTCOME_UNKNOWN",
|
|
69
|
+
status: 502,
|
|
70
|
+
message: "The operation may have been applied; check its result before repeating it."
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export { STANDARD_FAILURES as t };
|