@tangle-network/agent-app 0.60.130 → 0.60.132

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,226 @@
1
+ /**
2
+ * Delegated product keys: a child key minted from the paying user's linked
3
+ * Tangle key, scoped to one product, its models and its budget, so an app
4
+ * never sends the user's own key to Router or Sandbox.
5
+ *
6
+ * WHY ONE. Seven apps minted these by hand (Tax, Legal, GTM, Creative,
7
+ * Builder, Hardware, workcomp; survey 2026-10-12) with different scope,
8
+ * expiry and revocation rules, and four never noticed a key Platform had
9
+ * revoked, superseded or expired.
10
+ *
11
+ * TWO WAYS TO HOLD ONE.
12
+ * - Per turn: `client.delegate` before the turn, `client.revoke` after it.
13
+ * Nothing is cached, so nothing stale can be handed out.
14
+ * - Per workspace: `createDelegatedKeyProvisioner` plugs this client into
15
+ * `createIdentityBoundWorkspaceKeyManager` (`./billing`), which owns the
16
+ * durable, lease-fenced slot. Its `getKey` asks Platform's
17
+ * `verify-by-id`, which also refuses superseded generations, and reports
18
+ * any key that is not valid as missing, so the manager marks it revoked
19
+ * and mints a fresh one on the next use.
20
+ *
21
+ * THE MINT CONTRACT (`POST /v1/keys/delegate`, service-authenticated; the
22
+ * response is the key row plus `attribution`, and the granted expiry is
23
+ * `attribution.expiresAt`). The child is checked field by field: an
24
+ * `sk-tan-` key that is not the source, the canonical name, this service as
25
+ * provisioner and attribution origin, the requested product, resource, model
26
+ * set and payer, a budget no larger than requested, and an expiry in the
27
+ * future and no later than requested. A child that fails is revoked and
28
+ * refused; if that revoke fails too, the refusal carries the child's id (never
29
+ * its key) so the app can retire it.
30
+ *
31
+ * Errors carry a code and status, never a response body, a source key or a
32
+ * child key.
33
+ */
34
+ export type DelegatedKeyCode = 'delegated_key.payment_required' | 'delegated_key.budget_exhausted' | 'delegated_key.owner_unverified' | 'delegated_key.unavailable' | 'delegated_key.refused' | 'delegated_key.response_invalid' | 'delegated_key.invalid_request';
35
+ export interface DelegatedKeyRefusal {
36
+ status: number;
37
+ code: DelegatedKeyCode;
38
+ message: string;
39
+ /** Set when an untrusted child could not be revoked: the id (never the key) the app must retire. */
40
+ unrevokedKeyId?: string;
41
+ }
42
+ export type DelegatedKeyOutcome<T> = {
43
+ succeeded: true;
44
+ value: T;
45
+ } | {
46
+ succeeded: false;
47
+ error: DelegatedKeyRefusal;
48
+ };
49
+ /** How the child is paid for: its own budget, or spending the source's budget directly. */
50
+ export type DelegatedKeyBudget = {
51
+ usd: number;
52
+ monthlyUsd?: number;
53
+ } | {
54
+ spendThrough: true;
55
+ monthlyUsd?: number;
56
+ };
57
+ export interface DelegatedKeyRequest {
58
+ /** The payer's linked `sk-tan-` key. Never a shared app key. */
59
+ sourceKey: string;
60
+ /** The logical slot, e.g. `turn:<id>`. Sent as Platform's canonical name; see {@link canonicalDelegatedKeyName}. */
61
+ name: string;
62
+ product: 'router' | 'sandbox' | (string & {});
63
+ resource?: {
64
+ type: string;
65
+ id: string;
66
+ };
67
+ /** The only models the child may call. */
68
+ allowedModels?: readonly string[];
69
+ budget?: DelegatedKeyBudget;
70
+ rpmLimit?: number;
71
+ expiresAt: Date;
72
+ /** Checked against the child's attribution when given: the payer's Platform user id, the source key's id, and
73
+ * the origin app Platform carries over from the source (an app's SSO key; a personal key has none). */
74
+ expect?: {
75
+ payerId?: string;
76
+ sourceKeyId?: string;
77
+ originAppId?: string | null;
78
+ };
79
+ }
80
+ export interface DelegatedKey {
81
+ key: string;
82
+ id: string;
83
+ /** The canonical name Platform stored. */
84
+ name: string;
85
+ product: string;
86
+ /** The expiry Platform granted (`attribution.expiresAt`), never later than requested. */
87
+ expiresAt: Date;
88
+ allowedModels: readonly string[] | null;
89
+ budgetUsd: number | null;
90
+ }
91
+ export interface PlatformDelegatedKeyClientOptions {
92
+ /** Platform origin, e.g. `https://id.tangle.tools`. */
93
+ platformUrl: string;
94
+ /** This app's Platform service name; Platform admits delegation per named service. */
95
+ serviceName: string;
96
+ serviceToken: string | (() => string);
97
+ fetch?: typeof fetch;
98
+ now?: () => number;
99
+ }
100
+ /** Platform's `verify-by-id` verdict on one key, secret-free. */
101
+ export interface DelegatedKeyVerdict {
102
+ valid: boolean;
103
+ /** Platform's reason when not valid, e.g. `key_revoked`, `budget_exhausted`. */
104
+ invalidReason?: string;
105
+ budgetUsd?: number;
106
+ budgetRemaining?: number;
107
+ expiresAt?: string;
108
+ }
109
+ /**
110
+ * Identifies a key's slot for Platform's service-authenticated `revoke-slot`. Without `name` and `product`,
111
+ * the client reads them from the key itself (`GET /v1/keys/:id`, which an SSO source may call), so a
112
+ * provisioner restarted since the mint can still retire the key. Tax and Legal need `sourceKeyId`; GTM
113
+ * and Builder admit `revoke-slot` only for their protected and preview keys, so their other keys keep
114
+ * the refused DELETE as a typed error.
115
+ */
116
+ export interface DelegatedKeySlotRef {
117
+ userId: string;
118
+ name?: string;
119
+ product?: string;
120
+ sourceKeyId?: string;
121
+ }
122
+ export interface PlatformDelegatedKeyClient {
123
+ delegate(request: DelegatedKeyRequest): Promise<DelegatedKeyOutcome<DelegatedKey>>;
124
+ /** Platform's authoritative verdict (`verify-by-id`), including revoked, expired and spent keys. */
125
+ verify(input: {
126
+ keyId: string;
127
+ product: string;
128
+ }): Promise<DelegatedKeyOutcome<DelegatedKeyVerdict>>;
129
+ /**
130
+ * `DELETE /v1/keys/:id` with the source key; a key already gone counts as revoked. Platform refuses key
131
+ * mutations from a service-provisioned source (an app's SSO key) with 403; given `slot`, the client then
132
+ * retires the slot through `revoke-slot` with the service token.
133
+ */
134
+ revoke(input: {
135
+ sourceKey: string;
136
+ keyId: string;
137
+ slot?: DelegatedKeySlotRef;
138
+ }): Promise<DelegatedKeyOutcome<null>>;
139
+ /** Children of the source key in one slot, from `GET /v1/keys` with the source key. */
140
+ listChildren(input: {
141
+ sourceKey: string;
142
+ name: string;
143
+ product: string;
144
+ }): Promise<DelegatedKeyOutcome<Array<{
145
+ id: string;
146
+ }>>>;
147
+ }
148
+ /**
149
+ * The name Platform stores for a slot: `auto:<service>:<product>:<logical>` for
150
+ * Router and Sandbox keys (Platform's `canonicalProvisionedKeyName`), so the
151
+ * echo can be checked exactly. A name already qualified is kept.
152
+ */
153
+ export declare function canonicalDelegatedKeyName(input: {
154
+ serviceName: string;
155
+ product: string;
156
+ name: string;
157
+ }): string;
158
+ export declare function createPlatformDelegatedKeyClient(options: PlatformDelegatedKeyClientOptions): PlatformDelegatedKeyClient;
159
+ /** The `DurableWorkspaceKeyProvisioner` shape (`./billing`), kept structural so this module stays standalone. */
160
+ export interface DelegatedKeyProvisioner {
161
+ createKey(input: {
162
+ name: string;
163
+ product: string;
164
+ budgetUsd: number;
165
+ expiresAt: string;
166
+ idempotencyKey: string;
167
+ }): Promise<{
168
+ id: string;
169
+ key: string;
170
+ budgetUsd?: number | null;
171
+ expiresAt?: string | null;
172
+ }>;
173
+ getKey(id: string): Promise<{
174
+ budgetUsd?: number | null;
175
+ expiresAt?: string | null;
176
+ }>;
177
+ revokeKey(id: string): Promise<unknown>;
178
+ findCreatedKeys(input: {
179
+ name: string;
180
+ product: string;
181
+ sourceKeyId?: string | null;
182
+ }): Promise<Array<{
183
+ id: string;
184
+ }>>;
185
+ }
186
+ /** A remote key the durable manager must treat as gone (it marks the row revoked and mints again). */
187
+ export declare class DelegatedKeyMissingError extends Error {
188
+ readonly status = 404;
189
+ readonly code = "not_found";
190
+ constructor(keyId: string);
191
+ }
192
+ /** A Platform refusal surfaced to the durable manager. Carries the typed refusal, never a key. */
193
+ export declare class DelegatedKeyRefusalError extends Error {
194
+ readonly refusal: DelegatedKeyRefusal;
195
+ constructor(refusal: DelegatedKeyRefusal);
196
+ }
197
+ /**
198
+ * Plug the client into `createIdentityBoundWorkspaceKeyManager` for a
199
+ * workspace-held key. Pass the manager `nameForIdentity` returning a logical
200
+ * slot name (the client sends Platform's canonical `auto:` form).
201
+ *
202
+ * `getKey` reads Platform's verdict: a key gone for good is reported missing
203
+ * (the manager marks it revoked and mints again); a spent key is reported
204
+ * exhausted (the manager revokes it remotely and mints again); a funding or
205
+ * eligibility refusal is a typed error, so a lapse never retires a key that
206
+ * still works.
207
+ */
208
+ export declare function createDelegatedKeyProvisioner(input: {
209
+ client: PlatformDelegatedKeyClient;
210
+ sourceKey: string;
211
+ product: string;
212
+ resource?: {
213
+ type: string;
214
+ id: string;
215
+ };
216
+ allowedModels?: readonly string[];
217
+ monthlyBudgetUsd?: number;
218
+ rpmLimit?: number;
219
+ expect?: {
220
+ payerId?: string;
221
+ sourceKeyId?: string;
222
+ originAppId?: string | null;
223
+ };
224
+ /** Enables the `revoke-slot` fallback when the source is an app's SSO key (Platform refuses its key mutations). */
225
+ payerId?: string;
226
+ }): DelegatedKeyProvisioner;
@@ -11,3 +11,4 @@ export * from './guards.js';
11
11
  export * from './api-key-auth.js';
