@zjazj/server 0.0.8 → 0.0.10

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/index.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  configureLog,
3
3
  log,
4
4
  requestLogger
5
- } from "./chunk-26AAYRI3.js";
5
+ } from "./chunk-VJRJ53T2.js";
6
6
  import {
7
7
  ORGANIZATION_AUDIENCE_PREFIX,
8
8
  authenticate,
@@ -17,30 +17,41 @@ import {
17
17
  supportFromClaims,
18
18
  userFromClaims,
19
19
  verifierFromEnv
20
- } from "./chunk-EIZ24ILA.js";
20
+ } from "./chunk-7FPH47F6.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-UWDDQH25.js";
49
+ } from "./chunk-OBKMOVBA.js";
41
50
  import {
42
- isDevIdentityEnabled
43
- } from "./chunk-NMKEVYGN.js";
51
+ devIdentity,
52
+ isDevIdentityEnabled,
53
+ resolveDevKeyUser
54
+ } from "./chunk-3X4RSAM6.js";
44
55
  import {
45
56
  REQUEST_ID_HEADER,
46
57
  coerceRequestId,
@@ -56,6 +67,138 @@ import { serve } from "@hono/node-server";
56
67
  import { serveStatic } from "@hono/node-server/serve-static";
57
68
  import { Hono } from "hono";
58
69
 
70
+ // src/jobs.ts
71
+ import { matchedRoutes } from "hono/route";
72
+ var JOB_NAME_PATTERN = /^[a-z][a-z0-9-]{0,62}$/;
73
+ function jobCode(appName) {
74
+ return `${appName}:job:run`;
75
+ }
76
+ var JOB = /* @__PURE__ */ Symbol.for("zjazj.platform.job");
77
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
78
+ function jobOf(handler) {
79
+ let current = handler;
80
+ for (let depth = 0; typeof current === "function" && depth < 10; depth += 1) {
81
+ const options = current[JOB];
82
+ if (options) return options;
83
+ current = current[COMPOSED_HANDLER];
84
+ }
85
+ return void 0;
86
+ }
87
+ function job(options) {
88
+ if (options.scope !== "tenant" && options.scope !== "platform") {
89
+ throw new Error(`job(): scope must be 'tenant' or 'platform', not ${String(options.scope)}`);
90
+ }
91
+ if (options.scope === "platform" && options.schedulableWith !== void 0) {
92
+ throw new Error("job(): a platform job is scheduled by an operator. Leave out schedulableWith.");
93
+ }
94
+ const spec = { ...options };
95
+ const handler = async (_c, next) => {
96
+ await next();
97
+ };
98
+ Object.defineProperty(handler, JOB, { value: spec });
99
+ return handler;
100
+ }
101
+ function matchedJob(c) {
102
+ for (const route of matchedRoutes(c)) {
103
+ const found = jobOf(route.handler);
104
+ if (found) return found;
105
+ }
106
+ return void 0;
107
+ }
108
+ function jobRoutes(router, catalog) {
109
+ const found = /* @__PURE__ */ new Map();
110
+ for (const route of router.routes) {
111
+ const spec = jobOf(route.handler);
112
+ if (!spec) continue;
113
+ const name = route.path.replace(/^\//, "");
114
+ if (route.method !== "POST" || !JOB_NAME_PATTERN.test(name)) {
115
+ throw new Error(
116
+ `A job is POST /<name>, with a name of at most 63 lower case letters, digits and dashes: ${route.method} ${route.path}`
117
+ );
118
+ }
119
+ if (spec.schedulableWith !== void 0 && !catalog.has(spec.schedulableWith)) {
120
+ throw new Error(
121
+ `The job ${name} is schedulable with ${spec.schedulableWith}, which is not in the permission catalog`
122
+ );
123
+ }
124
+ found.set(name, {
125
+ name,
126
+ path: `/internal/jobs/${name}`,
127
+ title: spec.title ?? null,
128
+ scope: spec.scope,
129
+ schedulable_with: spec.schedulableWith ?? null
130
+ });
131
+ }
132
+ return [...found.values()];
133
+ }
134
+ function routesWithoutJob(router) {
135
+ const routes = /* @__PURE__ */ new Map();
136
+ for (const route of router.routes) {
137
+ if (route.method === "ALL" && route.path.endsWith("*")) continue;
138
+ const name = `${route.method} ${route.path}`;
139
+ routes.set(name, (routes.get(name) ?? false) || jobOf(route.handler) !== void 0);
140
+ }
141
+ return [...routes].filter(([, isJob]) => !isJob).map(([name]) => name);
142
+ }
143
+ function devJobCaller(appName, env) {
144
+ const identity = devIdentity(env);
145
+ return {
146
+ ...identity,
147
+ id: "key:dev",
148
+ username: "dev key",
149
+ permissions: [...identity.permissions, jobCode(appName)],
150
+ apiKey: { id: "dev", kind: "tenant", platform: true }
151
+ };
152
+ }
153
+ function authenticateJob(options) {
154
+ const env = options.env ?? process.env;
155
+ const dev = isDevIdentityEnabled(env);
156
+ const code = jobCode(options.appName);
157
+ return async (c, next) => {
158
+ const spec = matchedJob(c);
159
+ if (!spec) {
160
+ if (matchedRoutes(c).some((route) => route.method !== "ALL")) {
161
+ log.warn("A route of app.jobs has no job() and is not served", { path: c.req.path });
162
+ }
163
+ return c.notFound();
164
+ }
165
+ const token = bearerToken(c.req.header("Authorization"));
166
+ let user;
167
+ if (dev && token === void 0) {
168
+ user = devJobCaller(options.appName, env);
169
+ } else if (!isApiKey(token)) {
170
+ throw new UnauthorizedError("a job takes the API key of a tenant", {
171
+ code: "api_key_required"
172
+ });
173
+ } else if (dev) {
174
+ user = resolveDevKeyUser(token, env);
175
+ } else {
176
+ user = await options.keyVerifier.verify(token);
177
+ }
178
+ if (user.apiKey?.kind !== "tenant") {
179
+ throw new ForbiddenError("a job takes the API key of a tenant, not of a user", {
180
+ code: "tenant_key_required"
181
+ });
182
+ }
183
+ if (!user.permissions.includes(code)) {
184
+ throw new ForbiddenError(`requires permission: ${code}`, {
185
+ code: "insufficient_permission"
186
+ });
187
+ }
188
+ if (spec.scope === "platform" && user.apiKey.platform !== true) {
189
+ throw new ForbiddenError("a platform job takes a key of the platform\u2019s own tenant", {
190
+ code: "platform_key_required"
191
+ });
192
+ }
193
+ c.set("user", user);
194
+ c.set("apiKeyAccepted", true);
195
+ c.set("job", { name: c.req.path.split("/").pop() ?? "", scope: spec.scope });
196
+ const context = getRequestContext();
197
+ if (context) context.user = user;
198
+ await next();
199
+ };
200
+ }
201
+
59
202
  // src/tools.ts
60
203
  var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]{0,40}$/;
61
204
  var PERMISSION_CODE = /^[a-z][a-z0-9-]*(:[a-z][a-z0-9-]*)+$/;
@@ -93,6 +236,11 @@ function toolProblems(tools) {
93
236
  `${label}: a tool that changes data must say destructiveHint, true when it can delete or overwrite data.`
94
237
  );
95
238
  }
