@tangle-network/agent-app 0.60.266 → 0.60.268

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.
@@ -0,0 +1,23 @@
1
+ // src/billing/crypto-probe.ts
2
+ async function assertWorkspaceKeyCryptoUsable(crypto) {
3
+ const probe = "agent-app:key-manager:crypto-probe";
4
+ let roundTripped;
5
+ try {
6
+ roundTripped = await crypto.decrypt(await crypto.encrypt(probe));
7
+ } catch (error) {
8
+ throw new Error(
9
+ "Key encryption is misconfigured: the crypto seam threw before minting. Validate FIELD_ENCRYPTION_KEY (64-char hex) at startup. No platform key was minted.",
10
+ { cause: error }
11
+ );
12
+ }
13
+ if (roundTripped !== probe) {
14
+ throw new Error(
15
+ "Key encryption is misconfigured: encrypt/decrypt round-trip did not preserve the plaintext. No platform key was minted."
16
+ );
17
+ }
18
+ }
19
+
20
+ export {
21
+ assertWorkspaceKeyCryptoUsable
22
+ };
23
+ //# sourceMappingURL=chunk-VGS2NXLB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/billing/crypto-probe.ts"],"sourcesContent":["import type { KeyCrypto } from './index'\n\n/** Prove the at-rest crypto seam before a remote key is minted. */\nexport async function assertWorkspaceKeyCryptoUsable(crypto: KeyCrypto): Promise<void> {\n const probe = 'agent-app:key-manager:crypto-probe'\n let roundTripped: string\n try {\n roundTripped = await crypto.decrypt(await crypto.encrypt(probe))\n } catch (error) {\n throw new Error(\n 'Key encryption is misconfigured: the crypto seam threw before minting. ' +\n 'Validate FIELD_ENCRYPTION_KEY (64-char hex) at startup. No platform key was minted.',\n { cause: error },\n )\n }\n if (roundTripped !== probe) {\n throw new Error(\n 'Key encryption is misconfigured: encrypt/decrypt round-trip did not preserve the plaintext. ' +\n 'No platform key was minted.',\n )\n }\n}\n"],"mappings":";AAGA,eAAsB,+BAA+B,QAAkC;AACrF,QAAM,QAAQ;AACd,MAAI;AACJ,MAAI;AACF,mBAAe,MAAM,OAAO,QAAQ,MAAM,OAAO,QAAQ,KAAK,CAAC;AAAA,EACjE,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR;AAAA,MAEA,EAAE,OAAO,MAAM;AAAA,IACjB;AAAA,EACF;AACA,MAAI,iBAAiB,OAAO;AAC1B,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACF;","names":[]}
@@ -8,9 +8,14 @@
8
8
  * expiry and revocation rules, and four never noticed a key Platform had
9
9
  * revoked, superseded or expired.
10
10
  *
11
- * TWO WAYS TO HOLD ONE.
11
+ * THREE WAYS TO HOLD ONE.
12
12
  * - Per turn: `client.delegate` before the turn, `client.revoke` after it.
13
13
  * Nothing is cached, so nothing stale can be handed out.
14
+ * - Pre-minted per turn: `createDelegatedTurnKeys` (`./delegated-turn-keys`) gives each turn its own
15
+ * child, same cap and expiry, but mints the next turn's child in the
16
+ * background and parks it in D1, so the ~320 ms mint leaves the turn's
17
+ * critical path. A parked key is taken exactly once; anything else mints
18
+ * inline as before.
14
19
  * - Per workspace: `createDelegatedKeyProvisioner` plugs this client into
15
20
  * `createIdentityBoundWorkspaceKeyManager` (`./billing`), which owns the
16
21
  * durable, lease-fenced slot. Its `getKey` asks Platform's
