@zjazj/server 0.0.9 → 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
@@ -17,7 +17,7 @@ import {
17
17
  supportFromClaims,
18
18
  userFromClaims,
19
19
  verifierFromEnv
20
- } from "./chunk-44UTXMKV.js";
20
+ } from "./chunk-7FPH47F6.js";
21
21
  import {
22
22
  API_KEY_PREFIX,
23
23
  API_KEY_REFUSAL_SECONDS,
@@ -46,10 +46,12 @@ import {
46
46
  toErrorResponse,
47
47
  userFromKeyVerification,
48
48
  uuidv7
49
- } from "./chunk-UWTSXBJL.js";
49
+ } from "./chunk-OBKMOVBA.js";
50
50
  import {
51
- isDevIdentityEnabled
52
- } from "./chunk-SLNRMJDM.js";
51
+ devIdentity,
52
+ isDevIdentityEnabled,
53
+ resolveDevKeyUser
54
+ } from "./chunk-3X4RSAM6.js";
53
55
  import {
54
56
  REQUEST_ID_HEADER,
55
57
  coerceRequestId,
@@ -65,6 +67,138 @@ import { serve } from "@hono/node-server";
65
67
  import { serveStatic } from "@hono/node-server/serve-static";
66
68
  import { Hono } from "hono";
67
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
+
68
202
  // src/tools.ts
69
203
  var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]{0,40}$/;
70
204
  var PERMISSION_CODE = /^[a-z][a-z0-9-]*(:[a-z][a-z0-9-]*)+$/;
@@ -118,12 +252,12 @@ function toolProblems(tools) {
118
252
  return problems;
119
253
  }
120
254
  function defineTools(tools) {
121
- const list = [...tools];
122
- const problems = toolProblems(list);
255
+ const list2 = [...tools];
256
+ const problems = toolProblems(list2);
123
257
  if (problems.length > 0) throw new Error(`Invalid tools:
124
258
  - ${problems.join("\n- ")}`);
125
- Object.defineProperty(list, TOOL_SET, { value: true });
126
- return Object.freeze(list);
259
+ Object.defineProperty(list2, TOOL_SET, { value: true });
260
+ return Object.freeze(list2);
127
261
  }
128
262
  function toolManifest(tools) {
129
263
  return tools.map((tool) => ({
@@ -150,10 +284,12 @@ function platformManifest(options) {
150
284
  permission_manifest: (options.permissions ?? []).map((permission) => ({
151
285
  code: permission.code,
152
286
  title: permission.title,
153
- description: permission.description ?? null
287
+ description: permission.description ?? null,
288
+ scope: permission.scope ?? "tenant"
154
289
  })),
155
290
  tools: toolManifest(options.tools ?? []),
156
291
  api_key_routes: (options.apiKeyRoutes ?? []).map((route) => ({ ...route })),
292
+ jobs: (options.jobs ?? []).map((entry) => ({ ...entry })),
157
293
  release_version: manifest.version ?? null,
158
294
  source_commit: env.GIT_SHA || null
159
295
  };
@@ -225,9 +361,9 @@ async function callPlatform(c, path2, call = {}, options = {}) {
225
361
  }
226
362
  return answer;
227
363
  }
228
- const refused = status < 500 ? errorBody(answer) : void 0;
229
- if (refused) {
230
- 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 });
231
367
  }
232
368
  throw new AppError(
233
369
  status < 500 ? "The control plane refused the request" : "The control plane failed",
@@ -277,8 +413,28 @@ function createApp(options) {
277
413
  );
278
414
  configureLog({ app: manifest.name, env: env.ENV || env.NODE_ENV || "development" });
279
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
+ }
280
430
  if (options.permissions) {
281
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
+ }
282
438
  const unknown = tools.filter((tool) => !catalog.has(tool.permission));
283
439
  if (unknown.length > 0) {
284
440
  throw new Error(
@@ -303,6 +459,10 @@ function createApp(options) {
303
459
  migrationsFolder: databaseOptions.migrationsFolder,
304
460
  appName: manifest.name
305
461
  });
462
+ if (options.objects) {
463
+ const { assertObjectTables } = await import("./objects.js");
464
+ await assertObjectTables(database);
465
+ }
306
466
  return database;
307
467
  })();