239
+ if (annotations && typeof annotations.openWorldHint !== "boolean") {
240
+ problems.push(
241
+ `${label}: the annotations must say openWorldHint, true when the tool calls a system outside the platform and false otherwise.`
242
+ );
243
+ }
96
244
  const input = tool?.input;
97
245
  if (!input || typeof input !== "object" || !("~standard" in input)) {
98
246
  problems.push(`${label}: the input must be a schema, such as z.object({ ... }).`);
@@ -104,12 +252,12 @@ function toolProblems(tools) {
104
252
  return problems;
105
253
  }
106
254
  function defineTools(tools) {
107
- const list = [...tools];
108
- const problems = toolProblems(list);
255
+ const list2 = [...tools];
256
+ const problems = toolProblems(list2);
109
257
  if (problems.length > 0) throw new Error(`Invalid tools:
110
258
  - ${problems.join("\n- ")}`);
111
- Object.defineProperty(list, TOOL_SET, { value: true });
112
- return Object.freeze(list);
259
+ Object.defineProperty(list2, TOOL_SET, { value: true });
260
+ return Object.freeze(list2);
113
261
  }
114
262
  function toolManifest(tools) {
115
263
  return tools.map((tool) => ({
@@ -136,9 +284,12 @@ function platformManifest(options) {
136
284
  permission_manifest: (options.permissions ?? []).map((permission) => ({
137
285
  code: permission.code,
138
286
  title: permission.title,
139
- description: permission.description ?? null
287
+ description: permission.description ?? null,
288
+ scope: permission.scope ?? "tenant"
140
289
  })),
141
290
  tools: toolManifest(options.tools ?? []),
291
+ api_key_routes: (options.apiKeyRoutes ?? []).map((route) => ({ ...route })),
292
+ jobs: (options.jobs ?? []).map((entry) => ({ ...entry })),
142
293
  release_version: manifest.version ?? null,
143
294
  source_commit: env.GIT_SHA || null
144
295
  };
@@ -160,6 +311,7 @@ function errorBody(value) {
160
311
  return { code, message, field: typeof field === "string" ? field : void 0 };
161
312
  }
162
313
  async function callPlatform(c, path2, call = {}, options = {}) {
314
+ assertApiKeyAccepted(c);
163
315
  const env = options.env ?? process.env;
164
316
  const base = env.PLATFORM_URL?.replace(/\/+$/, "");
165
317
  if (!base) {
@@ -209,9 +361,9 @@ async function callPlatform(c, path2, call = {}, options = {}) {
209
361
  }
210
362
  return answer;
211
363
  }
212
- const refused = status < 500 ? errorBody(answer) : void 0;
213
- if (refused) {
214
- throw new AppError(refused.message, { code: refused.code, status, field: refused.field });
364
+ const refused2 = status < 500 ? errorBody(answer) : void 0;
365
+ if (refused2) {
366
+ throw new AppError(refused2.message, { code: refused2.code, status, field: refused2.field });
215
367
  }
216
368
  throw new AppError(
217
369
  status < 500 ? "The control plane refused the request" : "The control plane failed",
@@ -261,8 +413,28 @@ function createApp(options) {
261
413
  );
262
414
  configureLog({ app: manifest.name, env: env.ENV || env.NODE_ENV || "development" });
263
415
  const tools = options.tools ?? [];
416
+ const objectKinds = options.objects?.kinds ?? {};
417
+ const objectRegistry = options.objects ? { appName: manifest.name, schema: manifest.id, kinds: objectKinds } : void 0;
418
+ const reserved = [jobCode(manifest.name), `${manifest.name}:object:admin`];
419
+ const declaredReserved = (options.permissions ?? []).filter(
420
+ (permission) => reserved.includes(permission.code)
421
+ );
422
+ if (declaredReserved.length > 0) {
423
+ throw new Error(
424
+ `The platform declares ${declaredReserved.map((permission) => permission.code).join(" and ")} by itself. Take it out of the catalog.`
425
+ );
426
+ }
427
+ if (options.objects && !options.database) {
428
+ throw new Error("Object kinds need the tenant database. Pass `database: true` to createApp.");
429
+ }
264
430
  if (options.permissions) {
265
431
  const catalog = new Set(options.permissions.map((permission) => permission.code));
432
+ const unshared = Object.entries(objectKinds).filter(([, kind]) => !catalog.has(kind.permission));
433
+ if (unshared.length > 0) {
434
+ throw new Error(
435
+ `Object kinds are shared with permissions that are not in the catalog: ${unshared.map(([type, kind]) => `${type} (${kind.permission})`).join(", ")}`
436
+ );
437
+ }
266
438
  const unknown = tools.filter((tool) => !catalog.has(tool.permission));
267
439
  if (unknown.length > 0) {
268
440
  throw new Error(
@@ -287,6 +459,10 @@ function createApp(options) {
287
459
  migrationsFolder: databaseOptions.migrationsFolder,
288
460
  appName: manifest.name
289
461
  });
462
+ if (options.objects) {
463
+ const { assertObjectTables } = await import("./objects.js");
464
+ await assertObjectTables(database);
465
+ }
290
466
  return database;
291
467
  })();
292
468
  pending.catch(() => cache.delete(manifest.id));
@@ -294,9 +470,11 @@ function createApp(options) {
294
470
  }
295
471
  return pending;
296
472
  };
473
+ const keyVerifier = options.keyVerifier ?? createKeyVerifier({ env, fetch: options.fetch });
474
+ const credentials = { verifier: options.verifier, keyVerifier, env };
297
475
  const forUsers = () => {
298
476
  const router = new Hono();
299
- router.use("*", authenticate({ verifier: options.verifier, env }));
477
+ router.use("*", authenticate(credentials));
300
478
  if (databaseOptions) {
301
479
  router.use("*", async (c, next) => {
302
480
  const { tenantDatabase } = await import("./db.js");
@@ -309,8 +487,17 @@ function createApp(options) {
309
487
  const delegated = forUsers();
310
488
  const publicApi = new Hono();
311
489
  const internal = new Hono();
490
+ const jobs = new Hono();
491
+ jobs.use("*", authenticateJob({ appName: manifest.name, keyVerifier, env }));
492
+ if (databaseOptions) {
493
+ jobs.use("*", async (c, next) => {
494
+ if (c.get("job")?.scope !== "tenant") return next();
495
+ const { tenantDatabase } = await import("./db.js");
496
+ return tenantDatabase(getDatabase)(c, next);
497
+ });
498
+ }
312
499
  const platformRoutes = new Hono();
313
- platformRoutes.use("*", authenticate({ verifier: options.verifier, env }));
500
+ platformRoutes.use("*", authenticate(credentials));
314
501
  const toPlatform = { env, fetch: options.fetch };
315
502
  platformRoutes.get("/tenants", async (c) => {
316
503
  const { q, page, page_size: pageSize } = c.req.query();
@@ -336,22 +523,129 @@ function createApp(options) {
336
523
  await callPlatform(c, "/support/sessions/current", { method: "DELETE" }, toPlatform);
337
524
  return c.body(null, 204);
338
525
  });
526
+ const devDirectory = isDevIdentityEnabled(env) && !env.PLATFORM_URL;
527
+ platformRoutes.get("/directory/members", async (c) => {
528
+ const { q, page, page_size: pageSize, ids } = c.req.query();
529
+ if (devDirectory) {
530
+ const user = getUser(c);
531
+ const wanted = ids?.split(",").map((id) => id.trim());
532
+ const items = wanted && !wanted.includes(user.id) ? [] : [{ id: user.id, name: user.username, avatar: null }];
533
+ return c.json({ items, page: 1, page_size: Number(pageSize) || 20, total: items.length });
534
+ }
535
+ const query = { q, page, page_size: pageSize, ids };
536
+ return c.json(await callPlatform(c, "/directory/members", { query }, toPlatform));
537
+ });
538
+ platformRoutes.get("/directory/roles", async (c) => {
539
+ if (devDirectory) return c.json(getUser(c).roles.map((code) => ({ code, name: code })));
540
+ return c.json(await callPlatform(c, "/directory/roles", {}, toPlatform));
541
+ });
542
+ if (objectRegistry) {
543
+ platformRoutes.use("/objects/*", async (c, next) => {
544
+ const { tenantDatabase } = await import("./db.js");
545
+ return tenantDatabase(getDatabase)(c, next);
546
+ });
547
+ const kindOf = (c) => {
548
+ const type = c.req.param("type") ?? "";
549
+ const kind = Object.hasOwn(objectKinds, type) ? objectKinds[type] : void 0;
550
+ if (!kind) throw new NotFoundError(`No ${type} with this id`);
551
+ if (!hasPermissions(getUser(c).permissions, [kind.permission])) {
552
+ throw new ForbiddenError(`requires permission: ${kind.permission}`, {
553
+ code: "insufficient_permission"
554
+ });
555
+ }
556
+ return type;
557
+ };
558
+ const sharingOf = async (c, type, id) => {
559
+ const { getSharing } = await import("./objects.js");
560
+ const sharing = await getSharing(c, type, id);
561
+ return {
562
+ owner_id: sharing.ownerId,
563
+ visibility: sharing.visibility,
564
+ grants: sharing.grants.map((grant) => ({
565
+ principal_type: grant.principalType,
566
+ principal_id: grant.principalId,
567
+ level: grant.level
568
+ })),
569
+ level: sharing.level
570
+ };
571
+ };
572
+ platformRoutes.get(
573
+ "/objects/:type/:id/sharing",
574
+ async (c) => c.json(await sharingOf(c, kindOf(c), c.req.param("id")))
575
+ );
576
+ platformRoutes.put("/objects/:type/:id/sharing", async (c) => {
577
+ const type = kindOf(c);
578
+ const id = c.req.param("id");
579
+ const body = await c.req.json().catch(() => ({}));
580
+ const { parseGrants, setSharing } = await import("./objects.js");
581
+ const visibility = body.visibility;
582
+ if (visibility !== "private" && visibility !== "tenant") {
583
+ throw new ValidationError("visibility is private or tenant", "visibility");
584
+ }
585
+ const grants = parseGrants(body.grants);
586
+ await setSharing(c, type, id, { visibility, grants });
587
+ return c.json(await sharingOf(c, type, id));
588
+ });
589
+ platformRoutes.put("/objects/:type/:id/owner", async (c) => {
590
+ const type = kindOf(c);
591
+ const id = c.req.param("id");
592
+ const body = await c.req.json().catch(() => ({ owner_id: void 0 }));
593
+ const ownerId = body.owner_id;
594
+ if (typeof ownerId !== "string" || ownerId === "" || ownerId.length > 200) {
595
+ throw new ValidationError("owner_id must be the id of a member", "owner_id");
596
+ }
597
+ const { assertCan, transferObject } = await import("./objects.js");
598
+ await assertCan(c, type, id, "transfer");
599
+ if (!devDirectory) {
600
+ const answer = await callPlatform(
601
+ c,
602
+ "/directory/members",
603
+ { query: { ids: ownerId } },
604
+ toPlatform
605
+ );
606
+ if (!answer?.items?.some((member) => member.id === ownerId)) {
607
+ throw new ValidationError("The new owner is not a member of the tenant", "owner_id");
608
+ }
609
+ }
610
+ await transferObject(c, type, id, ownerId);
611
+ const after = await sharingOf(c, type, id).catch(() => void 0);
612
+ return c.json(after ?? { owner_id: ownerId });
613
+ });
614
+ }
339
615
  let built;
340
616
  const build = () => {
617
+ const misplaced = internal.routes.filter(
618
+ (route) => (route.path === "/jobs" || route.path.startsWith("/jobs/")) && !(route.method === "ALL" && route.path.endsWith("*"))
619
+ );
620
+ if (misplaced.length > 0) {
621
+ throw new Error(
622
+ `Move the jobs from app.internal to app.jobs, with job(): ${misplaced.map((route) => `${route.method} /internal${route.path}`).join(", ")}`
623
+ );
624
+ }
625
+ const unmarked = routesWithoutJob(jobs);
626
+ if (unmarked.length > 0) {
627
+ throw new Error(`Every route of app.jobs starts with job(...): ${unmarked.join(", ")}`);
628
+ }
629
+ manifestNow();
341
630
  const root = new Hono();
342
631
  root.use("*", requestContext());
343
632
  root.use("*", requestLogger());
633
+ if (objectRegistry) {
634
+ root.use("*", async (c, next) => {
635
+ c.set("platformObjects", objectRegistry);
636
+ await next();
637
+ });
638
+ }
344
639
  root.onError(errorHandler((error) => log.error("Unhandled error", { err: error })));
345
640
  root.notFound(notFoundHandler());
346
641
  root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
347
642
  root.use("/internal/*", internalCallersOnly);
348
- root.get(
349
- "/internal/_platform/manifest",
350
- (c) => c.json(platformManifest({ manifest, permissions: options.permissions, tools, env }))
351
- );
643
+ root.get("/internal/_platform/manifest", (c) => c.json(manifestNow()));
352
644
  root.all("/internal/_platform/*", (c) => c.notFound());
353
645
  root.route("/internal/delegated", delegated);
354
646
  root.all("/internal/delegated/*", (c) => c.notFound());
647
+ root.route("/internal/jobs", jobs);
648
+ root.all("/internal/jobs/*", (c) => c.notFound());
355
649
  root.route("/internal", internal);
356
650
  const scoped = new Hono();
357
651
  scoped.get(
@@ -370,11 +664,11 @@ function createApp(options) {
370
664
  scoped.all("/api/*", (c) => c.notFound());
371
665
  if (tools.length > 0) {
372
666
  const mcp = new Hono();
373
- mcp.use("*", authenticate({ verifier: options.verifier, env }));
667
+ mcp.use("*", authenticate({ ...credentials, acceptApiKeys: true }));
374
668
  let route;
375
669
  mcp.all("/", async (c) => {
376
670
  if (!route) {
377
- const { createMcpRoute } = await import("./mcp-UM4G354G.js");
671
+ const { createMcpRoute } = await import("./mcp-6W7AB46O.js");
378
672
  route ??= createMcpRoute({
379
673
  manifest,
380
674
  tools,
@@ -406,6 +700,40 @@ function createApp(options) {
406
700
  root.route(basePath || "/", scoped);
407
701
  return root;
408
702
  };
703
+ const manifestNow = () => {
704
+ const declared = options.permissions ?? [];
705
+ const catalog = new Set(declared.map((permission) => permission.code));
706
+ const jobList = jobRoutes(jobs, catalog);
707
+ const title = manifest.platform?.title ?? manifest.name;
708
+ const added = [
709
+ ...jobList.length > 0 ? [
710
+ {
711
+ code: jobCode(manifest.name),
712
+ title: `Run the scheduled jobs of ${title}`,
713
+ description: "Held by the role of the tenant\u2019s default key for scheduled jobs, and by nothing else."
714
+ }
715
+ ] : [],
716
+ ...objectRegistry ? [
717
+ {
718
+ code: `${manifest.name}:object:admin`,
719
+ title: `Act on every object of ${title}`,
720
+ description: "See, change, share, delete and restore any object of the app, and pass ownership on."
721
+ }
722
+ ] : []
723
+ ];
724
+ return platformManifest({
725
+ manifest,
726
+ permissions: [...declared, ...added],
727
+ jobs: jobList,
728
+ tools,
729
+ apiKeyRoutes: [
730
+ ...tools.length > 0 ? [{ method: "POST", path: "/mcp" }] : [],
731
+ ...apiKeyRoutes(api, "/api"),
732
+ ...apiKeyRoutes(delegated, "/internal/delegated")
733
+ ],
734
+ env
735
+ });
736
+ };
409
737
  const fetchHandler = (request, ...rest) => {
410
738
  built ??= build();
411
739
  return built.fetch(request, ...rest);
@@ -417,8 +745,10 @@ function createApp(options) {
417
745
  publicApi,
418
746
  internal,
419
747
  delegated,
748
+ jobs,
420
749
  fetch: fetchHandler,
421
750
  database: getDatabase,
751
+ platformManifest: manifestNow,
422
752
  async start() {
423
753
  const port = Number(env.PORT ?? 8080);
424
754
  if (!Number.isInteger(port) || port <= 0) throw new Error(`Invalid PORT: ${env.PORT}`);
@@ -447,6 +777,324 @@ function createApp(options) {
447
777
  };
448
778
  }
449
779
 
780
+ // src/fetch-public.ts
781
+ import { request as httpRequest } from "http";
782
+ import { request as httpsRequest } from "https";
783
+ import { isIP as isIP2 } from "net";
784
+
785
+ // src/url-guard.ts
786
+ import { lookup as dnsLookup } from "dns/promises";
787
+ import { BlockList, isIP } from "net";
788
+ var UnsafeUrlError = class extends AppError {
789
+ constructor(message) {
790
+ super(message, { code: "unsafe_url", status: 400 });
791
+ }
792
+ };
793
+ var reservedIpv4 = new BlockList();
794
+ for (const [network, prefix] of [
795
+ ["0.0.0.0", 8],
796
+ // this network, unspecified
797
+ ["10.0.0.0", 8],
798
+ // private
799
+ ["100.64.0.0", 10],
800
+ // shared address space, CGNAT
801
+ ["127.0.0.0", 8],
802
+ // loopback
803
+ ["169.254.0.0", 16],
804
+ // link local, cloud metadata
805
+ ["172.16.0.0", 12],
806
+ // private
807
+ ["192.0.0.0", 24],
808
+ // protocol assignments
809
+ ["192.0.2.0", 24],
810
+ // documentation
811
+ ["192.88.99.0", 24],
812
+ // 6to4 relay
813
+ ["192.168.0.0", 16],
814
+ // private
815
+ ["198.18.0.0", 15],
816
+ // benchmarking
817
+ ["198.51.100.0", 24],
818
+ // documentation
819
+ ["203.0.113.0", 24],
820
+ // documentation
821
+ ["224.0.0.0", 4],
822
+ // multicast
823
+ ["240.0.0.0", 4]
824
+ // reserved, broadcast
825
+ ]) {
826
+ reservedIpv4.addSubnet(network, prefix, "ipv4");
827
+ }
828
+ var reservedIpv6 = new BlockList();
829
+ for (const [network, prefix] of [
830
+ ["2001::", 23],
831
+ // protocol assignments: Teredo, benchmarking, ORCHID
832
+ ["2001:db8::", 32],
833
+ // documentation
834
+ ["2002::", 16],
835
+ // 6to4, which carries an IPv4 address of any kind
836
+ ["3fff::", 20]
837
+ // documentation
838
+ ]) {
839
+ reservedIpv6.addSubnet(network, prefix, "ipv6");
840
+ }
841
+ function ipv6Words(address) {
842
+ const canonical = new URL(`http://[${address}]`).hostname.slice(1, -1);
843
+ const [head = "", tail] = canonical.split("::");
844
+ const left = head ? head.split(":") : [];
845
+ const right = tail ? tail.split(":") : [];
846
+ const zeros = tail === void 0 ? [] : Array(8 - left.length - right.length).fill("0");
847
+ return [...left, ...zeros, ...right].map((word) => Number.parseInt(word, 16));
848
+ }
849
+ function plainAddress(address) {
850
+ const bare = address.replace(/%.*$/, "");
851
+ const family = isIP(bare);
852
+ if (family === 4) return { address: bare, family: 4 };
853
+ if (family !== 6) return void 0;
854
+ const words = ipv6Words(bare);
855
+ if (words.slice(0, 5).every((word) => word === 0) && words[5] === 65535) {
856
+ const [high = 0, low = 0] = words.slice(6);
857
+ return { address: `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`, family: 4 };
858
+ }
859
+ return { address: bare, family: 6 };
860
+ }
861
+ function isReservedAddress(address) {
862
+ const plain = plainAddress(address);
863
+ if (!plain) return true;
864
+ if (plain.family === 4) return reservedIpv4.check(plain.address, "ipv4");
865
+ const [first = 0] = ipv6Words(plain.address);
866
+ if ((first & 57344) !== 8192) return true;
867
+ return reservedIpv6.check(plain.address, "ipv6");
868
+ }
869
+ function list(value) {
870
+ return (value ?? "").split(",").map((item) => item.trim().toLowerCase()).filter(Boolean);
871
+ }
872
+ var warned = false;
873
+ function devAllowances(env) {
874
+ const hosts = list(env.URL_GUARD_ALLOW_HOSTS);
875
+ const networks = list(env.DEV_PUBLIC_NETWORKS);
876
+ if (!isDevIdentityEnabled(env)) {
877
+ if ((hosts.length > 0 || networks.length > 0) && !warned) {
878
+ warned = true;
879
+ log.warn(
880
+ "URL_GUARD_ALLOW_HOSTS and DEV_PUBLIC_NETWORKS are ignored: they count only with ENV=dev"
881
+ );
882
+ }
883
+ return { hosts: [] };
884
+ }
885
+ if (networks.length === 0) return { hosts };
886
+ const allowed = new BlockList();
887
+ for (const entry of networks) {
888
+ const [network = "", bits = ""] = entry.split("/");
889
+ const family = isIP(network);
890
+ const prefix = Number(bits);
891
+ const most = family === 4 ? 32 : 128;
892
+ if (family === 0 || !/^\d+$/.test(bits) || prefix > most) {
893
+ throw new Error(`DEV_PUBLIC_NETWORKS: ${entry} is not a network such as 198.18.0.0/15`);
894
+ }
895
+ allowed.addSubnet(network, prefix, family === 4 ? "ipv4" : "ipv6");
896
+ }
897
+ return { hosts, networks: allowed };
898
+ }
899
+ function refused(address, networks) {
900
+ const plain = plainAddress(address);
901
+ if (!plain) return true;
902
+ if (networks?.check(plain.address, plain.family === 4 ? "ipv4" : "ipv6")) return false;
903
+ return isReservedAddress(address);
904
+ }
905
+ async function resolve(hostname) {
906
+ const records = await dnsLookup(hostname, { all: true });
907
+ return records.map((record) => record.address);
908
+ }
909
+ async function checkPublicUrl(input, options = {}) {
910
+ let url;
911
+ try {
912
+ url = input instanceof URL ? new URL(input.href) : new URL(input);
913
+ } catch {
914
+ throw new UnsafeUrlError("URL is not valid");
915
+ }
916
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
917
+ throw new UnsafeUrlError("URL must use http or https");
918
+ }
919
+ const hostname = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
920
+ if (!hostname) throw new UnsafeUrlError("URL has no host");
921
+ const dev = devAllowances(options.env ?? process.env);
922
+ const allowed = [...(options.allowHosts ?? []).map((host) => host.toLowerCase()), ...dev.hosts];
923
+ if (allowed.includes(hostname)) return { url, addresses: [] };
924
+ if (isIP(hostname)) {
925
+ if (refused(hostname, dev.networks)) {
926
+ throw new UnsafeUrlError("URL resolves to a private or reserved address");
927
+ }
928
+ return { url, addresses: [] };
929
+ }
930
+ let addresses;
931
+ try {
932
+ addresses = await (options.lookup ?? resolve)(hostname);
933
+ } catch {
934
+ throw new UnsafeUrlError("URL host cannot be resolved");
935
+ }
936
+ if (addresses.length === 0 || addresses.some((address) => refused(address, dev.networks))) {
937
+ throw new UnsafeUrlError("URL resolves to a private or reserved address");
938
+ }
939
+ return { url, addresses };
940
+ }
941
+ async function assertPublicUrl(input, options = {}) {
942
+ return (await checkPublicUrl(input, options)).url;
943
+ }
944
+
945
+ // src/fetch-public.ts
946
+ var FAILURES = {
947
+ redirect: { code: "upstream_redirect", status: 502 },
948
+ timeout: { code: "upstream_timeout", status: 504 },
949
+ unreachable: { code: "upstream_unreachable", status: 502 },
950
+ too_large: { code: "upstream_too_large", status: 502 }
951
+ };
952
+ var FetchPublicError = class extends AppError {
953
+ reason;
954
+ /** The status of a redirect the address answered with. */
955
+ upstreamStatus;
956
+ constructor(reason, message, options = {}) {
957
+ super(message, { ...FAILURES[reason], cause: options.cause });
958
+ this.reason = reason;
959
+ if (options.upstreamStatus !== void 0) this.upstreamStatus = options.upstreamStatus;
960
+ }
961
+ };
962
+ var FETCH_PUBLIC_TIMEOUT = 1e4;
963
+ var FETCH_PUBLIC_MAX_BYTES = 5 * 1024 * 1024;
964
+ var NO_BODY = /* @__PURE__ */ new Set([101, 103, 204, 205, 304]);
965
+ function headersOf(response) {
966
+ const headers = new Headers();
967
+ const raw = response.rawHeaders;
968
+ for (let i = 0; i + 1 < raw.length; i += 2) {
969
+ try {
970
+ headers.append(raw[i], raw[i + 1]);
971
+ } catch {
972
+ }
973
+ }
974
+ return headers;
975
+ }
976
+ async function fetchPublic(input, init = {}) {
977
+ const timeout = init.timeout ?? FETCH_PUBLIC_TIMEOUT;
978
+ const maxBytes = init.maxBytes ?? FETCH_PUBLIC_MAX_BYTES;
979
+ const timer = AbortSignal.timeout(timeout);
980
+ const signal = init.signal ? AbortSignal.any([timer, init.signal]) : timer;
981
+ const { url, addresses } = await checkPublicUrl(input, init);
982
+ if (signal.aborted) throw stopped(signal, timer, timeout);
983
+ const pinned = addresses.length > 0 ? (_hostname, options, callback) => {
984
+ const wanted = options.family === 4 || options.family === 6 ? options.family : 0;
985
+ const entries = addresses.map((address) => ({ address, family: isIP2(address) })).filter((entry) => wanted === 0 || entry.family === wanted);
986
+ const [first] = entries;
987
+ if (!first) {
988
+ callback(
989
+ Object.assign(new Error("No checked address of that family"), { code: "ENOTFOUND" }),
990
+ "",
991
+ 0
992
+ );
993
+ } else if (options.all) {
994
+ ;
995
+ callback(null, entries);
996
+ } else {
997
+ callback(null, first.address, first.family);
998
+ }
999
+ } : void 0;
1000
+ const headers = {};
1001
+ new Headers(init.headers).forEach((value, name) => {
1002
+ headers[name] = value;
1003
+ });
1004
+ headers["accept-encoding"] = "identity";
1005
+ const body = init.body ?? void 0;
1006
+ if (body !== void 0) headers["content-length"] = String(Buffer.byteLength(body));
1007
+ return new Promise((resolve2, reject) => {
1008
+ const fail = (error) => {
1009
+ if (signal.aborted) reject(stopped(signal, timer, timeout));
1010
+ else if (error instanceof FetchPublicError) reject(error);
1011
+ else
1012
+ reject(
1013
+ new FetchPublicError("unreachable", `${url.host} cannot be reached`, { cause: error })
1014
+ );
1015
+ };
1016
+ const send = url.protocol === "https:" ? httpsRequest : httpRequest;
1017
+ const request = send(
1018
+ url,
1019
+ {
1020
+ method: init.method ?? "GET",
1021
+ headers,
1022
+ lookup: pinned,
1023
+ // A connection of its own, closed afterwards. A kept one is found again by the name
1024
+ // alone, whatever the name pointed to when it was opened.
1025
+ agent: false,
1026
+ signal
1027
+ },
1028
+ (response) => {
1029
+ const status = response.statusCode ?? 0;
1030
+ if (status >= 300 && status < 400 && status !== 304) {
1031
+ response.destroy();
1032
+ fail(
1033
+ new FetchPublicError(
1034
+ "redirect",
1035
+ `${url.host} answered with a redirect, which is not followed`,
1036
+ {
1037
+ upstreamStatus: status
1038
+ }
1039
+ )
1040
+ );
1041
+ return;
1042
+ }
1043
+ const declared = Number(response.headers["content-length"]);
1044
+ if (Number.isFinite(declared) && declared > maxBytes) {
1045
+ response.destroy();
1046
+ fail(
1047
+ new FetchPublicError(
1048
+ "too_large",
1049
+ `${url.host} answered with more than ${maxBytes} bytes`
1050
+ )
1051
+ );
1052
+ return;
1053
+ }
1054
+ const chunks = [];
1055
+ let size = 0;
1056
+ response.on("data", (chunk) => {
1057
+ size += chunk.length;
1058
+ if (size > maxBytes) {
1059
+ response.destroy();
1060
+ fail(
1061
+ new FetchPublicError(
1062
+ "too_large",
1063
+ `${url.host} answered with more than ${maxBytes} bytes`
1064
+ )
1065
+ );
1066
+ return;
1067
+ }
1068
+ chunks.push(chunk);
1069
+ });
1070
+ response.on("error", fail);
1071
+ response.on("close", () => {
1072
+ if (!response.complete) fail(new Error("The answer broke off"));
1073
+ });
1074
+ response.on("end", () => {
1075
+ const answer = new Response(NO_BODY.has(status) ? null : Buffer.concat(chunks), {
1076
+ status,
1077
+ statusText: response.statusMessage ?? "",
1078
+ headers: headersOf(response)
1079
+ });
1080
+ Object.defineProperty(answer, "url", { value: url.href });
1081
+ resolve2(answer);
1082
+ });
1083
+ }
1084
+ );
1085
+ request.on("error", fail);
1086
+ request.end(body);
1087
+ });
1088
+ }
1089
+ function stopped(signal, timer, timeout) {
1090
+ if (timer.aborted) {
1091
+ return new FetchPublicError("timeout", `No answer within ${timeout} ms`, {
1092
+ cause: signal.reason
1093
+ });
1094
+ }
1095
+ return signal.reason;
1096
+ }
1097
+
450
1098
  // src/oauth.ts
451
1099
  import * as client from "openid-client";
452
1100
  var OAuthError = class extends AppError {
@@ -718,102 +1366,20 @@ function createSecretBox(options) {
718
1366
  }
719
1367
  };
720
1368
  }
721
-
722
- // src/url-guard.ts
723
- import { lookup as dnsLookup } from "dns/promises";
724
- import { BlockList, isIP } from "net";
725
- var UnsafeUrlError = class extends AppError {
726
- constructor(message) {
727
- super(message, { code: "unsafe_url", status: 400 });
728
- }
729
- };
730
- var blocked = new BlockList();
731
- for (const [network, prefix] of [
732
- ["0.0.0.0", 8],
733
- ["10.0.0.0", 8],
734
- ["100.64.0.0", 10],
735
- ["127.0.0.0", 8],
736
- ["169.254.0.0", 16],
737
- ["172.16.0.0", 12],
738
- ["192.0.0.0", 24],
739
- ["192.0.2.0", 24],
740
- ["192.168.0.0", 16],
741
- ["198.18.0.0", 15],
742
- ["198.51.100.0", 24],
743
- ["203.0.113.0", 24],
744
- ["224.0.0.0", 4],
745
- ["240.0.0.0", 4]
746
- ]) {
747
- blocked.addSubnet(network, prefix, "ipv4");
748
- }
749
- for (const [network, prefix] of [
750
- ["::", 127],
751
- // unspecified and loopback
752
- ["64:ff9b::", 96],
753
- // NAT64
754
- ["2001:db8::", 32],
755
- // documentation
756
- ["fc00::", 7],
757
- // unique local
758
- ["fe80::", 10],
759
- // link local
760
- ["ff00::", 8]
761
- // multicast
762
- ]) {
763
- blocked.addSubnet(network, prefix, "ipv6");
764
- }
765
- function isReservedAddress(address) {
766
- const family = isIP(address);
767
- if (family === 4) return blocked.check(address, "ipv4");
768
- if (family === 6) return blocked.check(address, "ipv6");
769
- return true;
770
- }
771
- function envAllowList() {
772
- return (process.env.URL_GUARD_ALLOW_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(Boolean);
773
- }
774
- async function resolve(hostname) {
775
- const records = await dnsLookup(hostname, { all: true });
776
- return records.map((record) => record.address);
777
- }
778
- async function assertPublicUrl(input, options = {}) {
779
- let url;
780
- try {
781
- url = input instanceof URL ? input : new URL(input);
782
- } catch {
783
- throw new UnsafeUrlError("URL is not valid");
784
- }
785
- if (url.protocol !== "http:" && url.protocol !== "https:") {
786
- throw new UnsafeUrlError("URL must use http or https");
787
- }
788
- const hostname = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
789
- if (!hostname) throw new UnsafeUrlError("URL has no host");
790
- const allowed = [
791
- ...(options.allowHosts ?? []).map((host) => host.toLowerCase()),
792
- ...envAllowList()
793
- ];
794
- if (allowed.includes(hostname)) return url;
795
- let addresses;
796
- if (isIP(hostname)) {
797
- addresses = [hostname];
798
- } else {
799
- try {
800
- addresses = await (options.lookup ?? resolve)(hostname);
801
- } catch {
802
- throw new UnsafeUrlError("URL host cannot be resolved");
803
- }
804
- }
805
- if (addresses.length === 0 || addresses.some(isReservedAddress)) {
806
- throw new UnsafeUrlError("URL resolves to a private or reserved address");
807
- }
808
- return url;
809
- }
810
1369
  export {
1370
+ API_KEY_PREFIX,
1371
+ API_KEY_REFUSAL_SECONDS,
811
1372
  APP_ID_PATTERN,
812
1373
  APP_NAME_PATTERN,
813
1374
  AppError,
814
1375
  ConflictError,
815
1376
  DEFAULT_PAGE_SIZE,
1377
+ FETCH_PUBLIC_MAX_BYTES,
1378
+ FETCH_PUBLIC_TIMEOUT,
1379
+ FetchPublicError,
816
1380
  ForbiddenError,
1381
+ JOB_NAME_PATTERN,
1382
+ MAX_API_KEY_CACHE_SECONDS,
817
1383
  MAX_PAGE_SIZE,
818
1384
  MIN_SECRET_KEY_LENGTH,
819
1385
  NotFoundError,
@@ -824,13 +1390,19 @@ export {
824
1390
  UnauthorizedError,
825
1391
  UnsafeUrlError,
826
1392
  ValidationError,
1393
+ acceptApiKey,
1394
+ apiKeyRoutes,
827
1395
  appBasePath,
1396
+ assertApiKeyAccepted,
828
1397
  assertPublicUrl,
829
1398
  authenticate,
1399
+ authenticateJob,
830
1400
  bearerToken,
831
1401
  callPlatform,
1402
+ checkPublicUrl,
832
1403
  coerceRequestId,
833
1404
  createApp,
1405
+ createKeyVerifier,
834
1406
  createOAuthClient,
835
1407
  createSecretBox,
836
1408
  createVerifier,
@@ -838,16 +1410,20 @@ export {
838
1410
  defineTools,
839
1411
  discoverOAuth,
840
1412
  errorHandler,
1413
+ fetchPublic,
841
1414
  generateAppId,
842
1415
  getRequestContext,
843
1416
  getRequestId,
844
1417
  getUser,
845
1418
  hasPermissions,
1419
+ isApiKey,
846
1420
  isReservedAddress,
847
1421
  isToolSet,
848
1422
  isUuid,
849
1423
  isValidAppId,
850
1424
  isValidAppName,
1425
+ job,
1426
+ jobCode,
851
1427
  notFoundHandler,
852
1428
  pageOf,
853
1429
  parsePage,
@@ -861,6 +1437,7 @@ export {
861
1437
  toolManifest,
862
1438
  toolProblems,
863
1439
  userFromClaims,
1440
+ userFromKeyVerification,
864
1441
  uuidv7,
865
1442
  verifierFromEnv
866
1443
  };