@tangle-network/agent-app 0.60.59 → 0.60.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +2 -2
- package/dist/brand-extraction/index.js +89 -2
- package/dist/brand-extraction/index.js.map +1 -1
- package/dist/chat-react/index.js +1 -1
- package/dist/chat-routes/index.js +2 -2
- package/dist/chat-routes/turn-routes.d.ts +9 -0
- package/dist/{chunk-6LPQRKH7.js → chunk-4WJREKXX.js} +222 -190
- package/dist/chunk-4WJREKXX.js.map +1 -0
- package/dist/{chunk-CZ7KLS7N.js → chunk-FWLCPAST.js} +10 -1
- package/dist/chunk-FWLCPAST.js.map +1 -0
- package/dist/{chunk-EQ6CGOZK.js → chunk-GNA5I5NM.js} +3 -1
- package/dist/chunk-GNA5I5NM.js.map +1 -0
- package/dist/{chunk-WMCROSA4.js → chunk-TZD35SBQ.js} +82 -1
- package/dist/chunk-TZD35SBQ.js.map +1 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +155 -5
- package/dist/platform/index.js.map +1 -1
- package/dist/platform/sso-identity-store.d.ts +69 -0
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/public-consultation/index.js +1 -1
- package/dist/sandbox/index.d.ts +1 -0
- package/dist/sandbox/index.js +5 -1
- package/dist/sandbox/prewarm-route.d.ts +100 -0
- package/dist/turn-stream/adapters.d.ts +17 -0
- package/dist/turn-stream/core.d.ts +2 -0
- package/dist/turn-stream/index.js +16 -0
- package/dist/turn-stream/index.js.map +1 -1
- package/dist/web-react/chat-composer.d.ts +5 -1
- package/dist/web-react/command-palette.d.ts +6 -3
- package/dist/web-react/index.d.ts +1 -0
- package/dist/web-react/index.js +6 -2
- package/dist/web-react/workspace-prewarm.d.ts +36 -0
- package/package.json +1 -1
- package/dist/chunk-6LPQRKH7.js.map +0 -1
- package/dist/chunk-CZ7KLS7N.js.map +0 -1
- package/dist/chunk-EQ6CGOZK.js.map +0 -1
- package/dist/chunk-WMCROSA4.js.map +0 -1
package/dist/platform/index.d.ts
CHANGED
package/dist/platform/index.js
CHANGED
|
@@ -32,6 +32,153 @@ import {
|
|
|
32
32
|
} from "../chunk-3NCPXNBZ.js";
|
|
33
33
|
import "../chunk-TXD5HXLE.js";
|
|
34
34
|
|
|
35
|
+
// src/platform/sso-identity-store.ts
|
|
36
|
+
var TANGLE_IDENTITY_PROVIDER_ID = "tangle";
|
|
37
|
+
var TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL = [
|
|
38
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_platform_user ON account(accountId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`,
|
|
39
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_user ON account(userId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`
|
|
40
|
+
];
|
|
41
|
+
var SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
42
|
+
function identifier(value, field) {
|
|
43
|
+
if (!SQL_IDENTIFIER.test(value)) throw new Error(`createD1TangleIdentityStore: invalid ${field}`);
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
function randomToken() {
|
|
47
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
48
|
+
}
|
|
49
|
+
function createD1TangleIdentityStore(options) {
|
|
50
|
+
const { db, linkingUserId } = options;
|
|
51
|
+
const provider = TANGLE_IDENTITY_PROVIDER_ID;
|
|
52
|
+
const legacy = options.legacyLinkTable && {
|
|
53
|
+
table: identifier(options.legacyLinkTable.table, "legacyLinkTable.table"),
|
|
54
|
+
userId: identifier(options.legacyLinkTable.userIdColumn, "legacyLinkTable.userIdColumn"),
|
|
55
|
+
platformUserId: identifier(options.legacyLinkTable.platformUserIdColumn, "legacyLinkTable.platformUserIdColumn")
|
|
56
|
+
};
|
|
57
|
+
const selectAccount = `SELECT u.id AS userId, u.email AS email, u.emailVerified AS emailVerified,
|
|
58
|
+
a.accountId AS accountPlatformUserId,
|
|
59
|
+
${legacy ? `l.${legacy.platformUserId}` : "NULL"} AS legacyPlatformUserId
|
|
60
|
+
FROM user u
|
|
61
|
+
LEFT JOIN account a ON a.userId = u.id AND a.providerId = '${provider}'
|
|
62
|
+
${legacy ? `LEFT JOIN ${legacy.table} l ON l.${legacy.userId} = u.id` : ""}`;
|
|
63
|
+
function toCandidate(row) {
|
|
64
|
+
const fromAccount = row.accountPlatformUserId?.trim() || null;
|
|
65
|
+
const fromLegacy = row.legacyPlatformUserId?.trim() || null;
|
|
66
|
+
return {
|
|
67
|
+
userId: row.userId,
|
|
68
|
+
email: row.email,
|
|
69
|
+
emailVerified: row.emailVerified === 1 || row.emailVerified === true,
|
|
70
|
+
platformUserId: fromAccount ?? fromLegacy,
|
|
71
|
+
divergent: Boolean(fromAccount && fromLegacy && fromAccount !== fromLegacy)
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
async function candidates(email, platformUserId) {
|
|
75
|
+
const where = legacy ? `WHERE lower(trim(u.email)) = ? OR a.accountId = ? OR l.${legacy.platformUserId} = ?` : "WHERE lower(trim(u.email)) = ? OR a.accountId = ?";
|
|
76
|
+
const values = legacy ? [email, platformUserId, platformUserId] : [email, platformUserId];
|
|
77
|
+
const { results } = await db.prepare(`${selectAccount} ${where}`).bind(...values).all();
|
|
78
|
+
const rows = results.map(toCandidate);
|
|
79
|
+
return {
|
|
80
|
+
divergent: rows.some((row) => row.divergent),
|
|
81
|
+
platformMatches: rows.filter((row) => row.platformUserId === platformUserId),
|
|
82
|
+
emailMatches: rows.filter((row) => normalizeTangleSsoEmail(row.email) === email)
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const store = {
|
|
86
|
+
async resolveAccount({ email, platformUserId }) {
|
|
87
|
+
const normalizedEmail = normalizeTangleSsoEmail(email);
|
|
88
|
+
const stableId = platformUserId.trim();
|
|
89
|
+
const found = await candidates(normalizedEmail, stableId);
|
|
90
|
+
if (found.divergent) return { kind: "reject", reason: "platform-id-email-conflict" };
|
|
91
|
+
if (!linkingUserId) {
|
|
92
|
+
return resolveTangleSsoAccount({
|
|
93
|
+
email: normalizedEmail,
|
|
94
|
+
platformUserId: stableId,
|
|
95
|
+
platformMatches: found.platformMatches,
|
|
96
|
+
emailMatches: found.emailMatches
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const ownRow = await db.prepare(`${selectAccount} WHERE u.id = ?`).bind(linkingUserId).first();
|
|
100
|
+
if (!ownRow) return { kind: "reject", reason: "email-match-mismatch" };
|
|
101
|
+
const own = toCandidate(ownRow);
|
|
102
|
+
if (own.divergent) return { kind: "reject", reason: "platform-id-email-conflict" };
|
|
103
|
+
if (own.platformUserId && own.platformUserId !== stableId) {
|
|
104
|
+
return { kind: "reject", reason: "email-platform-id-conflict" };
|
|
105
|
+
}
|
|
106
|
+
if (found.platformMatches.some((row) => row.userId !== linkingUserId) || found.emailMatches.some((row) => row.userId !== linkingUserId)) {
|
|
107
|
+
return { kind: "reject", reason: "platform-id-email-conflict" };
|
|
108
|
+
}
|
|
109
|
+
return { kind: "existing", userId: linkingUserId, matchedBy: "platform-id" };
|
|
110
|
+
},
|
|
111
|
+
async upsertUserByEmail({ email, name, tangleUserId, resolution }) {
|
|
112
|
+
const normalizedEmail = normalizeTangleSsoEmail(email);
|
|
113
|
+
const platformUserId = tangleUserId.trim();
|
|
114
|
+
const current = await store.resolveAccount({ email: normalizedEmail, platformUserId });
|
|
115
|
+
if (current.kind === "reject") throw new TangleSsoAccountConflictError(current.reason);
|
|
116
|
+
if (current.kind === "existing") {
|
|
117
|
+
if (resolution.kind === "existing" && resolution.userId !== current.userId) {
|
|
118
|
+
throw new TangleSsoAccountConflictError("platform-id-email-conflict");
|
|
119
|
+
}
|
|
120
|
+
return { userId: current.userId };
|
|
121
|
+
}
|
|
122
|
+
if (resolution.kind !== "create") throw new TangleSsoUserCreateError("The selected account changed");
|
|
123
|
+
const userId = crypto.randomUUID();
|
|
124
|
+
try {
|
|
125
|
+
await db.prepare(`INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt)
|
|
126
|
+
VALUES (?, ?, ?, 1, unixepoch(), unixepoch())`).bind(userId, name || normalizedEmail, normalizedEmail).run();
|
|
127
|
+
} catch {
|
|
128
|
+
const after = await store.resolveAccount({ email: normalizedEmail, platformUserId });
|
|
129
|
+
if (after.kind === "reject") throw new TangleSsoAccountConflictError(after.reason);
|
|
130
|
+
if (after.kind === "existing") return { userId: after.userId };
|
|
131
|
+
throw new TangleSsoUserCreateError();
|
|
132
|
+
}
|
|
133
|
+
return { userId };
|
|
134
|
+
},
|
|
135
|
+
async createSession({ userId, expiresAt, ipAddress, userAgent }) {
|
|
136
|
+
const token = randomToken();
|
|
137
|
+
await db.prepare(`INSERT INTO session (id, userId, token, expiresAt, ipAddress, userAgent, createdAt, updatedAt)
|
|
138
|
+
VALUES (?, ?, ?, ?, ?, ?, unixepoch(), unixepoch())`).bind(crypto.randomUUID(), userId, token, Math.floor(expiresAt.getTime() / 1e3), ipAddress, userAgent).run();
|
|
139
|
+
return { token };
|
|
140
|
+
},
|
|
141
|
+
async saveTangleLink({ userId, sessionToken, tangleUserId, email }) {
|
|
142
|
+
const platformUserId = tangleUserId.trim();
|
|
143
|
+
const normalizedEmail = normalizeTangleSsoEmail(email);
|
|
144
|
+
const session = await db.prepare("SELECT userId FROM session WHERE token = ? AND expiresAt > unixepoch()").bind(sessionToken).first();
|
|
145
|
+
if (session?.userId !== userId) throw new TangleSsoAccountConflictError("email-platform-id-conflict");
|
|
146
|
+
const current = await store.resolveAccount({ email: normalizedEmail, platformUserId });
|
|
147
|
+
if (current.kind === "reject") throw new TangleSsoAccountConflictError(current.reason);
|
|
148
|
+
if (current.kind !== "existing" || current.userId !== userId) {
|
|
149
|
+
throw new TangleSsoAccountConflictError("platform-id-email-conflict");
|
|
150
|
+
}
|
|
151
|
+
const liveSession = "EXISTS (SELECT 1 FROM session WHERE token = ? AND userId = ? AND expiresAt > unixepoch())";
|
|
152
|
+
const emailFree = "NOT EXISTS (SELECT 1 FROM user WHERE lower(trim(email)) = ? AND id <> ?)";
|
|
153
|
+
const linked = `EXISTS (SELECT 1 FROM account WHERE providerId = '${provider}' AND userId = ? AND accountId = ?)`;
|
|
154
|
+
const statements = [
|
|
155
|
+
db.prepare(`INSERT INTO account (id, userId, accountId, providerId, createdAt, updatedAt)
|
|
156
|
+
SELECT ?, ?, ?, '${provider}', unixepoch(), unixepoch()
|
|
157
|
+
WHERE EXISTS (SELECT 1 FROM user WHERE id = ?) AND ${liveSession} AND ${emailFree}
|
|
158
|
+
ON CONFLICT DO NOTHING`).bind(crypto.randomUUID(), userId, platformUserId, userId, sessionToken, userId, normalizedEmail, userId)
|
|
159
|
+
];
|
|
160
|
+
if (legacy) {
|
|
161
|
+
statements.push(db.prepare(`INSERT INTO ${legacy.table} (${legacy.userId}, ${legacy.platformUserId})
|
|
162
|
+
SELECT ?, ? WHERE ${linked}
|
|
163
|
+
ON CONFLICT DO NOTHING`).bind(userId, platformUserId, userId, platformUserId));
|
|
164
|
+
}
|
|
165
|
+
statements.push(db.prepare(`UPDATE user SET emailVerified = CASE WHEN lower(trim(email)) = ? THEN 1 ELSE emailVerified END,
|
|
166
|
+
updatedAt = unixepoch()
|
|
167
|
+
WHERE id = ? AND ${liveSession} AND ${linked} AND ${emailFree}`).bind(normalizedEmail, userId, sessionToken, userId, userId, platformUserId, normalizedEmail, userId));
|
|
168
|
+
const results = await db.batch(statements);
|
|
169
|
+
if (results[results.length - 1]?.meta?.changes !== 1) {
|
|
170
|
+
throw new TangleSsoAccountConflictError("email-platform-id-conflict");
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
// `saveTangleLink` is one atomic batch, so a rejected call wrote nothing;
|
|
174
|
+
// removing the unpublished session is the whole cleanup.
|
|
175
|
+
async deleteSession({ sessionToken }) {
|
|
176
|
+
await db.prepare("DELETE FROM session WHERE token = ?").bind(sessionToken).run();
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
return store;
|
|
180
|
+
}
|
|
181
|
+
|
|
35
182
|
// src/platform/hub-connect-callback.ts
|
|
36
183
|
var HUB_CONNECT_CALLBACK_PARAMS = ["provider", "nonce", "context"];
|
|
37
184
|
function isHubConnectCallbackUrl(returnUrl, callbackPath, provider) {
|
|
@@ -61,7 +208,7 @@ function text(value, max = 256) {
|
|
|
61
208
|
if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) invalid();
|
|
62
209
|
return value;
|
|
63
210
|
}
|
|
64
|
-
function
|
|
211
|
+
function identifier2(value) {
|
|
65
212
|
const id = text(value, 128);
|
|
66
213
|
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid();
|
|
67
214
|
return id;
|
|
@@ -101,7 +248,7 @@ function oauthInput(body2, url, provider, callbackPath) {
|
|
|
101
248
|
const parameters = record(body2.connectionParameters);
|
|
102
249
|
if (Object.keys(parameters).length > 20) invalid();
|
|
103
250
|
input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {
|
|
104
|
-
|
|
251
|
+
identifier2(key);
|
|
105
252
|
if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, "").toLowerCase())) invalid();
|
|
106
253
|
return [key, text(value, 1024)];
|
|
107
254
|
}));
|
|
@@ -178,20 +325,20 @@ async function prepare(request, basePath, callbackPath) {
|
|
|
178
325
|
if (route.kind === "providers") return { intent: { operation: "providers.list", target: "caller-account" }, call: (hub) => hub.connections.providers() };
|
|
179
326
|
if (route.kind === "connections") return { intent: { operation: "connections.list", target: "caller-account" }, call: (hub) => hub.connections.list() };
|
|
180
327
|
if (isPolicyRead) {
|
|
181
|
-
const connectionId =
|
|
328
|
+
const connectionId = identifier2(url.searchParams.get("connectionId"));
|
|
182
329
|
return { intent: { operation: "policies.list", connectionId }, call: (hub) => hub.permissions.list(connectionId) };
|
|
183
330
|
}
|
|
184
331
|
if (route.kind === "policies") {
|
|
185
332
|
const input = await body(request);
|
|
186
333
|
onlyKeys(input, request.method === "PUT" ? ["connectionId", "actionPath", "decision"] : ["connectionId", "actionPath"]);
|
|
187
|
-
const connectionId =
|
|
334
|
+
const connectionId = identifier2(input.connectionId);
|
|
188
335
|
const actionPath = action(input.actionPath);
|
|
189
336
|
if (request.method === "DELETE") return { intent: { operation: "policy.reset", connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) };
|
|
190
337
|
const decision = input.decision;
|
|
191
338
|
if (decision !== "allow" && decision !== "ask" && decision !== "deny") invalid();
|
|
192
339
|
return { intent: { operation: "policy.set", connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) };
|
|
193
340
|
}
|
|
194
|
-
const id =
|
|
341
|
+
const id = identifier2(target);
|
|
195
342
|
if (isActions) {
|
|
196
343
|
const search = url.searchParams.get("query") ?? "";
|
|
197
344
|
if (search.length > 512 || /[\u0000-\u001f\u007f]/.test(search)) invalid();
|
|
@@ -564,6 +711,8 @@ export {
|
|
|
564
711
|
PLATFORM_AGENT_KEY_PROVISIONER,
|
|
565
712
|
PLATFORM_KEY_PREFIX,
|
|
566
713
|
PlatformBillingHttpError,
|
|
714
|
+
TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL,
|
|
715
|
+
TANGLE_IDENTITY_PROVIDER_ID,
|
|
567
716
|
TangleSsoAccountConflictError,
|
|
568
717
|
TangleSsoUserCreateError,
|
|
569
718
|
agentOperatorScopes,
|
|
@@ -572,6 +721,7 @@ export {
|
|
|
572
721
|
createApiKeyRequestAuth,
|
|
573
722
|
createAuthGuard,
|
|
574
723
|
createBetterAuthSessionCookieMinter,
|
|
724
|
+
createD1TangleIdentityStore,
|
|
575
725
|
createHubSettingsRoutes,
|
|
576
726
|
createPlatformAgentKeyVerifier,
|
|
577
727
|
createPlatformAgentSpend,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/agent-spend.ts"],"sourcesContent":["/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. */\n serviceToken: string | (() => string)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n","/**\n * Bill work an agent app runs for a Platform agent key to that key's one cap.\n *\n * An owner approves an agent key with one lifetime cap shared across every\n * product. Work the app runs for the key must spend that cap, even when the\n * owner already has their own credential in the app:\n *\n * - Model calls: `modelKey` delegates a Router key from the agent key that\n * spends its cap directly (\"spend-through\"). Router refuses every call once\n * the cap is spent, so a turn cannot run past it.\n * - Work the app cannot route through the key, such as compute in a sandbox\n * the owner's own credential pays for: `hold` reserves the work's maximum\n * against the cap before it starts, and `consume` spends what it measured,\n * up to the hold, without charging the owner's wallet again.\n *\n * A spent or insufficient cap answers 402 `agent_key.budget_exhausted`, so an\n * app refuses the work before it starts. Web-standard fetch only.\n */\n\nexport interface AgentSpendRefusal {\n status: 402 | 403 | 503\n code: string\n message: string\n}\n\nexport type AgentSpendOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: AgentSpendRefusal }\n\nexport interface PlatformAgentSpendOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name. */\n serviceName: string\n serviceToken: string | (() => string)\n /** The Platform product this app bills, e.g. `gtm-agent`. */\n product: string\n fetch?: typeof fetch\n}\n\nexport interface PlatformAgentSpend {\n /**\n * A Router key whose charges spend the agent key's cap. `name` must start\n * `auto:`; give each piece of work its own.\n */\n modelKey(input: { agentKey: string; name: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ key: string; keyId: string | null }>>\n /** Reserve up to `amountUsd` of the agent key's cap for work billed elsewhere. */\n hold(input: { keyId: string; amountUsd: number; referenceId: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ authorizationId: string }>>\n /** Spend what the work measured, at most the hold. A retry repeats the amount. */\n consume(input: { authorizationId: string; amountUsd: number }): Promise<AgentSpendOutcome<{ consumedUsd: number }>>\n /** Return a hold whose work never ran. */\n release(authorizationId: string): Promise<AgentSpendOutcome<null>>\n}\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nconst budgetExhausted: AgentSpendRefusal = {\n status: 402,\n code: 'agent_key.budget_exhausted',\n message: 'The key has spent, or cannot cover, the cap its owner approved.',\n}\n\nfunction refusal(status: number, code: unknown): AgentSpendRefusal {\n if (code === 'KEY_BUDGET_EXHAUSTED' || code === 'KEY_BUDGET_EXCEEDED' || code === 'PRODUCT_BUDGET_EXCEEDED') return budgetExhausted\n if (code === 'INSUFFICIENT_BALANCE') {\n return { status: 402, code: 'agent_key.payment_required', message: \"The key owner's Tangle account has no credit.\" }\n }\n if (code === 'EMAIL_VERIFICATION_REQUIRED') {\n return { status: 403, code: 'agent_key.owner_unverified', message: 'The key owner must verify their Tangle email.' }\n }\n if (status >= 500 || status === 429 || code === 'PLATFORM_BUSY') {\n return { status: 503, code: 'agent_key.spend_unavailable', message: 'Platform could not record the spend; retry.' }\n }\n return { status: 403, code: 'agent_key.spend_refused', message: 'Platform refused to bill this work to the key.' }\n}\n\ninterface PlatformBody {\n success?: unknown\n data?: { key?: unknown; id?: unknown; consumedAmount?: unknown }\n error?: { code?: unknown }\n}\n\nexport function createPlatformAgentSpend(options: PlatformAgentSpendOptions): PlatformAgentSpend {\n const fetchImpl = options.fetch ?? fetch\n const base = options.platformUrl.replace(/\\/+$/, '')\n\n async function call(path: string, body: unknown): Promise<{ status: number; body: PlatformBody } | null> {\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n try {\n const response = await fetchImpl(`${base}${path}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n return { status: response.status, body: (await response.json().catch(() => ({}))) as PlatformBody }\n } catch {\n return null\n }\n }\n\n const unavailable = (): { succeeded: false; error: AgentSpendRefusal } => ({ succeeded: false, error: refusal(503, null) })\n\n return {\n async modelKey({ agentKey, name, expiresAt }) {\n const result = await call('/v1/keys/delegate', {\n sourceKey: agentKey, name, product: 'router', spendThrough: true, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const key = result.body.data?.key\n if (result.status !== 201 || typeof key !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n const keyId = result.body.data?.id\n return { succeeded: true, value: { key, keyId: typeof keyId === 'string' ? keyId : null } }\n },\n async hold({ keyId, amountUsd, referenceId, expiresAt }) {\n const result = await call('/v1/billing/authorizations', {\n keyId, amount: amountUsd, type: 'key_cap', product: options.product, referenceId, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const id = result.body.data?.id\n if (result.status !== 201 || typeof id !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n return { succeeded: true, value: { authorizationId: id } }\n },\n async consume({ authorizationId, amountUsd }) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/consume`, { amount: amountUsd })\n if (!result) return unavailable()\n const consumed = result.body.data?.consumedAmount\n if (result.status !== 200 || typeof consumed !== 'number') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n return { succeeded: true, value: { consumedUsd: consumed } }\n },\n async release(authorizationId) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/release`, {})\n if (!result) return unavailable()\n if (result.status !== 200) return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n return { succeeded: true, value: null }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,8BAA8B,CAAC,YAAY,SAAS,SAAS;AAG5D,SAAS,wBAAwB,WAAgB,cAAsB,UAA2B;AACvG,MAAI,UAAU,aAAa,gBAAgB,UAAU,KAAM,QAAO;AAClE,QAAM,OAAO,CAAC,GAAG,UAAU,aAAa,KAAK,CAAC;AAC9C,MAAI,KAAK,WAAW,4BAA4B,OAAQ,QAAO;AAC/D,MAAI,CAAC,4BAA4B,MAAM,CAAC,QAAQ,UAAU,aAAa,OAAO,GAAG,EAAE,WAAW,CAAC,EAAG,QAAO;AACzG,QAAM,SAAS,CAAC,UAAyB,CAAC,CAAC,SAAS,MAAM,UAAU,OAAO,m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AAAA,IACA,MAAM,QAAQ,EAAE,iBAAiB,UAAU,GAAG;AAC5C,YAAM,SAAS,MAAM,KAAK,8BAA8B,mBAAmB,eAAe,CAAC,YAAY,EAAE,QAAQ,UAAU,CAAC;AAC5H,UAAI,CAAC,OAAQ,QAAO,YAAY;AAChC,YAAM,WAAW,OAAO,KAAK,MAAM;AACnC,UAAI,OAAO,WAAW,OAAO,OAAO,aAAa,UAAU;AACzD,eAAO,EAAE,WAAW,OAAO,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK,OAAO,IAAI,EAAE;AAAA,MACpF;AACA,aAAO,EAAE,WAAW,MAAM,OAAO,EAAE,aAAa,SAAS,EAAE;AAAA,IAC7D;AAAA,IACA,MAAM,QAAQ,iBAAiB;AAC7B,YAAM,SAAS,MAAM,KAAK,8BAA8B,mBAAmB,eAAe,CAAC,YAAY,CAAC,CAAC;AACzG,UAAI,CAAC,OAAQ,QAAO,YAAY;AAChC,UAAI,OAAO,WAAW,IAAK,QAAO,EAAE,WAAW,OAAO,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK,OAAO,IAAI,EAAE;AAC7G,aAAO,EAAE,WAAW,MAAM,OAAO,KAAK;AAAA,IACxC;AAAA,EACF;AACF;","names":["body","body","body"]}
|
|
1
|
+
{"version":3,"sources":["../../src/platform/sso-identity-store.ts","../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/agent-spend.ts"],"sourcesContent":["/**\n * Better Auth `account`-table store for first-party Tangle identity sign-in\n * (`protocol: 'identity'`) on D1 / SQLite.\n *\n * The platform link is Better Auth's own external-identity row:\n * `account(providerId = 'tangle', accountId = <platform user id>, userId)`.\n * Run {@link TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL} in a product migration; its\n * two partial unique indexes make the link one-per-user and\n * one-per-platform-user, which the write path relies on.\n *\n * Schema expectations are Better Auth's default SQLite model with camelCase\n * columns: `user(id, name, email, emailVerified, createdAt, updatedAt)`,\n * `session(id, userId, token, expiresAt, ipAddress, userAgent, createdAt,\n * updatedAt)` and `account(id, userId, accountId, providerId, createdAt,\n * updatedAt)`, with unix-second integer timestamps (Drizzle `mode:\n * 'timestamp'`). D1 is structural: Cloudflare `D1Database` satisfies\n * {@link TangleIdentityD1Like}.\n */\n\nimport {\n normalizeTangleSsoEmail,\n resolveTangleSsoAccount,\n TangleSsoAccountConflictError,\n TangleSsoUserCreateError,\n type TangleIdentitySsoAccountStore,\n type TangleSsoAccountResolution,\n type TangleSsoLocalAccount,\n} from './sso'\n\n/** Better Auth `account.providerId` for the Tangle platform link. */\nexport const TANGLE_IDENTITY_PROVIDER_ID = 'tangle'\n\n/** Partial unique indexes the store requires on Better Auth's `account` table. */\nexport const TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL = [\n `CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_platform_user ON account(accountId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`,\n `CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_user ON account(userId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`,\n] as const\n\n/** A prepared D1 statement; Cloudflare `D1PreparedStatement` satisfies it. */\nexport interface TangleIdentityD1Statement {\n bind(...values: unknown[]): TangleIdentityD1Statement\n first<T = Record<string, unknown>>(): Promise<T | null>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n run(): Promise<unknown>\n}\n\n/** The D1 surface the store needs. `batch` must be atomic, as D1's is. */\nexport interface TangleIdentityD1Like {\n prepare(query: string): TangleIdentityD1Statement\n batch(statements: TangleIdentityD1Statement[]): Promise<Array<{ meta?: { changes?: number } }>>\n}\n\n/**\n * A link table the product used before this store. During migration the store\n * reads it after `account` and mirrors new links into it, so a link that\n * exists in either place still signs in and a rollback still finds new links.\n * Remove the option once a reconcile query proves every legacy row has an\n * equal `account` row.\n */\nexport interface TangleIdentityLegacyLinkTable {\n table: string\n /** Column holding the local `user.id`; must be unique. */\n userIdColumn: string\n /** Column holding the platform user id; must be unique. */\n platformUserIdColumn: string\n}\n\nexport interface D1TangleIdentityStoreOptions {\n db: TangleIdentityD1Like\n /**\n * The signed-in local user for an explicit \"connect Tangle\" flow. A live\n * local session plus a verified platform exchange jointly authorize linking\n * that user, even when its local email is unverified or differs. The host\n * must prove the session started this flow (for example with a signed,\n * session-bound cookie).\n */\n linkingUserId?: string\n legacyLinkTable?: TangleIdentityLegacyLinkTable\n}\n\nconst SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/\n\nfunction identifier(value: string, field: string): string {\n if (!SQL_IDENTIFIER.test(value)) throw new Error(`createD1TangleIdentityStore: invalid ${field}`)\n return value\n}\n\ninterface CandidateRow {\n userId: string\n email: string\n emailVerified: number | boolean | null\n accountPlatformUserId: string | null\n legacyPlatformUserId: string | null\n}\n\ninterface Candidate extends TangleSsoLocalAccount {\n /** The account row and the legacy row name different platform users. */\n divergent: boolean\n}\n\nfunction randomToken(): string {\n return Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/** Create the identity-protocol account store for one request. */\nexport function createD1TangleIdentityStore(options: D1TangleIdentityStoreOptions): TangleIdentitySsoAccountStore {\n const { db, linkingUserId } = options\n const provider = TANGLE_IDENTITY_PROVIDER_ID\n const legacy = options.legacyLinkTable && {\n table: identifier(options.legacyLinkTable.table, 'legacyLinkTable.table'),\n userId: identifier(options.legacyLinkTable.userIdColumn, 'legacyLinkTable.userIdColumn'),\n platformUserId: identifier(options.legacyLinkTable.platformUserIdColumn, 'legacyLinkTable.platformUserIdColumn'),\n }\n\n const selectAccount = `SELECT u.id AS userId, u.email AS email, u.emailVerified AS emailVerified,\n a.accountId AS accountPlatformUserId,\n ${legacy ? `l.${legacy.platformUserId}` : 'NULL'} AS legacyPlatformUserId\n FROM user u\n LEFT JOIN account a ON a.userId = u.id AND a.providerId = '${provider}'\n ${legacy ? `LEFT JOIN ${legacy.table} l ON l.${legacy.userId} = u.id` : ''}`\n\n function toCandidate(row: CandidateRow): Candidate {\n const fromAccount = row.accountPlatformUserId?.trim() || null\n const fromLegacy = row.legacyPlatformUserId?.trim() || null\n return {\n userId: row.userId,\n email: row.email,\n emailVerified: row.emailVerified === 1 || row.emailVerified === true,\n platformUserId: fromAccount ?? fromLegacy,\n divergent: Boolean(fromAccount && fromLegacy && fromAccount !== fromLegacy),\n }\n }\n\n async function candidates(email: string, platformUserId: string) {\n const where = legacy\n ? `WHERE lower(trim(u.email)) = ? OR a.accountId = ? OR l.${legacy.platformUserId} = ?`\n : 'WHERE lower(trim(u.email)) = ? OR a.accountId = ?'\n const values = legacy ? [email, platformUserId, platformUserId] : [email, platformUserId]\n const { results } = await db.prepare(`${selectAccount} ${where}`).bind(...values).all<CandidateRow>()\n const rows = results.map(toCandidate)\n return {\n divergent: rows.some(row => row.divergent),\n platformMatches: rows.filter(row => row.platformUserId === platformUserId),\n emailMatches: rows.filter(row => normalizeTangleSsoEmail(row.email) === email),\n }\n }\n\n const store: TangleIdentitySsoAccountStore = {\n async resolveAccount({ email, platformUserId }): Promise<TangleSsoAccountResolution> {\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const stableId = platformUserId.trim()\n const found = await candidates(normalizedEmail, stableId)\n if (found.divergent) return { kind: 'reject', reason: 'platform-id-email-conflict' }\n if (!linkingUserId) {\n return resolveTangleSsoAccount({\n email: normalizedEmail,\n platformUserId: stableId,\n platformMatches: found.platformMatches,\n emailMatches: found.emailMatches,\n })\n }\n\n const ownRow = await db.prepare(`${selectAccount} WHERE u.id = ?`).bind(linkingUserId).first<CandidateRow>()\n if (!ownRow) return { kind: 'reject', reason: 'email-match-mismatch' }\n const own = toCandidate(ownRow)\n if (own.divergent) return { kind: 'reject', reason: 'platform-id-email-conflict' }\n if (own.platformUserId && own.platformUserId !== stableId) {\n return { kind: 'reject', reason: 'email-platform-id-conflict' }\n }\n if (found.platformMatches.some(row => row.userId !== linkingUserId)\n || found.emailMatches.some(row => row.userId !== linkingUserId)) {\n return { kind: 'reject', reason: 'platform-id-email-conflict' }\n }\n return { kind: 'existing', userId: linkingUserId, matchedBy: 'platform-id' }\n },\n\n async upsertUserByEmail({ email, name, tangleUserId, resolution }) {\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const platformUserId = tangleUserId.trim()\n const current = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (current.kind === 'reject') throw new TangleSsoAccountConflictError(current.reason)\n if (current.kind === 'existing') {\n if (resolution.kind === 'existing' && resolution.userId !== current.userId) {\n throw new TangleSsoAccountConflictError('platform-id-email-conflict')\n }\n return { userId: current.userId }\n }\n\n if (resolution.kind !== 'create') throw new TangleSsoUserCreateError('The selected account changed')\n const userId = crypto.randomUUID()\n try {\n await db.prepare(`INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt)\n VALUES (?, ?, ?, 1, unixepoch(), unixepoch())`)\n .bind(userId, name || normalizedEmail, normalizedEmail).run()\n } catch {\n // A concurrent callback may have won the email UNIQUE race. Re-apply the\n // policy; never adopt that row by email alone.\n const after = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (after.kind === 'reject') throw new TangleSsoAccountConflictError(after.reason)\n if (after.kind === 'existing') return { userId: after.userId }\n throw new TangleSsoUserCreateError()\n }\n return { userId }\n },\n\n async createSession({ userId, expiresAt, ipAddress, userAgent }) {\n const token = randomToken()\n await db.prepare(`INSERT INTO session (id, userId, token, expiresAt, ipAddress, userAgent, createdAt, updatedAt)\n VALUES (?, ?, ?, ?, ?, ?, unixepoch(), unixepoch())`)\n .bind(crypto.randomUUID(), userId, token, Math.floor(expiresAt.getTime() / 1000), ipAddress, userAgent)\n .run()\n return { token }\n },\n\n async saveTangleLink({ userId, sessionToken, tangleUserId, email }) {\n const platformUserId = tangleUserId.trim()\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const session = await db.prepare('SELECT userId FROM session WHERE token = ? AND expiresAt > unixepoch()')\n .bind(sessionToken).first<{ userId: string }>()\n if (session?.userId !== userId) throw new TangleSsoAccountConflictError('email-platform-id-conflict')\n const current = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (current.kind === 'reject') throw new TangleSsoAccountConflictError(current.reason)\n if (current.kind !== 'existing' || current.userId !== userId) {\n throw new TangleSsoAccountConflictError('platform-id-email-conflict')\n }\n\n // One atomic batch: every statement re-checks the live session and the\n // email owner, and the final verified-email update runs only when this\n // exact link exists, so a lost race commits nothing and rejects.\n const liveSession = 'EXISTS (SELECT 1 FROM session WHERE token = ? AND userId = ? AND expiresAt > unixepoch())'\n const emailFree = 'NOT EXISTS (SELECT 1 FROM user WHERE lower(trim(email)) = ? AND id <> ?)'\n const linked = `EXISTS (SELECT 1 FROM account WHERE providerId = '${provider}' AND userId = ? AND accountId = ?)`\n const statements = [\n db.prepare(`INSERT INTO account (id, userId, accountId, providerId, createdAt, updatedAt)\n SELECT ?, ?, ?, '${provider}', unixepoch(), unixepoch()\n WHERE EXISTS (SELECT 1 FROM user WHERE id = ?) AND ${liveSession} AND ${emailFree}\n ON CONFLICT DO NOTHING`)\n .bind(crypto.randomUUID(), userId, platformUserId, userId, sessionToken, userId, normalizedEmail, userId),\n ]\n if (legacy) {\n statements.push(db.prepare(`INSERT INTO ${legacy.table} (${legacy.userId}, ${legacy.platformUserId})\n SELECT ?, ? WHERE ${linked}\n ON CONFLICT DO NOTHING`)\n .bind(userId, platformUserId, userId, platformUserId))\n }\n statements.push(db.prepare(`UPDATE user SET emailVerified = CASE WHEN lower(trim(email)) = ? THEN 1 ELSE emailVerified END,\n updatedAt = unixepoch()\n WHERE id = ? AND ${liveSession} AND ${linked} AND ${emailFree}`)\n .bind(normalizedEmail, userId, sessionToken, userId, userId, platformUserId, normalizedEmail, userId))\n const results = await db.batch(statements)\n if (results[results.length - 1]?.meta?.changes !== 1) {\n throw new TangleSsoAccountConflictError('email-platform-id-conflict')\n }\n },\n\n // `saveTangleLink` is one atomic batch, so a rejected call wrote nothing;\n // removing the unpublished session is the whole cleanup.\n async deleteSession({ sessionToken }) {\n await db.prepare('DELETE FROM session WHERE token = ?').bind(sessionToken).run()\n },\n }\n return store\n}\n","/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. */\n serviceToken: string | (() => string)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n","/**\n * Bill work an agent app runs for a Platform agent key to that key's one cap.\n *\n * An owner approves an agent key with one lifetime cap shared across every\n * product. Work the app runs for the key must spend that cap, even when the\n * owner already has their own credential in the app:\n *\n * - Model calls: `modelKey` delegates a Router key from the agent key that\n * spends its cap directly (\"spend-through\"). Router refuses every call once\n * the cap is spent, so a turn cannot run past it.\n * - Work the app cannot route through the key, such as compute in a sandbox\n * the owner's own credential pays for: `hold` reserves the work's maximum\n * against the cap before it starts, and `consume` spends what it measured,\n * up to the hold, without charging the owner's wallet again.\n *\n * A spent or insufficient cap answers 402 `agent_key.budget_exhausted`, so an\n * app refuses the work before it starts. Web-standard fetch only.\n */\n\nexport interface AgentSpendRefusal {\n status: 402 | 403 | 503\n code: string\n message: string\n}\n\nexport type AgentSpendOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: AgentSpendRefusal }\n\nexport interface PlatformAgentSpendOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name. */\n serviceName: string\n serviceToken: string | (() => string)\n /** The Platform product this app bills, e.g. `gtm-agent`. */\n product: string\n fetch?: typeof fetch\n}\n\nexport interface PlatformAgentSpend {\n /**\n * A Router key whose charges spend the agent key's cap. `name` must start\n * `auto:`; give each piece of work its own.\n */\n modelKey(input: { agentKey: string; name: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ key: string; keyId: string | null }>>\n /** Reserve up to `amountUsd` of the agent key's cap for work billed elsewhere. */\n hold(input: { keyId: string; amountUsd: number; referenceId: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ authorizationId: string }>>\n /** Spend what the work measured, at most the hold. A retry repeats the amount. */\n consume(input: { authorizationId: string; amountUsd: number }): Promise<AgentSpendOutcome<{ consumedUsd: number }>>\n /** Return a hold whose work never ran. */\n release(authorizationId: string): Promise<AgentSpendOutcome<null>>\n}\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nconst budgetExhausted: AgentSpendRefusal = {\n status: 402,\n code: 'agent_key.budget_exhausted',\n message: 'The key has spent, or cannot cover, the cap its owner approved.',\n}\n\nfunction refusal(status: number, code: unknown): AgentSpendRefusal {\n if (code === 'KEY_BUDGET_EXHAUSTED' || code === 'KEY_BUDGET_EXCEEDED' || code === 'PRODUCT_BUDGET_EXCEEDED') return budgetExhausted\n if (code === 'INSUFFICIENT_BALANCE') {\n return { status: 402, code: 'agent_key.payment_required', message: \"The key owner's Tangle account has no credit.\" }\n }\n if (code === 'EMAIL_VERIFICATION_REQUIRED') {\n return { status: 403, code: 'agent_key.owner_unverified', message: 'The key owner must verify their Tangle email.' }\n }\n if (status >= 500 || status === 429 || code === 'PLATFORM_BUSY') {\n return { status: 503, code: 'agent_key.spend_unavailable', message: 'Platform could not record the spend; retry.' }\n }\n return { status: 403, code: 'agent_key.spend_refused', message: 'Platform refused to bill this work to the key.' }\n}\n\ninterface PlatformBody {\n success?: unknown\n data?: { key?: unknown; id?: unknown; consumedAmount?: unknown }\n error?: { code?: unknown }\n}\n\nexport function createPlatformAgentSpend(options: PlatformAgentSpendOptions): PlatformAgentSpend {\n const fetchImpl = options.fetch ?? fetch\n const base = options.platformUrl.replace(/\\/+$/, '')\n\n async function call(path: string, body: unknown): Promise<{ status: number; body: PlatformBody } | null> {\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n try {\n const response = await fetchImpl(`${base}${path}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n return { status: response.status, body: (await response.json().catch(() => ({}))) as PlatformBody }\n } catch {\n return null\n }\n }\n\n const unavailable = (): { succeeded: false; error: AgentSpendRefusal } => ({ succeeded: false, error: refusal(503, null) })\n\n return {\n async modelKey({ agentKey, name, expiresAt }) {\n const result = await call('/v1/keys/delegate', {\n sourceKey: agentKey, name, product: 'router', spendThrough: true, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const key = result.body.data?.key\n if (result.status !== 201 || typeof key !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n const keyId = result.body.data?.id\n return { succeeded: true, value: { key, keyId: typeof keyId === 'string' ? keyId : null } }\n },\n async hold({ keyId, amountUsd, referenceId, expiresAt }) {\n const result = await call('/v1/billing/authorizations', {\n keyId, amount: amountUsd, type: 'key_cap', product: options.product, referenceId, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const id = result.body.data?.id\n if (result.status !== 201 || typeof id !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n return { succeeded: true, value: { authorizationId: id } }\n },\n async consume({ authorizationId, amountUsd }) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/consume`, { amount: amountUsd })\n if (!result) return unavailable()\n const consumed = result.body.data?.consumedAmount\n if (result.status !== 200 || typeof consumed !== 'number') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n return { succeeded: true, value: { consumedUsd: consumed } }\n },\n async release(authorizationId) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/release`, {})\n if (!result) return unavailable()\n if (result.status !== 200) return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n return { succeeded: true, value: null }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BO,IAAM,8BAA8B;AAGpC,IAAM,sCAAsC;AAAA,EACjD,4GAA4G,2BAA2B;AAAA,EACvI,gGAAgG,2BAA2B;AAC7H;AA4CA,IAAM,iBAAiB;AAEvB,SAAS,WAAW,OAAe,OAAuB;AACxD,MAAI,CAAC,eAAe,KAAK,KAAK,EAAG,OAAM,IAAI,MAAM,wCAAwC,KAAK,EAAE;AAChG,SAAO;AACT;AAeA,SAAS,cAAsB;AAC7B,SAAO,MAAM,KAAK,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,GAAG,UAAQ,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACnH;AAGO,SAAS,4BAA4B,SAAsE;AAChH,QAAM,EAAE,IAAI,cAAc,IAAI;AAC9B,QAAM,WAAW;AACjB,QAAM,SAAS,QA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