308
468
  pending.catch(() => cache.delete(manifest.id));
@@ -327,6 +487,15 @@ function createApp(options) {
327
487
  const delegated = forUsers();
328
488
  const publicApi = new Hono();
329
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
+ }
330
499
  const platformRoutes = new Hono();
331
500
  platformRoutes.use("*", authenticate(credentials));
332
501
  const toPlatform = { env, fetch: options.fetch };
@@ -354,11 +523,119 @@ function createApp(options) {
354
523
  await callPlatform(c, "/support/sessions/current", { method: "DELETE" }, toPlatform);
355
524
  return c.body(null, 204);
356
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
+ }
357
615
  let built;
358
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();
359
630
  const root = new Hono();
360
631
  root.use("*", requestContext());
361
632
  root.use("*", requestLogger());
633
+ if (objectRegistry) {
634
+ root.use("*", async (c, next) => {
635
+ c.set("platformObjects", objectRegistry);
636
+ await next();
637
+ });
638
+ }
362
639
  root.onError(errorHandler((error) => log.error("Unhandled error", { err: error })));
363
640
  root.notFound(notFoundHandler());
364
641
  root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
@@ -367,6 +644,8 @@ function createApp(options) {
367
644
  root.all("/internal/_platform/*", (c) => c.notFound());
368
645
  root.route("/internal/delegated", delegated);
369
646
  root.all("/internal/delegated/*", (c) => c.notFound());
647
+ root.route("/internal/jobs", jobs);
648
+ root.all("/internal/jobs/*", (c) => c.notFound());
370
649
  root.route("/internal", internal);
371
650
  const scoped = new Hono();
372
651
  scoped.get(
@@ -389,7 +668,7 @@ function createApp(options) {
389
668
  let route;
390
669
  mcp.all("/", async (c) => {
391
670
  if (!route) {
392
- const { createMcpRoute } = await import("./mcp-4RD7G65J.js");
671
+ const { createMcpRoute } = await import("./mcp-6W7AB46O.js");
393
672
  route ??= createMcpRoute({
394
673
  manifest,
395
674
  tools,
@@ -421,17 +700,40 @@ function createApp(options) {
421
700
  root.route(basePath || "/", scoped);
422
701
  return root;
423
702
  };
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
- });
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
+ };
435
737
  const fetchHandler = (request, ...rest) => {
436
738
  built ??= build();
437
739
  return built.fetch(request, ...rest);
@@ -443,6 +745,7 @@ function createApp(options) {
443
745
  publicApi,
444
746
  internal,
445
747
  delegated,
748
+ jobs,
446
749
  fetch: fetchHandler,
447
750
  database: getDatabase,
448
751
  platformManifest: manifestNow,
@@ -474,6 +777,324 @@ function createApp(options) {
474
777
  };
475
778
  }
476
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
+
477
1098
  // src/oauth.ts
478
1099
  import * as client from "openid-client";
479
1100
  var OAuthError = class extends AppError {
@@ -745,95 +1366,6 @@ function createSecretBox(options) {
745
1366
  }
746
1367
  };
747
1368
  }
748
-
749
- // src/url-guard.ts
750
- import { lookup as dnsLookup } from "dns/promises";
751
- import { BlockList, isIP } from "net";
752
- var UnsafeUrlError = class extends AppError {
753
- constructor(message) {
754
- super(message, { code: "unsafe_url", status: 400 });
755
- }
756
- };
757
- var blocked = new BlockList();
758
- for (const [network, prefix] of [
759
- ["0.0.0.0", 8],
760
- ["10.0.0.0", 8],
761
- ["100.64.0.0", 10],
762
- ["127.0.0.0", 8],
763
- ["169.254.0.0", 16],
764
- ["172.16.0.0", 12],
765
- ["192.0.0.0", 24],
766
- ["192.0.2.0", 24],
767
- ["192.168.0.0", 16],
768
- ["198.18.0.0", 15],
769
- ["198.51.100.0", 24],
770
- ["203.0.113.0", 24],
771
- ["224.0.0.0", 4],
772
- ["240.0.0.0", 4]
773
- ]) {
774
- blocked.addSubnet(network, prefix, "ipv4");
775
- }
776
- for (const [network, prefix] of [
777
- ["::", 127],
778
- // unspecified and loopback
779
- ["64:ff9b::", 96],
780
- // NAT64
781
- ["2001:db8::", 32],
782
- // documentation
783
- ["fc00::", 7],
784
- // unique local
785
- ["fe80::", 10],
786
- // link local
787
- ["ff00::", 8]
788
- // multicast
789
- ]) {
790
- blocked.addSubnet(network, prefix, "ipv6");
791
- }
792
- function isReservedAddress(address) {
793
- const family = isIP(address);
794
- if (family === 4) return blocked.check(address, "ipv4");
795
- if (family === 6) return blocked.check(address, "ipv6");
796
- return true;
797
- }
798
- function envAllowList() {
799
- return (process.env.URL_GUARD_ALLOW_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(Boolean);
800
- }
801
- async function resolve(hostname) {
802
- const records = await dnsLookup(hostname, { all: true });
803
- return records.map((record) => record.address);
804
- }
805
- async function assertPublicUrl(input, options = {}) {
806
- let url;
807
- try {
808
- url = input instanceof URL ? input : new URL(input);
809
- } catch {
810
- throw new UnsafeUrlError("URL is not valid");
811
- }
812
- if (url.protocol !== "http:" && url.protocol !== "https:") {
813
- throw new UnsafeUrlError("URL must use http or https");
814
- }
815
- const hostname = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
816
- if (!hostname) throw new UnsafeUrlError("URL has no host");
817
- const allowed = [
818
- ...(options.allowHosts ?? []).map((host) => host.toLowerCase()),
819
- ...envAllowList()
820
- ];
821
- if (allowed.includes(hostname)) return url;
822
- let addresses;
823
- if (isIP(hostname)) {
824
- addresses = [hostname];
825
- } else {
826
- try {
827
- addresses = await (options.lookup ?? resolve)(hostname);
828
- } catch {
829
- throw new UnsafeUrlError("URL host cannot be resolved");
830
- }
831
- }
832
- if (addresses.length === 0 || addresses.some(isReservedAddress)) {
833
- throw new UnsafeUrlError("URL resolves to a private or reserved address");
834
- }
835
- return url;
836
- }
837
1369
  export {
838
1370
  API_KEY_PREFIX,
839
1371
  API_KEY_REFUSAL_SECONDS,
@@ -842,7 +1374,11 @@ export {
842
1374
  AppError,
843
1375
  ConflictError,
844
1376
  DEFAULT_PAGE_SIZE,
1377
+ FETCH_PUBLIC_MAX_BYTES,
1378
+ FETCH_PUBLIC_TIMEOUT,
1379
+ FetchPublicError,
845
1380
  ForbiddenError,
1381
+ JOB_NAME_PATTERN,
846
1382
  MAX_API_KEY_CACHE_SECONDS,
847
1383
  MAX_PAGE_SIZE,
848
1384
  MIN_SECRET_KEY_LENGTH,
@@ -860,8 +1396,10 @@ export {
860
1396
  assertApiKeyAccepted,
861
1397
  assertPublicUrl,
862
1398
  authenticate,
1399
+ authenticateJob,
863
1400
  bearerToken,
864
1401
  callPlatform,
1402
+ checkPublicUrl,
865
1403
  coerceRequestId,
866
1404
  createApp,
867
1405
  createKeyVerifier,
@@ -872,6 +1410,7 @@ export {
872
1410
  defineTools,
873
1411
  discoverOAuth,
874
1412
  errorHandler,
1413
+ fetchPublic,
875
1414
  generateAppId,
876
1415
  getRequestContext,
877
1416
  getRequestId,
@@ -883,6 +1422,8 @@ export {
883
1422
  isUuid,
884
1423
  isValidAppId,
885
1424
  isValidAppName,
1425
+ job,
1426
+ jobCode,
886
1427
  notFoundHandler,
887
1428
  pageOf,
888
1429
  parsePage,