@zjazj/server 0.0.7 → 0.0.9
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/dist/api-keys-R2145cd9.d.ts +208 -0
- package/dist/{chunk-EIZ24ILA.js → chunk-44UTXMKV.js} +20 -4
- package/dist/{chunk-NMKEVYGN.js → chunk-SLNRMJDM.js} +20 -1
- package/dist/chunk-UWTSXBJL.js +345 -0
- package/dist/{chunk-26AAYRI3.js → chunk-VJRJ53T2.js} +1 -0
- package/dist/db.js +3 -1
- package/dist/dev.d.ts +18 -2
- package/dist/dev.js +7 -1
- package/dist/index.d.ts +249 -10
- package/dist/index.js +397 -10
- package/dist/log.js +1 -1
- package/dist/mcp-4RD7G65J.js +139 -0
- package/dist/testing.d.ts +29 -2
- package/dist/testing.js +64 -4
- package/package.json +5 -2
- package/dist/auth-Ckmm4C6y.d.ts +0 -81
- package/dist/chunk-UWDDQH25.js +0 -146
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
configureLog,
|
|
3
3
|
log,
|
|
4
4
|
requestLogger
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-VJRJ53T2.js";
|
|
6
6
|
import {
|
|
7
7
|
ORGANIZATION_AUDIENCE_PREFIX,
|
|
8
8
|
authenticate,
|
|
@@ -17,30 +17,39 @@ import {
|
|
|
17
17
|
supportFromClaims,
|
|
18
18
|
userFromClaims,
|
|
19
19
|
verifierFromEnv
|
|
20
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-44UTXMKV.js";
|
|
21
21
|
import {
|
|
22
|
+
API_KEY_PREFIX,
|
|
23
|
+
API_KEY_REFUSAL_SECONDS,
|
|
22
24
|
APP_ID_PATTERN,
|
|
23
25
|
APP_NAME_PATTERN,
|
|
24
26
|
AppError,
|
|
25
27
|
ConflictError,
|
|
26
28
|
ForbiddenError,
|
|
29
|
+
MAX_API_KEY_CACHE_SECONDS,
|
|
27
30
|
NotFoundError,
|
|
28
31
|
UnauthorizedError,
|
|
29
32
|
ValidationError,
|
|
33
|
+
acceptApiKey,
|
|
34
|
+
apiKeyRoutes,
|
|
30
35
|
appBasePath,
|
|
36
|
+
assertApiKeyAccepted,
|
|
31
37
|
assertValidAppId,
|
|
38
|
+
createKeyVerifier,
|
|
32
39
|
errorHandler,
|
|
33
40
|
generateAppId,
|
|
41
|
+
isApiKey,
|
|
34
42
|
isUuid,
|
|
35
43
|
isValidAppId,
|
|
36
44
|
isValidAppName,
|
|
37
45
|
notFoundHandler,
|
|
38
46
|
toErrorResponse,
|
|
47
|
+
userFromKeyVerification,
|
|
39
48
|
uuidv7
|
|
40
|
-
} from "./chunk-
|
|
49
|
+
} from "./chunk-UWTSXBJL.js";
|
|
41
50
|
import {
|
|
42
51
|
isDevIdentityEnabled
|
|
43
|
-
} from "./chunk-
|
|
52
|
+
} from "./chunk-SLNRMJDM.js";
|
|
44
53
|
import {
|
|
45
54
|
REQUEST_ID_HEADER,
|
|
46
55
|
coerceRequestId,
|
|
@@ -56,6 +65,76 @@ import { serve } from "@hono/node-server";
|
|
|
56
65
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
57
66
|
import { Hono } from "hono";
|
|
58
67
|
|
|
68
|
+
// src/tools.ts
|
|
69
|
+
var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]{0,40}$/;
|
|
70
|
+
var PERMISSION_CODE = /^[a-z][a-z0-9-]*(:[a-z][a-z0-9-]*)+$/;
|
|
71
|
+
var TOOL_SET = /* @__PURE__ */ Symbol.for("zjazj.platform.tools");
|
|
72
|
+
function isToolSet(value) {
|
|
73
|
+
return Array.isArray(value) && value[TOOL_SET] === true;
|
|
74
|
+
}
|
|
75
|
+
function toolProblems(tools) {
|
|
76
|
+
const problems = [];
|
|
77
|
+
const seen = /* @__PURE__ */ new Set();
|
|
78
|
+
tools.forEach((tool, index) => {
|
|
79
|
+
const name = typeof tool?.name === "string" ? tool.name : "";
|
|
80
|
+
const label = name ? `Tool ${name}` : `Tool ${index + 1}`;
|
|
81
|
+
if (!TOOL_NAME_PATTERN.test(name)) {
|
|
82
|
+
problems.push(
|
|
83
|
+
`${label}: the name must be lower-case letters, digits and underscores, start with a letter and have at most 41 characters. Got ${JSON.stringify(tool?.name)}.`
|
|
84
|
+
);
|
|
85
|
+
} else if (seen.has(name)) {
|
|
86
|
+
problems.push(`${label}: the name is used twice.`);
|
|
87
|
+
}
|
|
88
|
+
seen.add(name);
|
|
89
|
+
if (typeof tool?.description !== "string" || tool.description.trim() === "") {
|
|
90
|
+
problems.push(`${label}: the description is empty. Say what the tool does, for the model.`);
|
|
91
|
+
}
|
|
92
|
+
if (typeof tool?.permission !== "string" || !PERMISSION_CODE.test(tool.permission)) {
|
|
93
|
+
problems.push(
|
|
94
|
+
`${label}: the permission must be a code of the app's catalog, such as "app:item:read". Got ${JSON.stringify(tool?.permission)}.`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
const annotations = tool?.annotations;
|
|
98
|
+
if (!annotations || typeof annotations.readOnlyHint !== "boolean") {
|
|
99
|
+
problems.push(`${label}: the annotations must say readOnlyHint, true or false.`);
|
|
100
|
+
} else if (annotations.readOnlyHint === false && typeof annotations.destructiveHint !== "boolean") {
|
|
101
|
+
problems.push(
|
|
102
|
+
`${label}: a tool that changes data must say destructiveHint, true when it can delete or overwrite data.`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
if (annotations && typeof annotations.openWorldHint !== "boolean") {
|
|
106
|
+
problems.push(
|
|
107
|
+
`${label}: the annotations must say openWorldHint, true when the tool calls a system outside the platform and false otherwise.`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const input = tool?.input;
|
|
111
|
+
if (!input || typeof input !== "object" || !("~standard" in input)) {
|
|
112
|
+
problems.push(`${label}: the input must be a schema, such as z.object({ ... }).`);
|
|
113
|
+
}
|
|
114
|
+
if (typeof tool?.handler !== "function") {
|
|
115
|
+
problems.push(`${label}: the handler is missing.`);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
return problems;
|
|
119
|
+
}
|
|
120
|
+
function defineTools(tools) {
|
|
121
|
+
const list = [...tools];
|
|
122
|
+
const problems = toolProblems(list);
|
|
123
|
+
if (problems.length > 0) throw new Error(`Invalid tools:
|
|
124
|
+
- ${problems.join("\n- ")}`);
|
|
125
|
+
Object.defineProperty(list, TOOL_SET, { value: true });
|
|
126
|
+
return Object.freeze(list);
|
|
127
|
+
}
|
|
128
|
+
function toolManifest(tools) {
|
|
129
|
+
return tools.map((tool) => ({
|
|
130
|
+
name: tool.name,
|
|
131
|
+
title: tool.title ?? null,
|
|
132
|
+
description: tool.description,
|
|
133
|
+
permission: tool.permission,
|
|
134
|
+
annotations: tool.annotations
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
|
|
59
138
|
// src/manifest.ts
|
|
60
139
|
function platformManifest(options) {
|
|
61
140
|
const env = options.env ?? process.env;
|
|
@@ -73,6 +152,8 @@ function platformManifest(options) {
|
|
|
73
152
|
title: permission.title,
|
|
74
153
|
description: permission.description ?? null
|
|
75
154
|
})),
|
|
155
|
+
tools: toolManifest(options.tools ?? []),
|
|
156
|
+
api_key_routes: (options.apiKeyRoutes ?? []).map((route) => ({ ...route })),
|
|
76
157
|
release_version: manifest.version ?? null,
|
|
77
158
|
source_commit: env.GIT_SHA || null
|
|
78
159
|
};
|
|
@@ -94,6 +175,7 @@ function errorBody(value) {
|
|
|
94
175
|
return { code, message, field: typeof field === "string" ? field : void 0 };
|
|
95
176
|
}
|
|
96
177
|
async function callPlatform(c, path2, call = {}, options = {}) {
|
|
178
|
+
assertApiKeyAccepted(c);
|
|
97
179
|
const env = options.env ?? process.env;
|
|
98
180
|
const base = env.PLATFORM_URL?.replace(/\/+$/, "");
|
|
99
181
|
if (!base) {
|
|
@@ -194,6 +276,16 @@ function createApp(options) {
|
|
|
194
276
|
env.BASE_URL || (env.NODE_ENV === "production" ? appBasePath(manifest.name) : "/")
|
|
195
277
|
);
|
|
196
278
|
configureLog({ app: manifest.name, env: env.ENV || env.NODE_ENV || "development" });
|
|
279
|
+
const tools = options.tools ?? [];
|
|
280
|
+
if (options.permissions) {
|
|
281
|
+
const catalog = new Set(options.permissions.map((permission) => permission.code));
|
|
282
|
+
const unknown = tools.filter((tool) => !catalog.has(tool.permission));
|
|
283
|
+
if (unknown.length > 0) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
`Tools need permissions that are not in the catalog: ${unknown.map((tool) => `${tool.name} (${tool.permission})`).join(", ")}`
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
197
289
|
const databaseOptions = typeof options.database === "object" ? options.database : options.database ? {} : void 0;
|
|
198
290
|
const getDatabase = () => {
|
|
199
291
|
if (!databaseOptions) {
|
|
@@ -218,9 +310,11 @@ function createApp(options) {
|
|
|
218
310
|
}
|
|
219
311
|
return pending;
|
|
220
312
|
};
|
|
313
|
+
const keyVerifier = options.keyVerifier ?? createKeyVerifier({ env, fetch: options.fetch });
|
|
314
|
+
const credentials = { verifier: options.verifier, keyVerifier, env };
|
|
221
315
|
const forUsers = () => {
|
|
222
316
|
const router = new Hono();
|
|
223
|
-
router.use("*", authenticate(
|
|
317
|
+
router.use("*", authenticate(credentials));
|
|
224
318
|
if (databaseOptions) {
|
|
225
319
|
router.use("*", async (c, next) => {
|
|
226
320
|
const { tenantDatabase } = await import("./db.js");
|
|
@@ -234,7 +328,7 @@ function createApp(options) {
|
|
|
234
328
|
const publicApi = new Hono();
|
|
235
329
|
const internal = new Hono();
|
|
236
330
|
const platformRoutes = new Hono();
|
|
237
|
-
platformRoutes.use("*", authenticate(
|
|
331
|
+
platformRoutes.use("*", authenticate(credentials));
|
|
238
332
|
const toPlatform = { env, fetch: options.fetch };
|
|
239
333
|
platformRoutes.get("/tenants", async (c) => {
|
|
240
334
|
const { q, page, page_size: pageSize } = c.req.query();
|
|
@@ -269,10 +363,7 @@ function createApp(options) {
|
|
|
269
363
|
root.notFound(notFoundHandler());
|
|
270
364
|
root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
|
|
271
365
|
root.use("/internal/*", internalCallersOnly);
|
|
272
|
-
root.get(
|
|
273
|
-
"/internal/_platform/manifest",
|
|
274
|
-
(c) => c.json(platformManifest({ manifest, permissions: options.permissions, env }))
|
|
275
|
-
);
|
|
366
|
+
root.get("/internal/_platform/manifest", (c) => c.json(manifestNow()));
|
|
276
367
|
root.all("/internal/_platform/*", (c) => c.notFound());
|
|
277
368
|
root.route("/internal/delegated", delegated);
|
|
278
369
|
root.all("/internal/delegated/*", (c) => c.notFound());
|
|
@@ -292,6 +383,23 @@ function createApp(options) {
|
|
|
292
383
|
scoped.route("/api/_platform", platformRoutes);
|
|
293
384
|
scoped.route("/api", api);
|
|
294
385
|
scoped.all("/api/*", (c) => c.notFound());
|
|
386
|
+
if (tools.length > 0) {
|
|
387
|
+
const mcp = new Hono();
|
|
388
|
+
mcp.use("*", authenticate({ ...credentials, acceptApiKeys: true }));
|
|
389
|
+
let route;
|
|
390
|
+
mcp.all("/", async (c) => {
|
|
391
|
+
if (!route) {
|
|
392
|
+
const { createMcpRoute } = await import("./mcp-4RD7G65J.js");
|
|
393
|
+
route ??= createMcpRoute({
|
|
394
|
+
manifest,
|
|
395
|
+
tools,
|
|
396
|
+
...databaseOptions ? { database: getDatabase } : {}
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return route(c);
|
|
400
|
+
});
|
|
401
|
+
scoped.route("/mcp", mcp);
|
|
402
|
+
}
|
|
295
403
|
const staticDir = path.resolve(options.staticDir ?? "dist/client");
|
|
296
404
|
const indexFile = path.join(staticDir, "index.html");
|
|
297
405
|
if (existsSync(indexFile)) {
|
|
@@ -313,6 +421,17 @@ function createApp(options) {
|
|
|
313
421
|
root.route(basePath || "/", scoped);
|
|
314
422
|
return root;
|
|
315
423
|
};
|
|
424
|
+
const manifestNow = () => platformManifest({
|
|
425
|
+
manifest,
|
|
426
|
+
permissions: options.permissions,
|
|
427
|
+
tools,
|
|
428
|
+
apiKeyRoutes: [
|
|
429
|
+
...tools.length > 0 ? [{ method: "POST", path: "/mcp" }] : [],
|
|
430
|
+
...apiKeyRoutes(api, "/api"),
|
|
431
|
+
...apiKeyRoutes(delegated, "/internal/delegated")
|
|
432
|
+
],
|
|
433
|
+
env
|
|
434
|
+
});
|
|
316
435
|
const fetchHandler = (request, ...rest) => {
|
|
317
436
|
built ??= build();
|
|
318
437
|
return built.fetch(request, ...rest);
|
|
@@ -326,6 +445,7 @@ function createApp(options) {
|
|
|
326
445
|
delegated,
|
|
327
446
|
fetch: fetchHandler,
|
|
328
447
|
database: getDatabase,
|
|
448
|
+
platformManifest: manifestNow,
|
|
329
449
|
async start() {
|
|
330
450
|
const port = Number(env.PORT ?? 8080);
|
|
331
451
|
if (!Number.isInteger(port) || port <= 0) throw new Error(`Invalid PORT: ${env.PORT}`);
|
|
@@ -354,6 +474,197 @@ function createApp(options) {
|
|
|
354
474
|
};
|
|
355
475
|
}
|
|
356
476
|
|
|
477
|
+
// src/oauth.ts
|
|
478
|
+
import * as client from "openid-client";
|
|
479
|
+
var OAuthError = class extends AppError {
|
|
480
|
+
/** The OAuth error code, such as `invalid_grant`, or `server_error` when there is none. */
|
|
481
|
+
oauthError;
|
|
482
|
+
/** True when the grant is gone and only a new authorization helps. */
|
|
483
|
+
needsAuthorization;
|
|
484
|
+
constructor(message, oauthError, cause) {
|
|
485
|
+
const needsAuthorization = oauthError === "invalid_grant" || oauthError === "access_denied";
|
|
486
|
+
super(message, {
|
|
487
|
+
code: needsAuthorization ? "oauth_needs_authorization" : "oauth_failed",
|
|
488
|
+
status: needsAuthorization ? 409 : 502,
|
|
489
|
+
cause
|
|
490
|
+
});
|
|
491
|
+
this.oauthError = oauthError;
|
|
492
|
+
this.needsAuthorization = needsAuthorization;
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
function toOAuthError(error, doing) {
|
|
496
|
+
if (error instanceof OAuthError) return error;
|
|
497
|
+
if (error instanceof client.ResponseBodyError || error instanceof client.AuthorizationResponseError) {
|
|
498
|
+
const description = error.error_description ? `: ${error.error_description}` : "";
|
|
499
|
+
return new OAuthError(`${doing} was refused (${error.error}${description})`, error.error, error);
|
|
500
|
+
}
|
|
501
|
+
return new OAuthError(`${doing} failed`, "server_error", error);
|
|
502
|
+
}
|
|
503
|
+
function customFetch2(options) {
|
|
504
|
+
const fetcher = options.fetch;
|
|
505
|
+
return fetcher ? (url, init) => fetcher(url, init) : void 0;
|
|
506
|
+
}
|
|
507
|
+
async function getJson(url, options) {
|
|
508
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
509
|
+
headers: { Accept: "application/json" },
|
|
510
|
+
redirect: "error"
|
|
511
|
+
});
|
|
512
|
+
if (!response.ok) return void 0;
|
|
513
|
+
const body = await response.json().catch(() => void 0);
|
|
514
|
+
return body && typeof body === "object" ? body : void 0;
|
|
515
|
+
}
|
|
516
|
+
async function protectedResource(service, options) {
|
|
517
|
+
const path2 = service.pathname.replace(/\/+$/, "");
|
|
518
|
+
const candidates = [
|
|
519
|
+
...path2 ? [new URL(`/.well-known/oauth-protected-resource${path2}`, service)] : [],
|
|
520
|
+
new URL("/.well-known/oauth-protected-resource", service)
|
|
521
|
+
];
|
|
522
|
+
for (const candidate of candidates) {
|
|
523
|
+
const metadata = await getJson(candidate, options).catch(() => void 0);
|
|
524
|
+
if (!metadata) continue;
|
|
525
|
+
const servers = Array.isArray(metadata.authorization_servers) ? metadata.authorization_servers.filter((value) => typeof value === "string") : [];
|
|
526
|
+
const resource = typeof metadata.resource === "string" ? metadata.resource : service.href;
|
|
527
|
+
const scopes = Array.isArray(metadata.scopes_supported) ? metadata.scopes_supported.filter((value) => typeof value === "string") : [];
|
|
528
|
+
return { resource, servers, scopes };
|
|
529
|
+
}
|
|
530
|
+
return void 0;
|
|
531
|
+
}
|
|
532
|
+
function discoveryOptions(options, algorithm) {
|
|
533
|
+
const fetcher = customFetch2(options);
|
|
534
|
+
return {
|
|
535
|
+
algorithm,
|
|
536
|
+
...options.allowHttp ? { execute: [client.allowInsecureRequests] } : {},
|
|
537
|
+
...fetcher ? { [client.customFetch]: fetcher } : {}
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
async function discoverOAuth(serviceUrl, options = {}) {
|
|
541
|
+
const service = new URL(serviceUrl);
|
|
542
|
+
if (service.protocol !== "https:" && !(options.allowHttp && service.protocol === "http:")) {
|
|
543
|
+
throw new OAuthError("The service address must use https", "invalid_request");
|
|
544
|
+
}
|
|
545
|
+
const found = await protectedResource(service, options);
|
|
546
|
+
const issuer = found?.servers[0] ?? service.origin;
|
|
547
|
+
let lastError;
|
|
548
|
+
for (const algorithm of ["oauth2", "oidc"]) {
|
|
549
|
+
try {
|
|
550
|
+
const config = await client.discovery(
|
|
551
|
+
new URL(issuer),
|
|
552
|
+
"discovery",
|
|
553
|
+
void 0,
|
|
554
|
+
void 0,
|
|
555
|
+
discoveryOptions(options, algorithm)
|
|
556
|
+
);
|
|
557
|
+
const server = { ...config.serverMetadata() };
|
|
558
|
+
if (!server.authorization_endpoint || !server.token_endpoint) {
|
|
559
|
+
throw new OAuthError(
|
|
560
|
+
"The authorization server names no authorization or token endpoint",
|
|
561
|
+
"invalid_server"
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
return {
|
|
565
|
+
resource: found?.resource ?? null,
|
|
566
|
+
issuer: server.issuer,
|
|
567
|
+
scopes: found?.scopes.length ? found.scopes : server.scopes_supported ?? [],
|
|
568
|
+
server
|
|
569
|
+
};
|
|
570
|
+
} catch (error) {
|
|
571
|
+
lastError = error;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
throw toOAuthError(lastError, `Finding the authorization server of ${service.origin}`);
|
|
575
|
+
}
|
|
576
|
+
function tokensFrom(response, previousRefreshToken) {
|
|
577
|
+
const expiresIn = response.expiresIn();
|
|
578
|
+
return {
|
|
579
|
+
accessToken: response.access_token,
|
|
580
|
+
tokenType: response.token_type ?? "bearer",
|
|
581
|
+
refreshToken: response.refresh_token ?? previousRefreshToken,
|
|
582
|
+
expiresAt: expiresIn === void 0 ? null : Math.floor(Date.now() / 1e3) + expiresIn,
|
|
583
|
+
scope: response.scope ?? null
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
function createOAuthClient(options) {
|
|
587
|
+
const { server, clientId, clientSecret } = options;
|
|
588
|
+
const methods = server.token_endpoint_auth_methods_supported;
|
|
589
|
+
const authentication = !clientSecret ? client.None() : !methods || methods.includes("client_secret_basic") ? client.ClientSecretBasic(clientSecret) : client.ClientSecretPost(clientSecret);
|
|
590
|
+
const config = new client.Configuration(
|
|
591
|
+
server,
|
|
592
|
+
clientId,
|
|
593
|
+
void 0,
|
|
594
|
+
authentication
|
|
595
|
+
);
|
|
596
|
+
const fetcher = customFetch2(options);
|
|
597
|
+
if (fetcher) config[client.customFetch] = fetcher;
|
|
598
|
+
if (options.allowHttp) client.allowInsecureRequests(config);
|
|
599
|
+
const parameters = (values) => Object.fromEntries(
|
|
600
|
+
Object.entries(values).filter((entry) => Boolean(entry[1]))
|
|
601
|
+
);
|
|
602
|
+
return {
|
|
603
|
+
async authorize(input) {
|
|
604
|
+
const supported = server.code_challenge_methods_supported;
|
|
605
|
+
if (supported && !supported.includes("S256")) {
|
|
606
|
+
throw new OAuthError(
|
|
607
|
+
"The authorization server does not support PKCE with S256",
|
|
608
|
+
"invalid_server"
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
const codeVerifier = client.randomPKCECodeVerifier();
|
|
612
|
+
const state = client.randomState();
|
|
613
|
+
const url = client.buildAuthorizationUrl(
|
|
614
|
+
config,
|
|
615
|
+
parameters({
|
|
616
|
+
redirect_uri: input.redirectUri,
|
|
617
|
+
response_type: "code",
|
|
618
|
+
code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
|
|
619
|
+
code_challenge_method: "S256",
|
|
620
|
+
state,
|
|
621
|
+
scope: input.scope,
|
|
622
|
+
resource: input.resource
|
|
623
|
+
})
|
|
624
|
+
);
|
|
625
|
+
return { url: url.href, state, codeVerifier };
|
|
626
|
+
},
|
|
627
|
+
async exchangeCode(input) {
|
|
628
|
+
let callback;
|
|
629
|
+
if (typeof input.callback === "string") {
|
|
630
|
+
callback = new URL(input.callback);
|
|
631
|
+
} else {
|
|
632
|
+
callback = new URL(input.redirectUri);
|
|
633
|
+
for (const [name, value] of Object.entries(input.callback)) {
|
|
634
|
+
callback.searchParams.set(name, value);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
try {
|
|
638
|
+
const response = await client.authorizationCodeGrant(
|
|
639
|
+
config,
|
|
640
|
+
callback,
|
|
641
|
+
{
|
|
642
|
+
pkceCodeVerifier: input.codeVerifier,
|
|
643
|
+
expectedState: input.state,
|
|
644
|
+
idTokenExpected: false
|
|
645
|
+
},
|
|
646
|
+
parameters({ redirect_uri: input.redirectUri, resource: input.resource })
|
|
647
|
+
);
|
|
648
|
+
return tokensFrom(response, null);
|
|
649
|
+
} catch (error) {
|
|
650
|
+
throw toOAuthError(error, "The authorization");
|
|
651
|
+
}
|
|
652
|
+
},
|
|
653
|
+
async refresh(refreshToken, input = {}) {
|
|
654
|
+
try {
|
|
655
|
+
const response = await client.refreshTokenGrant(
|
|
656
|
+
config,
|
|
657
|
+
refreshToken,
|
|
658
|
+
parameters({ scope: input.scope, resource: input.resource })
|
|
659
|
+
);
|
|
660
|
+
return tokensFrom(response, refreshToken);
|
|
661
|
+
} catch (error) {
|
|
662
|
+
throw toOAuthError(error, "Renewing the token");
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
357
668
|
// src/pagination.ts
|
|
358
669
|
var DEFAULT_PAGE_SIZE = 20;
|
|
359
670
|
var MAX_PAGE_SIZE = 100;
|
|
@@ -378,6 +689,63 @@ function pageOf(items, total, params) {
|
|
|
378
689
|
return { items, page: params.page, page_size: params.pageSize, total };
|
|
379
690
|
}
|
|
380
691
|
|
|
692
|
+
// src/secrets.ts
|
|
693
|
+
import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from "crypto";
|
|
694
|
+
var VERSION = "v1";
|
|
695
|
+
var TAG_LENGTH = 16;
|
|
696
|
+
var MIN_SECRET_KEY_LENGTH = 32;
|
|
697
|
+
var DEV_SECRET = "platform-local-development-key-not-a-secret";
|
|
698
|
+
function createSecretBox(options) {
|
|
699
|
+
const { keyVariable, purpose } = options;
|
|
700
|
+
if (!keyVariable || !purpose) throw new Error("createSecretBox needs keyVariable and purpose");
|
|
701
|
+
let derived;
|
|
702
|
+
const key = () => {
|
|
703
|
+
const env = options.env ?? process.env;
|
|
704
|
+
const secret = env[keyVariable] || (isDevIdentityEnabled(env) ? DEV_SECRET : "");
|
|
705
|
+
if (secret.length < MIN_SECRET_KEY_LENGTH) {
|
|
706
|
+
throw new AppError(
|
|
707
|
+
`Secrets cannot be stored or read: the app has no encryption key. Ask the platform operator to set ${keyVariable}.`,
|
|
708
|
+
{ code: "secret_key_missing", status: 503 }
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
if (derived?.from !== secret) {
|
|
712
|
+
const bytes = hkdfSync("sha256", secret, Buffer.alloc(0), purpose, 32);
|
|
713
|
+
derived = { from: secret, key: Buffer.from(bytes) };
|
|
714
|
+
}
|
|
715
|
+
return derived.key;
|
|
716
|
+
};
|
|
717
|
+
return {
|
|
718
|
+
encrypt(plain, context) {
|
|
719
|
+
const iv = randomBytes(12);
|
|
720
|
+
const cipher = createCipheriv("aes-256-gcm", key(), iv, { authTagLength: TAG_LENGTH });
|
|
721
|
+
cipher.setAAD(Buffer.from(context, "utf8"));
|
|
722
|
+
const data = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
|
|
723
|
+
return [VERSION, iv, cipher.getAuthTag(), data].map((part) => typeof part === "string" ? part : part.toString("base64url")).join(".");
|
|
724
|
+
},
|
|
725
|
+
decrypt(stored, context) {
|
|
726
|
+
const secretKey = key();
|
|
727
|
+
const [version, iv, tag, data] = stored.split(".");
|
|
728
|
+
try {
|
|
729
|
+
if (version !== VERSION || !iv || !tag || data === void 0) throw new Error("format");
|
|
730
|
+
const decipher = createDecipheriv("aes-256-gcm", secretKey, Buffer.from(iv, "base64url"), {
|
|
731
|
+
authTagLength: TAG_LENGTH
|
|
732
|
+
});
|
|
733
|
+
decipher.setAAD(Buffer.from(context, "utf8"));
|
|
734
|
+
decipher.setAuthTag(Buffer.from(tag, "base64url"));
|
|
735
|
+
return Buffer.concat([
|
|
736
|
+
decipher.update(Buffer.from(data, "base64url")),
|
|
737
|
+
decipher.final()
|
|
738
|
+
]).toString("utf8");
|
|
739
|
+
} catch {
|
|
740
|
+
throw new AppError("The stored secret cannot be read. Enter it again.", {
|
|
741
|
+
code: "credential_unreadable",
|
|
742
|
+
status: 409
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
|
|
381
749
|
// src/url-guard.ts
|
|
382
750
|
import { lookup as dnsLookup } from "dns/promises";
|
|
383
751
|
import { BlockList, isIP } from "net";
|
|
@@ -467,35 +835,51 @@ async function assertPublicUrl(input, options = {}) {
|
|
|
467
835
|
return url;
|
|
468
836
|
}
|
|
469
837
|
export {
|
|
838
|
+
API_KEY_PREFIX,
|
|
839
|
+
API_KEY_REFUSAL_SECONDS,
|
|
470
840
|
APP_ID_PATTERN,
|
|
471
841
|
APP_NAME_PATTERN,
|
|
472
842
|
AppError,
|
|
473
843
|
ConflictError,
|
|
474
844
|
DEFAULT_PAGE_SIZE,
|
|
475
845
|
ForbiddenError,
|
|
846
|
+
MAX_API_KEY_CACHE_SECONDS,
|
|
476
847
|
MAX_PAGE_SIZE,
|
|
848
|
+
MIN_SECRET_KEY_LENGTH,
|
|
477
849
|
NotFoundError,
|
|
850
|
+
OAuthError,
|
|
478
851
|
ORGANIZATION_AUDIENCE_PREFIX,
|
|
479
852
|
REQUEST_ID_HEADER,
|
|
853
|
+
TOOL_NAME_PATTERN,
|
|
480
854
|
UnauthorizedError,
|
|
481
855
|
UnsafeUrlError,
|
|
482
856
|
ValidationError,
|
|
857
|
+
acceptApiKey,
|
|
858
|
+
apiKeyRoutes,
|
|
483
859
|
appBasePath,
|
|
860
|
+
assertApiKeyAccepted,
|
|
484
861
|
assertPublicUrl,
|
|
485
862
|
authenticate,
|
|
486
863
|
bearerToken,
|
|
487
864
|
callPlatform,
|
|
488
865
|
coerceRequestId,
|
|
489
866
|
createApp,
|
|
867
|
+
createKeyVerifier,
|
|
868
|
+
createOAuthClient,
|
|
869
|
+
createSecretBox,
|
|
490
870
|
createVerifier,
|
|
491
871
|
definePermissions,
|
|
872
|
+
defineTools,
|
|
873
|
+
discoverOAuth,
|
|
492
874
|
errorHandler,
|
|
493
875
|
generateAppId,
|
|
494
876
|
getRequestContext,
|
|
495
877
|
getRequestId,
|
|
496
878
|
getUser,
|
|
497
879
|
hasPermissions,
|
|
880
|
+
isApiKey,
|
|
498
881
|
isReservedAddress,
|
|
882
|
+
isToolSet,
|
|
499
883
|
isUuid,
|
|
500
884
|
isValidAppId,
|
|
501
885
|
isValidAppName,
|
|
@@ -509,7 +893,10 @@ export {
|
|
|
509
893
|
requireRole,
|
|
510
894
|
supportFromClaims,
|
|
511
895
|
toErrorResponse,
|
|
896
|
+
toolManifest,
|
|
897
|
+
toolProblems,
|
|
512
898
|
userFromClaims,
|
|
899
|
+
userFromKeyVerification,
|
|
513
900
|
uuidv7,
|
|
514
901
|
verifierFromEnv
|
|
515
902
|
};
|