12
12
  export * from './agent-keys.js';
13
13
  export * from './agent-spend.js';
14
+ export * from './delegated-keys.js';
@@ -704,9 +704,321 @@ function createPlatformAgentSpend(options) {
704
704
  }
705
705
  };
706
706
  }
707
+
708
+ // src/platform/delegated-keys.ts
709
+ var REQUEST_TIMEOUT_MS2 = 1e4;
710
+ var KEY_PREFIX = "sk-tan-";
711
+ var AUTO_PREFIX = "auto:";
712
+ var PRODUCT_QUALIFIED = /* @__PURE__ */ new Set(["router", "sandbox"]);
713
+ function canonicalDelegatedKeyName(input) {
714
+ const logical = input.name.startsWith(AUTO_PREFIX) ? input.name.slice(AUTO_PREFIX.length) : input.name;
715
+ if (!PRODUCT_QUALIFIED.has(input.product)) return `${AUTO_PREFIX}${logical}`;
716
+ if (logical.startsWith(`${input.serviceName}:${input.product}:`)) return `${AUTO_PREFIX}${logical}`;
717
+ const withoutService = logical.startsWith(`${input.serviceName}:`) ? logical.slice(input.serviceName.length + 1) : logical;
718
+ return `${AUTO_PREFIX}${input.serviceName}:${input.product}:${withoutService}`;
719
+ }
720
+ function refusal2(status, code) {
721
+ if (code === "INSUFFICIENT_BALANCE") {
722
+ return { status: 402, code: "delegated_key.payment_required", message: "The payer's Tangle account has no credit." };
723
+ }
724
+ if (code === "KEY_BUDGET_EXHAUSTED" || code === "KEY_BUDGET_EXCEEDED" || code === "PRODUCT_BUDGET_EXCEEDED") {
725
+ return { status: 402, code: "delegated_key.budget_exhausted", message: "The payer's key has spent the budget it allows." };
726
+ }
727
+ if (code === "EMAIL_VERIFICATION_REQUIRED") {
728
+ return { status: 403, code: "delegated_key.owner_unverified", message: "The payer must verify their Tangle email." };
729
+ }
730
+ if (status >= 500 || status === 429 || code === "PLATFORM_BUSY") {
731
+ return { status: 503, code: "delegated_key.unavailable", message: "Platform could not answer; retry." };
732
+ }
733
+ return { status: 403, code: "delegated_key.refused", message: "Platform refused to delegate this key." };
734
+ }
735
+ var failure = (status, code, message, extra = {}) => ({ succeeded: false, error: { status, code, message, ...extra } });
736
+ var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
737
+ function sameSet(granted, requested) {
738
+ if (!Array.isArray(granted) || granted.some((model) => typeof model !== "string")) return false;
739
+ const a = [...new Set(granted)].sort();
740
+ const b = [...new Set(requested)].sort();
741
+ return granted.length === a.length && a.length === b.length && a.every((model, index) => model === b[index]);
742
+ }
743
+ function childProblem(data, request, name, serviceName, nowMs) {
744
+ const key = data.key;
745
+ const id = data.id;
746
+ if (typeof id !== "string" || !id) return "no key id";
747
+ if (typeof key !== "string" || !key.startsWith(KEY_PREFIX) || key.length <= KEY_PREFIX.length) return "not an sk-tan child key";
748
+ if (key === request.sourceKey) return "the source key itself";
749
+ if (typeof data.prefix === "string" && !key.startsWith(data.prefix)) return "a key that does not match its prefix";
750
+ if (data.name !== name) return "a different name";
751
+ if (data.product !== request.product) return "a different product";
752
+ if (data.provisionedByService !== serviceName) return "a different provisioner";
753
+ if (data.scopes !== null && !(Array.isArray(data.scopes) && data.scopes.length === 0)) return "control-plane scopes";
754
+ if (request.allowedModels && !sameSet(data.allowedModels, request.allowedModels)) return "a different model set";
755
+ const budget = request.budget;
756
+ if (budget && "usd" in budget && !(typeof data.budgetUsd === "number" && data.budgetUsd <= budget.usd)) return "a budget larger than requested";
757
+ if (budget?.monthlyUsd !== void 0 && !(typeof data.monthlyBudgetUsd === "number" && data.monthlyBudgetUsd <= budget.monthlyUsd)) {
758
+ return "a monthly budget larger than requested";
759
+ }
760
+ const attribution = record2(data.attribution);
761
+ if (!attribution) return "no attribution";
762
+ if (attribution.version !== 1 || attribution.targetService !== request.product) return "attribution for another target";
763
+ if (request.expect?.originAppId !== void 0 && (attribution.originAppId ?? null) !== request.expect.originAppId) {
764
+ return "attribution from another app";
765
+ }
766
+ const parent = attribution.delegatedFromKeyId;
767
+ if (typeof parent !== "string" || !parent || parent === id) return "attribution without its parent key";
768
+ if (request.expect?.sourceKeyId !== void 0 && parent !== request.expect.sourceKeyId) return "attribution for another source key";
769
+ if (attribution.payerType !== "user") return "attribution to a non-user payer";
770
+ if (request.expect?.payerId !== void 0 && attribution.payerId !== request.expect.payerId) return "attribution to another payer";
771
+ if ((attribution.resourceType ?? null) !== (request.resource?.type ?? null) || (attribution.resourceId ?? null) !== (request.resource?.id ?? null)) {
772
+ return "attribution for another resource";
773
+ }
774
+ const expiresAt = typeof attribution.expiresAt === "string" ? Date.parse(attribution.expiresAt) : NaN;
775
+ if (!Number.isFinite(expiresAt) || expiresAt <= nowMs || expiresAt > request.expiresAt.getTime()) return "an expiry in the past or past the request";
776
+ return null;
777
+ }
778
+ function createPlatformDelegatedKeyClient(options) {
779
+ const fetchImpl = options.fetch ?? fetch;
780
+ const now = options.now ?? Date.now;
781
+ const base = options.platformUrl.replace(/\/+$/, "");
782
+ const serviceToken = () => typeof options.serviceToken === "function" ? options.serviceToken() : options.serviceToken;
783
+ async function call(path, init) {
784
+ try {
785
+ const response = await fetchImpl(`${base}${path}`, {
786
+ method: init.method,
787
+ headers: {
788
+ authorization: `Bearer ${init.bearer}`,
789
+ ...init.service ? { "x-service-name": options.serviceName } : {},
790
+ ...init.body === void 0 ? {} : { "content-type": "application/json" }
791
+ },
792
+ ...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
793
+ redirect: "manual",
794
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
795
+ });
796
+ return { status: response.status, body: record2(await response.json().catch(() => null)) };
797
+ } catch {
798
+ return null;
799
+ }
800
+ }
801
+ const client = {
802
+ async delegate(request) {
803
+ if (!request.sourceKey.startsWith(KEY_PREFIX)) return failure(400, "delegated_key.invalid_request", "The source must be a linked sk-tan- key.");
804
+ if (request.expiresAt.getTime() <= now()) return failure(400, "delegated_key.invalid_request", "The expiry must be in the future.");
805
+ const name = canonicalDelegatedKeyName({ serviceName: options.serviceName, product: request.product, name: request.name });
806
+ const budget = request.budget;
807
+ const result = await call("/v1/keys/delegate", {
808
+ method: "POST",
809
+ bearer: serviceToken(),
810
+ service: true,
811
+ body: {
812
+ sourceKey: request.sourceKey,
813
+ name,
814
+ product: request.product,
815
+ ...request.resource ? { resourceType: request.resource.type, resourceId: request.resource.id } : {},
816
+ ...budget && "usd" in budget ? { budgetUsd: budget.usd } : {},
817
+ ...budget && "spendThrough" in budget ? { spendThrough: true } : {},
818
+ ...budget?.monthlyUsd !== void 0 ? { monthlyBudgetUsd: budget.monthlyUsd } : {},
819
+ ...request.allowedModels ? { allowedModels: [...new Set(request.allowedModels)] } : {},
820
+ ...request.rpmLimit !== void 0 ? { rpmLimit: request.rpmLimit } : {},
821
+ // Omitted, Platform copies the source's scopes onto the child; a product key carries none.
822
+ scopes: [],
823
+ expiresAt: request.expiresAt.toISOString()
824
+ }
825
+ });
826
+ if (!result) return { succeeded: false, error: refusal2(503, null) };
827
+ const data = record2(result.body?.data);
828
+ if (result.status !== 201 || result.body?.success !== true || !data) {
829
+ return { succeeded: false, error: refusal2(result.status, record2(result.body?.error)?.code) };
830
+ }
831
+ const problem = childProblem(data, request, name, options.serviceName, now());
832
+ if (problem) {
833
+ const id = typeof data.id === "string" && data.id ? data.id : null;
834
+ const owner = request.expect?.payerId ? {
835
+ userId: request.expect.payerId,
836
+ name,
837
+ product: request.product,
838
+ ...request.expect.sourceKeyId ? { sourceKeyId: request.expect.sourceKeyId } : {}
839
+ } : void 0;
840
+ const revoked = id ? await client.revoke({ sourceKey: request.sourceKey, keyId: id, ...owner ? { slot: owner } : {} }) : null;
841
+ return failure(
842
+ 502,
843
+ "delegated_key.response_invalid",
844
+ `Platform returned ${problem}.`,
845
+ id && !revoked?.succeeded ? { unrevokedKeyId: id } : {}
846
+ );
847
+ }
848
+ const attribution = record2(data.attribution);
849
+ return { succeeded: true, value: {
850
+ key: data.key,
851
+ id: data.id,
852
+ name,
853
+ product: request.product,
854
+ expiresAt: new Date(attribution.expiresAt),
855
+ allowedModels: request.allowedModels ? [...new Set(request.allowedModels)] : null,
856
+ budgetUsd: typeof data.budgetUsd === "number" ? data.budgetUsd : null
857
+ } };
858
+ },
859
+ async verify({ keyId, product }) {
860
+ const result = await call("/v1/keys/verify-by-id", {
861
+ method: "POST",
862
+ bearer: serviceToken(),
863
+ service: true,
864
+ body: { keyId, expectedProduct: product }
865
+ });
866
+ if (!result || result.status >= 500 || result.status === 429) return { succeeded: false, error: refusal2(503, null) };
867
+ const body2 = result.body;
868
+ if (result.status !== 200 || typeof body2?.valid !== "boolean" || body2.valid && body2.keyId !== keyId) {
869
+ return failure(502, "delegated_key.response_invalid", "Platform returned no verification verdict for this key.");
870
+ }
871
+ const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
872
+ return { succeeded: true, value: {
873
+ valid: body2.valid,
874
+ ...typeof body2.invalidReason === "string" ? { invalidReason: body2.invalidReason } : {},
875
+ ...number(body2.budgetUsd) !== void 0 ? { budgetUsd: number(body2.budgetUsd) } : {},
876
+ ...number(body2.budgetRemaining) !== void 0 ? { budgetRemaining: number(body2.budgetRemaining) } : {},
877
+ ...typeof body2.expiresAt === "string" ? { expiresAt: body2.expiresAt } : {}
878
+ } };
879
+ },
880
+ async revoke({ sourceKey, keyId, slot }) {
881
+ const result = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: "DELETE", bearer: sourceKey, service: false });
882
+ if (!result) return { succeeded: false, error: refusal2(503, null) };
883
+ if (result.status === 404 || result.status >= 200 && result.status < 300 && result.body?.success === true) {
884
+ return { succeeded: true, value: null };
885
+ }
886
+ if (result.status === 403 && slot) {
887
+ let name = slot.name;
888
+ let product = slot.product;
889
+ if (!name || !product) {
890
+ const row = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: "GET", bearer: sourceKey, service: false });
891
+ const data = record2(row?.body?.data);
892
+ if (row?.status === 404) return { succeeded: true, value: null };
893
+ if (!row || row.status !== 200 || typeof data?.name !== "string" || typeof data.product !== "string") {
894
+ return { succeeded: false, error: refusal2(row?.status ?? 503, null) };
895
+ }
896
+ if (data.revokedAt) return { succeeded: true, value: null };
897
+ name = data.name;
898
+ product = data.product;
899
+ }
900
+ const retired = await call("/v1/keys/auto-provisioned/revoke-slot", {
901
+ method: "POST",
902
+ bearer: serviceToken(),
903
+ service: true,
904
+ body: {
905
+ userId: slot.userId,
906
+ name,
907
+ product,
908
+ childKeyId: keyId,
909
+ ...slot.sourceKeyId ? { sourceKeyId: slot.sourceKeyId } : {}
910
+ }
911
+ });
912
+ if (!retired) return { succeeded: false, error: refusal2(503, null) };
913
+ if (retired.status >= 200 && retired.status < 300 && retired.body?.success === true) return { succeeded: true, value: null };
914
+ return { succeeded: false, error: refusal2(retired.status, record2(retired.body?.error)?.code) };
915
+ }
916
+ return { succeeded: false, error: refusal2(result.status, record2(result.body?.error)?.code) };
917
+ },
918
+ async listChildren({ sourceKey, name, product }) {
919
+ const canonical = canonicalDelegatedKeyName({ serviceName: options.serviceName, product, name });
920
+ const result = await call("/v1/keys", { method: "GET", bearer: sourceKey, service: false });
921
+ if (!result) return { succeeded: false, error: refusal2(503, null) };
922
+ const rows = result.body?.data;
923
+ if (result.status !== 200 || result.body?.success !== true || !Array.isArray(rows)) {
924
+ return { succeeded: false, error: refusal2(result.status, record2(result.body?.error)?.code) };
925
+ }
926
+ return { succeeded: true, value: rows.flatMap((row) => {
927
+ const value = record2(row);
928
+ return value && typeof value.id === "string" && value.name === canonical && value.product === product && !value.revokedAt ? [{ id: value.id }] : [];
929
+ }) };
930
+ }
931
+ };
932
+ return client;
933
+ }
934
+ var DelegatedKeyMissingError = class extends Error {
935
+ status = 404;
936
+ code = "not_found";
937
+ constructor(keyId) {
938
+ super(`Platform no longer accepts key ${keyId}`);
939
+ this.name = "DelegatedKeyMissingError";
940
+ }
941
+ };
942
+ var DelegatedKeyRefusalError = class extends Error {
943
+ constructor(refusal3) {
944
+ super(refusal3.message);
945
+ this.refusal = refusal3;
946
+ this.name = "DelegatedKeyRefusalError";
947
+ }
948
+ refusal;
949
+ };
950
+ var GONE_REASONS = /* @__PURE__ */ new Set([
951
+ "key_not_found",
952
+ "key_revoked",
953
+ "key_expired",
954
+ "key_lineage_revoked",
955
+ "parent_key_not_found",
956
+ "parent_key_revoked",
957
+ "parent_key_expired",
958
+ "parent_key_lineage_revoked",
959
+ "ancestor_key_not_found",
960
+ "ancestor_key_revoked",
961
+ "ancestor_key_expired",
962
+ "ancestor_key_lineage_revoked"
963
+ ]);
964
+ var SPENT_REASONS = /* @__PURE__ */ new Set(["budget_exhausted", "monthly_budget_exhausted"]);
965
+ function createDelegatedKeyProvisioner(input) {
966
+ const product = input.product;
967
+ const slotOwner = input.payerId ? { userId: input.payerId, ...input.expect?.sourceKeyId ? { sourceKeyId: input.expect.sourceKeyId } : {} } : void 0;
968
+ return {
969
+ async createKey(create) {
970
+ const minted = await input.client.delegate({
971
+ sourceKey: input.sourceKey,
972
+ name: create.name,
973
+ product,
974
+ ...input.resource ? { resource: input.resource } : {},
975
+ ...input.allowedModels ? { allowedModels: input.allowedModels } : {},
976
+ budget: { usd: create.budgetUsd, ...input.monthlyBudgetUsd !== void 0 ? { monthlyUsd: input.monthlyBudgetUsd } : {} },
977
+ ...input.rpmLimit !== void 0 ? { rpmLimit: input.rpmLimit } : {},
978
+ expiresAt: new Date(create.expiresAt),
979
+ ...input.expect ? { expect: input.expect } : {}
980
+ });
981
+ if (!minted.succeeded) throw new DelegatedKeyRefusalError(minted.error);
982
+ return { id: minted.value.id, key: minted.value.key, budgetUsd: minted.value.budgetUsd, expiresAt: minted.value.expiresAt.toISOString() };
983
+ },
984
+ async getKey(id) {
985
+ const verdict = await input.client.verify({ keyId: id, product });
986
+ if (!verdict.succeeded) throw new DelegatedKeyRefusalError(verdict.error);
987
+ const v = verdict.value;
988
+ if (v.valid) {
989
+ return {
990
+ ...v.budgetUsd !== void 0 ? { budgetUsd: v.budgetUsd } : {},
991
+ ...v.budgetUsd !== void 0 && v.budgetRemaining !== void 0 ? { budgetSpent: Math.max(0, v.budgetUsd - v.budgetRemaining) } : {},
992
+ ...v.expiresAt ? { expiresAt: v.expiresAt } : {}
993
+ };
994
+ }
995
+ if (v.invalidReason && GONE_REASONS.has(v.invalidReason)) throw new DelegatedKeyMissingError(id);
996
+ if (v.invalidReason && SPENT_REASONS.has(v.invalidReason)) {
997
+ return { budgetUsd: v.budgetUsd ?? 0, budgetSpent: v.budgetUsd ?? 0, ...v.expiresAt ? { expiresAt: v.expiresAt } : {} };
998
+ }
999
+ throw new DelegatedKeyRefusalError({
1000
+ status: 403,
1001
+ code: "delegated_key.refused",
1002
+ message: `Platform refused the key for now (${v.invalidReason ?? "no reason"}).`
1003
+ });
1004
+ },
1005
+ async revokeKey(id) {
1006
+ const revoked = await input.client.revoke({ sourceKey: input.sourceKey, keyId: id, ...slotOwner ? { slot: slotOwner } : {} });
1007
+ if (!revoked.succeeded) throw new DelegatedKeyRefusalError(revoked.error);
1008
+ return null;
1009
+ },
1010
+ async findCreatedKeys(find) {
1011
+ const listed = await input.client.listChildren({ sourceKey: input.sourceKey, name: find.name, product: find.product });
1012
+ if (!listed.succeeded) throw new DelegatedKeyRefusalError(listed.error);
1013
+ return listed.value;
1014
+ }
1015
+ };
1016
+ }
707
1017
  export {
708
1018
  DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR,
709
1019
  DEFAULT_TANGLE_TIER_POLICY,
1020
+ DelegatedKeyMissingError,
1021
+ DelegatedKeyRefusalError,
710
1022
  FREE_TIER_SPEND_CAP_USD,
711
1023
  PLATFORM_AGENT_KEY_PROVISIONER,
712
1024
  PLATFORM_KEY_PREFIX,
@@ -717,15 +1029,18 @@ export {
717
1029
  TangleSsoUserCreateError,
718
1030
  agentOperatorScopes,
719
1031
  assertBillableBalance,
1032
+ canonicalDelegatedKeyName,
720
1033
  createAdminGuard,
721
1034
  createApiKeyRequestAuth,
722
1035
  createAuthGuard,
723
1036
  createBetterAuthSessionCookieMinter,
724
1037
  createD1TangleIdentityStore,
1038
+ createDelegatedKeyProvisioner,
725
1039
  createHubSettingsRoutes,
726
1040
  createPlatformAgentKeyVerifier,
727
1041
  createPlatformAgentSpend,
728
1042
  createPlatformBillingHttp,
1043
+ createPlatformDelegatedKeyClient,
729
1044
  createSignedSsoState,
730
1045
  createTanglePlatformBillingClient,
731
1046
  createTangleSsoHandlers,