@impz/testing 6.12.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +727 -1295
  2. package/package.json +10 -11
package/dist/index.js CHANGED
@@ -18994,7 +18994,7 @@ function readBusyPorts() {
18994
18994
  // packages/daemon/src/test-utils/start-test-impd.ts
18995
18995
  import { createORPCClient as createORPCClient2 } from "@orpc/client";
18996
18996
  import { RPCLink } from "@orpc/client/fetch";
18997
- import invariant14 from "tiny-invariant";
18997
+ import invariant16 from "tiny-invariant";
18998
18998
 
18999
18999
  // packages/daemon/src/config.ts
19000
19000
  import { join as join4 } from "path";
@@ -19965,28 +19965,29 @@ var MAX_REDIRECT_URIS = 8;
19965
19965
  var RedirectUriSchema = z29.string().max(2048).refine(isAllowedRedirectUri, "must be an https URL, or http on a loopback host, with no fragment");
19966
19966
  var RedirectUrisSchema = z29.array(RedirectUriSchema).min(1).max(MAX_REDIRECT_URIS).refine((uris) => new Set(uris).size === uris.length, "must not name a redirect URI twice");
19967
19967
  var GrantPatternSchema = z29.string().regex(/^(?:\*|[a-z][a-z0-9-]{0,30}|[a-z][a-z0-9-]{0,29}\*)$/u, "must be an imp name, or a name prefix and a trailing *, such as dev-*");
19968
- var ApprovalCodeSchema = z29.string().trim().transform((code) => code.toUpperCase().replaceAll("-", "")).pipe(z29.string().regex(/^[A-HJ-NP-Z2-9]{8}$/u, "must be the 8-symbol code the sign-in page shows"));
19968
+ var OAuthClientReferenceSchema = z29.string().min(1).max(200);
19969
19969
  var OAuthClientSchema = z29.object({
19970
- name: NameSchema,
19970
+ name: z29.string(),
19971
19971
  clientId: z29.string(),
19972
19972
  redirectUris: z29.array(z29.string()).readonly(),
19973
19973
  createdAt: z29.date()
19974
19974
  });
19975
19975
  var OAuthGrantSchema = z29.object({
19976
19976
  id: z29.string(),
19977
- client: NameSchema,
19978
- token: NameSchema,
19977
+ client: z29.string(),
19978
+ approvedBy: z29.string(),
19979
19979
  scope: ScopeSchema,
19980
- imps: z29.array(GrantPatternSchema).readonly().nullable(),
19981
19980
  createdAt: z29.date(),
19982
19981
  lastUsedAt: z29.date().nullable()
19983
19982
  });
19984
- var OAuthApprovalSchema = z29.object({
19985
- client: NameSchema,
19986
- redirectUri: z29.string(),
19987
- requestedScope: ScopeSchema,
19988
- requestedAt: z29.date(),
19989
- expiresAt: z29.date()
19983
+ var OAuthPasskeySchema = z29.object({
19984
+ id: z29.string(),
19985
+ createdAt: z29.date(),
19986
+ lastUsedAt: z29.date().nullable()
19987
+ });
19988
+ var OAuthEnrollmentSchema = z29.object({
19989
+ token: z29.string(),
19990
+ url: z29.string().nullable()
19990
19991
  });
19991
19992
  function isAllowedRedirectUri(text) {
19992
19993
  let url;
@@ -20347,7 +20348,7 @@ var ResourceKindSchema = z35.enum([
20347
20348
  "network",
20348
20349
  "oauth-client",
20349
20350
  "oauth-grant",
20350
- "oauth-approval",
20351
+ "oauth-passkey",
20351
20352
  "database-copy"
20352
20353
  ]);
20353
20354
  var ResourceDataSchema = z35.object({
@@ -20699,20 +20700,18 @@ var callerContract = {
20699
20700
  clients: {
20700
20701
  list: contractBase.meta(ACCESS.manageHost).output(z43.array(OAuthClientSchema)),
20701
20702
  add: contractBase.meta(ACCESS.manageHost).input(z43.object({ name: NameSchema, redirectUris: RedirectUrisSchema })).output(OAuthClientSchema),
20702
- update: contractBase.meta(ACCESS.manageHost).input(z43.object({ name: NameSchema, redirectUris: RedirectUrisSchema })).output(OAuthClientSchema),
20703
- delete: contractBase.meta(ACCESS.manageHost).input(NameInputSchema).output(EmptySchema)
20703
+ update: contractBase.meta(ACCESS.manageHost).input(z43.object({ client: OAuthClientReferenceSchema, redirectUris: RedirectUrisSchema })).output(OAuthClientSchema),
20704
+ delete: contractBase.meta(ACCESS.manageHost).input(z43.object({ client: OAuthClientReferenceSchema })).output(EmptySchema)
20704
20705
  },
20705
20706
  grants: {
20706
20707
  list: contractBase.meta(ACCESS.manageHost).output(z43.array(OAuthGrantSchema)),
20707
20708
  delete: contractBase.meta(ACCESS.manageHost).input(z43.object({ id: z43.string().min(1).max(64) })).output(EmptySchema)
20708
20709
  },
20709
- approvals: {
20710
- get: contractBase.meta(ACCESS.readAny).input(z43.object({ code: ApprovalCodeSchema })).output(OAuthApprovalSchema),
20711
- approve: contractBase.meta(ACCESS.readAny).input(z43.object({
20712
- code: ApprovalCodeSchema,
20713
- scope: ScopeSchema,
20714
- imps: z43.array(GrantPatternSchema).min(1).max(32).optional()
20715
- })).output(EmptySchema)
20710
+ passkeys: {
20711
+ list: contractBase.meta(ACCESS.manageHost).output(z43.array(OAuthPasskeySchema)),
20712
+ enroll: contractBase.meta(ACCESS.manageHost).output(OAuthEnrollmentSchema),
20713
+ delete: contractBase.meta(ACCESS.manageHost).input(z43.object({ id: z43.string().min(1).max(512) })).output(EmptySchema),
20714
+ reset: contractBase.meta(ACCESS.manageHost).output(EmptySchema)
20716
20715
  }
20717
20716
  },
20718
20717
  tokens: tokensContract
@@ -22047,7 +22046,7 @@ import { join as join49 } from "path";
22047
22046
  // packages/daemon/package.json
22048
22047
  var package_default = {
22049
22048
  name: "@impz/daemon",
22050
- version: "6.12.0",
22049
+ version: "7.0.0",
22051
22050
  private: true,
22052
22051
  description: "impd: the imp host daemon",
22053
22052
  type: "module",
@@ -22061,8 +22060,6 @@ var package_default = {
22061
22060
  "./package.json": "./package.json"
22062
22061
  },
22063
22062
  dependencies: {
22064
- "@better-auth/mcp": "catalog:",
22065
- "@better-auth/oauth-provider": "catalog:",
22066
22063
  "@bufbuild/protobuf": "catalog:",
22067
22064
  "@impz/agent-protocol": "workspace:*",
22068
22065
  "@impz/api": "workspace:*",
@@ -22085,8 +22082,9 @@ var package_default = {
22085
22082
  "@orpc/server": "catalog:",
22086
22083
  "@peculiar/x509": "catalog:",
22087
22084
  "@zgeoff/kysely-bun-sqlite": "catalog:",
22085
+ "@zgeoff/mcp-auth": "catalog:",
22086
+ "@zgeoff/std": "catalog:",
22088
22087
  "acme-client": "catalog:",
22089
- "better-auth": "catalog:",
22090
22088
  "dns-packet": "catalog:",
22091
22089
  elysia: "catalog:",
22092
22090
  "ipaddr.js": "catalog:",
@@ -24112,6 +24110,8 @@ import { ORPCError as ORPCError5, onError as onError2 } from "@orpc/server";
24112
24110
  import { RPCHandler as RPCHandler2 } from "@orpc/server/fetch";
24113
24111
  import { StrictGetMethodPlugin as StrictGetMethodPlugin2 } from "@orpc/server/plugins";
24114
24112
  import { Elysia as Elysia4 } from "elysia";
24113
+ import { autoHead } from "elysia/auto-head";
24114
+ import { websocket as websocket3 } from "elysia/websocket";
24115
24115
 
24116
24116
  // packages/daemon/src/platform/http/is-allowed-origin.ts
24117
24117
  import { match as match6 } from "ts-pattern";
@@ -24399,13 +24399,10 @@ async function readTokenGrantable(db, id) {
24399
24399
  const row = await db.selectFrom("tokens").select("grantable").where("id", "=", id).executeTakeFirst();
24400
24400
  return row === undefined ? null : GrantableSchema2.parse(JSON.parse(row.grantable));
24401
24401
  }
24402
- function removeTokenRecord(db, id) {
24403
- return db.transaction().execute(async (trx) => {
24402
+ async function removeTokenRecord(db, id) {
24403
+ await db.transaction().execute(async (trx) => {
24404
24404
  await trx.deleteFrom("token_ssh_keys").where("token_id", "=", id).execute();
24405
- const grants = await trx.deleteFrom("user").where("tokenId", "=", id).returning("id").execute();
24406
- const grantIds = grants.map((grant) => grant.id);
24407
24405
  await trx.deleteFrom("tokens").where("id", "=", id).execute();
24408
- return grantIds;
24409
24406
  });
24410
24407
  }
24411
24408
  async function writeTokenSshKeyRecord(db, key) {
@@ -24827,15 +24824,13 @@ async function loadTokenStore(deps) {
24827
24824
  remove: async (name) => {
24828
24825
  const record = requireByName(name);
24829
24826
  requireNotInFile(listKeys(record.id));
24830
- const grantIds = await removeTokenRecord(deps.db, record.id);
24827
+ await removeTokenRecord(deps.db, record.id);
24831
24828
  byId.delete(record.id);
24832
24829
  for (const entry of listKeys(record.id)) {
24833
24830
  keysByFingerprint.delete(entry.record.fingerprint);
24834
24831
  }
24835
24832
  deps.onRemove(record.id);
24836
- for (const grantId of grantIds) {
24837
- deps.onRemove(grantId);
24838
- }
24833
+ await deps.removeGrants(record.id);
24839
24834
  },
24840
24835
  addKey: async (name, line) => {
24841
24836
  const record = requireByName(name);
@@ -25245,7 +25240,8 @@ function createDashboardRoutes(dashboardDir) {
25245
25240
  }
25246
25241
 
25247
25242
  // packages/daemon/src/surface/create-exec-sockets.ts
25248
- import { Elysia as Elysia2 } from "elysia";
25243
+ import { Elysia as Elysia2, status } from "elysia";
25244
+ import { websocket } from "elysia/websocket";
25249
25245
 
25250
25246
  // packages/daemon/src/imps/exec/exec-session.ts
25251
25247
  import { match as match7 } from "ts-pattern";
@@ -26480,6 +26476,14 @@ function buildGrantedBackend(backend, grant) {
26480
26476
  };
26481
26477
  }
26482
26478
 
26479
+ // packages/daemon/src/surface/get-raw-socket.ts
26480
+ import { ElysiaWS } from "elysia/ws";
26481
+ import invariant8 from "tiny-invariant";
26482
+ function getRawSocket(ws) {
26483
+ invariant8(ws instanceof ElysiaWS, "a WebSocket hook got a socket that Elysia did not wrap");
26484
+ return ws.raw;
26485
+ }
26486
+
26483
26487
  // packages/daemon/src/surface/read-buffered-amount.ts
26484
26488
  function readBufferedAmount(socket) {
26485
26489
  const read = Reflect.get(socket, "getBufferedAmount");
@@ -26494,17 +26498,13 @@ function readBufferedAmount(socket) {
26494
26498
  var CLOSE_REVOKED = 1008;
26495
26499
  function createExecSockets(deps) {
26496
26500
  const sessions = createSocketRegistry();
26497
- const grants = new WeakMap;
26498
- const buildExecBackend = (grant) => {
26499
- const actor = grant?.caller ?? { kind: "token", name: "unknown" };
26500
- return buildAuditedBackend({
26501
- backend: buildGrantedBackend(deps.imps, grant),
26502
- audit: deps.audit,
26503
- actor,
26504
- events: deps.imps.events,
26505
- now: deps.now
26506
- });
26507
- };
26501
+ const buildExecBackend = (grant) => buildAuditedBackend({
26502
+ backend: buildGrantedBackend(deps.imps, grant),
26503
+ audit: deps.audit,
26504
+ actor: grant.caller,
26505
+ events: deps.imps.events,
26506
+ now: deps.now
26507
+ });
26508
26508
  const openExecSocket = (url) => {
26509
26509
  const ticket = new URL(url).searchParams.get(EXEC_TICKET_PARAM);
26510
26510
  const holder = ticket === null ? null : deps.execTickets.redeem(ticket);
@@ -26527,38 +26527,37 @@ function createExecSockets(deps) {
26527
26527
  };
26528
26528
  });
26529
26529
  };
26530
- const route = new Elysia2().ws(EXEC_PATH, {
26531
- beforeHandle: async (context) => {
26532
- const ticket = new URL(context.request.url).searchParams.get(EXEC_TICKET_PARAM);
26533
- if (ticket !== null) {
26534
- const holder = deps.execTickets.redeem(ticket);
26535
- if (holder === null) {
26536
- return Response.json({ error: "unauthorized" }, { status: 401 });
26537
- }
26538
- grants.set(context.request, { caller: holder.caller, name: holder.name });
26539
- return;
26540
- }
26541
- const caller = await deps.findCaller(context.request, context.server);
26542
- if (caller === null) {
26543
- return Response.json({ error: "unauthorized" }, { status: 401 });
26530
+ const authorized = new Elysia2().use(websocket()).derive(async (context) => {
26531
+ const ticket = new URL(context.request.url).searchParams.get(EXEC_TICKET_PARAM);
26532
+ if (ticket !== null) {
26533
+ const holder = deps.execTickets.redeem(ticket);
26534
+ if (holder === null) {
26535
+ return status(401, { error: "unauthorized" });
26544
26536
  }
26545
- grants.set(context.request, { caller, name: null });
26546
- return;
26547
- },
26537
+ return { grant: { caller: holder.caller, name: holder.name } };
26538
+ }
26539
+ const caller = await deps.findCaller(context.request, context.server);
26540
+ if (caller === null) {
26541
+ return status(401, { error: "unauthorized" });
26542
+ }
26543
+ return { grant: { caller, name: null } };
26544
+ });
26545
+ const route = authorized.ws(EXEC_PATH, {
26548
26546
  open: (ws) => {
26549
- const grant = grants.get(ws.data.request);
26547
+ const grant = ws.grant;
26548
+ const raw = getRawSocket(ws);
26550
26549
  const close = (code, reason) => {
26551
- ws.raw.close(code, reason);
26550
+ raw.close(code, reason);
26552
26551
  };
26553
26552
  const session = createExecSession({
26554
26553
  sendText: (text) => {
26555
- ws.raw.send(text);
26554
+ raw.send(text);
26556
26555
  },
26557
- sendBinary: (data) => ws.raw.send(data) !== 0,
26556
+ sendBinary: (data) => raw.send(data) !== 0,
26558
26557
  close,
26559
- readBufferedAmount: () => readBufferedAmount(ws.raw)
26558
+ readBufferedAmount: () => readBufferedAmount(raw)
26560
26559
  }, buildExecBackend(grant));
26561
- const forget = deps.closeOnRevocation(grant?.caller, () => {
26560
+ const forget = deps.closeOnRevocation(grant.caller, () => {
26562
26561
  close(CLOSE_REVOKED, "the token was removed");
26563
26562
  });
26564
26563
  sessions.add(ws.id, { session, close, forget });
@@ -29722,7 +29721,7 @@ async function runFollower(db, parts, head) {
29722
29721
  }
29723
29722
 
29724
29723
  // packages/daemon/src/platform/db/run-migrations.ts
29725
- import { sql as sql15 } from "kysely";
29724
+ import { sql as sql16 } from "kysely";
29726
29725
  import { Migrator } from "kysely/migration";
29727
29726
 
29728
29727
  // packages/daemon/src/platform/db/migrations/migration-001-create-initial-schema.ts
@@ -30392,6 +30391,62 @@ var MIGRATION_045_ADD_IMP_LAST_REQUEST = {
30392
30391
  }
30393
30392
  };
30394
30393
 
30394
+ // packages/daemon/src/platform/db/migrations/migration-046-move-grants-to-mcp-auth.ts
30395
+ import { sql as sql15 } from "kysely";
30396
+ var NOW = sql15`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;
30397
+ var STATEMENTS = [
30398
+ sql15`CREATE TEMP TABLE imp_grant_token AS
30399
+ SELECT userId, clientId, scopes, createdAt, expiresAt, revoked FROM oauthRefreshToken
30400
+ UNION ALL
30401
+ SELECT userId, clientId, scopes, createdAt, expiresAt, revoked FROM oauthAccessToken
30402
+ WHERE userId IS NOT NULL`,
30403
+ sql15`DELETE FROM "user" WHERE id NOT IN (
30404
+ SELECT userId FROM imp_grant_token WHERE revoked IS NULL AND expiresAt > ${NOW}
30405
+ )`,
30406
+ sql15`ALTER TABLE "user" ADD COLUMN "clientId" text`,
30407
+ sql15`ALTER TABLE "user" ADD COLUMN "scopes" text`,
30408
+ sql15`ALTER TABLE "user" ADD COLUMN "approvedBy" text`,
30409
+ sql15`ALTER TABLE "user" ADD COLUMN "limits" text`,
30410
+ sql15`UPDATE "user" SET
30411
+ "clientId" = live.clientId,
30412
+ "scopes" = (SELECT json_group_array(scope.value) FROM json_each(live.scopes) AS scope
30413
+ WHERE scope.value <> 'offline_access'),
30414
+ "approvedBy" = 'token:' || "user"."tokenId",
30415
+ "limits" = json_object(
30416
+ 'imps', json("user"."imps"),
30417
+ 'grantable', json(CASE
30418
+ WHEN coalesce(
30419
+ (SELECT json_array_length(approver.grantable) FROM tokens AS approver
30420
+ WHERE approver.id = "user"."tokenId"),
30421
+ 0
30422
+ ) > 0 THEN 'true'
30423
+ ELSE 'false'
30424
+ END)
30425
+ )
30426
+ FROM (
30427
+ SELECT userId, clientId, scopes, max(createdAt) AS newestAt FROM imp_grant_token
30428
+ WHERE revoked IS NULL AND expiresAt > ${NOW}
30429
+ GROUP BY userId
30430
+ ) AS live
30431
+ WHERE live.userId = "user"."id"`,
30432
+ sql15`ALTER TABLE "user" DROP COLUMN "tokenId"`,
30433
+ sql15`ALTER TABLE "user" DROP COLUMN "imps"`,
30434
+ sql15`DROP TABLE temp.imp_grant_token`
30435
+ ];
30436
+ var MIGRATION_046_MOVE_GRANTS_TO_MCP_AUTH = {
30437
+ async up(db) {
30438
+ await db.transaction().execute(async (trx) => {
30439
+ for (const statement of STATEMENTS) {
30440
+ await statement.execute(trx);
30441
+ }
30442
+ const broken = await sql15`PRAGMA foreign_key_check`.execute(trx);
30443
+ if (broken.rows.length > 0) {
30444
+ throw new Error(`the grant migration left ${String(broken.rows.length)} rows whose foreign key points at no row`);
30445
+ }
30446
+ });
30447
+ }
30448
+ };
30449
+
30395
30450
  // packages/daemon/src/platform/db/run-migrations.ts
30396
30451
  var MIGRATIONS = {
30397
30452
  "001_create_initial_schema": MIGRATION_001_CREATE_INITIAL_SCHEMA,
@@ -30438,7 +30493,8 @@ var MIGRATIONS = {
30438
30493
  "042_add_secret_env": MIGRATION_042_ADD_SECRET_ENV,
30439
30494
  "043_merge_secret_kinds": MIGRATION_043_MERGE_SECRET_KINDS,
30440
30495
  "044_add_imp_image_digests": MIGRATION_044_ADD_IMP_IMAGE_DIGESTS,
30441
- "045_add_imp_last_request": MIGRATION_045_ADD_IMP_LAST_REQUEST
30496
+ "045_add_imp_last_request": MIGRATION_045_ADD_IMP_LAST_REQUEST,
30497
+ "046_move_grants_to_mcp_auth": MIGRATION_046_MOVE_GRANTS_TO_MCP_AUTH
30442
30498
  };
30443
30499
  var DURABLE_MIGRATION_TABLE = "kysely_migration_durable";
30444
30500
  async function runMigrations(db) {
@@ -30457,13 +30513,13 @@ async function runMigrations(db) {
30457
30513
  requireMigrated(durableResult);
30458
30514
  }
30459
30515
  async function requireKnownMigrations(db, table, migrations) {
30460
- const found = await sql15`
30516
+ const found = await sql16`
30461
30517
  SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${table}
30462
30518
  `.execute(db);
30463
30519
  if (found.rows.length === 0) {
30464
30520
  return;
30465
30521
  }
30466
- const executed = await sql15`SELECT name FROM ${sql15.table(table)}`.execute(db);
30522
+ const executed = await sql16`SELECT name FROM ${sql16.table(table)}`.execute(db);
30467
30523
  const unknown = executed.rows.map((row) => row.name).filter((name) => !Object.hasOwn(migrations, name));
30468
30524
  if (unknown.length === 0) {
30469
30525
  return;
@@ -30496,6 +30552,7 @@ async function openDatabase(source, now = Date.now) {
30496
30552
  const log = createImpEventLog(builder, now);
30497
30553
  const db = Object.assign(builder, {
30498
30554
  log,
30555
+ sqlite,
30499
30556
  destroy: async () => {
30500
30557
  await log.stop();
30501
30558
  await destroyDriver();
@@ -31613,7 +31670,7 @@ function createIdentityRoutes(os, deps) {
31613
31670
 
31614
31671
  // packages/daemon/src/surface/create-image-routes.ts
31615
31672
  import { ORPCError as ORPCError3 } from "@orpc/server";
31616
- import invariant8 from "tiny-invariant";
31673
+ import invariant9 from "tiny-invariant";
31617
31674
 
31618
31675
  // packages/daemon/src/surface/to-api-image.ts
31619
31676
  function toApiImage(image) {
@@ -31758,7 +31815,7 @@ function findPinRefPrefix(caller) {
31758
31815
  if (caller.imps === null) {
31759
31816
  return null;
31760
31817
  }
31761
- invariant8(caller.imageRefPrefix !== null, "a scoped pin without a prefix passed its check");
31818
+ invariant9(caller.imageRefPrefix !== null, "a scoped pin without a prefix passed its check");
31762
31819
  return caller.imageRefPrefix;
31763
31820
  }
31764
31821
 
@@ -31993,34 +32050,163 @@ function createNetworkRoutes(os, deps) {
31993
32050
  };
31994
32051
  }
31995
32052
 
32053
+ // packages/daemon/src/surface/create-oauth-routes.ts
32054
+ import { MCPAuthError } from "@zgeoff/mcp-auth";
32055
+ import { toTagged } from "@zgeoff/std";
32056
+ import { match as match12 } from "ts-pattern";
32057
+
32058
+ // packages/daemon/src/identity/oauth/grant-limits.ts
32059
+ function isPatternsWithin(grant, token) {
32060
+ if (token === null) {
32061
+ return true;
32062
+ }
32063
+ if (grant === null) {
32064
+ return false;
32065
+ }
32066
+ return grant.every((pattern) => token.some((own) => isPatternWithin(pattern, own)));
32067
+ }
32068
+ function isPatternWithin(pattern, own) {
32069
+ if (pattern === own) {
32070
+ return true;
32071
+ }
32072
+ const star = own.indexOf("*");
32073
+ return star === own.length - 1 && pattern.startsWith(own.slice(0, -1));
32074
+ }
32075
+ function pickLowerScope(left, right) {
32076
+ return hasScope(left, right) ? right : left;
32077
+ }
32078
+ function formatScopeList(scope) {
32079
+ const nested = {
32080
+ read: "read",
32081
+ exec: "read exec",
32082
+ manage: "read exec manage"
32083
+ };
32084
+ return nested[scope];
32085
+ }
32086
+ function pickGrantScope(scopes) {
32087
+ return ScopeSchema.options.reduce((highest, scope) => scopes.includes(scope) && hasScope(scope, highest) ? scope : highest, "read");
32088
+ }
32089
+
32090
+ // packages/daemon/src/identity/oauth/pick-oauth-client.ts
32091
+ function pickOAuthClient(reference, clients, named) {
32092
+ const byID = clients.find((client) => client.clientID === reference);
32093
+ if (byID !== undefined) {
32094
+ return { kind: "found", client: byID };
32095
+ }
32096
+ const [first, ...rest] = named;
32097
+ if (first === undefined) {
32098
+ return { kind: "missing" };
32099
+ }
32100
+ if (rest.length > 0) {
32101
+ return { kind: "ambiguous", clientIDs: named.map((client) => client.clientID) };
32102
+ }
32103
+ return { kind: "found", client: first };
32104
+ }
32105
+
31996
32106
  // packages/daemon/src/surface/create-oauth-routes.ts
31997
32107
  function createOAuthRoutes(os, deps) {
32108
+ const admin = deps.oauth.admin;
32109
+ const server = deps.oauth.server;
31998
32110
  return {
31999
32111
  clients: {
32000
- list: os.oauth.clients.list.handler(() => deps.oauth.listClients()),
32001
- add: os.oauth.clients.add.handler((context) => deps.oauth.addClient(context.input.name, context.input.redirectUris)),
32002
- update: os.oauth.clients.update.handler((context) => deps.oauth.updateClient(context.input.name, context.input.redirectUris)),
32003
- delete: os.oauth.clients.delete.handler(async (context) => {
32004
- await deps.oauth.removeClient(context.input.name);
32112
+ list: os.oauth.clients.list.handler(async () => {
32113
+ const clients = await admin.clients.list();
32114
+ return clients.map((client) => toOAuthClient(client));
32115
+ }),
32116
+ add: os.oauth.clients.add.handler((context) => withClientErrors(context.input.name, async () => {
32117
+ const added = await admin.clients.add(context.input.name, context.input.redirectUris);
32118
+ return toOAuthClient(added);
32119
+ })),
32120
+ update: os.oauth.clients.update.handler((context) => withClientErrors(context.input.client, async () => {
32121
+ const target = await resolveClient(admin, context.input.client);
32122
+ const updated = await admin.clients.update(target.clientID, context.input.redirectUris);
32123
+ return toOAuthClient(updated);
32124
+ })),
32125
+ delete: os.oauth.clients.delete.handler((context) => withClientErrors(context.input.client, async () => {
32126
+ const target = await resolveClient(admin, context.input.client);
32127
+ await admin.clients.remove(target.clientID);
32005
32128
  return {};
32006
- })
32129
+ }))
32007
32130
  },
32008
32131
  grants: {
32009
- list: os.oauth.grants.list.handler(() => deps.oauth.listGrants()),
32132
+ list: os.oauth.grants.list.handler(async () => {
32133
+ const grants = await admin.grants.list();
32134
+ return grants.map((grant) => toOAuthGrant(grant, deps.tokens));
32135
+ }),
32010
32136
  delete: os.oauth.grants.delete.handler(async (context) => {
32011
- await deps.oauth.removeGrant(context.input.id);
32137
+ const isRevoked = await admin.grants.revoke(toTagged(context.input.id));
32138
+ if (!isRevoked) {
32139
+ throw buildNotFoundError("oauth-grant", context.input.id);
32140
+ }
32012
32141
  return {};
32013
32142
  })
32014
32143
  },
32015
- approvals: {
32016
- get: os.oauth.approvals.get.handler((context) => deps.oauth.readApproval(context.input.code, context.context.caller)),
32017
- approve: os.oauth.approvals.approve.handler((context) => {
32018
- deps.oauth.approve(context.input.code, context.context.caller, context.input.scope, context.input.imps);
32144
+ passkeys: {
32145
+ list: os.oauth.passkeys.list.handler(async () => {
32146
+ const passkeys = await admin.passkeys.list();
32147
+ return passkeys.map((passkey) => ({
32148
+ id: passkey.id,
32149
+ createdAt: new Date(passkey.createdAt),
32150
+ lastUsedAt: passkey.lastUsedAt === null ? null : new Date(passkey.lastUsedAt)
32151
+ }));
32152
+ }),
32153
+ enroll: os.oauth.passkeys.enroll.handler(async () => ({
32154
+ token: await admin.passkeys.createEnrollmentToken(),
32155
+ url: server === null ? null : `${server.issuer}${server.paths.browser.enroll}`
32156
+ })),
32157
+ delete: os.oauth.passkeys.delete.handler(async (context) => {
32158
+ await admin.passkeys.remove(toTagged(context.input.id));
32159
+ return {};
32160
+ }),
32161
+ reset: os.oauth.passkeys.reset.handler(async () => {
32162
+ await admin.passkeys.reset();
32019
32163
  return {};
32020
32164
  })
32021
32165
  }
32022
32166
  };
32023
32167
  }
32168
+ function toOAuthClient(client) {
32169
+ return {
32170
+ name: client.name,
32171
+ clientId: client.clientID,
32172
+ redirectUris: client.redirectURIs,
32173
+ createdAt: new Date(client.createdAt)
32174
+ };
32175
+ }
32176
+ async function withClientErrors(name, run) {
32177
+ try {
32178
+ return await run();
32179
+ } catch (error) {
32180
+ if (!(error instanceof MCPAuthError)) {
32181
+ throw error;
32182
+ }
32183
+ throw match12(error.code).with("conflict", () => buildConflictError("oauth-client", name)).with("not-found", () => buildNotFoundError("oauth-client", name)).with("invalid-client-name", "invalid-redirect-uri", () => new ImpdError("BAD_REQUEST", { message: error.message })).with("invalid-setup", () => error).exhaustive();
32184
+ }
32185
+ }
32186
+ async function resolveClient(admin, reference) {
32187
+ const clients = await admin.clients.list();
32188
+ const named = await admin.clients.readByName(reference);
32189
+ const picked = pickOAuthClient(reference, clients, named);
32190
+ return match12(picked).with({ kind: "found" }, (found) => found.client).with({ kind: "missing" }, () => {
32191
+ throw buildNotFoundError("oauth-client", reference);
32192
+ }).with({ kind: "ambiguous" }, (ambiguous) => {
32193
+ throw buildConflictError("oauth-client", reference, `${String(ambiguous.clientIDs.length)} clients are named ${reference}: ${ambiguous.clientIDs.join(", ")}; name one by its client ID`);
32194
+ }).exhaustive();
32195
+ }
32196
+ function toOAuthGrant(grant, tokens) {
32197
+ const approvedBy = grant.approvedBy.startsWith("token:") ? `token:${formatApprover(grant.approvedBy.slice("token:".length), tokens)}` : grant.approvedBy;
32198
+ return {
32199
+ id: grant.grantID,
32200
+ client: grant.clientName,
32201
+ approvedBy,
32202
+ scope: pickGrantScope(grant.scopes),
32203
+ createdAt: new Date(grant.createdAt),
32204
+ lastUsedAt: grant.lastUsedAt === null ? null : new Date(grant.lastUsedAt)
32205
+ };
32206
+ }
32207
+ function formatApprover(tokenID, tokens) {
32208
+ return tokens.findById(tokenID)?.name ?? tokenID;
32209
+ }
32024
32210
 
32025
32211
  // packages/daemon/src/surface/create-secret-routes.ts
32026
32212
  function createSecretRoutes(os, deps) {
@@ -32398,7 +32584,8 @@ function createRouter(deps) {
32398
32584
  }
32399
32585
 
32400
32586
  // packages/daemon/src/surface/create-tunnel-socket-route.ts
32401
- import { Elysia as Elysia3 } from "elysia";
32587
+ import { Elysia as Elysia3, status as status2 } from "elysia";
32588
+ import { websocket as websocket2 } from "elysia/websocket";
32402
32589
 
32403
32590
  // packages/daemon/src/platform/process/counted-limit.ts
32404
32591
  function createCountedLimit(max) {
@@ -32463,7 +32650,7 @@ function createReverseForwards(max = MAX_RELAYS_PER_FORWARD) {
32463
32650
  }
32464
32651
 
32465
32652
  // packages/daemon/src/vm/guest-channels/tunnel-session.ts
32466
- import { match as match12 } from "ts-pattern";
32653
+ import { match as match13 } from "ts-pattern";
32467
32654
 
32468
32655
  // packages/daemon/src/vm/guest-channels/stop-guest-client.ts
32469
32656
  async function stopGuestClient(openAccept) {
@@ -32669,7 +32856,7 @@ function createTunnelSession(peer, backend, limits, forwards) {
32669
32856
  stopTunnel(TUNNEL_CLOSE_PROTOCOL, `${control.type} before opened`);
32670
32857
  return;
32671
32858
  }
32672
- match12(control).with({ type: "eof" }, () => {
32859
+ match13(control).with({ type: "eof" }, () => {
32673
32860
  state.peerEof = true;
32674
32861
  stream.end();
32675
32862
  }).with({ type: "ack" }, (ack) => {
@@ -32681,7 +32868,7 @@ function createTunnelSession(peer, backend, limits, forwards) {
32681
32868
  stopTunnel(TUNNEL_CLOSE_PROTOCOL, `${control.type} after the start`);
32682
32869
  return;
32683
32870
  }
32684
- match12(control).with({ type: "open" }, (open) => {
32871
+ match13(control).with({ type: "open" }, (open) => {
32685
32872
  const target = { network: "tcp", address: `127.0.0.1:${String(open.port)}` };
32686
32873
  openTunnel(open.name, (impId) => allocateTunnel(open.name, impId), () => backend.openDial(open.name, target));
32687
32874
  }).with({ type: "accept" }, (accept) => {
@@ -32734,27 +32921,26 @@ function createTunnelSocketRoute(deps) {
32734
32921
  const tunnels = createSocketRegistry();
32735
32922
  const tunnelLimits = createTunnelLimits();
32736
32923
  const reverseForwards = createReverseForwards();
32737
- const callers = new WeakMap;
32738
- const route = new Elysia3().ws(TUNNEL_PATH, {
32739
- beforeHandle: async (context) => {
32740
- const caller = await deps.findCaller(context.request, context.server);
32741
- if (caller === null) {
32742
- return Response.json({ error: "unauthorized" }, { status: 401 });
32743
- }
32744
- callers.set(context.request, caller);
32745
- return;
32746
- },
32924
+ const authorized = new Elysia3().use(websocket2()).derive(async (context) => {
32925
+ const caller = await deps.findCaller(context.request, context.server);
32926
+ if (caller === null) {
32927
+ return status2(401, { error: "unauthorized" });
32928
+ }
32929
+ return { caller };
32930
+ });
32931
+ const route = authorized.ws(TUNNEL_PATH, {
32747
32932
  open: (ws) => {
32748
- const caller = callers.get(ws.data.request);
32933
+ const caller = ws.caller;
32934
+ const raw = getRawSocket(ws);
32749
32935
  const close = (code, reason) => {
32750
- ws.raw.close(code, reason);
32936
+ raw.close(code, reason);
32751
32937
  };
32752
32938
  const session = createTunnelSession({
32753
32939
  sendText: (text) => {
32754
- ws.raw.send(text);
32940
+ raw.send(text);
32755
32941
  },
32756
32942
  sendBinary: (data) => {
32757
- ws.raw.send(data);
32943
+ raw.send(data);
32758
32944
  },
32759
32945
  close
32760
32946
  }, {
@@ -32770,7 +32956,7 @@ function createTunnelSocketRoute(deps) {
32770
32956
  const port = target.address.split(":").at(-1) ?? "";
32771
32957
  return withAuditedOpen(deps.audit, {
32772
32958
  procedure: `tunnel:${port}`,
32773
- actor: caller ?? { kind: "token", name: "unknown" },
32959
+ actor: caller,
32774
32960
  impName: name,
32775
32961
  startedAt: deps.now()
32776
32962
  }, () => deps.imps.openDial(name, target, "tunnel"));
@@ -32779,13 +32965,13 @@ function createTunnelSocketRoute(deps) {
32779
32965
  const where = "port" in spec ? String(spec.port) : readListenPath(spec);
32780
32966
  return withAuditedOpen(deps.audit, {
32781
32967
  procedure: `reverse:${where}`,
32782
- actor: caller ?? { kind: "token", name: "unknown" },
32968
+ actor: caller,
32783
32969
  impName: name,
32784
32970
  startedAt: deps.now()
32785
32971
  }, () => deps.imps.openListener(name, spec, null));
32786
32972
  },
32787
32973
  openAccept: (name, listener, connection) => deps.imps.openAccept(name, listener, connection, "tunnel"),
32788
- owner: caller === undefined ? "" : `${caller.kind}:${caller.name}:${caller.tokenId ?? ""}`
32974
+ owner: `${caller.kind}:${caller.name}:${caller.tokenId ?? ""}`
32789
32975
  }, tunnelLimits, reverseForwards);
32790
32976
  const forget = deps.closeOnRevocation(caller, () => {
32791
32977
  close(CLOSE_REVOKED2, "the token was removed");
@@ -33266,7 +33452,7 @@ var CHECKPOINT_TOOLS = [
33266
33452
  ];
33267
33453
 
33268
33454
  // packages/mcp/src/tools/event-tool.ts
33269
- import { P as P4, match as match13 } from "ts-pattern";
33455
+ import { P as P4, match as match14 } from "ts-pattern";
33270
33456
  import * as z72 from "zod";
33271
33457
  var EVENT_TOOL = defineTool({
33272
33458
  name: "imp_event_list",
@@ -33289,7 +33475,7 @@ var EVENT_TOOL = defineTool({
33289
33475
  }
33290
33476
  });
33291
33477
  function isAllowedEvent(guard, event) {
33292
- return match13(event).with({ ev: P4.union("Reset", "Position") }, () => true).with({ ev: P4.union("ImpAdded", "ImpChanged", "ImpRemoved") }, (changed) => guard.isAllowed(changed.imp.name)).with({ ev: P4.union("CheckpointAdded", "CheckpointRemoved", "GovernorDecision", "AgentExec") }, (named) => guard.isAllowed(named.name)).otherwise(() => false);
33478
+ return match14(event).with({ ev: P4.union("Reset", "Position") }, () => true).with({ ev: P4.union("ImpAdded", "ImpChanged", "ImpRemoved") }, (changed) => guard.isAllowed(changed.imp.name)).with({ ev: P4.union("CheckpointAdded", "CheckpointRemoved", "GovernorDecision", "AgentExec") }, (named) => guard.isAllowed(named.name)).otherwise(() => false);
33293
33479
  }
33294
33480
 
33295
33481
  // packages/mcp/src/tools/exec-tool.ts
@@ -34423,17 +34609,24 @@ function createApp(deps) {
34423
34609
  connectExec: execSockets.openExecSocket,
34424
34610
  readEnds
34425
34611
  });
34426
- const publicMcp = createMcpEndpoint({
34427
- findCaller: (request) => {
34428
- const bearer = findBearer(request.headers.get("authorization"));
34429
- return bearer === null ? Promise.resolve(null) : deps.oauth.resolveAccess(bearer);
34430
- },
34612
+ const publicCallers = new WeakMap;
34613
+ const publicOrigin = deps.oauth.server?.issuer ?? null;
34614
+ const publicTransport = createMcpEndpoint({
34615
+ findCaller: (request) => Promise.resolve(publicCallers.get(request) ?? null),
34431
34616
  handleRpc,
34432
34617
  connectExec: execSockets.openExecSocket,
34433
34618
  readEnds,
34434
- isCrossOrigin: (request) => !isAllowedOrigin(request, { kind: "public-route", origin: deps.oauth.issuer }),
34435
- challenge: `Bearer resource_metadata="${deps.oauth.issuer}/.well-known/oauth-protected-resource/mcp", scope="read"`
34619
+ isCrossOrigin: (request) => publicOrigin === null || !isAllowedOrigin(request, { kind: "public-route", origin: publicOrigin }),
34620
+ challenge: `Bearer resource_metadata="${publicOrigin ?? ""}/.well-known/oauth-protected-resource/mcp"`
34436
34621
  });
34622
+ const publicMcp = {
34623
+ respond: (request, caller) => {
34624
+ publicCallers.set(request, caller);
34625
+ return publicTransport.respond(request);
34626
+ },
34627
+ close: publicTransport.close,
34628
+ readCallEnd: publicTransport.readCallEnd
34629
+ };
34437
34630
  const sessionCalls = createSessionHandler({
34438
34631
  tokens: deps.tokens,
34439
34632
  rootToken: deps.rootToken,
@@ -34442,11 +34635,11 @@ function createApp(deps) {
34442
34635
  logFailure: logRpcFailure
34443
34636
  });
34444
34637
  const dashboardRoutes = createDashboardRoutes(deps.config.dashboardDir);
34445
- const app = new Elysia4({ websocket: EXEC_SOCKET_OPTIONS }).get("/health", () => ({
34638
+ const app = new Elysia4().use(autoHead()).use(websocket3(EXEC_SOCKET_OPTIONS)).get("/health", () => ({
34446
34639
  status: "ok",
34447
34640
  ready: deps.isReady(),
34448
34641
  warnings: buildHealthWarnings(deps.imps.readRebootReason(), deps.storage.readWarnings())
34449
- })).use(dashboardRoutes).all("/rpc*", async (context) => {
34642
+ })).use(dashboardRoutes).all("/rpc*", { parse: "none" }, async (context) => {
34450
34643
  const answered = await sessionCalls.respond(context.request);
34451
34644
  if (answered !== null) {
34452
34645
  return answered;
@@ -34456,22 +34649,22 @@ function createApp(deps) {
34456
34649
  return Response.json({ error: "unauthorized" }, { status: 401 });
34457
34650
  }
34458
34651
  return handleRpc(context.request, caller);
34459
- }, { parse: "none" }).all(MCP_PATH, (context) => {
34652
+ }).all(MCP_PATH, { parse: "none" }, (context) => {
34460
34653
  context.server?.timeout(context.request, 0);
34461
34654
  mcpServers.set(context.request, context.server);
34462
34655
  return mcp.respond(context.request);
34463
- }, { parse: "none" }).post(BUILD_CONTEXT_PATH, async (context) => {
34656
+ }).post(BUILD_CONTEXT_PATH, { parse: "none" }, async (context) => {
34464
34657
  const caller = await findCaller(context.request, context.server, true);
34465
34658
  if (caller === null) {
34466
34659
  return Response.json({ error: "unauthorized" }, { status: 401 });
34467
34660
  }
34468
34661
  context.server?.timeout(context.request, 0);
34469
34662
  return deps.buildContexts.respond(context.request, caller);
34470
- }, { parse: "none" }).post("/move/:step", (context) => {
34663
+ }).post("/move/:step", { parse: "none" }, (context) => {
34471
34664
  context.server?.timeout(context.request, 0);
34472
34665
  const peer = context.server?.requestIP(context.request)?.address ?? null;
34473
34666
  return deps.moves.respond(context.request, peer);
34474
- }, { parse: "none" }).use(execSockets.route).use(tunnelSockets.route);
34667
+ }).use(execSockets.route).use(tunnelSockets.route);
34475
34668
  return {
34476
34669
  app,
34477
34670
  publicMcp,
@@ -35087,7 +35280,7 @@ function buildHostReach(ranges, uplinks, hasIPv6) {
35087
35280
 
35088
35281
  // packages/daemon/src/network/broker/broker-service.ts
35089
35282
  import { join as join16 } from "path";
35090
- import { match as match15 } from "ts-pattern";
35283
+ import { match as match16 } from "ts-pattern";
35091
35284
 
35092
35285
  // packages/daemon/src/platform/db/broker-audit.ts
35093
35286
  var AUDIT_ROWS_PER_IMP = 1000;
@@ -35831,7 +36024,7 @@ async function readBrokerPeer(db, slot) {
35831
36024
  }
35832
36025
 
35833
36026
  // packages/daemon/src/platform/http/open-upstream-socket.ts
35834
- import invariant9 from "tiny-invariant";
36027
+ import invariant10 from "tiny-invariant";
35835
36028
  function openUpstreamSocket(target, protocols, headers, options) {
35836
36029
  return new Promise((resolve, reject) => {
35837
36030
  const socketOptions = {
@@ -35840,7 +36033,7 @@ function openUpstreamSocket(target, protocols, headers, options) {
35840
36033
  ...options.ca !== undefined && { tls: { ca: [...options.ca] } }
35841
36034
  };
35842
36035
  const socket = Reflect.construct(WebSocket, [target, socketOptions]);
35843
- invariant9(socket instanceof WebSocket);
36036
+ invariant10(socket instanceof WebSocket);
35844
36037
  socket.binaryType = "arraybuffer";
35845
36038
  const cancelTimer = options.startTimer(() => {
35846
36039
  socket.close();
@@ -37088,9 +37281,9 @@ function createBrokerProxy(deps) {
37088
37281
  }
37089
37282
 
37090
37283
  // packages/daemon/src/network/broker/secrets/build-stored-binding.ts
37091
- import { P as P5, match as match14 } from "ts-pattern";
37284
+ import { P as P5, match as match15 } from "ts-pattern";
37092
37285
  function buildStoredBinding(input) {
37093
- return match14(input).returnType().with({ kind: "static" }, (given) => ({
37286
+ return match15(input).returnType().with({ kind: "static" }, (given) => ({
37094
37287
  kind: "static",
37095
37288
  rules: given.rules,
37096
37289
  env: given.env ?? [],
@@ -38037,7 +38230,7 @@ ${key.host}`));
38037
38230
  if (outcome.kind === "granted") {
38038
38231
  return;
38039
38232
  }
38040
- throw match15(outcome).with({ kind: "no-secret" }, () => buildNotFoundError("secret", secretName)).with({ kind: "no-token" }, () => buildTokenGoneError()).with({ kind: "not-grantable" }, () => buildStaleError(secretName)).with({ kind: "clash" }, (refused) => buildClashError(impName, secretName, refused.clash)).exhaustive();
38233
+ throw match16(outcome).with({ kind: "no-secret" }, () => buildNotFoundError("secret", secretName)).with({ kind: "no-token" }, () => buildTokenGoneError()).with({ kind: "not-grantable" }, () => buildStaleError(secretName)).with({ kind: "clash" }, (refused) => buildClashError(impName, secretName, refused.clash)).exhaustive();
38041
38234
  },
38042
38235
  removeGrant: async (impName, secretName, authority = null) => {
38043
38236
  const imp = await requireImp(impName);
@@ -38046,7 +38239,7 @@ ${key.host}`));
38046
38239
  }
38047
38240
  const outcome = await removeCheckedGrant(db, imp.id, secretName, authority);
38048
38241
  if (outcome.kind !== "revoked") {
38049
- throw match15(outcome).with({ kind: "no-token" }, () => buildTokenGoneError()).with({ kind: "not-grantable" }, () => buildStaleError(secretName)).with({ kind: "no-grant" }, () => buildNotFoundError("grant", `${impName}/${secretName}`)).exhaustive();
38242
+ throw match16(outcome).with({ kind: "no-token" }, () => buildTokenGoneError()).with({ kind: "not-grantable" }, () => buildStaleError(secretName)).with({ kind: "no-grant" }, () => buildNotFoundError("grant", `${impName}/${secretName}`)).exhaustive();
38050
38243
  }
38051
38244
  await applyGrants();
38052
38245
  },
@@ -38121,7 +38314,7 @@ ${key.host}`));
38121
38314
  if (outcome.kind === "staged") {
38122
38315
  return live.readDocument();
38123
38316
  }
38124
- throw match15(outcome).with({ kind: "already-staged" }, () => new ImpdError("CONFLICT", {
38317
+ throw match16(outcome).with({ kind: "already-staged" }, () => new ImpdError("CONFLICT", {
38125
38318
  message: "a key change is already staged; it has no cancel, and the next stage waits for its switch time"
38126
38319
  })).with({ kind: "not-in-future" }, () => new ImpdError("BAD_REQUEST", { message: "the switch time must be in the future" })).exhaustive();
38127
38320
  },
@@ -39637,11 +39830,11 @@ function readTapOwner(tap) {
39637
39830
  }
39638
39831
 
39639
39832
  // packages/daemon/src/imp-ops/governor/build-deferred-admission.ts
39640
- import invariant10 from "tiny-invariant";
39833
+ import invariant11 from "tiny-invariant";
39641
39834
  function buildDeferredAdmission() {
39642
39835
  const holder = { governor: null };
39643
39836
  const requireGovernor = () => {
39644
- invariant10(holder.governor, "RAM admission ran before the RAM governor was attached");
39837
+ invariant11(holder.governor, "RAM admission ran before the RAM governor was attached");
39645
39838
  return holder.governor;
39646
39839
  };
39647
39840
  return {
@@ -41022,7 +41215,7 @@ import {
41022
41215
  } from "fs";
41023
41216
  import { join as join19 } from "path";
41024
41217
  import { withContext as withContext2 } from "@logtape/logtape";
41025
- import { match as match19 } from "ts-pattern";
41218
+ import { match as match20 } from "ts-pattern";
41026
41219
  import * as z80 from "zod";
41027
41220
 
41028
41221
  // packages/daemon/src/platform/process/semaphore.ts
@@ -41110,12 +41303,12 @@ function buildTemplateKey(identity, shape) {
41110
41303
  }
41111
41304
 
41112
41305
  // packages/daemon/src/vm/templates/pick-restore-failure-outcome.ts
41113
- import { match as match16 } from "ts-pattern";
41306
+ import { match as match17 } from "ts-pattern";
41114
41307
  function pickRestoreFailureOutcome(facts) {
41115
41308
  if (!facts.isCurrentBuild) {
41116
41309
  return "ignore";
41117
41310
  }
41118
- return match16(facts.fault).with(null, () => "ignore").with("agent", () => facts.restoredNow > facts.restoredBefore ? "keep" : pickCountedOutcome(facts)).with("load", () => pickCountedOutcome(facts)).exhaustive();
41311
+ return match17(facts.fault).with(null, () => "ignore").with("agent", () => facts.restoredNow > facts.restoredBefore ? "keep" : pickCountedOutcome(facts)).with("load", () => pickCountedOutcome(facts)).exhaustive();
41119
41312
  }
41120
41313
  var MAX_RESTORE_FAILURES = 3;
41121
41314
  function pickCountedOutcome(facts) {
@@ -41123,7 +41316,7 @@ function pickCountedOutcome(facts) {
41123
41316
  }
41124
41317
 
41125
41318
  // packages/daemon/src/vm/templates/template-locks.ts
41126
- import { match as match18 } from "ts-pattern";
41319
+ import { match as match19 } from "ts-pattern";
41127
41320
 
41128
41321
  // packages/daemon/src/vm/templates/can-admit-lock.ts
41129
41322
  var MAX_LOCKED_PERCENT = 10;
@@ -41134,10 +41327,10 @@ function canAdmitLock(admission) {
41134
41327
  }
41135
41328
 
41136
41329
  // packages/daemon/src/vm/templates/pick-lock-outcome.ts
41137
- import { P as P6, match as match17 } from "ts-pattern";
41330
+ import { P as P6, match as match18 } from "ts-pattern";
41138
41331
  var MIB4 = 1024 * 1024;
41139
41332
  function pickLockOutcome(result, isCurrent) {
41140
- return match17(result).with({ errno: P6.number }, (failed) => ({ kind: "failed", errno: failed.errno })).with({ declinedBytes: P6.number }, (declined) => ({
41333
+ return match18(result).with({ errno: P6.number }, (failed) => ({ kind: "failed", errno: failed.errno })).with({ declinedBytes: P6.number }, (declined) => ({
41141
41334
  kind: "declined",
41142
41335
  lockMib: Math.ceil(declined.declinedBytes / MIB4)
41143
41336
  })).with({ lock: P6.select() }, (lock) => isCurrent ? { kind: "held", lock, lockMib: Math.ceil(lock.lockedBytes / MIB4) } : { kind: "stale", lock }).exhaustive();
@@ -41165,7 +41358,7 @@ function createTemplateLocks(deps) {
41165
41358
  }
41166
41359
  return isAdmitted;
41167
41360
  });
41168
- match18(pickLockOutcome(result, deps.probeCurrent(target))).with({ kind: "failed" }, (failed) => {
41361
+ match19(pickLockOutcome(result, deps.probeCurrent(target))).with({ kind: "failed" }, (failed) => {
41169
41362
  deps.logger.warning("boot template {key} memory not locked (errno {errno}): a restore reads what the host dropped", { key, errno: String(failed.errno) });
41170
41363
  }).with({ kind: "declined" }, (declined) => {
41171
41364
  deps.logger.info("boot template {key} memory not locked: {lockMib} MiB would take the locks past a tenth of the RAM budget", { key, lockMib: String(declined.lockMib) });
@@ -41521,7 +41714,7 @@ function createBootTemplates(deps) {
41521
41714
  record.restoreFailures += 1;
41522
41715
  removeDir(files.key);
41523
41716
  };
41524
- match19(outcome).with("ignore", () => {}).with("keep", () => {
41717
+ match20(outcome).with("ignore", () => {}).with("keep", () => {
41525
41718
  getImpdLogger("boot").info("boot template {key} kept: its agent timed out while another restore of it succeeded", { key: files.key.slice(0, 12) });
41526
41719
  }).with("remove", removeFailed).with("disable", () => {
41527
41720
  removeFailed();
@@ -41643,8 +41836,8 @@ function splitRun(run) {
41643
41836
  }
41644
41837
 
41645
41838
  // packages/daemon/src/vm/vmm/create-memory-warm.ts
41646
- import invariant11 from "tiny-invariant";
41647
- import { match as match20 } from "ts-pattern";
41839
+ import invariant12 from "tiny-invariant";
41840
+ import { match as match21 } from "ts-pattern";
41648
41841
  import * as z81 from "zod";
41649
41842
  var BLOCK_MIB2 = 2;
41650
41843
  var WARM_CONCURRENCY = 2;
@@ -41693,7 +41886,7 @@ function createMemoryWarm(deps) {
41693
41886
  logWarm(target, { kind: "closed" }, deps.capMib);
41694
41887
  return;
41695
41888
  }
41696
- invariant11(!running.has(target.impID), `imp ${target.impID} slept with its warm running`);
41889
+ invariant12(!running.has(target.impID), `imp ${target.impID} slept with its warm running`);
41697
41890
  const controller = new AbortController;
41698
41891
  const state = { phase: "queued", end: null };
41699
41892
  const startedMs = performance.now();
@@ -41727,7 +41920,7 @@ function createMemoryWarm(deps) {
41727
41920
  }
41728
41921
  function logWarm(target, outcome, capMib) {
41729
41922
  const logger = getImpdLogger("imps").with({ imp: target.name });
41730
- match20(outcome).with({ kind: "warmed" }, (warmed) => {
41923
+ match21(outcome).with({ kind: "warmed" }, (warmed) => {
41731
41924
  logger.info("warmed the memory file in {warmMs}ms: {blocks} blocks of 2 MiB", {
41732
41925
  warmMs: String(warmed.warmMs),
41733
41926
  blocks: String(warmed.blocks)
@@ -41746,7 +41939,7 @@ function logWarm(target, outcome, capMib) {
41746
41939
  }).exhaustive();
41747
41940
  }
41748
41941
  function formatWarmEnd(end) {
41749
- return match20(end).with("woke", () => "the imp woke").with("stopped", () => "the imp stopped").with("destroyed", () => "the imp is destroyed").with("impdStopped", () => "impd stopped").exhaustive();
41942
+ return match21(end).with("woke", () => "the imp woke").with("stopped", () => "the imp stopped").with("destroyed", () => "the imp is destroyed").with("impdStopped", () => "impd stopped").exhaustive();
41750
41943
  }
41751
41944
 
41752
41945
  // packages/daemon/src/vm/vmm/vm-stats.ts
@@ -46087,7 +46280,7 @@ function countStepsMs(timings) {
46087
46280
  }
46088
46281
 
46089
46282
  // packages/daemon/src/imps/imps/services/service-api.ts
46090
- import { match as match21 } from "ts-pattern";
46283
+ import { match as match22 } from "ts-pattern";
46091
46284
 
46092
46285
  // packages/daemon/src/imps/imps/services/create-log-decoders.ts
46093
46286
  function createLogDecoders() {
@@ -46311,7 +46504,7 @@ function handleAgentError(service) {
46311
46504
  if (!(error instanceof AgentError)) {
46312
46505
  throw error;
46313
46506
  }
46314
- throw match21(error.code).with("NO_SERVICE", () => buildNotFoundError("service", service)).with("SERVICE_EXISTS", () => buildConflictError("service", service)).with("BAD_REQUEST", () => new ImpdError("BAD_REQUEST", { message: error.detail })).with("AGENT_OUTDATED", () => buildAgentOutdatedApiError(error.message)).otherwise(() => error);
46507
+ throw match22(error.code).with("NO_SERVICE", () => buildNotFoundError("service", service)).with("SERVICE_EXISTS", () => buildConflictError("service", service)).with("BAD_REQUEST", () => new ImpdError("BAD_REQUEST", { message: error.detail })).with("AGENT_OUTDATED", () => buildAgentOutdatedApiError(error.message)).otherwise(() => error);
46315
46508
  };
46316
46509
  }
46317
46510
  function stopStreams(streams) {
@@ -48224,7 +48417,7 @@ function readReceipt(receipt, secret) {
48224
48417
  import { mkdirSync as mkdirSync20, rmSync as rmSync24 } from "fs";
48225
48418
  import { open as open7 } from "fs/promises";
48226
48419
  import { join as join26 } from "path";
48227
- import invariant12 from "tiny-invariant";
48420
+ import invariant13 from "tiny-invariant";
48228
48421
 
48229
48422
  // packages/daemon/src/imp-ops/moves/build-received-digest.ts
48230
48423
  import { createHash as createHash6 } from "crypto";
@@ -49015,7 +49208,7 @@ async function requireImage(deps, options) {
49015
49208
  { kind: "image-rootfs", sha256: rootfs.sha256, bytes: rootfs.bytes },
49016
49209
  { kind: "image-config", sha256: config.sha256, bytes: config.bytes }
49017
49210
  ];
49018
- invariant12(rootfs.contentSha256 !== null && config.contentSha256 !== null);
49211
+ invariant13(rootfs.contentSha256 !== null && config.contentSha256 !== null);
49019
49212
  const digest = buildReceivedDigest(rootfs.contentSha256, config.contentSha256);
49020
49213
  const known = await readImageInUse(deps.db, [digest], deps.now());
49021
49214
  if (known !== undefined) {
@@ -49320,8 +49513,8 @@ function readSettled2(row, imp) {
49320
49513
  }
49321
49514
 
49322
49515
  // packages/daemon/src/imp-ops/moves/move-sender.ts
49323
- import invariant13 from "tiny-invariant";
49324
- import { match as match22 } from "ts-pattern";
49516
+ import invariant14 from "tiny-invariant";
49517
+ import { match as match23 } from "ts-pattern";
49325
49518
 
49326
49519
  // packages/daemon/src/platform/db/move-send-steps.ts
49327
49520
  var MOVE_SEND_STEPS = [
@@ -49884,7 +50077,7 @@ function createMoveSender(deps) {
49884
50077
  };
49885
50078
  const recoverSend = async (imp, row) => {
49886
50079
  const log = getImpdLogger("move").with({ imp: imp.name });
49887
- await match22(pickSendRecovery(imp.moveState, row?.step)).with("unmark", () => removeMark(imp)).with("wait", () => {
50080
+ await match23(pickSendRecovery(imp.moveState, row?.step)).with("unmark", () => removeMark(imp)).with("wait", () => {
49888
50081
  log.info("a prepared send waits for its send after a restart");
49889
50082
  }).with("abort", async () => {
49890
50083
  const isUndone = await resetSend(imp, row?.peer_url ?? null, row?.ticket ?? null);
@@ -49892,7 +50085,7 @@ function createMoveSender(deps) {
49892
50085
  log.info("a send cut short by a restart was undone");
49893
50086
  }
49894
50087
  }).with("commit", async () => {
49895
- invariant13(row !== undefined && row.peer_url !== null && row.ticket !== null);
50088
+ invariant14(row !== undefined && row.peer_url !== null && row.ticket !== null);
49896
50089
  const moved = imp.moveState === "moved" ? imp : await updateImpMove(deps.db, imp.id, "moved");
49897
50090
  await runCommitAfterRestart(moved, row.peer_url, row.ticket);
49898
50091
  }).with("none", () => {}).exhaustive();
@@ -50006,7 +50199,7 @@ function buildPublicError(name) {
50006
50199
  }
50007
50200
  function pickSendRecovery(moveState, step) {
50008
50201
  if (moveState === "sending") {
50009
- return match22(step).with(undefined, () => "unmark").with("prepared", () => "wait").with("streaming", () => "abort").with("sent", () => "commit").exhaustive();
50202
+ return match23(step).with(undefined, () => "unmark").with("prepared", () => "wait").with("streaming", () => "abort").with("sent", () => "commit").exhaustive();
50010
50203
  }
50011
50204
  return moveState === "moved" && step === "sent" ? "commit" : "none";
50012
50205
  }
@@ -50058,7 +50251,7 @@ function createMoveService(deps) {
50058
50251
  // packages/daemon/src/surface/moves/create-move-peer-handler.ts
50059
50252
  import { OpenAPIHandler } from "@orpc/openapi/fetch";
50060
50253
  import { ORPCError as ORPCError7, implement as implement3, onError as onError3 } from "@orpc/server";
50061
- import { match as match23 } from "ts-pattern";
50254
+ import { match as match24 } from "ts-pattern";
50062
50255
  function createMovePeerHandler(deps) {
50063
50256
  const withTicket = async (step, context, call) => {
50064
50257
  const startedAt = deps.now();
@@ -50109,7 +50302,7 @@ function createMovePeerHandler(deps) {
50109
50302
  const respondReceive = async (context) => {
50110
50303
  try {
50111
50304
  const received = await withTicket("receive", context, (checked) => deps.calls.receive(checked, context.request));
50112
- return match23(received).with({ kind: "part" }, (sent) => Response.json({ part: sent.part }, { status: 202 })).with({ kind: "receipt" }, (sent) => Response.json(sent.receipt)).exhaustive();
50305
+ return match24(received).with({ kind: "part" }, (sent) => Response.json({ part: sent.part }, { status: 202 })).with({ kind: "receipt" }, (sent) => Response.json(sent.receipt)).exhaustive();
50113
50306
  } catch (error) {
50114
50307
  const failure = toPeerError(error);
50115
50308
  return Response.json(encodePeerError(failure), { status: failure.status });
@@ -54112,1092 +54305,209 @@ function createRevocations() {
54112
54305
  };
54113
54306
  }
54114
54307
 
54115
- // packages/daemon/src/identity/oauth/create-mcp-auth.ts
54116
- import { mcp } from "@better-auth/mcp";
54117
- import { oauthProvider } from "@better-auth/oauth-provider";
54118
- import { betterAuth } from "better-auth";
54119
- import { isAPIError } from "better-auth/api";
54308
+ // packages/daemon/src/identity/oauth/create-impd-mcp-auth.ts
54309
+ import { DEFAULT_PATHS, openMCPAuth, openMCPAuthAdmin } from "@zgeoff/mcp-auth";
54120
54310
 
54121
- // packages/daemon/src/identity/oauth/create-approver-plugin.ts
54122
- import { getOAuthProviderApi } from "@better-auth/oauth-provider";
54123
- import { createAuthEndpoint } from "better-auth/api";
54124
- import { setSessionCookie } from "better-auth/cookies";
54125
- import { generateRandomString } from "better-auth/crypto";
54311
+ // packages/daemon/src/identity/oauth/imp-limits-schema.ts
54126
54312
  import * as z96 from "zod";
54127
- var CLIENT_SCOPES = [...ScopeSchema.options, "offline_access"];
54128
- var APPROVAL_EMAIL_DOMAIN = "approval.imp.invalid";
54129
- var SignInBodySchema = z96.object({
54130
- oauth_query: z96.string(),
54131
- tokenID: z96.string().min(1),
54132
- tokenName: z96.string().min(1),
54133
- imps: z96.array(z96.string()).nullable()
54313
+ var ImpLimitsSchema = z96.object({
54314
+ imps: z96.array(GrantPatternSchema).min(1).max(32).nullable(),
54315
+ grantable: z96.boolean()
54134
54316
  });
54135
- var FixedClientBodySchema = z96.object({
54136
- name: z96.string().min(1),
54137
- redirectURIs: z96.array(z96.string()).min(1)
54138
- });
54139
- function createApproverPlugin() {
54140
- return {
54141
- id: "imp-approver",
54142
- endpoints: {
54143
- signInApproval: createAuthEndpoint("/imp/sign-in-approval", {
54144
- method: "POST",
54145
- body: SignInBodySchema,
54146
- metadata: { SERVER_ONLY: true }
54147
- }, async (ctx) => {
54148
- const adapter = ctx.context.internalAdapter;
54149
- const local = generateRandomString(24, "a-z", "0-9");
54150
- const user = await adapter.createUser({
54151
- email: `${local}@${APPROVAL_EMAIL_DOMAIN}`,
54152
- name: ctx.body.tokenName,
54153
- emailVerified: true,
54154
- tokenId: ctx.body.tokenID,
54155
- imps: ctx.body.imps === null ? null : JSON.stringify(ctx.body.imps)
54156
- }, { method: "admin" });
54157
- const session = await adapter.createSession(user.id);
54158
- await setSessionCookie(ctx, { session, user });
54159
- return ctx.json({ signedIn: true });
54160
- }),
54161
- verifyMCPAccessToken: createAuthEndpoint("/imp/verify-access-token", {
54162
- method: "POST",
54163
- body: z96.object({ token: z96.string() }),
54164
- metadata: { SERVER_ONLY: true }
54165
- }, async (ctx) => {
54166
- const provider = ctx.context.getPlugin("oauth-provider");
54167
- if (provider === null) {
54168
- throw new Error("the oauth-provider plugin is not installed");
54169
- }
54170
- const payload = await getOAuthProviderApi(ctx, provider.options).requireActiveAccessToken(ctx.body.token);
54171
- return ctx.json(payload);
54172
- }),
54173
- createFixedClient: createAuthEndpoint("/imp/create-fixed-client", {
54174
- method: "POST",
54175
- body: FixedClientBodySchema,
54176
- metadata: { SERVER_ONLY: true }
54177
- }, async (ctx) => {
54178
- const clientID = `impc_${generateRandomString(32, "a-z", "A-Z", "0-9")}`;
54179
- const now = new Date;
54180
- const isWeb = ctx.body.redirectURIs.every((uri) => uri.startsWith("https:"));
54181
- await ctx.context.adapter.create({
54182
- model: "oauthClient",
54183
- data: {
54184
- clientId: clientID,
54185
- name: ctx.body.name,
54186
- redirectUris: ctx.body.redirectURIs,
54187
- scopes: CLIENT_SCOPES,
54188
- clientCredentialsScopes: [],
54189
- tokenEndpointAuthMethod: "none",
54190
- grantTypes: ["authorization_code", "refresh_token"],
54191
- responseTypes: ["code"],
54192
- applicationType: isWeb ? "web" : "native",
54193
- requirePKCE: true,
54194
- disabled: false,
54195
- createdAt: now,
54196
- updatedAt: now
54197
- }
54198
- });
54199
- return ctx.json({ clientID, createdAt: now.toISOString() });
54200
- })
54201
- }
54202
- };
54203
- }
54204
-
54205
- // packages/daemon/src/identity/oauth/create-oauth-handlers.ts
54206
- import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
54207
- import * as z97 from "zod";
54208
-
54209
- // packages/daemon/src/identity/oauth/build-bad-token-request.ts
54210
- function buildBadTokenRequest() {
54211
- return Response.json({ error: "invalid_request", error_description: "the request body is missing or too large" }, { status: 400, headers: { "cache-control": "no-store" } });
54212
- }
54213
-
54214
- // packages/daemon/src/identity/oauth/build-consent-binding.ts
54215
- function buildConsentBinding(oauthQuery) {
54216
- const params = new URLSearchParams(oauthQuery);
54217
- return JSON.stringify(["client_id", "redirect_uri", "scope", "resource", "state", "code_challenge"].map((name) => params.get(name) ?? ""));
54218
- }
54219
-
54220
- // packages/daemon/src/identity/oauth/build-pkce-refusal.ts
54221
- function buildPKCERefusal() {
54222
- return Response.json({ error: "invalid_grant", error_description: "code verification failed" }, { status: 400, headers: { "cache-control": "no-store" } });
54223
- }
54224
-
54225
- // packages/daemon/src/identity/oauth/create-sign-ins.ts
54226
- import { randomBytes as randomBytes11 } from "crypto";
54227
54317
 
54228
- // packages/daemon/src/identity/oauth/grant-limits.ts
54229
- function isGrantPattern(pattern) {
54230
- return GrantPatternSchema.safeParse(pattern).success;
54231
- }
54232
- function isPatternsWithin(grant, token) {
54233
- if (token === null) {
54234
- return true;
54318
+ // packages/daemon/src/identity/oauth/parse-consent-imps.ts
54319
+ var MAX_PATTERNS = 32;
54320
+ function parseConsentImps(form) {
54321
+ const patterns = [
54322
+ ...new Set((form.get("imps") ?? "").split(/[\s,]+/v).filter((pattern) => pattern !== ""))
54323
+ ];
54324
+ if (patterns.length === 0) {
54325
+ return { ok: false, error: "Name at least one imp, or * for every imp." };
54235
54326
  }
54236
- if (grant === null) {
54237
- return false;
54327
+ if (patterns.length > MAX_PATTERNS) {
54328
+ return { ok: false, error: `Name at most ${String(MAX_PATTERNS)} imp patterns.` };
54238
54329
  }
54239
- return grant.every((pattern) => token.some((own) => isPatternWithin(pattern, own)));
54240
- }
54241
- function isPatternWithin(pattern, own) {
54242
- if (pattern === own) {
54243
- return true;
54330
+ const bad = patterns.find((pattern) => !GrantPatternSchema.safeParse(pattern).success);
54331
+ if (bad !== undefined) {
54332
+ return {
54333
+ ok: false,
54334
+ error: "Each pattern must be an imp name, or a name prefix and a trailing *, such as dev-*."
54335
+ };
54244
54336
  }
54245
- const star = own.indexOf("*");
54246
- return star === own.length - 1 && pattern.startsWith(own.slice(0, -1));
54247
- }
54248
- function readLowerScope(left, right) {
54249
- return hasScope(left, right) ? right : left;
54250
- }
54251
- function formatScopeList(scope) {
54252
- const nested = {
54253
- read: "read",
54254
- exec: "read exec",
54255
- manage: "read exec manage"
54256
- };
54257
- return nested[scope];
54258
- }
54259
- function pickGrantScope(scopes) {
54260
- return ScopeSchema.options.reduce((highest, scope) => scopes.includes(scope) && hasScope(scope, highest) ? scope : highest, "read");
54337
+ return { ok: true, limits: { imps: patterns, grantable: false } };
54261
54338
  }
54262
54339
 
54263
- // packages/daemon/src/identity/oauth/create-sign-ins.ts
54264
- var MINUTE_MS = 60000;
54265
- var SIGN_IN_MS = 10 * MINUTE_MS;
54266
- var MAX_PENDING = 16;
54267
- var MAX_PENDING_PER_CLIENT = 3;
54268
- var START_BUCKET = { size: 10, refillMs: 6000 };
54269
- var APPROVE_FAILURE_BUCKET = { size: 20, refillMs: 3000 };
54270
- var SIGN_IN_MOVES = {
54271
- waiting: ["approved"],
54272
- approved: []
54273
- };
54274
- function createSignIns(deps) {
54275
- const pending = new Map;
54276
- const byCode = new Map;
54277
- const tryStart = createTokenBuckets(() => START_BUCKET, deps.now);
54278
- const tryApproveFailure = createTokenBuckets(() => APPROVE_FAILURE_BUCKET, deps.now);
54279
- const removeEntry = (entry) => {
54280
- pending.delete(entry.key);
54281
- byCode.delete(entry.approvalCode);
54282
- };
54283
- const dropStale = () => {
54284
- const at = deps.now();
54285
- for (const entry of pending.values()) {
54286
- if (entry.expiresAt <= at) {
54287
- removeEntry(entry);
54288
- }
54289
- }
54290
- };
54291
- const requirePending = (code, approver) => {
54292
- const tokenID = requireNamedToken(approver);
54293
- dropStale();
54294
- const key = byCode.get(code);
54295
- const entry = key === undefined ? undefined : pending.get(key);
54296
- if (entry === undefined) {
54297
- if (!tryApproveFailure(tokenID)) {
54298
- throw new ImpdError("TOO_MANY_REQUESTS", {
54299
- message: "too many codes that match no sign-in; wait a few seconds"
54300
- });
54301
- }
54302
- throw buildNotFoundError("oauth-approval", formatApprovalCode(code));
54303
- }
54304
- return entry;
54305
- };
54306
- return {
54307
- start: (entry) => {
54308
- dropStale();
54309
- if (!tryStart(entry.clientID)) {
54310
- return { kind: "too-many", retryS: START_BUCKET.refillMs / 1000 };
54311
- }
54312
- const ofClient = [...pending.values()].filter((other) => other.clientID === entry.clientID);
54313
- if (ofClient.length >= MAX_PENDING_PER_CLIENT) {
54314
- const evicted = ofClient.find((other) => other.approval === null) ?? ofClient[0];
54315
- if (evicted !== undefined) {
54316
- removeEntry(evicted);
54317
- }
54318
- }
54319
- if (pending.size >= MAX_PENDING) {
54320
- return { kind: "too-many", retryS: SIGN_IN_MS / 1000 };
54321
- }
54322
- const at = deps.now();
54323
- const signIn = {
54324
- ...entry,
54325
- approvalCode: createUniqueApprovalCode(byCode),
54326
- createdAt: at,
54327
- expiresAt: at + SIGN_IN_MS,
54328
- approval: null
54329
- };
54330
- pending.set(signIn.key, signIn);
54331
- byCode.set(signIn.approvalCode, signIn.key);
54332
- return { kind: "started", signIn };
54333
- },
54334
- find: (key) => {
54335
- dropStale();
54336
- return pending.get(key) ?? null;
54337
- },
54338
- remove: (key) => {
54339
- const entry = pending.get(key);
54340
- if (entry !== undefined) {
54341
- removeEntry(entry);
54342
- }
54343
- },
54344
- removeClient: (clientID) => {
54345
- for (const entry of pending.values()) {
54346
- if (entry.clientID === clientID) {
54347
- removeEntry(entry);
54348
- }
54349
- }
54350
- },
54351
- readApproval: (code, approver) => {
54352
- const entry = requirePending(code, approver);
54353
- return {
54354
- client: entry.clientName,
54355
- redirectUri: entry.redirectURI,
54356
- requestedScope: entry.requestedScope,
54357
- requestedAt: new Date(entry.createdAt),
54358
- expiresAt: new Date(entry.expiresAt)
54359
- };
54360
- },
54361
- approve: (code, approver, scope, imps) => {
54362
- const entry = requirePending(code, approver);
54363
- if (!SIGN_IN_MOVES[entry.approval === null ? "waiting" : "approved"].includes("approved")) {
54364
- throw buildConflictError("oauth-approval", formatApprovalCode(code), "this sign-in is approved already");
54365
- }
54366
- if (!hasScope(entry.requestedScope, scope)) {
54367
- throw new ImpdError("BAD_REQUEST", {
54368
- message: `the client asked for ${entry.requestedScope}; approve that or less`
54369
- });
54370
- }
54371
- if (!hasScope(approver.scope, scope)) {
54372
- throw buildForbiddenError(`token ${approver.name} has ${approver.scope}, so it may approve that or less`);
54373
- }
54374
- const patterns = imps ?? approver.imps;
54375
- if (patterns !== null && !patterns.every((pattern) => isGrantPattern(pattern))) {
54376
- throw new ImpdError("BAD_REQUEST", {
54377
- message: `token ${approver.name}'s patterns are not all an imp name or a prefix and *; name the imps with --imps`
54378
- });
54379
- }
54380
- if (!isPatternsWithin(patterns, approver.imps)) {
54381
- throw buildForbiddenError(`the imps must stay within token ${approver.name}'s: ${(approver.imps ?? []).join(", ")}`);
54382
- }
54383
- const approved = {
54384
- ...entry,
54385
- approval: {
54386
- tokenID: requireNamedToken(approver),
54387
- tokenName: approver.name,
54388
- scope,
54389
- imps: patterns
54390
- }
54391
- };
54392
- pending.set(entry.key, approved);
54393
- return approved;
54394
- }
54395
- };
54396
- }
54397
- function formatApprovalCode(code) {
54398
- return `${code.slice(0, 4)}-${code.slice(4)}`;
54399
- }
54400
- function requireNamedToken(approver) {
54401
- const isNamedKind = approver.kind === "token" || approver.kind === "dashboard";
54402
- if (!isNamedKind || approver.tokenId === null || approver.tokenId === ROOT_TOKEN_ID) {
54403
- throw buildForbiddenError("only a named token approves a sign-in; make one with impz token new and use it");
54340
+ // packages/daemon/src/identity/oauth/pick-grant-check.ts
54341
+ function pickGrantCheck(grant, approver) {
54342
+ if (grant.approvedBy === "passkey") {
54343
+ return { kind: "allow", scopes: grant.scopes };
54404
54344
  }
54405
- return approver.tokenId;
54406
- }
54407
- var CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
54408
- var CODE_LENGTH = 8;
54409
- function createUniqueApprovalCode(taken) {
54410
- for (;; ) {
54411
- const bytes = randomBytes11(CODE_LENGTH);
54412
- const code = [...bytes].map((byte) => CODE_ALPHABET[byte % CODE_ALPHABET.length]).join("");
54413
- if (!taken.has(code)) {
54414
- return code;
54415
- }
54345
+ const scope = pickGrantScope(grant.scopes);
54346
+ const imps = grant.limits?.imps ?? null;
54347
+ if (approver === null || !hasScope(approver.scope, scope)) {
54348
+ return { kind: "revoke", reason: "the token that approved it no longer covers it" };
54416
54349
  }
54350
+ if (!isPatternsWithin(imps, approver.imps)) {
54351
+ return { kind: "revoke", reason: "the token that approved it no longer covers it" };
54352
+ }
54353
+ return {
54354
+ kind: "allow",
54355
+ scopes: formatScopeList(pickLowerScope(scope, approver.scope)).split(" ")
54356
+ };
54417
54357
  }
54418
54358
 
54419
- // packages/daemon/src/identity/oauth/derive-token-hash.ts
54420
- function deriveTokenHash(token) {
54421
- return hashSecret(token).toString("base64url");
54422
- }
54423
-
54424
- // packages/daemon/src/identity/oauth/expand-scopes.ts
54425
- function expandScopes(asked) {
54426
- const SCOPE_ORDER = ScopeSchema.options;
54427
- const expanded = asked.flatMap((word) => {
54428
- const index = SCOPE_ORDER.indexOf(word);
54429
- return index === -1 ? [word] : SCOPE_ORDER.slice(0, index + 1);
54430
- });
54431
- return [...new Set(expanded)];
54432
- }
54433
-
54434
- // packages/daemon/src/platform/http/render-html.ts
54435
- import { P as P7, match as match24 } from "ts-pattern";
54436
- var MARKUP = Symbol("markup");
54437
- function renderHTML(strings, ...parts) {
54438
- const html = parts.reduce((text, part, index) => `${text}${toHTML(part)}${strings[index + 1] ?? ""}`, strings[0] ?? "");
54439
- return { [MARKUP]: true, html };
54440
- }
54441
- function toHTML(part) {
54442
- return match24(part).with(P7.string, (text) => escapeHTML(text)).with(P7.array(), (list) => list.map((each) => each.html).join("")).with({ html: P7.string }, (markup) => markup.html).exhaustive();
54443
- }
54444
- function escapeHTML(text) {
54445
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
54446
- }
54447
-
54448
- // packages/daemon/src/identity/oauth/oauth-pages.ts
54449
- var ERROR_TEXT = {
54450
- expired: "This sign-in ended or is not valid. Start it again from the client.",
54451
- bad_request: "This request is not valid.",
54452
- unknown_client: "This client is not one this host knows. Ask its operator to add it.",
54453
- too_many: "Too many sign-ins wait already. Wait a few minutes, then start again.",
54454
- approver_gone: "The token that approved this sign-in is gone or no longer covers it. Start it again from the client."
54455
- };
54456
- function buildPageHeaders(redirectOrigin) {
54457
- const formAction = redirectOrigin === null ? "'self'" : `'self' ${redirectOrigin}`;
54458
- return new Headers({
54459
- "content-type": "text/html; charset=utf-8",
54460
- "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; form-action ${formAction}; frame-ancestors 'none'; base-uri 'none'`,
54461
- "x-frame-options": "DENY",
54462
- "referrer-policy": "same-origin",
54463
- "cache-control": "no-store",
54464
- "x-content-type-options": "nosniff"
54465
- });
54466
- }
54467
- function renderPendingPage(view, issuerHost) {
54468
- const returnsTo = new URL(view.redirectURI).host;
54469
- return renderPage("Approve this sign-in", renderHTML`<p><strong>${view.clientName}</strong> asks to use the imps on <strong>${issuerHost}</strong>, with up to <strong>${view.requestedScope}</strong> scope. It returns to <strong>${returnsTo}</strong>.</p>
54470
- <p>If you started this sign-in, approve it with a named imp token:</p>
54471
- <pre>impz oauth approve ${view.approvalCode}</pre>
54472
- <p>Then press Continue. Approve only a sign-in you started: anyone can open this page for a client this host knows. The code ends in 10 minutes.</p>
54473
- <form method="post" action="/login">${renderHiddenQuery(view.oauthQuery)}<button name="action" value="continue">Continue</button> <button name="action" value="deny">Deny</button></form>`);
54474
- }
54475
- function renderAllowPage(view) {
54476
- const imps = view.imps === null ? "every imp, and the host" : view.imps.join(", ");
54477
- return renderPage("Allow this sign-in", renderHTML`<p><strong>${view.clientName}</strong> gets <strong>${view.scope}</strong> scope on <strong>${imps}</strong>, and returns to <strong>${view.redirectURI}</strong>.</p>
54478
- <form method="post" action="/consent">${renderHiddenQuery(view.oauthQuery)}<button name="action" value="allow">Allow</button> <button name="action" value="deny">Deny</button></form>`);
54479
- }
54480
- function renderErrorPage(error) {
54481
- return renderPage("Sign-in refused", renderHTML`<p>${ERROR_TEXT[error]}</p>`);
54482
- }
54483
- function renderHiddenQuery(oauthQuery) {
54484
- return renderHTML`<input type="hidden" name="oauth_query" value="${oauthQuery}">`;
54485
- }
54486
- function renderPage(title, body) {
54487
- return renderHTML`<!doctype html>
54488
- <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title>
54489
- <style>body{font:16px/1.5 system-ui,sans-serif;max-width:36rem;margin:3rem auto;padding:0 1rem}pre{padding:.75rem;background:#eee;font-size:1.25rem}button{font:inherit;padding:.4rem 1rem}</style>
54490
- </head><body><h1>${title}</h1>
54491
- ${body}
54492
- </body></html>
54493
- `.html;
54359
+ // packages/daemon/src/identity/oauth/render-consent-imps.ts
54360
+ function renderConsentImps() {
54361
+ return [
54362
+ '<label for="imps">Imps this client may reach</label>',
54363
+ '<input id="imps" name="imps" type="text" required autocomplete="off" spellcheck="false" placeholder="dev-*">',
54364
+ "<p>Imp names or name prefixes with a trailing *, split by spaces. Write * for every imp.</p>"
54365
+ ].join(`
54366
+ `);
54494
54367
  }
54495
54368
 
54496
- // packages/daemon/src/identity/oauth/read-body-text.ts
54497
- async function readBodyText(request, max) {
54498
- if (request.body === null) {
54499
- return null;
54500
- }
54501
- const body = request.body;
54502
- const chunks = [];
54503
- let total = 0;
54504
- for await (const chunk of body) {
54505
- total += chunk.byteLength;
54506
- if (total > max) {
54507
- return null;
54369
+ // packages/daemon/src/identity/oauth/build-imp-grant-limits.ts
54370
+ function buildImpGrantLimits(deps) {
54371
+ return {
54372
+ renderConsentFields: () => renderConsentImps(),
54373
+ parseConsentFields: (form) => parseConsentImps(form),
54374
+ parseStored: (json) => ImpLimitsSchema.safeParse(json).data ?? null,
54375
+ check: (grant) => {
54376
+ const approver = grant.approvedBy.startsWith("token:") ? deps.findToken(grant.approvedBy.slice("token:".length)) : null;
54377
+ return Promise.resolve(pickGrantCheck(grant, approver));
54508
54378
  }
54509
- chunks.push(chunk);
54510
- }
54511
- return new TextDecoder().decode(Buffer.concat(chunks));
54512
- }
54513
-
54514
- // packages/daemon/src/identity/oauth/read-error-description.ts
54515
- function readErrorDescription(answer) {
54516
- if (typeof answer !== "object" || answer === null) {
54517
- return null;
54518
- }
54519
- const fields = new Map(Object.entries(answer));
54520
- const description = fields.get("error_description");
54521
- return typeof description === "string" ? description : null;
54379
+ };
54522
54380
  }
54523
54381
 
54524
- // packages/daemon/src/identity/oauth/read-form.ts
54525
- async function readForm(request, maxBytes) {
54526
- const type = request.headers.get("content-type") ?? "";
54527
- if (!type.startsWith("application/x-www-form-urlencoded")) {
54382
+ // packages/daemon/src/identity/oauth/build-oauth-caller.ts
54383
+ function buildOAuthCaller(access, approver) {
54384
+ if (access.scopes.length === 0 || access.limits === null) {
54528
54385
  return null;
54529
54386
  }
54530
- const text = await readBodyText(request, maxBytes);
54531
- return text === null ? null : new URLSearchParams(text);
54532
- }
54533
-
54534
- // packages/daemon/src/identity/oauth/read-url-field.ts
54535
- function readURLField(answer) {
54536
- if (typeof answer !== "object" || answer === null) {
54537
- return null;
54387
+ const shared = {
54388
+ kind: "oauth",
54389
+ name: `${access.clientName}/${access.grantID}`,
54390
+ scope: pickGrantScope(access.scopes),
54391
+ imps: access.limits.imps,
54392
+ imageRefPrefix: null,
54393
+ grantId: access.grantID,
54394
+ principal: `grant:${access.grantID}`
54395
+ };
54396
+ if (approver === null) {
54397
+ return {
54398
+ ...shared,
54399
+ grantable: [],
54400
+ tokenId: null,
54401
+ expiresAt: null,
54402
+ display: `${access.clientName} via passkey`
54403
+ };
54538
54404
  }
54539
- const fields = new Map(Object.entries(answer));
54540
- const next = fields.get("url") ?? fields.get("redirect_uri");
54541
- return typeof next === "string" ? next : null;
54405
+ return {
54406
+ ...shared,
54407
+ grantable: approver.grantable,
54408
+ tokenId: approver.tokenId,
54409
+ expiresAt: approver.expiresAt,
54410
+ display: `${access.clientName} via ${approver.display}`
54411
+ };
54542
54412
  }
54543
54413
 
54544
- // packages/daemon/src/identity/oauth/remove-replayed-grant.ts
54545
- async function removeReplayedGrant(deps, form) {
54546
- const refreshToken = form.get("refresh_token");
54547
- const clientID = form.get("client_id");
54548
- if (form.get("grant_type") !== "refresh_token" || refreshToken === null || clientID === null) {
54549
- return;
54550
- }
54551
- const spent = await deps.db.selectFrom("oauthRefreshToken").select("userId").where("token", "=", deriveTokenHash(refreshToken)).where("clientId", "=", clientID).where((eb) => eb.or([eb("revoked", "is not", null), eb("rotatedAt", "is not", null)])).executeTakeFirst();
54552
- if (spent !== undefined) {
54553
- await deps.removeGrantRows([spent.userId], "a spent refresh token came again");
54414
+ // packages/daemon/src/identity/oauth/record-security-event.ts
54415
+ function recordSecurityEvent(event) {
54416
+ const fields = {
54417
+ kind: event.kind,
54418
+ outcome: event.outcome,
54419
+ reason: event.reason ?? "-",
54420
+ path: event.path,
54421
+ client: event.client?.name ?? "-"
54422
+ };
54423
+ const isRefusal = event.outcome === "rejected" || event.outcome === "failed";
54424
+ const log = getImpdLogger("oauth");
54425
+ if (isRefusal) {
54426
+ log.warning("{kind} {outcome} ({reason}) at {path} for {client}", fields);
54427
+ } else {
54428
+ log.info("{kind} {outcome} at {path} for {client}", fields);
54554
54429
  }
54555
54430
  }
54556
54431
 
54557
- // packages/daemon/src/identity/oauth/remove-token-sessions.ts
54558
- async function removeTokenSessions(db) {
54559
- const held = await db.selectFrom("oauthAccessToken").select("sessionId").where("sessionId", "is not", null).union(db.selectFrom("oauthRefreshToken").select("sessionId").where("sessionId", "is not", null)).execute();
54560
- const sessionIDs = held.flatMap((row) => row.sessionId === null ? [] : [row.sessionId]);
54561
- await db.deleteFrom("session").where((eb) => eb.or([
54562
- eb("expiresAt", "<", new Date().toISOString()),
54563
- ...sessionIDs.length === 0 ? [] : [eb("id", "in", sessionIDs)]
54564
- ])).execute();
54565
- }
54566
-
54567
- // packages/daemon/src/identity/oauth/strip-dpop-proof.ts
54568
- function stripDpopProof(request) {
54569
- const kept = new Headers(request.headers);
54570
- kept.delete("dpop");
54571
- return kept;
54572
- }
54573
-
54574
- // packages/daemon/src/identity/oauth/create-oauth-handlers.ts
54575
- var MINUTE_MS2 = 60000;
54576
- var CONSENT_MS = 10 * MINUTE_MS2;
54577
- var MAX_FORM_BYTES = 16 * 1024;
54578
- var METADATA_HEADERS = { "cache-control": "no-store" };
54579
- var PKCEMissSchema = z97.object({
54580
- error: z97.literal("invalid_request"),
54581
- error_description: z97.literal("code verification failed")
54582
- });
54583
- function createOAuthHandlers(deps) {
54584
- const host = new URL(deps.origin).host;
54585
- const signedIn = new Map;
54586
- const findSignedIn = (sessionID) => {
54587
- const entry = signedIn.get(sessionID);
54588
- if (entry === undefined || entry.expiresAt <= deps.now()) {
54589
- signedIn.delete(sessionID);
54590
- return null;
54591
- }
54592
- return entry;
54593
- };
54594
- const removeExpiredSignedIn = () => {
54595
- const now = deps.now();
54596
- for (const [sessionID, entry] of signedIn) {
54597
- if (entry.expiresAt <= now) {
54598
- signedIn.delete(sessionID);
54599
- }
54432
+ // packages/daemon/src/identity/oauth/create-impd-mcp-auth.ts
54433
+ var TABLES = { passkey: "oauth_passkeys", enrollmentToken: "oauth_enrollment_tokens" };
54434
+ async function createImpdMcpAuth(deps) {
54435
+ const log = getImpdLogger("oauth");
54436
+ const options = {
54437
+ database: deps.db,
54438
+ scopes: ScopeSchema.options,
54439
+ tables: TABLES,
54440
+ clock: { now: deps.now },
54441
+ onGrantRevoked: (grantID) => {
54442
+ deps.revocations.revoke(grantID);
54443
+ log.info("grant {id} revoked", { id: grantID });
54600
54444
  }
54601
54445
  };
54602
- const toPublicRequest = (request, url) => new Request(`${deps.origin}${url.pathname}${url.search}`, request);
54603
- const toPublicFormRequest = (request, url, body) => new Request(`${deps.origin}${url.pathname}${url.search}`, {
54604
- method: request.method,
54605
- headers: stripDpopProof(request),
54606
- body
54607
- });
54608
- const readAdvertised = async (request) => {
54609
- const response = await deps.auth.handler(toPublicRequest(request, new URL(request.url)));
54610
- const metadata = await response.json();
54611
- if (typeof metadata !== "object" || metadata === null) {
54612
- return null;
54613
- }
54614
- const fields = Object.fromEntries(Object.entries(metadata).filter(([key]) => !key.startsWith("introspection_") && !key.startsWith("dpop_")));
54615
- return { status: response.status, fields };
54616
- };
54617
- const runAuthorize = async (url) => {
54618
- const params = new URLSearchParams(url.search);
54619
- const asked = (params.get("scope") ?? "").split(" ").filter((word) => word !== "");
54620
- const askedOrRead = asked.length === 0 ? ["read"] : asked;
54621
- const scopes = expandScopes(askedOrRead);
54622
- params.set("prompt", "login consent");
54623
- params.set("scope", [...scopes, "offline_access"].join(" "));
54624
- if (!params.has("resource")) {
54625
- params.set("resource", deps.resource);
54626
- }
54627
- const response = await deps.auth.handler(new Request(`${deps.origin}/oauth2/authorize?${params.toString()}`, {
54628
- headers: { accept: "text/html" }
54629
- }));
54630
- const location = response.headers.get("location");
54631
- const target = location === null ? null : new URL(location, deps.origin);
54632
- if (target === null || target.origin !== deps.origin || target.pathname !== "/login") {
54633
- return response;
54634
- }
54635
- const clientID = target.searchParams.get("client_id") ?? "";
54636
- const clientName = await readClientName(deps.db, clientID);
54637
- const started = deps.signIns.start({
54638
- key: target.search.slice(1),
54639
- clientID,
54640
- clientName,
54641
- redirectURI: target.searchParams.get("redirect_uri") ?? "",
54642
- requestedScope: pickGrantScope(scopes)
54643
- });
54644
- if (started.kind === "too-many") {
54645
- const headers = buildPageHeaders(null);
54646
- headers.set("retry-after", String(started.retryS));
54647
- return new Response(renderErrorPage("too_many"), { status: 429, headers });
54648
- }
54649
- getImpdLogger("oauth").info("{clientName} asks to sign in; it waits for impz oauth approve", {
54650
- clientName
54651
- });
54652
- return response;
54653
- };
54654
- const runLogin = async (request, url) => {
54655
- const form = request.method === "POST" ? await readForm(request, MAX_FORM_BYTES) : null;
54656
- const oauthQuery = request.method === "GET" ? url.search.slice(1) : form?.get("oauth_query") ?? "";
54657
- const entry = deps.signIns.find(oauthQuery);
54658
- if (entry === null) {
54659
- return buildErrorPage("expired");
54660
- }
54661
- const buildPendingResponse = () => new Response(renderPendingPage({
54662
- oauthQuery,
54663
- clientName: entry.clientName,
54664
- redirectURI: entry.redirectURI,
54665
- requestedScope: entry.requestedScope,
54666
- approvalCode: formatApprovalCode(entry.approvalCode)
54667
- }, host), { status: 200, headers: buildPageHeaders(new URL(entry.redirectURI).origin) });
54668
- const action = form?.get("action");
54669
- if (request.method === "GET" || action === "continue" && entry.approval === null) {
54670
- return buildPendingResponse();
54671
- }
54672
- if (action === "deny") {
54673
- deps.signIns.remove(oauthQuery);
54674
- return buildDenial(oauthQuery);
54675
- }
54676
- const approval = entry.approval;
54677
- if (action !== "continue" || approval === null) {
54678
- return buildErrorPage("bad_request");
54679
- }
54680
- deps.signIns.remove(oauthQuery);
54681
- if (deps.readApprover(approval.tokenID, approval.scope, approval.imps) === null) {
54682
- return buildErrorPage("approver_gone");
54683
- }
54684
- const signedInResponse = await deps.auth.signIn(oauthQuery, approval);
54685
- const resumed = await signedInResponse.json();
54686
- const next = readURLField(resumed);
54687
- const setCookies = signedInResponse.headers.getSetCookie();
54688
- const cookie = setCookies.map((line) => line.split(";")[0]).join("; ");
54689
- const sessionID = await deps.auth.readSessionID(cookie);
54690
- if (!signedInResponse.ok || next === null || sessionID === null) {
54691
- getImpdLogger("oauth").warning("a sign-in for {clientName} could not reach consent", {
54692
- clientName: entry.clientName
54693
- });
54694
- return buildErrorPage("expired");
54695
- }
54696
- removeExpiredSignedIn();
54697
- signedIn.set(sessionID, {
54698
- binding: buildConsentBinding(oauthQuery),
54699
- approval,
54700
- clientName: entry.clientName,
54701
- expiresAt: deps.now() + CONSENT_MS
54702
- });
54703
- const headers = new Headers({ location: new URL(next, deps.origin).href });
54704
- for (const line of setCookies) {
54705
- headers.append("set-cookie", line);
54706
- }
54707
- return new Response(null, { status: 302, headers });
54708
- };
54709
- const runConsent = async (request, url) => {
54710
- const form = request.method === "POST" ? await readForm(request, MAX_FORM_BYTES) : null;
54711
- const oauthQuery = request.method === "GET" ? url.search.slice(1) : form?.get("oauth_query") ?? "";
54712
- const cookie = request.headers.get("cookie") ?? "";
54713
- const prompt = (new URLSearchParams(oauthQuery).get("prompt") ?? "").split(" ");
54714
- const secret = await deps.auth.readSecret();
54715
- const isSigned = await verifyOAuthQueryParams(oauthQuery, secret);
54716
- const sessionID = cookie === "" ? null : await deps.auth.readSessionID(cookie);
54717
- const entry = sessionID === null ? null : findSignedIn(sessionID);
54718
- if (!isSigned || prompt.includes("login") || sessionID === null || entry === null || entry.binding !== buildConsentBinding(oauthQuery)) {
54719
- return buildErrorPage("expired");
54720
- }
54721
- const params = new URLSearchParams(oauthQuery);
54722
- const redirectURI = params.get("redirect_uri") ?? "";
54723
- if (request.method === "GET") {
54724
- return new Response(renderAllowPage({
54725
- oauthQuery,
54726
- clientName: entry.clientName,
54727
- redirectURI,
54728
- scope: entry.approval.scope,
54729
- imps: entry.approval.imps
54730
- }), { status: 200, headers: buildPageHeaders(new URL(redirectURI).origin) });
54731
- }
54732
- const action = form?.get("action");
54733
- if (action !== "allow" && action !== "deny") {
54734
- return buildErrorPage("bad_request");
54735
- }
54736
- signedIn.delete(sessionID);
54737
- const accept = action === "allow";
54738
- const scope = `${formatScopeList(entry.approval.scope)} offline_access`;
54739
- const choice = JSON.stringify({
54740
- accept,
54741
- ...accept && { scope },
54742
- oauth_query: oauthQuery
54743
- });
54744
- const consented = await deps.auth.handler(new Request(`${deps.origin}/oauth2/consent`, {
54745
- method: "POST",
54746
- headers: {
54747
- "content-type": "application/json",
54748
- accept: "application/json",
54749
- origin: deps.origin,
54750
- cookie
54751
- },
54752
- body: choice
54753
- }));
54754
- const answer = await consented.json();
54755
- const next = readURLField(answer);
54756
- const isIssued = consented.ok && next !== null && new URL(next).searchParams.has("code");
54757
- await (isIssued ? deps.db.updateTable("session").set({ expiresAt: new Date(Date.now() + CONSENT_MS).toISOString() }).where("id", "=", sessionID).execute() : deps.db.deleteFrom("session").where("id", "=", sessionID).execute());
54758
- if (!consented.ok || next === null) {
54759
- return buildErrorPage("expired");
54760
- }
54761
- if (isIssued) {
54762
- getImpdLogger("oauth").info("{clientName} signed in, approved by token {tokenName}", {
54763
- clientName: entry.clientName,
54764
- tokenName: entry.approval.tokenName
54765
- });
54766
- }
54767
- const sessionCookie = await deps.auth.readSessionCookie();
54768
- const secure = sessionCookie.secure ? "; Secure" : "";
54769
- return new Response(null, {
54770
- status: 302,
54771
- headers: {
54772
- location: next,
54773
- "cache-control": "no-store",
54774
- "referrer-policy": "no-referrer",
54775
- "set-cookie": `${sessionCookie.name}=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax${secure}`
54776
- }
54777
- });
54778
- };
54779
- const runTokenRequest = async (request, url) => {
54780
- const body = await readBodyText(request, MAX_FORM_BYTES);
54781
- if (body === null) {
54782
- return buildBadTokenRequest();
54783
- }
54784
- const response = await deps.auth.handler(toPublicFormRequest(request, url, body));
54785
- if (response.status === 400) {
54786
- await removeReplayedGrant(deps, new URLSearchParams(body));
54787
- }
54788
- if (response.ok) {
54789
- await removeTokenSessions(deps.db);
54790
- }
54791
- if (response.status === 401 && new URLSearchParams(body).get("grant_type") === "authorization_code") {
54792
- const refusal = await response.clone().json().catch(() => null);
54793
- if (PKCEMissSchema.safeParse(refusal).success) {
54794
- return buildPKCERefusal();
54795
- }
54796
- }
54797
- return response;
54798
- };
54799
- const runRevoke = async (request, url) => {
54800
- const body = await readBodyText(request, MAX_FORM_BYTES);
54801
- if (body === null) {
54802
- return buildBadTokenRequest();
54803
- }
54804
- const form = new URLSearchParams(body);
54805
- const hash = deriveTokenHash(form.get("token") ?? "");
54806
- const owner = await deps.db.selectFrom("oauthAccessToken").select(["userId", "clientId"]).where("token", "=", hash).union(deps.db.selectFrom("oauthRefreshToken").select(["userId", "clientId"]).where("token", "=", hash)).executeTakeFirst();
54807
- const response = await deps.auth.handler(toPublicFormRequest(request, url, body));
54808
- if (owner === undefined && response.status === 400) {
54809
- const refusal = await response.clone().json().catch(() => null);
54810
- if (readErrorDescription(refusal) === "token not found") {
54811
- return new Response(null, { status: 200, headers: { "cache-control": "no-store" } });
54812
- }
54813
- }
54814
- if (response.ok && owner !== undefined && owner.userId !== null && owner.clientId === form.get("client_id")) {
54815
- await deps.removeGrantRows([owner.userId], "its client revoked it");
54816
- }
54817
- return response;
54818
- };
54819
- const buildDenial = (oauthQuery) => {
54820
- const params = new URLSearchParams(oauthQuery);
54821
- const target = new URL(params.get("redirect_uri") ?? "");
54822
- const state = params.get("state");
54823
- target.searchParams.set("error", "access_denied");
54824
- target.searchParams.set("error_description", "the sign-in was denied");
54825
- if (state !== null) {
54826
- target.searchParams.set("state", state);
54827
- }
54828
- target.searchParams.set("iss", deps.origin);
54829
- return new Response(null, {
54830
- status: 302,
54831
- headers: {
54832
- location: target.href,
54833
- "cache-control": "no-store",
54834
- "referrer-policy": "no-referrer"
54835
- }
54836
- });
54837
- };
54838
- const runPage = (request, run) => {
54839
- if (request.method === "POST" && !isAllowedOrigin(request, { kind: "same-origin-form", origin: deps.origin })) {
54840
- return Promise.resolve(buildErrorPage("bad_request"));
54841
- }
54842
- return run(request, new URL(request.url));
54843
- };
54844
- return {
54845
- readServerMetadata: async (request) => {
54846
- const advertised = await readAdvertised(request);
54847
- if (advertised === null) {
54848
- return new Response(null, { status: 503 });
54849
- }
54850
- return Response.json({
54851
- ...advertised.fields,
54852
- token_endpoint_auth_methods_supported: ["none"],
54853
- revocation_endpoint_auth_methods_supported: ["none"]
54854
- }, { headers: METADATA_HEADERS });
54855
- },
54856
- readResourceMetadata: async (request) => {
54857
- const advertised = await readAdvertised(request);
54858
- if (advertised === null) {
54859
- return new Response(null, { status: 503 });
54860
- }
54861
- return Response.json({ ...advertised.fields, resource_name: "imp" }, { status: advertised.status, headers: METADATA_HEADERS });
54862
- },
54863
- answerError: (request) => {
54864
- const isUnknownClient = new URL(request.url).searchParams.get("error") === "invalid_client";
54865
- const page = isUnknownClient ? "unknown_client" : "bad_request";
54866
- return buildErrorPage(page);
54867
- },
54868
- runAuthorize: (request) => runAuthorize(new URL(request.url)),
54869
- runTokenRequest: (request) => runTokenRequest(request, new URL(request.url)),
54870
- runRevoke: (request) => runRevoke(request, new URL(request.url)),
54871
- runLogin: (request) => runPage(request, runLogin),
54872
- runConsent: (request) => runPage(request, runConsent)
54873
- };
54874
- }
54875
- async function readClientName(db, clientID) {
54876
- const row = await db.selectFrom("oauthClient").select("name").where("clientId", "=", clientID).executeTakeFirst();
54877
- return row?.name ?? clientID;
54878
- }
54879
- function buildErrorPage(error) {
54880
- return new Response(renderErrorPage(error), { status: 400, headers: buildPageHeaders(null) });
54881
- }
54882
-
54883
- // packages/daemon/src/identity/oauth/create-mcp-auth.ts
54884
- var MINUTE_MS3 = 60000;
54885
- var ACCESS_TOKEN_S = 15 * 60;
54886
- var REFRESH_TOKEN_S = 30 * 24 * 60 * 60;
54887
- var CODE_S = 10 * 60;
54888
- var TOUCH_MS = MINUTE_MS3;
54889
- var UNUSED_SIGN_IN_MS = 60 * MINUTE_MS3;
54890
- async function createMcpAuth(deps) {
54891
- process.env["BETTER_AUTH_TELEMETRY"] = "0";
54892
- process.env["BETTER_AUTH_TELEMETRY_ENDPOINT"] = "";
54893
- const origin = deps.config?.origin ?? "http://127.0.0.1";
54894
- const resource = `${origin}/mcp`;
54895
- const db = deps.db;
54896
- const providerOptions = {
54897
- loginPage: "/login",
54898
- consentPage: "/consent",
54899
- scopes: CLIENT_SCOPES,
54900
- disableJwtPlugin: true,
54901
- allowDynamicClientRegistration: false,
54902
- grantTypes: ["authorization_code", "refresh_token"],
54903
- enforcePerClientResources: false,
54904
- accessTokenExpiresIn: ACCESS_TOKEN_S,
54905
- refreshTokenExpiresIn: REFRESH_TOKEN_S,
54906
- codeExpiresIn: CODE_S,
54907
- refreshTokenReuseInterval: 0,
54908
- storeTokens: { hash: (token) => Promise.resolve(deriveTokenHash(token)) }
54909
- };
54910
- const provider = deps.config === null ? oauthProvider(providerOptions) : mcp({ ...providerOptions, resource });
54911
- const auth = betterAuth({
54912
- baseURL: origin,
54913
- basePath: "/",
54914
- secret: mintSecret(),
54915
- database: { db, type: "sqlite" },
54916
- telemetry: { enabled: false },
54917
- logger: { disabled: true },
54918
- rateLimit: { enabled: false },
54919
- advanced: { database: { validateSchema: false } },
54920
- trustedOrigins: [origin],
54921
- session: { expiresIn: 3 * CODE_S, disableSessionRefresh: true },
54922
- user: {
54923
- additionalFields: {
54924
- tokenId: { type: "string", required: true, input: false },
54925
- imps: { type: "string", required: false, input: false },
54926
- lastUsedAt: { type: "date", required: false, input: false }
54927
- }
54928
- },
54929
- plugins: [provider, createApproverPlugin()]
54930
- });
54931
- const signIns = createSignIns({ now: deps.now });
54932
- const removeGrantRows = async (ids, why) => {
54933
- if (ids.length === 0) {
54934
- return;
54935
- }
54936
- await db.deleteFrom("user").where("id", "in", ids).execute();
54937
- for (const id of ids) {
54938
- deps.revocations.revoke(id);
54939
- getImpdLogger("oauth").info("grant {id} revoked: {why}", { id, why });
54940
- }
54941
- };
54942
- const readApprover = (tokenID, scope, imps) => {
54943
- const token = deps.tokens.findById(tokenID);
54944
- if (token === null || !hasScope(token.scope, scope)) {
54945
- return null;
54946
- }
54947
- return isPatternsWithin(imps, token.imps) ? token : null;
54948
- };
54949
- const server = {
54950
- handler: (request) => auth.handler(request),
54951
- signIn: (oauthQuery, approval) => {
54952
- const headers = new Headers({
54953
- accept: "application/json",
54954
- "content-type": "application/json"
54955
- });
54956
- return auth.api.signInApproval({
54957
- body: {
54958
- oauth_query: oauthQuery,
54959
- tokenID: approval.tokenID,
54960
- tokenName: approval.tokenName,
54961
- imps: approval.imps === null ? null : [...approval.imps]
54962
- },
54963
- headers,
54964
- request: new Request(`${origin}/imp/sign-in-approval`, { method: "POST", headers }),
54965
- asResponse: true
54966
- });
54967
- },
54968
- readSessionID: async (cookie) => {
54969
- const found = await auth.api.getSession({ headers: new Headers({ cookie }) });
54970
- return found?.session.id ?? null;
54971
- },
54972
- readSecret: async () => {
54973
- const context = await auth.$context;
54974
- return context.secret;
54975
- },
54976
- readSessionCookie: async () => {
54977
- const context = await auth.$context;
54978
- const cookie = context.authCookies.sessionToken;
54979
- return { name: cookie.name, secure: cookie.attributes.secure === true };
54980
- }
54981
- };
54982
- const handlers = deps.config === null ? null : createOAuthHandlers({
54983
- auth: server,
54984
- db,
54985
- signIns,
54986
- origin,
54987
- resource,
54988
- now: deps.now,
54989
- readApprover,
54990
- removeGrantRows
54991
- });
54992
- const requireClient = async (name) => {
54993
- const client = await db.selectFrom("oauthClient").select(["clientId", "name", "redirectUris", "createdAt"]).where("name", "=", name).executeTakeFirst();
54994
- if (client === undefined) {
54995
- throw buildNotFoundError("oauth-client", name);
54996
- }
54997
- return client;
54998
- };
54999
- const probeClientNamed = async (name) => {
55000
- const client = await db.selectFrom("oauthClient").select("clientId").where("name", "=", name).executeTakeFirst();
55001
- return client !== undefined;
55002
- };
55003
- const createFixedClient = async (name, redirectUris) => {
55004
- try {
55005
- return await auth.api.createFixedClient({ body: { name, redirectURIs: [...redirectUris] } });
55006
- } catch (error) {
55007
- const isTaken = await probeClientNamed(name);
55008
- if (isTaken) {
55009
- throw buildConflictError("oauth-client", name);
55010
- }
55011
- throw error;
55012
- }
55013
- };
55014
- await auth.$context;
54446
+ const config = deps.config;
54447
+ const opened = config === null ? { server: null, admin: await openMCPAuthAdmin(options) } : await openImpdServer(options, config, deps.tokens);
54448
+ const server = opened.server;
54449
+ const admin = opened.admin;
55015
54450
  return {
55016
- resource,
55017
- issuer: origin,
55018
- listClients: async () => {
55019
- const rows = await db.selectFrom("oauthClient").select(["clientId", "name", "redirectUris", "createdAt"]).orderBy("name").execute();
55020
- return rows.map((row) => toClient(row));
55021
- },
55022
- addClient: async (name, redirectUris) => {
55023
- const isTaken = await probeClientNamed(name);
55024
- if (isTaken) {
55025
- throw buildConflictError("oauth-client", name);
55026
- }
55027
- const made = await createFixedClient(name, redirectUris);
55028
- return {
55029
- name,
55030
- clientId: made.clientID,
55031
- redirectUris,
55032
- createdAt: new Date(made.createdAt)
55033
- };
55034
- },
55035
- updateClient: async (name, redirectUris) => {
55036
- const client = await requireClient(name);
55037
- await db.updateTable("oauthClient").set({ redirectUris: JSON.stringify(redirectUris), updatedAt: new Date().toISOString() }).where("clientId", "=", client.clientId).execute();
55038
- return toClient({ ...client, redirectUris: JSON.stringify(redirectUris) });
55039
- },
55040
- removeClient: async (name) => {
55041
- const client = await requireClient(name);
55042
- signIns.removeClient(client.clientId);
55043
- const grants = await db.selectFrom("oauthAccessToken").select("userId").where("clientId", "=", client.clientId).union(db.selectFrom("oauthRefreshToken").select("userId").where("clientId", "=", client.clientId)).execute();
55044
- await removeGrantRows(grants.flatMap((row) => row.userId === null ? [] : [row.userId]), `its client ${name} was removed`);
55045
- await db.deleteFrom("oauthClient").where("clientId", "=", client.clientId).execute();
55046
- },
55047
- listGrants: async () => {
55048
- const rows = await db.selectFrom("oauthRefreshToken").innerJoin("user", "user.id", "oauthRefreshToken.userId").leftJoin("oauthClient", "oauthClient.clientId", "oauthRefreshToken.clientId").select([
55049
- "user.id",
55050
- "user.name as tokenName",
55051
- "user.tokenId",
55052
- "user.imps",
55053
- "user.createdAt",
55054
- "user.lastUsedAt",
55055
- "oauthRefreshToken.scopes",
55056
- "oauthRefreshToken.clientId",
55057
- "oauthClient.name as clientName"
55058
- ]).where("oauthRefreshToken.revoked", "is", null).where("oauthRefreshToken.expiresAt", ">", new Date().toISOString()).orderBy("user.createdAt").execute();
55059
- return rows.map((row) => ({
55060
- id: row.id,
55061
- client: row.clientName ?? row.clientId,
55062
- token: deps.tokens.findById(row.tokenId)?.name ?? row.tokenName,
55063
- scope: pickGrantScope(parseStrings(row.scopes)),
55064
- imps: parseImps(row.imps),
55065
- createdAt: new Date(row.createdAt),
55066
- lastUsedAt: row.lastUsedAt === null ? null : new Date(row.lastUsedAt)
55067
- }));
55068
- },
55069
- removeGrant: async (id) => {
55070
- const removed = await db.deleteFrom("user").where("id", "=", id).executeTakeFirst();
55071
- if (removed.numDeletedRows === 0n) {
55072
- throw buildNotFoundError("oauth-grant", id);
55073
- }
55074
- deps.revocations.revoke(id);
55075
- },
55076
- readApproval: (code, approver) => signIns.readApproval(code, approver),
55077
- approve: (code, approver, scope, imps) => {
55078
- const approved = signIns.approve(code, approver, scope, imps);
55079
- getImpdLogger("oauth").info("a sign-in for {clientName} approved by token {name}", {
55080
- clientName: approved.clientName,
55081
- name: approver.name
55082
- });
55083
- },
55084
- handlers,
55085
- resolveAccess: async (bearer) => {
55086
- let payload;
55087
- try {
55088
- payload = await auth.api.verifyMCPAccessToken({ body: { token: bearer } });
55089
- } catch (error) {
55090
- if (isAPIError(error)) {
55091
- return null;
54451
+ admin,
54452
+ server,
54453
+ removeTokenGrants: async (tokenID) => {
54454
+ const grants = await admin.grants.list();
54455
+ for (const grant of grants) {
54456
+ if (grant.approvedBy === `token:${tokenID}`) {
54457
+ await admin.grants.revoke(grant.grantID);
55092
54458
  }
55093
- throw error;
55094
54459
  }
55095
- const access = readAccessPayload(payload);
55096
- if (access === null || !access.audiences.includes(resource)) {
55097
- return null;
55098
- }
55099
- const grant = await db.selectFrom("user").select(["id", "tokenId", "imps", "lastUsedAt"]).where("id", "=", access.userID).executeTakeFirst();
55100
- if (grant === undefined || deps.revocations.isRevoked(grant.id)) {
54460
+ },
54461
+ readCaller: async (access) => {
54462
+ if (access.kind === "service") {
55101
54463
  return null;
55102
54464
  }
55103
- const scope = pickGrantScope(access.scopes);
55104
- const imps = parseImps(grant.imps);
55105
- const approver = readApprover(grant.tokenId, scope, imps);
55106
- if (approver === null) {
55107
- await removeGrantRows([grant.id], "the token that approved it no longer covers it");
54465
+ const grant = await deps.db.selectFrom("user").select("approvedBy").where("id", "=", access.grantID).executeTakeFirst();
54466
+ const approvedBy = grant?.approvedBy ?? null;
54467
+ if (approvedBy === null) {
55108
54468
  return null;
55109
54469
  }
55110
- const at = deps.now();
55111
- if (grant.lastUsedAt === null || at - Date.parse(grant.lastUsedAt) >= TOUCH_MS) {
55112
- await db.updateTable("user").set({ lastUsedAt: new Date(at).toISOString() }).where("id", "=", grant.id).execute();
54470
+ if (!approvedBy.startsWith("token:")) {
54471
+ return buildOAuthCaller(access, null);
55113
54472
  }
55114
- const client = await db.selectFrom("oauthClient").select("name").where("clientId", "=", access.clientID).executeTakeFirst();
55115
- const clientName = client?.name ?? access.clientID;
55116
- return {
55117
- kind: "oauth",
55118
- name: `${clientName}/${grant.id}`,
55119
- scope: readLowerScope(scope, approver.scope),
55120
- imps,
55121
- grantable: approver.grantable,
55122
- imageRefPrefix: null,
55123
- tokenId: approver.tokenId,
55124
- grantId: grant.id,
55125
- expiresAt: approver.expiresAt,
55126
- principal: `grant:${grant.id}`,
55127
- display: `${clientName} via ${approver.display}`
55128
- };
55129
- },
55130
- removeExpired: async () => {
55131
- const at = new Date().toISOString();
55132
- const stale = await db.selectFrom("user").select("id").where("createdAt", "<", new Date(Date.now() - UNUSED_SIGN_IN_MS).toISOString()).where((eb) => eb.not(eb.exists(eb.selectFrom("oauthRefreshToken").select("oauthRefreshToken.id").whereRef("oauthRefreshToken.userId", "=", "user.id").where("oauthRefreshToken.revoked", "is", null).where("oauthRefreshToken.expiresAt", ">", at)))).execute();
55133
- await removeGrantRows(stale.map((row) => row.id), "its refresh token expired");
55134
- await db.deleteFrom("oauthRefreshToken").where("expiresAt", "<", at).execute();
55135
- await db.deleteFrom("oauthAccessToken").where("expiresAt", "<", at).execute();
55136
- await db.deleteFrom("session").where("expiresAt", "<", at).execute();
55137
- await db.deleteFrom("verification").where("expiresAt", "<", at).execute();
54473
+ const approver = deps.tokens.findById(approvedBy.slice("token:".length));
54474
+ return approver === null ? null : buildOAuthCaller(access, approver);
55138
54475
  }
55139
54476
  };
55140
54477
  }
55141
- function toClient(row) {
55142
- return {
55143
- name: row.name ?? row.clientId,
55144
- clientId: row.clientId,
55145
- redirectUris: parseStrings(row.redirectUris),
55146
- createdAt: new Date(row.createdAt ?? 0)
55147
- };
55148
- }
55149
- function parseStrings(text) {
55150
- const parsed = JSON.parse(text);
55151
- return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
55152
- }
55153
- function parseImps(text) {
55154
- if (text === null) {
55155
- return null;
55156
- }
55157
- const parsed = JSON.parse(text);
55158
- return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
55159
- }
55160
- function readAccessPayload(payload) {
55161
- if (typeof payload !== "object" || payload === null) {
55162
- return null;
55163
- }
55164
- const fields = new Map(Object.entries(payload));
55165
- if (fields.get("cnf") !== undefined && fields.get("cnf") !== null) {
55166
- return null;
55167
- }
55168
- const userID = fields.get("sub");
55169
- const clientID = fields.get("client_id");
55170
- const scope = fields.get("scope");
55171
- const audience = fields.get("aud");
55172
- if (typeof userID !== "string" || typeof clientID !== "string" || clientID === "") {
55173
- return null;
55174
- }
55175
- return {
55176
- userID,
55177
- clientID,
55178
- audiences: [audience].flat().filter((item) => typeof item === "string"),
55179
- scopes: typeof scope === "string" ? scope.split(" ") : []
55180
- };
54478
+ async function openImpdServer(options, config, tokens) {
54479
+ const server = await openMCPAuth({
54480
+ ...options,
54481
+ origin: config.origin,
54482
+ productName: "imp",
54483
+ paths: DEFAULT_PATHS,
54484
+ grantLimits: buildImpGrantLimits({ findToken: tokens.findById }),
54485
+ security: { record: recordSecurityEvent }
54486
+ });
54487
+ return { server, admin: server };
55181
54488
  }
55182
54489
 
55183
54490
  // packages/daemon/src/load-impd-access.ts
55184
54491
  async function loadImpdAccess(config, deps, isFileKey) {
55185
54492
  const now = deps.now ?? Date.now;
55186
54493
  const revocations = createRevocations();
54494
+ const grants = { remove: () => Promise.resolve() };
55187
54495
  const tokens = await loadTokenStore({
55188
54496
  db: deps.db,
55189
54497
  rootToken: deps.rootToken,
55190
54498
  now,
55191
54499
  onRemove: revocations.revoke,
54500
+ removeGrants: (tokenID) => grants.remove(tokenID),
55192
54501
  isFileKey
55193
54502
  });
55194
- const oauth = await createMcpAuth({
54503
+ const oauth = await createImpdMcpAuth({
55195
54504
  db: deps.db,
55196
54505
  tokens,
55197
54506
  revocations,
55198
54507
  config: config.publicMcp,
55199
54508
  now
55200
54509
  });
54510
+ grants.remove = oauth.removeTokenGrants;
55201
54511
  return { revocations, tokens, oauth };
55202
54512
  }
55203
54513
 
@@ -55252,7 +54562,7 @@ function createPublicRecordsLink() {
55252
54562
  }
55253
54563
 
55254
54564
  // packages/daemon/src/network/tailnet-names/host-id.ts
55255
- import { randomBytes as randomBytes12 } from "crypto";
54565
+ import { randomBytes as randomBytes11 } from "crypto";
55256
54566
  import { existsSync as existsSync23, mkdirSync as mkdirSync24, readFileSync as readFileSync29, writeFileSync as writeFileSync11 } from "fs";
55257
54567
  import { join as join37 } from "path";
55258
54568
  function loadOrCreateHostId(dataDir) {
@@ -55262,7 +54572,7 @@ function loadOrCreateHostId(dataDir) {
55262
54572
  return readFileSync29(path, "utf8").trim();
55263
54573
  }
55264
54574
  mkdirSync24(directory, { recursive: true });
55265
- const id = randomBytes12(16).toString("hex");
54575
+ const id = randomBytes11(16).toString("hex");
55266
54576
  writeFileSync11(path, `${id}
55267
54577
  `, { mode: 384, flag: "wx" });
55268
54578
  return id;
@@ -55270,8 +54580,8 @@ function loadOrCreateHostId(dataDir) {
55270
54580
 
55271
54581
  // packages/daemon/src/network/tailnet-names/oauth-credential.ts
55272
54582
  import { readFileSync as readFileSync30, statSync as statSync14 } from "fs";
55273
- import * as z98 from "zod";
55274
- var CredentialSchema = z98.object({ clientId: z98.string().min(1), clientSecret: z98.string().min(1) });
54583
+ import * as z97 from "zod";
54584
+ var CredentialSchema = z97.object({ clientId: z97.string().min(1), clientSecret: z97.string().min(1) });
55275
54585
  function readOAuthCredential(path) {
55276
54586
  const mode = statSync14(path).mode & 511;
55277
54587
  if ((mode & 63) !== 0) {
@@ -55292,17 +54602,17 @@ function readJson(path) {
55292
54602
  }
55293
54603
 
55294
54604
  // packages/daemon/src/host-net/net/tailscale-serve.ts
55295
- import * as z99 from "zod";
55296
- var HandlerSchema = z99.object({ Proxy: z99.string().optional() });
55297
- var WebSchema = z99.object({
55298
- Handlers: z99.record(z99.string(), HandlerSchema).nullable().optional()
54605
+ import * as z98 from "zod";
54606
+ var HandlerSchema = z98.object({ Proxy: z98.string().optional() });
54607
+ var WebSchema = z98.object({
54608
+ Handlers: z98.record(z98.string(), HandlerSchema).nullable().optional()
55299
54609
  });
55300
- var ServiceConfigSchema = z99.object({
55301
- Web: z99.record(z99.string(), WebSchema).nullable().optional()
54610
+ var ServiceConfigSchema = z98.object({
54611
+ Web: z98.record(z98.string(), WebSchema).nullable().optional()
55302
54612
  });
55303
- var ServeStatusSchema = z99.object({
55304
- TCP: z99.record(z99.string(), z99.unknown()).optional(),
55305
- Services: z99.record(z99.string(), ServiceConfigSchema).nullable().optional()
54613
+ var ServeStatusSchema = z98.object({
54614
+ TCP: z98.record(z98.string(), z98.unknown()).optional(),
54615
+ Services: z98.record(z98.string(), ServiceConfigSchema).nullable().optional()
55306
54616
  });
55307
54617
  function parseServeStatus(json) {
55308
54618
  try {
@@ -55353,17 +54663,17 @@ function createServiceServe(run = runChecked) {
55353
54663
  }
55354
54664
 
55355
54665
  // packages/daemon/src/network/tailnet-names/services-api.ts
55356
- import * as z100 from "zod";
54666
+ import * as z99 from "zod";
55357
54667
  var TAILSCALE_API = "https://api.tailscale.com/api/v2";
55358
54668
  var TOKEN_MARGIN_MS = 60000;
55359
- var ServiceSchema2 = z100.object({
55360
- name: z100.string(),
55361
- comment: z100.string().optional(),
55362
- ports: z100.array(z100.string()).readonly().optional(),
55363
- tags: z100.array(z100.string()).readonly().nullable().optional()
54669
+ var ServiceSchema2 = z99.object({
54670
+ name: z99.string(),
54671
+ comment: z99.string().optional(),
54672
+ ports: z99.array(z99.string()).readonly().optional(),
54673
+ tags: z99.array(z99.string()).readonly().nullable().optional()
55364
54674
  }).readonly();
55365
- var ServiceListSchema2 = z100.object({ vipServices: z100.array(ServiceSchema2).nullable().optional() });
55366
- var TokenSchema3 = z100.object({ access_token: z100.string(), expires_in: z100.number().positive() });
54675
+ var ServiceListSchema2 = z99.object({ vipServices: z99.array(ServiceSchema2).nullable().optional() });
54676
+ var TokenSchema3 = z99.object({ access_token: z99.string(), expires_in: z99.number().positive() });
55367
54677
 
55368
54678
  class TailscaleApiError extends Error {
55369
54679
  status;
@@ -55452,7 +54762,7 @@ function createServicesApi(options) {
55452
54762
  }
55453
54763
  };
55454
54764
  }
55455
- var ErrorSchema = z100.object({ message: z100.string() });
54765
+ var ErrorSchema = z99.object({ message: z99.string() });
55456
54766
  function readErrorText(text) {
55457
54767
  try {
55458
54768
  return ErrorSchema.parse(JSON.parse(text)).message;
@@ -55638,9 +54948,9 @@ function makePresenceCheck(imps, db) {
55638
54948
  }
55639
54949
 
55640
54950
  // packages/daemon/src/platform/db/is-imp-set-change.ts
55641
- import { P as P8, match as match25 } from "ts-pattern";
54951
+ import { P as P7, match as match25 } from "ts-pattern";
55642
54952
  function isImpSetChange(event) {
55643
- return match25(event).with({ ev: P8.union("ImpAdded", "ImpRemoved") }, () => true).with({ ev: "ImpChanged" }, (changed) => changed.reason === "stopped").with({ ev: P8.union("CheckpointAdded", "CheckpointRemoved", "GovernorDecision", "AgentExec") }, () => false).exhaustive();
54953
+ return match25(event).with({ ev: P7.union("ImpAdded", "ImpRemoved") }, () => true).with({ ev: "ImpChanged" }, (changed) => changed.reason === "stopped").with({ ev: P7.union("CheckpointAdded", "CheckpointRemoved", "GovernorDecision", "AgentExec") }, () => false).exhaustive();
55644
54954
  }
55645
54955
 
55646
54956
  // packages/daemon/src/platform/telemetry/start-otlp-export.ts
@@ -55915,14 +55225,14 @@ function formatAcmeError(error) {
55915
55225
  // packages/daemon/src/network/https/acme/cert-store.ts
55916
55226
  import { existsSync as existsSync24, mkdirSync as mkdirSync25, readFileSync as readFileSync31, rmSync as rmSync30 } from "fs";
55917
55227
  import { join as join38 } from "path";
55918
- import * as z101 from "zod";
55919
- var AttemptStateSchema = z101.object({
55920
- failures: z101.int().nonnegative(),
55921
- lastAttemptAt: z101.number().nullable(),
55922
- lastError: z101.string().nullable()
55228
+ import * as z100 from "zod";
55229
+ var AttemptStateSchema = z100.object({
55230
+ failures: z100.int().nonnegative(),
55231
+ lastAttemptAt: z100.number().nullable(),
55232
+ lastError: z100.string().nullable()
55923
55233
  });
55924
- var AccountSchema = z101.object({ directoryUrl: z101.string(), url: z101.string(), keyPem: z101.string() });
55925
- var LegacyAccountSchema = z101.object({ directoryUrl: z101.string(), url: z101.string() });
55234
+ var AccountSchema = z100.object({ directoryUrl: z100.string(), url: z100.string(), keyPem: z100.string() });
55235
+ var LegacyAccountSchema = z100.object({ directoryUrl: z100.string(), url: z100.string() });
55926
55236
  var NO_ATTEMPTS = { failures: 0, lastAttemptAt: null, lastError: null };
55927
55237
  function createCertStore(dataDir) {
55928
55238
  const directory = join38(dataDir, "tls");
@@ -56060,7 +55370,7 @@ function createChalltestsrvProvider(apiUrl) {
56060
55370
  }
56061
55371
 
56062
55372
  // packages/daemon/src/network/https/dns/cloudflare-provider.ts
56063
- import * as z102 from "zod";
55373
+ import * as z101 from "zod";
56064
55374
 
56065
55375
  // packages/daemon/src/network/https/dns/wait-for-txt.ts
56066
55376
  import { Resolver as Resolver2 } from "dns/promises";
@@ -56122,30 +55432,30 @@ var CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
56122
55432
  var TXT_TTL_S = 60;
56123
55433
  var A_TTL_S = 300;
56124
55434
  var PAGE_SIZE = 500;
56125
- var ApiErrorSchema = z102.object({ code: z102.number().optional(), message: z102.string() });
56126
- var EnvelopeSchema = z102.object({
56127
- success: z102.boolean(),
56128
- errors: z102.array(ApiErrorSchema).default([]),
56129
- result: z102.unknown().optional(),
56130
- result_info: z102.object({ page: z102.number(), total_pages: z102.number() }).optional()
55435
+ var ApiErrorSchema = z101.object({ code: z101.number().optional(), message: z101.string() });
55436
+ var EnvelopeSchema = z101.object({
55437
+ success: z101.boolean(),
55438
+ errors: z101.array(ApiErrorSchema).default([]),
55439
+ result: z101.unknown().optional(),
55440
+ result_info: z101.object({ page: z101.number(), total_pages: z101.number() }).optional()
56131
55441
  });
56132
- var ZoneSchema = z102.object({
56133
- id: z102.string(),
56134
- name: z102.string(),
56135
- name_servers: z102.array(z102.string())
55442
+ var ZoneSchema = z101.object({
55443
+ id: z101.string(),
55444
+ name: z101.string(),
55445
+ name_servers: z101.array(z101.string())
56136
55446
  });
56137
- var RecordSchema = z102.object({
56138
- id: z102.string(),
56139
- name: z102.string().optional(),
56140
- type: z102.string().optional(),
56141
- content: z102.string(),
56142
- proxied: z102.boolean().optional(),
56143
- comment: z102.string().nullable().optional()
55447
+ var RecordSchema = z101.object({
55448
+ id: z101.string(),
55449
+ name: z101.string().optional(),
55450
+ type: z101.string().optional(),
55451
+ content: z101.string(),
55452
+ proxied: z101.boolean().optional(),
55453
+ comment: z101.string().nullable().optional()
56144
55454
  });
56145
55455
  var MANAGED_COMMENT = "managed by impd";
56146
55456
  var ADDRESS_TYPES = new Set(["A", "AAAA", "CNAME"]);
56147
- var ZoneListSchema = z102.array(ZoneSchema);
56148
- var RecordListSchema = z102.array(RecordSchema);
55457
+ var ZoneListSchema = z101.array(ZoneSchema);
55458
+ var RecordListSchema = z101.array(RecordSchema);
56149
55459
  function createCloudflareProvider(options) {
56150
55460
  const base = options.apiUrl ?? CLOUDFLARE_API;
56151
55461
  const send = options.fetch ?? fetch;
@@ -56433,6 +55743,20 @@ function buildPublicOwner(domain) {
56433
55743
  return `impd public imps of sha256:${hash.slice(0, 32)}`;
56434
55744
  }
56435
55745
 
55746
+ // packages/daemon/src/platform/http/render-html.ts
55747
+ import { P as P8, match as match26 } from "ts-pattern";
55748
+ var MARKUP = Symbol("markup");
55749
+ function renderHTML(strings, ...parts) {
55750
+ const html = parts.reduce((text, part, index) => `${text}${toHTML(part)}${strings[index + 1] ?? ""}`, strings[0] ?? "");
55751
+ return { [MARKUP]: true, html };
55752
+ }
55753
+ function toHTML(part) {
55754
+ return match26(part).with(P8.string, (text) => escapeHTML(text)).with(P8.array(), (list) => list.map((each) => each.html).join("")).with({ html: P8.string }, (markup) => markup.html).exhaustive();
55755
+ }
55756
+ function escapeHTML(text) {
55757
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
55758
+ }
55759
+
56436
55760
  // packages/daemon/src/network/proxy/error-pages.ts
56437
55761
  var STATUS_TITLES = {
56438
55762
  401: "Sign in to this imp",
@@ -56441,7 +55765,7 @@ var STATUS_TITLES = {
56441
55765
  502: "Nothing answers in the imp",
56442
55766
  503: "The imp could not wake"
56443
55767
  };
56444
- function buildErrorPage2(status, detail) {
55768
+ function buildErrorPage(status, detail) {
56445
55769
  const title = STATUS_TITLES[status] ?? "Proxy error";
56446
55770
  const page = renderHTML`<!doctype html>
56447
55771
  <title>${title}</title>
@@ -56537,7 +55861,7 @@ function createHttpsListeners(options) {
56537
55861
  }));
56538
55862
  const handleRedirectRequest = async (request) => {
56539
55863
  const isRedirected = await checkRedirect(request);
56540
- return isRedirected ? buildRedirect(request, domain, readRedirectPort(), hint) : buildErrorPage2(404, hint);
55864
+ return isRedirected ? buildRedirect(request, domain, readRedirectPort(), hint) : buildErrorPage(404, hint);
56541
55865
  };
56542
55866
  const startRedirect = (address) => tryBind(address, "http", () => Bun.serve({
56543
55867
  hostname: address,
@@ -56600,7 +55924,7 @@ function createHttpsListeners(options) {
56600
55924
  function buildRedirect(request, domain, httpsPort, hint) {
56601
55925
  const parsed = parseDomainHost(request.headers.get("host"), domain);
56602
55926
  if (parsed === null) {
56603
- return buildErrorPage2(404, hint);
55927
+ return buildErrorPage(404, hint);
56604
55928
  }
56605
55929
  const url = new URL(request.url);
56606
55930
  const port = httpsPort === 443 ? "" : `:${String(httpsPort)}`;
@@ -56908,15 +56232,15 @@ function startWakeProxy(deps) {
56908
56232
  };
56909
56233
  const handleRequest = async (request, server, route) => {
56910
56234
  if (route.kind === "none") {
56911
- return buildErrorPage2(404, route.hint);
56235
+ return buildErrorPage(404, route.hint);
56912
56236
  }
56913
56237
  if (route.kind === "unauthorized") {
56914
- const page = buildErrorPage2(401, "This imp asks for a token or a password.");
56238
+ const page = buildErrorPage(401, "This imp asks for a token or a password.");
56915
56239
  page.headers.set("www-authenticate", route.challenge);
56916
56240
  return page;
56917
56241
  }
56918
56242
  if (route.kind === "limited") {
56919
- const page = buildErrorPage2(429, route.detail);
56243
+ const page = buildErrorPage(429, route.detail);
56920
56244
  page.headers.set("retry-after", String(route.retryAfterS));
56921
56245
  return page;
56922
56246
  }
@@ -56945,7 +56269,7 @@ function startWakeProxy(deps) {
56945
56269
  });
56946
56270
  } catch (error) {
56947
56271
  opened.release();
56948
- return publicRequest === null ? buildWakeErrorPage(name, error) : buildErrorPage2(503, "This site is not available right now.");
56272
+ return publicRequest === null ? buildWakeErrorPage(name, error) : buildErrorPage(503, "This site is not available right now.");
56949
56273
  }
56950
56274
  const imp = running.imp;
56951
56275
  const wokeMs = running.wokeMs;
@@ -57041,7 +56365,7 @@ function startWakeProxy(deps) {
57041
56365
  });
57042
56366
  } catch (error) {
57043
56367
  release();
57044
- return buildErrorPage2(502, options.formatFailure(getErrorMessage(error)));
56368
+ return buildErrorPage(502, options.formatFailure(getErrorMessage(error)));
57045
56369
  }
57046
56370
  };
57047
56371
  const handleWebSocket = async (options) => {
@@ -57059,7 +56383,7 @@ function startWakeProxy(deps) {
57059
56383
  } catch (error) {
57060
56384
  release();
57061
56385
  const reason = getErrorMessage(error);
57062
- return buildErrorPage2(502, `The WebSocket to ${target} failed: ${reason}`);
56386
+ return buildErrorPage(502, `The WebSocket to ${target} failed: ${reason}`);
57063
56387
  }
57064
56388
  const handleEarlyMessage = (event) => {
57065
56389
  pending.push(event.data);
@@ -57157,10 +56481,10 @@ function startWakeProxy(deps) {
57157
56481
  }
57158
56482
  function buildWakeErrorPage(name, error) {
57159
56483
  if (isImpdError(error, "NOT_FOUND")) {
57160
- return buildErrorPage2(404, `There is no imp named ${name}.`);
56484
+ return buildErrorPage(404, `There is no imp named ${name}.`);
57161
56485
  }
57162
56486
  const reason = getErrorMessage(error);
57163
- const page = buildErrorPage2(503, `${name} could not wake: ${reason}`);
56487
+ const page = buildErrorPage(503, `${name} could not wake: ${reason}`);
57164
56488
  if (isImpdError(error, "MOVING")) {
57165
56489
  page.headers.set("retry-after", String(MOVING_RETRY_AFTER_S));
57166
56490
  }
@@ -57206,35 +56530,108 @@ function buildApiListenOptions(config, idleTimeout = API_IDLE_TIMEOUT_S, hostnam
57206
56530
  };
57207
56531
  }
57208
56532
 
56533
+ // packages/daemon/src/surface/oauth/public-listener.ts
56534
+ import invariant15 from "tiny-invariant";
56535
+
56536
+ // packages/daemon/src/identity/oauth/read-body-text.ts
56537
+ async function readBodyText(request, max) {
56538
+ if (request.body === null) {
56539
+ return null;
56540
+ }
56541
+ const body = request.body;
56542
+ const chunks = [];
56543
+ let total = 0;
56544
+ for await (const chunk of body) {
56545
+ total += chunk.byteLength;
56546
+ if (total > max) {
56547
+ return null;
56548
+ }
56549
+ chunks.push(chunk);
56550
+ }
56551
+ return new TextDecoder().decode(Buffer.concat(chunks));
56552
+ }
56553
+
57209
56554
  // packages/daemon/src/surface/oauth/create-public-app.ts
57210
- import { Elysia as Elysia5 } from "elysia";
57211
- var RAW = { parse: "none" };
56555
+ import { createMCPHTTPApp } from "@zgeoff/mcp-auth/elysia";
56556
+ import { Elysia as Elysia5, NotFound } from "elysia";
56557
+ var NO_OWN_PATHS = "/.impd-none";
57212
56558
  function createPublicApp(deps) {
57213
- const app = new Elysia5({ strictPath: true }).onRequest((context) => {
57214
- if (context.request.method === "HEAD" && new URL(context.request.url).pathname !== MCP_PATH) {
57215
- return buildNotFound();
56559
+ const challenge = `Bearer error="invalid_token", resource_metadata="${deps.auth.issuer}${deps.auth.paths.machine.mcpResourceMetadata}"`;
56560
+ const respondToMcp = async (request, access) => {
56561
+ const caller = await deps.readCaller(access);
56562
+ if (caller === null) {
56563
+ return new Response(null, { status: 401, headers: { "www-authenticate": challenge } });
57216
56564
  }
57217
- return;
57218
- }).onError((context) => {
57219
- if (context.code === "NOT_FOUND") {
57220
- return buildNotFound();
56565
+ return deps.respond(request, caller);
56566
+ };
56567
+ return new Elysia5({ strictPath: true }).onError((context) => {
56568
+ if (context.error instanceof NotFound) {
56569
+ return new Response("not found", { status: 404 });
57221
56570
  }
57222
56571
  getImpdLogger("public").warning("public mcp: {error}", {
57223
56572
  error: getErrorMessage(context.error)
57224
56573
  });
57225
56574
  return new Response("internal error", { status: 500 });
57226
- }).all(MCP_PATH, (context) => {
57227
- deps.holdOpen(context.request);
57228
- return deps.mcp.respond(context.request);
57229
- }, RAW);
57230
- const oauth = deps.oauth;
57231
- if (oauth === null) {
57232
- return app;
57233
- }
57234
- return app.get("/.well-known/oauth-authorization-server", (context) => oauth.readServerMetadata(context.request), RAW).get("/.well-known/oauth-protected-resource", (context) => oauth.readResourceMetadata(context.request), RAW).get("/.well-known/oauth-protected-resource/mcp", (context) => oauth.readResourceMetadata(context.request), RAW).get("/error", (context) => oauth.answerError(context.request), RAW).get("/oauth2/authorize", (context) => oauth.runAuthorize(context.request), RAW).post("/oauth2/token", (context) => oauth.runTokenRequest(context.request), RAW).post("/oauth2/revoke", (context) => oauth.runRevoke(context.request), RAW).get("/login", (context) => oauth.runLogin(context.request), RAW).post("/login", (context) => oauth.runLogin(context.request), RAW).get("/consent", (context) => oauth.runConsent(context.request), RAW).post("/consent", (context) => oauth.runConsent(context.request), RAW);
56575
+ }).use(createMCPHTTPApp({
56576
+ auth: deps.auth,
56577
+ hosts: new Set([deps.host]),
56578
+ origins: new Set([deps.auth.issuer]),
56579
+ readRequester: deps.readRequester,
56580
+ security: { record: recordSecurityEvent },
56581
+ mcp: { fetch: respondToMcp },
56582
+ besidePrefix: NO_OWN_PATHS
56583
+ }));
57235
56584
  }
57236
- function buildNotFound() {
57237
- return new Response("not found", { status: 404 });
56585
+
56586
+ // packages/daemon/src/surface/oauth/keep-stream-verified.ts
56587
+ function keepStreamVerified(body, check) {
56588
+ const reader = body.getReader();
56589
+ const state = { isEnded: false, cancelTimer: () => {} };
56590
+ const stop = () => {
56591
+ state.isEnded = true;
56592
+ state.cancelTimer();
56593
+ };
56594
+ return new ReadableStream({
56595
+ start: (controller) => {
56596
+ const arm = () => {
56597
+ state.cancelTimer = check.startTimer(() => {
56598
+ readTokenCheck(check, (isValid) => {
56599
+ if (state.isEnded) {
56600
+ return;
56601
+ }
56602
+ if (isValid) {
56603
+ arm();
56604
+ return;
56605
+ }
56606
+ stop();
56607
+ controller.close();
56608
+ reader.cancel();
56609
+ });
56610
+ }, check.everyMs);
56611
+ };
56612
+ arm();
56613
+ },
56614
+ pull: async (controller) => {
56615
+ const chunk = await reader.read().catch((error) => {
56616
+ stop();
56617
+ throw error;
56618
+ });
56619
+ if (chunk.done) {
56620
+ stop();
56621
+ controller.close();
56622
+ return;
56623
+ }
56624
+ controller.enqueue(chunk.value);
56625
+ },
56626
+ cancel: async (reason) => {
56627
+ stop();
56628
+ await reader.cancel(reason);
56629
+ }
56630
+ });
56631
+ }
56632
+ async function readTokenCheck(check, then) {
56633
+ const isValid = await check.probeToken().catch(() => false);
56634
+ then(isValid);
57238
56635
  }
57239
56636
 
57240
56637
  // packages/daemon/src/surface/oauth/public-listener.ts
@@ -57243,21 +56640,27 @@ var MAX_CONTROL = 16;
57243
56640
  var MAX_CONTROL_BYTES = 16 * 1024;
57244
56641
  var MAX_BODY_BYTES = 8 * 1024 * 1024;
57245
56642
  var IDLE_TIMEOUT_S2 = 30;
56643
+ var REVERIFY_MS = 10 * 60000;
57246
56644
  function createPublicHandler(deps) {
57247
56645
  const state = { open: 0, control: 0 };
57248
56646
  const servers = new WeakMap;
57249
- const host = deps.config.host.toLowerCase();
56647
+ const auth = deps.oauth.server;
56648
+ invariant15(auth !== null, "the public listener starts only with the public MCP route set");
57250
56649
  const app = createPublicApp({
57251
- oauth: deps.oauth.handlers,
57252
- mcp: deps.mcp,
57253
- holdOpen: (request) => {
56650
+ auth,
56651
+ host: deps.config.host,
56652
+ readCaller: deps.oauth.readCaller,
56653
+ readRequester: (request) => ({
56654
+ socketAddress: servers.get(request)?.requestIP(request)?.address ?? null,
56655
+ connectingIP: null,
56656
+ userAgent: request.headers.get("user-agent")
56657
+ }),
56658
+ respond: (request, caller) => {
57254
56659
  servers.get(request)?.timeout(request, 0);
56660
+ return deps.mcp.respond(request, caller);
57255
56661
  }
57256
56662
  });
57257
56663
  const handleRequest = (request, server) => {
57258
- if ((request.headers.get("host") ?? "").toLowerCase() !== host) {
57259
- return Promise.resolve(new Response("not found", { status: 404 }));
57260
- }
57261
56664
  if (server !== null) {
57262
56665
  servers.set(request, server);
57263
56666
  }
@@ -57285,13 +56688,37 @@ function createPublicHandler(deps) {
57285
56688
  });
57286
56689
  try {
57287
56690
  const response = await handleRequest(request, server);
57288
- return holdUntilDone(request, response, deps.mcp.readCallEnd(response), release);
56691
+ const held = holdUntilDone(request, response, deps.mcp.readCallEnd(response), release);
56692
+ return keepVerified(request, held, {
56693
+ verify: auth.verify,
56694
+ everyMs: deps.reverifyMs ?? REVERIFY_MS
56695
+ });
57289
56696
  } catch (error) {
57290
56697
  release();
57291
56698
  throw error;
57292
56699
  }
57293
56700
  };
57294
56701
  }
56702
+ function keepVerified(request, response, reverify) {
56703
+ const bearer = /^Bearer (?<token>\S+)$/iv.exec(request.headers.get("authorization") ?? "")?.groups?.["token"];
56704
+ const isStream = response.headers.get("content-type")?.startsWith("text/event-stream") ?? false;
56705
+ if (bearer === undefined || response.body === null || !isStream) {
56706
+ return response;
56707
+ }
56708
+ const body = keepStreamVerified(response.body, {
56709
+ probeToken: async () => {
56710
+ const access = await reverify.verify(bearer);
56711
+ return access !== null;
56712
+ },
56713
+ everyMs: reverify.everyMs,
56714
+ startTimer: startRealTimer
56715
+ });
56716
+ return new Response(body, {
56717
+ status: response.status,
56718
+ statusText: response.statusText,
56719
+ headers: response.headers
56720
+ });
56721
+ }
57295
56722
  function createRelease(release) {
57296
56723
  const state = { isReleased: false };
57297
56724
  return () => {
@@ -58560,6 +57987,10 @@ async function stopImpd(parts, options) {
58560
57987
  if (stopTelemetry !== undefined && stopTelemetry !== null) {
58561
57988
  await runStep("telemetry", readStepMs(), stopTelemetry);
58562
57989
  }
57990
+ const oauth = parts.oauth;
57991
+ if (oauth !== undefined) {
57992
+ await runStep("oauth", readStepMs(), () => oauth.close());
57993
+ }
58563
57994
  const db = parts.db;
58564
57995
  if (state.settled && db !== undefined && db !== null) {
58565
57996
  await runStep("database", readStepMs(), () => db.destroy());
@@ -58646,8 +58077,8 @@ import {
58646
58077
  statSync as statSync15
58647
58078
  } from "fs";
58648
58079
  import { basename as basename5, dirname as dirname11, join as join40 } from "path";
58649
- import * as z103 from "zod";
58650
- var CopiesSchema = z103.record(z103.string(), z103.object({ ino: z103.string(), ctimeNs: z103.string(), size: z103.string() }));
58080
+ import * as z102 from "zod";
58081
+ var CopiesSchema = z102.record(z102.string(), z102.object({ ino: z102.string(), ctimeNs: z102.string(), size: z102.string() }));
58651
58082
  function createXfsBackups(ctx) {
58652
58083
  const backup = buildBackupPaths(ctx.dataDir);
58653
58084
  const freshCopies = new Set;
@@ -60429,7 +59860,7 @@ function readUnmarked(dataDir) {
60429
59860
  }
60430
59861
 
60431
59862
  // packages/daemon/src/vm/storage/is-usage-change.ts
60432
- import { P as P9, match as match26 } from "ts-pattern";
59863
+ import { P as P9, match as match27 } from "ts-pattern";
60433
59864
  var CHANGES_USAGE = new Set([
60434
59865
  "resized",
60435
59866
  "restored",
@@ -60437,7 +59868,7 @@ var CHANGES_USAGE = new Set([
60437
59868
  "slept"
60438
59869
  ]);
60439
59870
  function isUsageChange(event) {
60440
- return match26(event).with({ ev: P9.union("ImpAdded", "ImpRemoved", "CheckpointAdded", "CheckpointRemoved") }, () => true).with({ ev: "ImpChanged" }, (changed) => CHANGES_USAGE.has(changed.reason)).with({ ev: P9.union("GovernorDecision", "AgentExec") }, () => false).exhaustive();
59871
+ return match27(event).with({ ev: P9.union("ImpAdded", "ImpRemoved", "CheckpointAdded", "CheckpointRemoved") }, () => true).with({ ev: "ImpChanged" }, (changed) => CHANGES_USAGE.has(changed.reason)).with({ ev: P9.union("GovernorDecision", "AgentExec") }, () => false).exhaustive();
60441
59872
  }
60442
59873
 
60443
59874
  // packages/daemon/src/vm/storage/setup-system-files.ts
@@ -60647,6 +60078,7 @@ async function startImpdParts(config, boundaries, plan) {
60647
60078
  const state = { ready: false };
60648
60079
  const authorizedKeys = createAuthorizedKeys(join49(setupSshDir(config.dataDir), "authorized_keys"));
60649
60080
  const access = await runStep("access", () => loadImpdAccess(config, deps, authorizedKeys.probeListed));
60081
+ plan.oauth = access.oauth.admin;
60650
60082
  const backups = config.backup === null ? null : createBackupService({
60651
60083
  dataDir: config.dataDir,
60652
60084
  backup: config.backup,
@@ -60737,7 +60169,7 @@ async function startImpdParts(config, boundaries, plan) {
60737
60169
  const idle = createIdleLoop({ config, db, imps });
60738
60170
  const tickers = runStep("tickers", () => startImpdTickers(config, {
60739
60171
  idle,
60740
- oauth: access.oauth,
60172
+ oauth: access.oauth.admin,
60741
60173
  governor,
60742
60174
  imps,
60743
60175
  memory: governed.memory,
@@ -61390,19 +60822,19 @@ log tail`);
61390
60822
  // packages/daemon/src/test-utils/vm/create-stub-uffd-handler.ts
61391
60823
  import { existsSync as existsSync35, readFileSync as readFileSync40, writeFileSync as writeFileSync17 } from "fs";
61392
60824
  import { join as join50 } from "path";
61393
- import * as z104 from "zod";
61394
- var StartSchema = z104.object({
61395
- options: z104.object({
61396
- socket: z104.string().optional(),
61397
- uid: z104.string().optional(),
61398
- gid: z104.string().optional()
60825
+ import * as z103 from "zod";
60826
+ var StartSchema = z103.object({
60827
+ options: z103.object({
60828
+ socket: z103.string().optional(),
60829
+ uid: z103.string().optional(),
60830
+ gid: z103.string().optional()
61399
60831
  }),
61400
- served: z104.string()
60832
+ served: z103.string()
61401
60833
  });
61402
- var WarmRunSchema = z104.object({
61403
- mode: z104.enum(["--count-data", "--warm"]),
61404
- memFile: z104.string(),
61405
- pid: z104.int()
60834
+ var WarmRunSchema = z103.object({
60835
+ mode: z103.enum(["--count-data", "--warm"]),
60836
+ memFile: z103.string(),
60837
+ pid: z103.int()
61406
60838
  });
61407
60839
  function createStubUffdHandler(directory, mode = "serve") {
61408
60840
  const path = join50(directory, `uffd-handler-${mode}`);
@@ -61694,7 +61126,7 @@ async function startTestImpd(stack, options = {}) {
61694
61126
  reconcilerTimers.runFor(durationMs);
61695
61127
  },
61696
61128
  setClock: (nowMs) => {
61697
- invariant14(options.frozenClockMs !== undefined, "setClock needs a frozen clock");
61129
+ invariant16(options.frozenClockMs !== undefined, "setClock needs a frozen clock");
61698
61130
  clock.frozenAt = nowMs;
61699
61131
  clock.offsetMs = 0;
61700
61132
  },
@@ -61774,7 +61206,7 @@ function buildTestIdentity(dataDir, drive) {
61774
61206
  }
61775
61207
 
61776
61208
  // packages/testing/src/start-relay-guest.ts
61777
- import { randomBytes as randomBytes13 } from "crypto";
61209
+ import { randomBytes as randomBytes12 } from "crypto";
61778
61210
  import { Duplex } from "stream";
61779
61211
 
61780
61212
  // packages/daemon/src/test-utils/vm/start-stub-agent.ts
@@ -61851,7 +61283,7 @@ async function startRelayGuest(stack, vsockPath) {
61851
61283
  }
61852
61284
  const listener = {
61853
61285
  socket,
61854
- id: randomBytes13(8).toString("hex"),
61286
+ id: randomBytes12(8).toString("hex"),
61855
61287
  port,
61856
61288
  pending: new Map,
61857
61289
  counts: { next: 0 }