@@ -0,0 +1,103 @@
1
+ import type { KeyCrypto } from '../billing';
2
+ import type { DelegatedKeyOutcome, DelegatedKeyRequest, PlatformDelegatedKeyClient } from './delegated-keys';
3
+ /**
4
+ * Pre-minted turn keys. Creative minted each Router turn's child on the turn's critical path, ~320 ms of a
5
+ * 6,419 ms first-visible p50 (router-spec, 2026-10-22). `createDelegatedTurnKeys` keeps one child per turn with
6
+ * the same cap and expiry, and mints the next turn's child in the background (`waitUntil`) into a D1 slot. The
7
+ * next turn takes it with one `DELETE ... RETURNING`, so a parked key serves exactly one turn and a racing second
8
+ * turn mints inline. A parked key is used only when it was minted for the same request (source key, product,
9
+ * models, budget, resource, payer: the slot's `scope` digest) and has `minRemainingMs` of life; otherwise the turn
10
+ * mints inline exactly as before. A parked child Platform revoked or let expire is refused by the Router (401
11
+ * `invalid_key` with that reason); `delegatedKeyFallbackFetch` then mints inline once and resends. A spent budget
12
+ * never re-mints: the turn keeps one cap. Each slot holds at most one unused key; a displaced key, or one minted
13
+ * but not stored, is revoked, and one whose revoke fails expires on its own. The secret is stored encrypted.
14
+ */
15
+ /** Paste into a migration. `expires_at` is epoch ms; `scope` is the digest of the request the key was minted for. */
16
+ export declare const DELEGATED_KEY_PREMINT_TABLE_DDL = "CREATE TABLE IF NOT EXISTS delegated_key_premint (\n slot TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n key_id TEXT NOT NULL,\n key_encrypted TEXT NOT NULL,\n expires_at INTEGER NOT NULL\n)";
17
+ /** The D1 surface the slot store uses. A real `D1Database` satisfies it. */
18
+ export interface DelegatedKeyPremintD1Like {
19
+ prepare(query: string): {
20
+ bind(...values: unknown[]): {
21
+ first<T = Record<string, unknown>>(): Promise<T | null>;
22
+ run(): Promise<unknown>;
23
+ };
24
+ };
25
+ }
26
+ /** What a turn's key is minted for. Its digest decides whether a parked key may serve a turn. */
27
+ export type DelegatedTurnKeyScope = Omit<DelegatedKeyRequest, 'name' | 'expiresAt' | 'retryUnavailable'>;
28
+ export interface DelegatedTurnKeyInput {
29
+ /** One parked key per slot, e.g. `<userId>:<workspaceId>:router`. */
30
+ slot: string;
31
+ scope: DelegatedTurnKeyScope;
32
+ /** Life asked of Platform for each child; `notAfter` caps it. */
33
+ ttlMs: number;
34
+ notAfter?: Date;
35
+ retryUnavailable?: DelegatedKeyRequest['retryUnavailable'];
36
+ /** The payer's Platform user id. Platform refuses `DELETE` from an app-provisioned (SSO) source key, so an unused
37
+ * child is retired through `revoke-slot` with it; without it (or `scope.expect.payerId`) such a child just expires. */
38
+ payerId?: string;
39
+ }
40
+ export interface DelegatedTurnKey {
41
+ key: string;
42
+ id: string;
43
+ /** The id the child was minted for (`turn:<turnId>` at Platform): the turn's own id when minted inline, a
44
+ * random id when pre-minted. The turn records `id` beside its own id. */
45
+ turnId: string;
46
+ expiresAt: Date;
47
+ /** Parked before this turn: a revoked or expired refusal of it means mint inline (`delegatedKeyFallbackFetch`). */
48
+ preminted: boolean;
49
+ }
50
+ export type DelegatedTurnKeyEvent = {
51
+ type: 'claimed' | 'missed' | 'parked' | 'park_kept';
52
+ slot: string;
53
+ }
54
+ /** `keyId` names a child minted but not parked (retired best effort); never its key. */
55
+ | {
56
+ type: 'park_failed';
57
+ slot: string;
58
+ code: string;
59
+ keyId?: string;
60
+ };
61
+ export interface DelegatedTurnKeysOptions {
62
+ client: PlatformDelegatedKeyClient;
63
+ /** Null turns pre-minting off: every turn mints inline, as before. */
64
+ db: DelegatedKeyPremintD1Like | null;
65
+ /** The app's at-rest crypto (`createFieldCrypto` from `./crypto`). */
66
+ crypto: KeyCrypto;
67
+ /** Defaults to `delegated_key_premint`. */
68
+ table?: string;
69
+ /** A parked key serves a turn only with at least this much life left. Default 10 min, above a turn's budget. */
70
+ minRemainingMs?: number;
71
+ onEvent?: (event: DelegatedTurnKeyEvent) => void;
72
+ now?: () => number;
73
+ }
74
+ export interface DelegatedTurnKeys {
75
+ /**
76
+ * This turn's key: the slot's parked key, taken exactly once, else a fresh mint named `turn:<turnId>`. Then the
77
+ * next turn's key is minted and parked through `waitUntil` (the Worker's `ctx.waitUntil`), off this turn's path.
78
+ */
79
+ forTurn(input: DelegatedTurnKeyInput & {
80
+ turnId: string;
81
+ waitUntil?: (promise: Promise<unknown>) => void;
82
+ }): Promise<DelegatedKeyOutcome<DelegatedTurnKey>>;
83
+ /** Mint and park a key for the slot's next turn, e.g. when a member session opens. Never throws. */
84
+ park(input: DelegatedTurnKeyInput): Promise<boolean>;
85
+ /** Mint inline, as a turn did before pre-minting. */
86
+ mint(input: DelegatedTurnKeyInput & {
87
+ turnId: string;
88
+ }): Promise<DelegatedKeyOutcome<DelegatedTurnKey>>;
89
+ }
90
+ export declare function createDelegatedTurnKeys(options: DelegatedTurnKeysOptions): DelegatedTurnKeys;
91
+ /**
92
+ * A fetch for one turn that sends a pre-minted key. When the Router refuses the turn's FIRST request with it as
93
+ * revoked, expired or invalid (Platform retired the parked child), it mints inline once and resends that request
94
+ * with the fresh key; later requests carry the fresh key. Any other refusal, and any refusal later in the turn, is
95
+ * the turn's answer. A stream body on the first request is buffered so it can be resent. Requests whose
96
+ * `init.headers` carry another credential, and keys minted inline, pass through. Make one per turn.
97
+ */
98
+ export declare function delegatedKeyFallbackFetch(input: {
99
+ key: DelegatedTurnKey;
100
+ remint: () => Promise<DelegatedKeyOutcome<DelegatedTurnKey>>;
101
+ fetch?: typeof fetch;
102
+ onReplaced?: (key: DelegatedTurnKey) => void;
103
+ }): typeof fetch;
@@ -13,3 +13,4 @@ export * from './agent-keys.js';
13
13
  export * from './agent-spend.js';
