@arbol-ai/maximus 0.0.0-stage → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +51 -2
- package/config/oxfmt.d.mts +8 -0
- package/config/oxfmt.mjs +30 -0
- package/config/oxlint-plugin.mjs +41 -0
- package/config/oxlint.d.mts +8 -0
- package/config/oxlint.mjs +118 -0
- package/dist/analytics/analytics.d.ts +34 -0
- package/dist/analytics/analytics.js +62 -0
- package/dist/body.d.ts +2 -0
- package/dist/body.js +4 -0
- package/dist/chunks/body-BcMbreNd.js +106 -0
- package/dist/chunks/correlation-gaiEoMBr.js +45 -0
- package/dist/chunks/execution-qfZuMSIu.js +700 -0
- package/dist/chunks/json-Dwni3u4c.js +63 -0
- package/dist/chunks/record-D2H3cg8S.js +36 -0
- package/dist/chunks/schemas-q-51wBMQ.js +216 -0
- package/dist/chunks/src-Ph5KHCRP.js +1160 -0
- package/dist/chunks/telemetry-DvZgrzZn.js +220 -0
- package/dist/chunks/types-CGwAhnTE.d.ts +1630 -0
- package/dist/chunks/validation-DWxKk1Js.js +382 -0
- package/dist/client/client.d.ts +131 -0
- package/dist/client/client.js +325 -0
- package/dist/diagnostics.d.ts +41 -0
- package/dist/diagnostics.js +4 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +128 -0
- package/dist/http-paths.d.ts +2 -0
- package/dist/http-paths.js +200 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +11 -0
- package/dist/internals.d.ts +2 -0
- package/dist/internals.js +5 -0
- package/dist/mcp/index.d.ts +12 -0
- package/dist/mcp/index.js +406 -0
- package/dist/postgres/index.d.ts +81 -0
- package/dist/postgres/index.js +140 -0
- package/dist/schemas.d.ts +2 -0
- package/dist/schemas.js +4 -0
- package/dist/standard-failures.d.ts +91 -0
- package/dist/standard-failures.js +75 -0
- package/dist/tooling/cli.js +110 -0
- package/dist/tooling/testing.d.ts +7 -0
- package/dist/tooling/testing.js +21 -0
- package/dist/webhooks.d.ts +69 -0
- package/dist/webhooks.js +162 -0
- package/dist/workers/runtime.d.ts +112 -0
- package/dist/workers/runtime.js +228 -0
- package/package.json +153 -4
- package/skills/maximus/SKILL.md +89 -0
- package/skills/maximus/references/adding-an-operation.md +179 -0
- package/skills/maximus/references/building-a-service.md +158 -0
- package/skills/maximus/references/errors-and-results.md +77 -0
- package/skills/maximus/references/migration-from-v2.md +62 -0
- package/skills/maximus/references/migration-to-v5.md +37 -0
- package/skills/maximus/references/publishing-and-verification.md +39 -0
- package/skills/maximus/references/testing.md +73 -0
- package/skills/maximus/references/transports.md +119 -0
- package/templates/service/.agents/skills/project/SKILL.md.template +10 -0
- package/templates/service/.github/workflows/ci.yml.template +21 -0
- package/templates/service/.gitignore.template +8 -0
- package/templates/service/CLAUDE.md.template +3 -0
- package/templates/service/README.md.template +45 -0
- package/templates/service/cloudflare.config.ts.template +30 -0
- package/templates/service/oxfmt.config.ts.template +1 -0
- package/templates/service/oxlint.config.ts.template +1 -0
- package/templates/service/package.json.template +31 -0
- package/templates/service/src/app.ts.template +30 -0
- package/templates/service/src/index.ts.template +13 -0
- package/templates/service/tests/contract.test.ts.template +12 -0
- package/templates/service/tsconfig.json.template +16 -0
- package/templates/service/vite.config.ts.template +7 -0
- package/templates/service/vitest.config.ts.template +10 -0
package/dist/webhooks.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
//#region src/webhooks.ts
|
|
2
|
+
/** Why a webhook signature was refused: absent, malformed, outside the time tolerance, or not matching. */
|
|
3
|
+
const WEBHOOK_SIGNATURE_FAILURES = [
|
|
4
|
+
"missing",
|
|
5
|
+
"malformed",
|
|
6
|
+
"expired",
|
|
7
|
+
"mismatch"
|
|
8
|
+
];
|
|
9
|
+
/** The failure for a refused webhook signature. */
|
|
10
|
+
function webhookSignatureFailure(reason) {
|
|
11
|
+
return {
|
|
12
|
+
code: "WEBHOOK_SIGNATURE_INVALID",
|
|
13
|
+
message: "Webhook signature could not be verified",
|
|
14
|
+
retryable: false,
|
|
15
|
+
data: { reason }
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Five minutes either way, the Standard Webhooks recommendation. */
|
|
19
|
+
const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
20
|
+
/**
|
|
21
|
+
* The most signatures one header may carry. A provider rotating its secret sends two or three, and each
|
|
22
|
+
* costs an HMAC of the whole body, so a header with more is refused as malformed before any is computed.
|
|
23
|
+
*/
|
|
24
|
+
const MAX_SIGNATURES = 8;
|
|
25
|
+
/** Encodes the signed text as UTF-8. */
|
|
26
|
+
const encoder = new TextEncoder();
|
|
27
|
+
/** Text as UTF-8 bytes, or a copy of the bytes, as Web Crypto takes them. */
|
|
28
|
+
function bytes(value) {
|
|
29
|
+
if (typeof value === "string") return encoder.encode(value);
|
|
30
|
+
const copy = new Uint8Array(value.byteLength);
|
|
31
|
+
copy.set(value);
|
|
32
|
+
return copy;
|
|
33
|
+
}
|
|
34
|
+
/** The parts as one byte array. */
|
|
35
|
+
function concat(...parts) {
|
|
36
|
+
const total = parts.reduce((sum, part) => sum + part.byteLength, 0);
|
|
37
|
+
const result = new Uint8Array(total);
|
|
38
|
+
let offset = 0;
|
|
39
|
+
for (const part of parts) {
|
|
40
|
+
result.set(part, offset);
|
|
41
|
+
offset += part.byteLength;
|
|
42
|
+
}
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
/** The bytes of a hexadecimal signature, or null when it is not one. */
|
|
46
|
+
function fromHex(value) {
|
|
47
|
+
if (value.length === 0 || value.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(value)) return null;
|
|
48
|
+
const result = new Uint8Array(value.length / 2);
|
|
49
|
+
for (let index = 0; index < result.length; index += 1) result[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
/** The bytes of a base64 or base64url value, or null when it is not one. */
|
|
53
|
+
function fromBase64(value) {
|
|
54
|
+
if (value.length === 0 || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(value)) return null;
|
|
55
|
+
try {
|
|
56
|
+
const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
57
|
+
const binary = atob(normalized.padEnd(normalized.length + (4 - normalized.length % 4) % 4, "="));
|
|
58
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** An HMAC-SHA256 key that can only verify. */
|
|
64
|
+
async function hmacKey(secret) {
|
|
65
|
+
return await crypto.subtle.importKey("raw", secret, {
|
|
66
|
+
hash: "SHA-256",
|
|
67
|
+
name: "HMAC"
|
|
68
|
+
}, false, ["verify"]);
|
|
69
|
+
}
|
|
70
|
+
/** Whether a signed timestamp is within the tolerance of now, in either direction. */
|
|
71
|
+
function withinTolerance(timestampSeconds, toleranceSeconds, nowMs) {
|
|
72
|
+
return Math.abs(nowMs / 1e3 - timestampSeconds) <= toleranceSeconds;
|
|
73
|
+
}
|
|
74
|
+
/** A refusal with its reason. */
|
|
75
|
+
const failure = (reason) => ({
|
|
76
|
+
ok: false,
|
|
77
|
+
error: webhookSignatureFailure(reason)
|
|
78
|
+
});
|
|
79
|
+
/**
|
|
80
|
+
* Verify an HMAC-SHA256 of the raw body. `signature` is the header value,
|
|
81
|
+
* optionally with a scheme prefix such as `sha256=` (removed with `prefix`).
|
|
82
|
+
*/
|
|
83
|
+
async function verifyHmacSignature(options) {
|
|
84
|
+
if (!options.signature) return failure("missing");
|
|
85
|
+
const value = options.prefix && options.signature.startsWith(options.prefix) ? options.signature.slice(options.prefix.length) : options.signature;
|
|
86
|
+
const signature = options.encoding === "hex" ? fromHex(value.trim()) : fromBase64(value.trim());
|
|
87
|
+
if (!signature) return failure("malformed");
|
|
88
|
+
return await crypto.subtle.verify("HMAC", await hmacKey(bytes(options.secret)), signature, bytes(options.body)) ? {
|
|
89
|
+
ok: true,
|
|
90
|
+
value: null
|
|
91
|
+
} : failure("mismatch");
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Verify a `t=<unix seconds>,v0=<hex>` header (several `v0`/`v1` values may be
|
|
95
|
+
* present during secret rotation, up to {@link MAX_SIGNATURES}; one match is
|
|
96
|
+
* enough) signing `<t>.<body>`.
|
|
97
|
+
*/
|
|
98
|
+
async function verifyTimestampedSignature(options) {
|
|
99
|
+
if (!options.header) return failure("missing");
|
|
100
|
+
let timestamp = null;
|
|
101
|
+
const signatures = [];
|
|
102
|
+
for (const part of options.header.split(",")) {
|
|
103
|
+
const separator = part.indexOf("=");
|
|
104
|
+
const key = part.slice(0, separator).trim();
|
|
105
|
+
const value = part.slice(separator + 1).trim();
|
|
106
|
+
if (separator < 1) continue;
|
|
107
|
+
if (key === "t" && /^\d{1,12}$/.test(value)) timestamp = Number(value);
|
|
108
|
+
else if (options.labels.includes(key)) {
|
|
109
|
+
const decoded = fromHex(value);
|
|
110
|
+
if (decoded) signatures.push(decoded);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (timestamp === null || signatures.length === 0 || signatures.length > 8) return failure("malformed");
|
|
114
|
+
const now = options.now?.() ?? Date.now();
|
|
115
|
+
if (!withinTolerance(timestamp, options.toleranceSeconds ?? 300, now)) return failure("expired");
|
|
116
|
+
const key = await hmacKey(bytes(options.secret));
|
|
117
|
+
const message = concat(encoder.encode(`${timestamp}.`), bytes(options.body));
|
|
118
|
+
for (const signature of signatures) if (await crypto.subtle.verify("HMAC", key, signature, message)) return {
|
|
119
|
+
ok: true,
|
|
120
|
+
value: { timestamp }
|
|
121
|
+
};
|
|
122
|
+
return failure("mismatch");
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Verify a Standard Webhooks delivery. The secret is the provider's
|
|
126
|
+
* `whsec_<base64>` value (the prefix is optional), and the signature header may
|
|
127
|
+
* list up to {@link MAX_SIGNATURES} signatures. Returns the message id, the
|
|
128
|
+
* idempotency key of the delivery, and its timestamp.
|
|
129
|
+
*/
|
|
130
|
+
async function verifyStandardWebhook(options) {
|
|
131
|
+
/** A Standard Webhooks header, or its `svix-` spelling. */
|
|
132
|
+
const header = (name) => options.headers.get(`webhook-${name}`) ?? options.headers.get(`svix-${name}`);
|
|
133
|
+
const id = header("id");
|
|
134
|
+
const timestampValue = header("timestamp");
|
|
135
|
+
const signatureValue = header("signature");
|
|
136
|
+
if (!(id && timestampValue && signatureValue)) return failure("missing");
|
|
137
|
+
if (!/^\d{1,12}$/.test(timestampValue) || id.length > 256 || /[\s.]/.test(id)) return failure("malformed");
|
|
138
|
+
const timestamp = Number(timestampValue);
|
|
139
|
+
const now = options.now?.() ?? Date.now();
|
|
140
|
+
if (!withinTolerance(timestamp, options.toleranceSeconds ?? 300, now)) return failure("expired");
|
|
141
|
+
const secret = fromBase64(options.secret.startsWith("whsec_") ? options.secret.slice(6) : options.secret);
|
|
142
|
+
if (!secret) return failure("malformed");
|
|
143
|
+
const signatures = signatureValue.split(" ").flatMap((entry) => {
|
|
144
|
+
const [version, value] = entry.split(",", 2);
|
|
145
|
+
const decoded = version === "v1" && value ? fromBase64(value) : null;
|
|
146
|
+
return decoded ? [decoded] : [];
|
|
147
|
+
});
|
|
148
|
+
if (signatures.length === 0 || signatures.length > 8) return failure("malformed");
|
|
149
|
+
const key = await hmacKey(secret);
|
|
150
|
+
const message = concat(encoder.encode(`${id}.${timestamp}.`), bytes(options.body));
|
|
151
|
+
for (const signature of signatures) if (await crypto.subtle.verify("HMAC", key, signature, message)) return {
|
|
152
|
+
ok: true,
|
|
153
|
+
value: {
|
|
154
|
+
id,
|
|
155
|
+
timestamp
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
return failure("mismatch");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
//#endregion
|
|
162
|
+
export { DEFAULT_TOLERANCE_SECONDS, MAX_SIGNATURES, WEBHOOK_SIGNATURE_FAILURES, verifyHmacSignature, verifyStandardWebhook, verifyTimestampedSignature, webhookSignatureFailure };
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { At as AppManifest, T as HttpRoute, bn as Result, i as TSchema, kn as Failure, r as Static, tn as Principal, w as HttpOptions, zt as OperationShape } from "../chunks/types-CGwAhnTE.js";
|
|
2
|
+
import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
|
|
3
|
+
//#region src/workers/assets.d.ts
|
|
4
|
+
/** A Workers static-assets binding; product stores and secrets never satisfy this capability. */
|
|
5
|
+
interface AssetBinding {
|
|
6
|
+
/** Answers a request with the uploaded build file at its URL path. */
|
|
7
|
+
fetch: (request: Request) => Promise<Response>;
|
|
8
|
+
}
|
|
9
|
+
/** The names of the env bindings that are asset bindings. */
|
|
10
|
+
type AssetBindingName<E> = { [K in keyof E]-?: E[K] extends AssetBinding ? K : never; }[keyof E] & string;
|
|
11
|
+
/** Explicit assets policy. Unknown paths never receive the SPA shell. */
|
|
12
|
+
interface WorkerAssetsOptions<E> {
|
|
13
|
+
/** Environment binding whose fetch method serves the uploaded build files. */
|
|
14
|
+
binding: AssetBindingName<E>;
|
|
15
|
+
/** Known SPA routes. Stateless expressions may admit product-owned detail routes. */
|
|
16
|
+
pages?: {
|
|
17
|
+
paths: readonly string[];
|
|
18
|
+
patterns?: readonly RegExp[];
|
|
19
|
+
/** Build shell fetched for admitted pages; defaults to /index.html. */
|
|
20
|
+
shell?: string;
|
|
21
|
+
};
|
|
22
|
+
/** Named build files that must revalidate, such as manifests and service workers. */
|
|
23
|
+
files?: readonly string[];
|
|
24
|
+
/** Slash-delimited namespaces containing content-hashed, immutable build files. */
|
|
25
|
+
immutablePrefixes?: readonly string[];
|
|
26
|
+
/** Product browser policy, including CSP. Native content type and cache policy remain authoritative. */
|
|
27
|
+
headers?: HeadersInit | ((request: Request, env: E) => HeadersInit);
|
|
28
|
+
/**
|
|
29
|
+
* Development under Vite (the Cloudflare Vite plugin), whose dev server stands behind the binding:
|
|
30
|
+
* a GET the Worker does not serve as a page, file or immutable asset (Vite's client, modules and
|
|
31
|
+
* sources) is forwarded to it as it came. Pass `import.meta.env.DEV`, which a production build sets to
|
|
32
|
+
* false: a deployed Worker must never forward unknown paths.
|
|
33
|
+
*/
|
|
34
|
+
development?: boolean;
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region src/workers/credentials.d.ts
|
|
38
|
+
/** Typed organization credential preparation for one derived operation group. */
|
|
39
|
+
export declare function credentials<Schema extends TSchema>(options: {
|
|
40
|
+
principal: Principal;
|
|
41
|
+
accounts: {
|
|
42
|
+
getByName: (name: string) => {
|
|
43
|
+
readCredential: (organizationId: string) => Promise<Result<unknown, Failure>>;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
schema: Schema;
|
|
47
|
+
}): Promise<Result<{
|
|
48
|
+
credential: Static<Schema>;
|
|
49
|
+
}, Failure>>;
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/workers/runtime.d.ts
|
|
52
|
+
/**
|
|
53
|
+
* The RPC methods of a Worker's entrypoint: one per operation that declares `rpc`, taking the caller's
|
|
54
|
+
* principal and the input and answering a Result.
|
|
55
|
+
*/
|
|
56
|
+
export type RpcMethods<Ops extends Record<string, OperationShape>> = { [K in keyof Ops as Ops[K] extends {
|
|
57
|
+
rpc: true | {
|
|
58
|
+
callers: readonly string[];
|
|
59
|
+
};
|
|
60
|
+
} ? K : never]: (principal: Principal, input: Static<Ops[K]['input']>) => Promise<Result<Static<Ops[K]['output']>, Failure>>; };
|
|
61
|
+
/**
|
|
62
|
+
* What `createWorker` returns: the default export's handler, the named entrypoint for Worker RPC, and
|
|
63
|
+
* wrappers that run your own entrypoints and Durable Objects inside the application's diagnostics.
|
|
64
|
+
*/
|
|
65
|
+
export interface WorkerRuntime<E, O extends Record<string, OperationShape>> {
|
|
66
|
+
/** The Worker's default export: `fetch` for HTTP, plus the other `handlers` given to `createWorker`. */
|
|
67
|
+
handler: ExportedHandler<E>;
|
|
68
|
+
/**
|
|
69
|
+
* A `WorkerEntrypoint` class with one method per operation that declares `rpc`; export it by name for
|
|
70
|
+
* Service Bindings to call.
|
|
71
|
+
*/
|
|
72
|
+
entrypoint: new (ctx: ExecutionContext, env: E) => WorkerEntrypoint<E> & RpcMethods<O>;
|
|
73
|
+
/**
|
|
74
|
+
* Wraps your own `WorkerEntrypoint` class so its methods run inside the application's diagnostics; it keeps
|
|
75
|
+
* its methods and type.
|
|
76
|
+
*/
|
|
77
|
+
service: <D extends new (ctx: ExecutionContext, env: E) => WorkerEntrypoint<E>>(implementation: D) => D;
|
|
78
|
+
/**
|
|
79
|
+
* Wraps a Durable Object class so its methods run inside the application's diagnostics; it keeps its
|
|
80
|
+
* methods and type.
|
|
81
|
+
*/
|
|
82
|
+
durableObject: <T extends DurableObject<E>, D extends new (state: DurableObject['ctx'], env: E) => T>(implementation: D) => D;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* What `createWorker` takes besides the application: the Worker's other handlers, its transports, the HTTP
|
|
86
|
+
* handler's options, its static assets and its plain routes.
|
|
87
|
+
*/
|
|
88
|
+
export interface WorkerOptions<E> {
|
|
89
|
+
/** The Worker's other handlers (`scheduled`, `queue`, …), merged into the default export. */
|
|
90
|
+
handlers?: Omit<ExportedHandler<E>, 'fetch'>;
|
|
91
|
+
/** Protocol transports served beside the operations, such as `mcp()`. */
|
|
92
|
+
transports?: HttpOptions<E>['transports'];
|
|
93
|
+
/** Native HTTP mounting, product admission and static/protocol composition. */
|
|
94
|
+
http?: Omit<HttpOptions<E>, 'transports' | 'routes' | 'annotate'>;
|
|
95
|
+
/** Explicit build files and SPA page admission, served through the native HTTP fallback. */
|
|
96
|
+
assets?: WorkerAssetsOptions<E>;
|
|
97
|
+
/**
|
|
98
|
+
* Plain routes outside token admission (provider webhooks, signed links,
|
|
99
|
+
* OAuth callbacks), by exact path. Each handler verifies its own signature
|
|
100
|
+
* or token before reading the request. They run inside the same handler,
|
|
101
|
+
* so diagnostics cover them too.
|
|
102
|
+
*/
|
|
103
|
+
routes?: Readonly<Record<string, HttpRoute<E>>>;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Turns an application into a Cloudflare Worker: `handler` (export it as default) serves HTTP and the other
|
|
107
|
+
* handlers you pass; `entrypoint` (export it by name) serves every operation that declares `rpc` to the
|
|
108
|
+
* Workers whose Service Binding names an allowed `caller`.
|
|
109
|
+
*/
|
|
110
|
+
export declare function createWorker<E, C, O extends Record<string, OperationShape>>(application: AppManifest<E, C, O>, options?: WorkerOptions<E>): WorkerRuntime<E, O>;
|
|
111
|
+
//#endregion
|
|
112
|
+
export type { WorkerAssetsOptions };
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { r as parseInput } from "../chunks/validation-DWxKk1Js.js";
|
|
2
|
+
import { r as isRequestId } from "../chunks/correlation-gaiEoMBr.js";
|
|
3
|
+
import { standardErrors } from "../errors.js";
|
|
4
|
+
import { d as err, p as ok, r as PrincipalSchema, t as executeOperation } from "../chunks/execution-qfZuMSIu.js";
|
|
5
|
+
import { r as createHttpHandler } from "../chunks/src-Ph5KHCRP.js";
|
|
6
|
+
import { a as telemetryEnabled, r as recordExecution, s as withTelemetry } from "../chunks/telemetry-DvZgrzZn.js";
|
|
7
|
+
import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
|
|
8
|
+
|
|
9
|
+
//#region src/workers/assets.ts
|
|
10
|
+
/**
|
|
11
|
+
* Serves a web app's build through a Workers static-assets binding: known pages get the app shell, named
|
|
12
|
+
* files revalidate, content-hashed files are immutable, and every other path is refused.
|
|
13
|
+
*/
|
|
14
|
+
/** An absolute asset path of unreserved characters, without a query or a fragment. */
|
|
15
|
+
const ASSET_PATH = /^\/(?:[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*)?$/;
|
|
16
|
+
/** The path, refused at construction when it is not an absolute asset path or has dot segments. */
|
|
17
|
+
function requireAssetPath(path) {
|
|
18
|
+
if (!ASSET_PATH.test(path) || path.split("/").some((segment) => segment === "." || segment === "..")) throw new TypeError(`Asset path must be absolute without query, fragments or dot segments: ${path}`);
|
|
19
|
+
return path;
|
|
20
|
+
}
|
|
21
|
+
/** Whether a binding can fetch assets. */
|
|
22
|
+
function isAssetBinding(value) {
|
|
23
|
+
return typeof value === "object" && value !== null && "fetch" in value && typeof value.fetch === "function";
|
|
24
|
+
}
|
|
25
|
+
/** Compile the explicit build policy once; core HTTP retains ownership of API and transport misses. */
|
|
26
|
+
function createAssetHandler(options) {
|
|
27
|
+
const bindingName = options.binding;
|
|
28
|
+
const pages = new Set(options.pages?.paths.map(requireAssetPath));
|
|
29
|
+
const files = new Set(options.files?.map(requireAssetPath));
|
|
30
|
+
const shell = requireAssetPath(options.pages?.shell ?? "/index.html");
|
|
31
|
+
const patterns = options.pages?.patterns?.map((pattern) => {
|
|
32
|
+
if (!(pattern instanceof RegExp) || pattern.global || pattern.sticky) throw new TypeError("Asset page patterns must be stateless regular expressions without global or sticky flags.");
|
|
33
|
+
return new RegExp(pattern.source, pattern.flags);
|
|
34
|
+
}) ?? [];
|
|
35
|
+
const immutablePrefixes = options.immutablePrefixes?.map((path) => {
|
|
36
|
+
const prefix = requireAssetPath(path.endsWith("/") ? path.slice(0, -1) : path);
|
|
37
|
+
if (prefix === "/") throw new TypeError("An immutable assets prefix must not claim the entire origin.");
|
|
38
|
+
return prefix;
|
|
39
|
+
}) ?? [];
|
|
40
|
+
const configuredHeaders = typeof options.headers === "function" ? options.headers : new Headers(options.headers);
|
|
41
|
+
return async (request, env, context) => {
|
|
42
|
+
if (request.method !== "GET" && request.method !== "HEAD") return context.fail(standardErrors.methodNotAllowed.create(), { Allow: "GET, HEAD" });
|
|
43
|
+
const url = new URL(request.url);
|
|
44
|
+
const isPage = pages.has(url.pathname) || patterns.some((pattern) => pattern.test(url.pathname));
|
|
45
|
+
const isFile = files.has(url.pathname);
|
|
46
|
+
const isImmutable = immutablePrefixes.some((prefix) => url.pathname === prefix || url.pathname.startsWith(`${prefix}/`));
|
|
47
|
+
const binding = env[bindingName];
|
|
48
|
+
if (!(isPage || isFile || isImmutable)) {
|
|
49
|
+
if (options.development && isAssetBinding(binding)) return binding.fetch(request);
|
|
50
|
+
return context.fail(standardErrors.notFound.create());
|
|
51
|
+
}
|
|
52
|
+
if (!isAssetBinding(binding)) throw new TypeError("The configured Worker assets binding does not implement fetch.");
|
|
53
|
+
const assetUrl = new URL(isPage ? shell : url.pathname, url.origin);
|
|
54
|
+
const asset = await binding.fetch(new Request(assetUrl, { method: request.method }));
|
|
55
|
+
const headers = new Headers(asset.headers);
|
|
56
|
+
const policy = typeof configuredHeaders === "function" ? new Headers(configuredHeaders(request, env)) : configuredHeaders;
|
|
57
|
+
for (const [name, value] of policy) if (name !== "content-type" && name !== "cache-control") headers.set(name, value);
|
|
58
|
+
headers.set("x-content-type-options", "nosniff");
|
|
59
|
+
let cache = "public, max-age=31536000, immutable";
|
|
60
|
+
if (isPage || asset.status !== 200) cache = "no-store";
|
|
61
|
+
else if (isFile) cache = "no-cache";
|
|
62
|
+
headers.set("cache-control", cache);
|
|
63
|
+
if (request.method === "HEAD" && asset.body) await asset.body.cancel();
|
|
64
|
+
return new Response(request.method === "HEAD" ? null : asset.body, {
|
|
65
|
+
status: asset.status,
|
|
66
|
+
statusText: asset.statusText,
|
|
67
|
+
headers
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/workers/internal/instrumentation.ts
|
|
74
|
+
/**
|
|
75
|
+
* Runs the methods of a Worker's own entrypoints and Durable Objects inside the application's diagnostics.
|
|
76
|
+
*/
|
|
77
|
+
/**
|
|
78
|
+
* A subclass of `implementation` whose every method, its own and those it inherits up to the Workers
|
|
79
|
+
* base class `runtime`, runs inside the application's diagnostics for the instance's `env`.
|
|
80
|
+
*/
|
|
81
|
+
function instrumentMethods(implementation, runtime, telemetry) {
|
|
82
|
+
const Base = implementation;
|
|
83
|
+
const environments = /* @__PURE__ */ new WeakMap();
|
|
84
|
+
class Observed extends Base {
|
|
85
|
+
constructor(context, env) {
|
|
86
|
+
super(context, env);
|
|
87
|
+
environments.set(this, env);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
let { prototype } = implementation;
|
|
91
|
+
const methods = /* @__PURE__ */ new Set();
|
|
92
|
+
while (prototype && prototype !== runtime.prototype) {
|
|
93
|
+
for (const name of Object.getOwnPropertyNames(prototype)) {
|
|
94
|
+
const method = Object.getOwnPropertyDescriptor(prototype, name)?.value;
|
|
95
|
+
if (name === "constructor" || methods.has(name) || typeof method !== "function") continue;
|
|
96
|
+
methods.add(name);
|
|
97
|
+
Object.defineProperty(Observed.prototype, name, {
|
|
98
|
+
configurable: true,
|
|
99
|
+
value(...args) {
|
|
100
|
+
return withTelemetry(telemetry, environments.get(this), () => Reflect.apply(method, this, args));
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
105
|
+
}
|
|
106
|
+
return Observed;
|
|
107
|
+
}
|
|
108
|
+
/** A named entrypoint whose RPC methods run inside the application's diagnostics. */
|
|
109
|
+
function instrumentService(implementation, telemetry) {
|
|
110
|
+
return instrumentMethods(implementation, WorkerEntrypoint, telemetry);
|
|
111
|
+
}
|
|
112
|
+
/** A Durable Object whose methods run inside the application's diagnostics. */
|
|
113
|
+
function instrumentDurableObject(implementation, telemetry) {
|
|
114
|
+
return instrumentMethods(implementation, DurableObject, telemetry);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/workers/internal/worker-tracing.ts
|
|
119
|
+
/**
|
|
120
|
+
* Annotates the active Workers trace span with the service, the operation and the request id.
|
|
121
|
+
*/
|
|
122
|
+
/**
|
|
123
|
+
* Call inside the invocation, after authenticating the native principal. Service
|
|
124
|
+
* and operation are developer constants. Adds correlation to the existing native
|
|
125
|
+
* span; does not mint/fake trace ids or enable exporters. No raw exception is
|
|
126
|
+
* recorded on the native span.
|
|
127
|
+
* Older workerd versions do not expose getActiveSpan. Annotation is best effort:
|
|
128
|
+
* an unavailable or failing telemetry API must never change the business result.
|
|
129
|
+
*/
|
|
130
|
+
function annotateInvocation(service, operation, requestId, attributeNames = {
|
|
131
|
+
service: "service.name",
|
|
132
|
+
operation: "operation.name",
|
|
133
|
+
requestId: "request.id"
|
|
134
|
+
}) {
|
|
135
|
+
try {
|
|
136
|
+
if (typeof tracing.getActiveSpan === "function") tracing.getActiveSpan()?.setAttributes({
|
|
137
|
+
[attributeNames.service]: service,
|
|
138
|
+
[attributeNames.operation]: operation,
|
|
139
|
+
...isRequestId(requestId) ? { [attributeNames.requestId]: requestId } : {}
|
|
140
|
+
});
|
|
141
|
+
} catch {}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
//#endregion
|
|
145
|
+
//#region src/workers/credentials.ts
|
|
146
|
+
/**
|
|
147
|
+
* Reads one organization's credential from its own store, such as a Durable Object per organization, and
|
|
148
|
+
* checks that it belongs to that organization.
|
|
149
|
+
*/
|
|
150
|
+
/** Typed organization credential preparation for one derived operation group. */
|
|
151
|
+
async function credentials(options) {
|
|
152
|
+
const { organizationId } = options.principal;
|
|
153
|
+
const result = await options.accounts.getByName(organizationId).readCredential(organizationId);
|
|
154
|
+
if (!result.ok) return result;
|
|
155
|
+
const parsed = parseInput(options.schema, result.value);
|
|
156
|
+
if (!parsed.ok || !parsed.value || typeof parsed.value !== "object" || !("organizationId" in parsed.value) || parsed.value.organizationId !== organizationId) return err(standardErrors.internal.create());
|
|
157
|
+
return ok({ credential: parsed.value });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
//#endregion
|
|
161
|
+
//#region src/workers/runtime.ts
|
|
162
|
+
/**
|
|
163
|
+
* `@arbol-ai/maximus/workers`: turns an application into a Cloudflare Worker: its fetch handler, its RPC
|
|
164
|
+
* entrypoint, and the instrumentation of the Worker's other classes.
|
|
165
|
+
*/
|
|
166
|
+
/**
|
|
167
|
+
* Turns an application into a Cloudflare Worker: `handler` (export it as default) serves HTTP and the other
|
|
168
|
+
* handlers you pass; `entrypoint` (export it by name) serves every operation that declares `rpc` to the
|
|
169
|
+
* Workers whose Service Binding names an allowed `caller`.
|
|
170
|
+
*/
|
|
171
|
+
function createWorker(application, options = {}) {
|
|
172
|
+
if (options.assets && options.http?.fallback) throw new TypeError("Worker assets and an HTTP fallback cannot both own unmatched paths.");
|
|
173
|
+
const assets = options.assets ? createAssetHandler(options.assets) : void 0;
|
|
174
|
+
const manifest = application;
|
|
175
|
+
const fetch = createHttpHandler(manifest, {
|
|
176
|
+
...options.http,
|
|
177
|
+
fallback: assets ?? options.http?.fallback,
|
|
178
|
+
transports: options.transports,
|
|
179
|
+
routes: options.routes,
|
|
180
|
+
annotate: (operation, id) => annotateInvocation(manifest.name, operation, id)
|
|
181
|
+
});
|
|
182
|
+
class Entrypoint extends WorkerEntrypoint {}
|
|
183
|
+
for (const [name, op] of Object.entries(manifest.operations)) {
|
|
184
|
+
if (!op.rpc) continue;
|
|
185
|
+
const callers = op.rpc === true ? manifest.rpc.callers : op.rpc.callers;
|
|
186
|
+
Object.defineProperty(Entrypoint.prototype, name, {
|
|
187
|
+
configurable: true,
|
|
188
|
+
async value(principal, input) {
|
|
189
|
+
const props = this.ctx.props;
|
|
190
|
+
if (!props || Object.keys(props).length !== 1 || typeof props.caller !== "string" || !callers.includes(props.caller)) return err(standardErrors.unauthorized.create());
|
|
191
|
+
const parsed = parseInput(PrincipalSchema, principal);
|
|
192
|
+
if (!parsed.ok) return err(standardErrors.unauthorized.create());
|
|
193
|
+
if (telemetryEnabled(manifest.telemetry, this.env)) annotateInvocation(manifest.name, name, parsed.value.requestId);
|
|
194
|
+
const started = performance.now();
|
|
195
|
+
const result = await withTelemetry(manifest.telemetry, this.env, () => executeOperation(manifest, op, this.env, parsed.value, input, void 0, this.ctx));
|
|
196
|
+
recordExecution(manifest, this.env, this.ctx, {
|
|
197
|
+
principal: parsed.value,
|
|
198
|
+
operation: name,
|
|
199
|
+
surface: "rpc",
|
|
200
|
+
started,
|
|
201
|
+
result
|
|
202
|
+
});
|
|
203
|
+
return result;
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
const service = (implementation) => instrumentService(implementation, manifest.telemetry);
|
|
208
|
+
const entrypoint = service(Entrypoint);
|
|
209
|
+
const handler = {
|
|
210
|
+
...options.handlers,
|
|
211
|
+
fetch
|
|
212
|
+
};
|
|
213
|
+
const scheduledHandler = options.handlers?.scheduled;
|
|
214
|
+
if (scheduledHandler) handler.scheduled = function scheduled(controller, env, ctx) {
|
|
215
|
+
return withTelemetry(manifest.telemetry, env, () => scheduledHandler.call(this, controller, env, ctx));
|
|
216
|
+
};
|
|
217
|
+
return {
|
|
218
|
+
handler,
|
|
219
|
+
entrypoint,
|
|
220
|
+
service,
|
|
221
|
+
durableObject(implementation) {
|
|
222
|
+
return instrumentDurableObject(implementation, manifest.telemetry);
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
//#endregion
|
|
228
|
+
export { createWorker, credentials };
|
package/package.json
CHANGED
|
@@ -1,6 +1,155 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arbol-ai/maximus",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "7.0.0",
|
|
4
|
+
"description": "Maximus: define a service once and serve it over HTTP, MCP and Worker RPC on Cloudflare Workers, with its OpenAPI, typed client and CLI.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"api",
|
|
7
|
+
"cloudflare",
|
|
8
|
+
"cloudflare-workers",
|
|
9
|
+
"framework",
|
|
10
|
+
"mcp",
|
|
11
|
+
"model-context-protocol",
|
|
12
|
+
"multi-tenant",
|
|
13
|
+
"openapi",
|
|
14
|
+
"rpc",
|
|
15
|
+
"typebox"
|
|
16
|
+
],
|
|
17
|
+
"homepage": "https://github.com/getarbol/maximus#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/getarbol/maximus/issues"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"author": "Arbol",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/getarbol/maximus.git",
|
|
26
|
+
"directory": "packages/maximus"
|
|
27
|
+
},
|
|
28
|
+
"bin": {
|
|
29
|
+
"maximus": "dist/tooling/cli.js"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"config",
|
|
34
|
+
"templates",
|
|
35
|
+
"skills",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
],
|
|
39
|
+
"type": "module",
|
|
40
|
+
"sideEffects": false,
|
|
41
|
+
"exports": {
|
|
42
|
+
".": {
|
|
43
|
+
"types": "./dist/index.d.ts",
|
|
44
|
+
"import": "./dist/index.js"
|
|
45
|
+
},
|
|
46
|
+
"./schemas": {
|
|
47
|
+
"types": "./dist/schemas.d.ts",
|
|
48
|
+
"import": "./dist/schemas.js"
|
|
49
|
+
},
|
|
50
|
+
"./errors": {
|
|
51
|
+
"types": "./dist/errors.d.ts",
|
|
52
|
+
"import": "./dist/errors.js"
|
|
53
|
+
},
|
|
54
|
+
"./failures": {
|
|
55
|
+
"types": "./dist/standard-failures.d.ts",
|
|
56
|
+
"import": "./dist/standard-failures.js"
|
|
57
|
+
},
|
|
58
|
+
"./body": {
|
|
59
|
+
"types": "./dist/body.d.ts",
|
|
60
|
+
"import": "./dist/body.js"
|
|
61
|
+
},
|
|
62
|
+
"./webhooks": {
|
|
63
|
+
"types": "./dist/webhooks.d.ts",
|
|
64
|
+
"import": "./dist/webhooks.js"
|
|
65
|
+
},
|
|
66
|
+
"./http-paths": {
|
|
67
|
+
"types": "./dist/http-paths.d.ts",
|
|
68
|
+
"import": "./dist/http-paths.js"
|
|
69
|
+
},
|
|
70
|
+
"./diagnostics": {
|
|
71
|
+
"types": "./dist/diagnostics.d.ts",
|
|
72
|
+
"import": "./dist/diagnostics.js"
|
|
73
|
+
},
|
|
74
|
+
"./internals": {
|
|
75
|
+
"types": "./dist/internals.d.ts",
|
|
76
|
+
"import": "./dist/internals.js"
|
|
77
|
+
},
|
|
78
|
+
"./workers": {
|
|
79
|
+
"types": "./dist/workers/runtime.d.ts",
|
|
80
|
+
"import": "./dist/workers/runtime.js"
|
|
81
|
+
},
|
|
82
|
+
"./mcp": {
|
|
83
|
+
"types": "./dist/mcp/index.d.ts",
|
|
84
|
+
"import": "./dist/mcp/index.js"
|
|
85
|
+
},
|
|
86
|
+
"./client": {
|
|
87
|
+
"types": "./dist/client/client.d.ts",
|
|
88
|
+
"import": "./dist/client/client.js"
|
|
89
|
+
},
|
|
90
|
+
"./analytics": {
|
|
91
|
+
"types": "./dist/analytics/analytics.d.ts",
|
|
92
|
+
"import": "./dist/analytics/analytics.js"
|
|
93
|
+
},
|
|
94
|
+
"./postgres": {
|
|
95
|
+
"types": "./dist/postgres/index.d.ts",
|
|
96
|
+
"import": "./dist/postgres/index.js"
|
|
97
|
+
},
|
|
98
|
+
"./testing": {
|
|
99
|
+
"types": "./dist/tooling/testing.d.ts",
|
|
100
|
+
"import": "./dist/tooling/testing.js"
|
|
101
|
+
},
|
|
102
|
+
"./oxfmt": {
|
|
103
|
+
"types": "./config/oxfmt.d.mts",
|
|
104
|
+
"import": "./config/oxfmt.mjs"
|
|
105
|
+
},
|
|
106
|
+
"./oxlint": {
|
|
107
|
+
"types": "./config/oxlint.d.mts",
|
|
108
|
+
"import": "./config/oxlint.mjs"
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
"publishConfig": {
|
|
112
|
+
"access": "public",
|
|
113
|
+
"registry": "https://registry.npmjs.org/"
|
|
114
|
+
},
|
|
115
|
+
"scripts": {
|
|
116
|
+
"typecheck": "tsc --noEmit",
|
|
117
|
+
"build": "tsdown",
|
|
118
|
+
"test": "vitest run --exclude '**/*.integration.test.ts'",
|
|
119
|
+
"test:integration": "vitest run --config vitest.integration.config.ts"
|
|
120
|
+
},
|
|
121
|
+
"dependencies": {
|
|
122
|
+
"@modelcontextprotocol/server": "2.3.1",
|
|
123
|
+
"@sinclair/typebox": "0.34.52",
|
|
124
|
+
"ajv-formats": "3.0.1",
|
|
125
|
+
"jose": "6.2.12",
|
|
126
|
+
"yaml": "2.9.1"
|
|
127
|
+
},
|
|
128
|
+
"devDependencies": {
|
|
129
|
+
"@types/pg": "8.23.1",
|
|
130
|
+
"ajv": "8.20.0",
|
|
131
|
+
"miniflare": "5.20261012.1-beta",
|
|
132
|
+
"pg": "8.23.1",
|
|
133
|
+
"tsdown": "0.23.1"
|
|
134
|
+
},
|
|
135
|
+
"peerDependencies": {
|
|
136
|
+
"oxfmt": ">=0.71.0 <1",
|
|
137
|
+
"oxlint": "^1.86.0",
|
|
138
|
+
"pg": "^8.23.1",
|
|
139
|
+
"ultracite": "^8.0.0"
|
|
140
|
+
},
|
|
141
|
+
"peerDependenciesMeta": {
|
|
142
|
+
"oxfmt": {
|
|
143
|
+
"optional": true
|
|
144
|
+
},
|
|
145
|
+
"oxlint": {
|
|
146
|
+
"optional": true
|
|
147
|
+
},
|
|
148
|
+
"pg": {
|
|
149
|
+
"optional": true
|
|
150
|
+
},
|
|
151
|
+
"ultracite": {
|
|
152
|
+
"optional": true
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|