14
14
  export * from './billing-consent.js';
15
15
  export * from './delegated-keys.js';
16
+ export * from './delegated-turn-keys.js';
@@ -22,6 +22,9 @@ import {
22
22
  createPlatformAgentKeyVerifier,
23
23
  platformKeyRefusal
24
24
  } from "../chunk-XB4KZVUV.js";
25
+ import {
26
+ assertWorkspaceKeyCryptoUsable
27
+ } from "../chunk-VGS2NXLB.js";
25
28
  import {
26
29
  resolveTangleExecutionEnvironment
27
30
  } from "../chunk-D6UJEOZQ.js";
@@ -30,6 +33,9 @@ import "../chunk-RN4WPTBH.js";
30
33
  import {
31
34
  parseJsonObjectBody
32
35
  } from "../chunk-WP2GYFZ4.js";
36
+ import {
37
+ sha256Hex
38
+ } from "../chunk-HY57QRRW.js";
33
39
  import "../chunk-TXD5HXLE.js";
34
40
  import "../chunk-6Z7TZVKZ.js";
35
41
  import "../chunk-57XPEL7X.js";
@@ -1121,9 +1127,191 @@ function createDelegatedKeyProvisioner(input) {
1121
1127
  }
1122
1128
  };
1123
1129
  }
1130
+
1131
+ // src/platform/delegated-turn-keys.ts
1132
+ var DELEGATED_KEY_PREMINT_TABLE_DDL = `CREATE TABLE IF NOT EXISTS delegated_key_premint (
1133
+ slot TEXT PRIMARY KEY,
1134
+ scope TEXT NOT NULL,
1135
+ turn_id TEXT NOT NULL,
1136
+ key_id TEXT NOT NULL,
1137
+ key_encrypted TEXT NOT NULL,
1138
+ expires_at INTEGER NOT NULL
1139
+ )`;
1140
+ var PREMINT_TABLE = "delegated_key_premint";
1141
+ var PREMINT_MIN_REMAINING_MS = 10 * 6e4;
1142
+ var PREMINT_KEEP_SLACK_MS = 5 * 6e4;
1143
+ async function scopeDigest(scope) {
1144
+ const budget = scope.budget;
1145
+ return sha256Hex(JSON.stringify([
1146
+ scope.sourceKey,
1147
+ scope.product,
1148
+ scope.resource?.type ?? null,
1149
+ scope.resource?.id ?? null,
1150
+ scope.allowedModels ? [...new Set(scope.allowedModels)].sort() : null,
1151
+ budget && "usd" in budget ? budget.usd : null,
1152
+ budget && "spendThrough" in budget ? true : null,
1153
+ budget?.monthlyUsd ?? null,
1154
+ scope.rpmLimit ?? null,
1155
+ scope.expect?.payerId ?? null,
1156
+ scope.expect?.sourceKeyId ?? null,
1157
+ scope.expect?.originAppId ?? null
1158
+ ]));
1159
+ }
1160
+ function createDelegatedTurnKeys(options) {
1161
+ const table = options.table ?? PREMINT_TABLE;
1162
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`Invalid delegated key premint table: ${JSON.stringify(table)}`);
1163
+ const now = options.now ?? Date.now;
1164
+ const minRemainingMs = options.minRemainingMs ?? PREMINT_MIN_REMAINING_MS;
1165
+ const emit = (event) => {
1166
+ try {
1167
+ options.onEvent?.(event);
1168
+ } catch {
1169
+ }
1170
+ };
1171
+ const db = options.db;
1172
+ async function mint(input, preminted) {
1173
+ const expiresAt = new Date(Math.min(now() + input.ttlMs, input.notAfter?.getTime() ?? Infinity));
1174
+ const outcome = await options.client.delegate({
1175
+ ...input.scope,
1176
+ name: `turn:${input.turnId}`,
1177
+ expiresAt,
1178
+ ...input.retryUnavailable ? { retryUnavailable: input.retryUnavailable } : {}
1179
+ });
1180
+ if (!outcome.succeeded) return outcome;
1181
+ const { key, id } = outcome.value;
1182
+ return { succeeded: true, value: { key, id, turnId: input.turnId, expiresAt: outcome.value.expiresAt, preminted } };
1183
+ }
1184
+ async function retire(input, keyId) {
1185
+ const { scope } = input;
1186
+ const payerId = scope.expect?.payerId ?? input.payerId;
1187
+ await options.client.revoke({
1188
+ sourceKey: scope.sourceKey,
1189
+ keyId,
1190
+ ...payerId ? { slot: {
1191
+ userId: payerId,
1192
+ product: scope.product,
1193
+ ...scope.expect?.sourceKeyId ? { sourceKeyId: scope.expect.sourceKeyId } : {}
1194
+ } } : {}
1195
+ }).catch(() => null);
1196
+ }
1197
+ async function claim(input) {
1198
+ if (!db) return null;
1199
+ const { slot, scope } = input;
1200
+ const row = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 AND scope = ?2 AND expires_at > ?3
1201
+ RETURNING turn_id, key_id, key_encrypted, expires_at`).bind(slot, await scopeDigest(scope), now() + minRemainingMs).first();
1202
+ if (!row) return null;
1203
+ try {
1204
+ const key = await options.crypto.decrypt(row.key_encrypted);
1205
+ return { key, id: row.key_id, turnId: row.turn_id, expiresAt: new Date(row.expires_at), preminted: true };
1206
+ } catch {
1207
+ await retire(input, row.key_id);
1208
+ return null;
1209
+ }
1210
+ }
1211
+ async function park(input) {
1212
+ if (!db) return false;
1213
+ let scope;
1214
+ try {
1215
+ scope = await scopeDigest(input.scope);
1216
+ const held = await db.prepare(`SELECT scope, expires_at FROM ${table} WHERE slot = ?1`).bind(input.slot).first();
1217
+ if (held?.scope === scope && held.expires_at > now() + minRemainingMs + PREMINT_KEEP_SLACK_MS) {
1218
+ emit({ type: "park_kept", slot: input.slot });
1219
+ return true;
1220
+ }
1221
+ } catch {
1222
+ emit({ type: "park_failed", slot: input.slot, code: "premint_store_failed" });
1223
+ return false;
1224
+ }
1225
+ try {
1226
+ await assertWorkspaceKeyCryptoUsable(options.crypto);
1227
+ } catch {
1228
+ emit({ type: "park_failed", slot: input.slot, code: "premint_crypto_unusable" });
1229
+ return false;
1230
+ }
1231
+ const minted = await mint({ ...input, turnId: crypto.randomUUID() }, true);
1232
+ if (!minted.succeeded) {
1233
+ emit({ type: "park_failed", slot: input.slot, code: minted.error.code });
1234
+ return false;
1235
+ }
1236
+ try {
1237
+ const encrypted = await options.crypto.encrypt(minted.value.key);
1238
+ const displaced = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 RETURNING key_id`).bind(input.slot).first();
1239
+ if (displaced) await retire(input, displaced.key_id);
1240
+ const stored = await db.prepare(`INSERT INTO ${table} (slot, scope, turn_id, key_id, key_encrypted, expires_at)
1241
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(slot) DO NOTHING RETURNING slot`).bind(input.slot, scope, minted.value.turnId, minted.value.id, encrypted, minted.value.expiresAt.getTime()).first();
1242
+ if (!stored) {
1243
+ await retire(input, minted.value.id);
1244
+ emit({ type: "park_kept", slot: input.slot });
1245
+ return true;
1246
+ }
1247
+ emit({ type: "parked", slot: input.slot });
1248
+ return true;
1249
+ } catch {
1250
+ await retire(input, minted.value.id);
1251
+ emit({ type: "park_failed", slot: input.slot, code: "premint_store_failed", keyId: minted.value.id });
1252
+ return false;
1253
+ }
1254
+ }
1255
+ return {
1256
+ async forTurn(input) {
1257
+ const claimed = await claim(input).catch(() => null);
1258
+ if (db) {
1259
+ const next = park({
1260
+ slot: input.slot,
1261
+ scope: input.scope,
1262
+ ttlMs: input.ttlMs,
1263
+ ...input.notAfter ? { notAfter: input.notAfter } : {},
1264
+ ...input.payerId ? { payerId: input.payerId } : {}
1265
+ });
1266
+ input.waitUntil?.(next);
1267
+ }
1268
+ emit({ type: claimed ? "claimed" : "missed", slot: input.slot });
1269
+ return claimed ? { succeeded: true, value: claimed } : mint(input, false);
1270
+ },
1271
+ park,
1272
+ mint: (input) => mint(input, false)
1273
+ };
1274
+ }
1275
+ var REFUSED_KEY_CODES = /* @__PURE__ */ new Set(["key_revoked", "key_expired", "invalid_api_key", "invalid_key_contract"]);
1276
+ async function refusedKey(response) {
1277
+ if (response.status !== 401) return false;
1278
+ const body2 = await response.clone().json().catch(() => null);
1279
+ const code = body2?.error?.code;
1280
+ return typeof code === "string" && (REFUSED_KEY_CODES.has(code) || code === "invalid_key" && (body2?.error?.reason === "key_revoked" || body2?.error?.reason === "key_expired"));
1281
+ }
1282
+ function delegatedKeyFallbackFetch(input) {
1283
+ const base = input.fetch ?? fetch;
1284
+ if (!input.key.preminted) return base;
1285
+ const parked = `Bearer ${input.key.key}`;
1286
+ let first = true;
1287
+ let fresh;
1288
+ return async (resource, init) => {
1289
+ const headers = new Headers(init?.headers);
1290
+ if (headers.get("authorization") !== parked) return base(resource, init);
1291
+ if (fresh) {
1292
+ headers.set("authorization", fresh);
1293
+ return base(resource, { ...init, headers });
1294
+ }
1295
+ if (!first) return base(resource, init);
1296
+ first = false;
1297
+ const body2 = init?.body instanceof ReadableStream ? await new Response(init.body).arrayBuffer() : init?.body;
1298
+ const send = () => base(resource, { ...init, headers, ...body2 !== void 0 ? { body: body2 } : {} });
1299
+ const response = await send();
1300
+ if (!await refusedKey(response)) return response;
1301
+ const reminted = await input.remint();
1302
+ if (!reminted.succeeded) return response;
1303
+ await response.body?.cancel().catch(() => {
1304
+ });
1305
+ fresh = `Bearer ${reminted.value.key}`;
1306
+ headers.set("authorization", fresh);
1307
+ input.onReplaced?.(reminted.value);
1308
+ return send();
1309
+ };
1310
+ }
1124
1311
  export {
1125
1312
  DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR,
1126
1313
  DEFAULT_TANGLE_TIER_POLICY,
1314
+ DELEGATED_KEY_PREMINT_TABLE_DDL,
1127
1315
  DelegatedKeyMissingError,
1128
1316
  DelegatedKeyRefusalError,
1129
1317
  FREE_TIER_SPEND_CAP_USD,
@@ -1143,6 +1331,7 @@ export {
1143
1331
  createBetterAuthSessionCookieMinter,
1144
1332
  createD1TangleIdentityStore,
1145
1333
  createDelegatedKeyProvisioner,
1334
+ createDelegatedTurnKeys,
1146
1335
  createHubSettingsRoutes,
1147
1336
  createPlatformAgentKeyVerifier,
1148
1337
  createPlatformAgentSpend,
@@ -1152,6 +1341,7 @@ export {
1152
1341
  createSignedSsoState,
1153
1342
  createTanglePlatformBillingClient,
1154
1343
  createTangleSsoHandlers,
1344
+ delegatedKeyFallbackFetch,
1155
1345
  getProductEntitlement,
1156
1346
  guardResolution,
1157
1347
  isPlatformBillingHttpError,