@tangle-network/agent-app 0.50.33 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -112,6 +112,6 @@ export interface HubSettingsRoutes {
112
112
  /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */
113
113
  handle(request: Request): Promise<Response>;
114
114
  }
115
- /** Build a finite Hub settings server boundary; existing Hub proxy routes are unaffected. */
115
+ /** Build the finite, application-authorized Hub settings server boundary. */
116
116
  export declare function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes;
117
117
  export {};
@@ -4,7 +4,6 @@
4
4
  * and persistence are structural seams; this module owns the protocol.
5
5
  */
6
6
  export * from './sso';
7
- export * from './hub';
8
7
  export * from './hub-settings';
9
8
  export * from './billing';
10
9
  export * from './guards';
@@ -15,7 +15,6 @@ import {
15
15
  verifySignedSsoState
16
16
  } from "../chunk-5P6TB74H.js";
17
17
  import {
18
- resolveTangleDevOrUserKey,
19
18
  resolveTangleExecutionEnvironment
20
19
  } from "../chunk-JML7WKWU.js";
21
20
  import "../chunk-TZEEGDHS.js";
@@ -24,100 +23,6 @@ import {
24
23
  } from "../chunk-3NCPXNBZ.js";
25
24
  import "../chunk-TXD5HXLE.js";
26
25
 
27
- // src/platform/hub.ts
28
- var TangleBearerMissingError = class extends Error {
29
- constructor(userId) {
30
- super(`No Tangle platform link for user ${userId}`);
31
- this.userId = userId;
32
- this.name = "TangleBearerMissingError";
33
- }
34
- userId;
35
- };
36
- async function resolveUserTangleHubBearer(opts) {
37
- const resolved = await resolveTangleDevOrUserKey({
38
- environment: opts.environment,
39
- env: opts.env,
40
- getUserApiKey: opts.getUserApiKey
41
- });
42
- if (resolved) return { bearer: resolved.apiKey, source: resolved.source };
43
- throw new TangleBearerMissingError(opts.userId);
44
- }
45
- async function resolveUserTangleHubBearerForUser(opts) {
46
- return resolveUserTangleHubBearer({
47
- userId: String(opts.userId),
48
- environment: opts.environment,
49
- env: opts.env,
50
- getUserApiKey: () => opts.getUserApiKey(opts.userId)
51
- });
52
- }
53
- function isTangleBearerMissingError(error) {
54
- return error instanceof Error && error.name === "TangleBearerMissingError" && typeof error.userId === "string";
55
- }
56
- function isPlatformHubErrorLike(error) {
57
- return error instanceof Error && error.name === "PlatformHubError" && typeof error.status === "number";
58
- }
59
- function createHubProxyRoutes(ctx) {
60
- async function proxy(request, call) {
61
- const userId = await ctx.requireUserId(request);
62
- try {
63
- const bearer = await ctx.getBearer(userId);
64
- return await call(ctx.createHubClient(bearer));
65
- } catch (err) {
66
- if (isTangleBearerMissingError(err)) {
67
- return Response.json({ error: "tangle_link_required" }, { status: 412 });
68
- }
69
- if (isPlatformHubErrorLike(err)) {
70
- return Response.json({ error: err.message, code: err.code }, { status: err.status });
71
- }
72
- throw err;
73
- }
74
- }
75
- return {
76
- catalog: ({ request }) => proxy(request, async (hub) => Response.json({ catalog: await hub.catalog() })),
77
- connections: ({ request }) => proxy(request, async (hub) => Response.json({ connections: await hub.listConnections() })),
78
- connectionDelete: async ({ request, params }) => {
79
- if (request.method !== "DELETE") {
80
- return Response.json({ error: "Method not allowed" }, { status: 405 });
81
- }
82
- return proxy(request, async (hub) => Response.json(await hub.revokeConnection(params.connectionId)));
83
- },
84
- healthchecks: ({ request }) => proxy(request, async (hub) => Response.json({ healthchecks: await hub.listHealthchecks() })),
85
- authStart: async ({ request }) => {
86
- if (request.method !== "POST") {
87
- return Response.json({ error: "Method not allowed" }, { status: 405 });
88
- }
89
- const userId = await ctx.requireUserId(request);
90
- let body2;
91
- try {
92
- body2 = await request.json();
93
- } catch {
94
- return Response.json({ error: "Invalid JSON body" }, { status: 400 });
95
- }
96
- if (!body2.providerId || !body2.connectorId || !body2.returnUrl) {
97
- return Response.json({ error: "providerId, connectorId, and returnUrl are required" }, { status: 400 });
98
- }
99
- try {
100
- const bearer = await ctx.getBearer(userId);
101
- const result = await ctx.createHubClient(bearer).startAuth({
102
- providerId: body2.providerId,
103
- connectorId: body2.connectorId,
104
- returnUrl: body2.returnUrl,
105
- requestedScopes: body2.requestedScopes
106
- });
107
- return Response.json({ authorizationUrl: result.authorizationUrl, state: result.state });
108
- } catch (err) {
109
- if (isTangleBearerMissingError(err)) {
110
- return Response.json({ error: "tangle_link_required" }, { status: 412 });
111
- }
112
- if (isPlatformHubErrorLike(err)) {
113
- return Response.json({ error: err.message, code: err.code }, { status: err.status });
114
- }
115
- throw err;
116
- }
117
- }
118
- };
119
- }
120
-
121
26
  // src/platform/hub-settings.ts
122
27
  function json(value, status = 200, headers = {}) {
123
28
  return Response.json(value, { status, headers: { "Cache-Control": "no-store", ...headers } });
@@ -570,7 +475,6 @@ export {
570
475
  DEFAULT_TANGLE_TIER_POLICY,
571
476
  FREE_TIER_SPEND_CAP_USD,
572
477
  PlatformBillingHttpError,
573
- TangleBearerMissingError,
574
478
  TangleSsoAccountConflictError,
575
479
  TangleSsoUserCreateError,
576
480
  assertBillableBalance,
@@ -578,7 +482,6 @@ export {
578
482
  createApiKeyRequestAuth,
579
483
  createAuthGuard,
580
484
  createBetterAuthSessionCookieMinter,
581
- createHubProxyRoutes,
582
485
  createHubSettingsRoutes,
583
486
  createPlatformBillingHttp,
584
487
  createSignedSsoState,
@@ -587,17 +490,13 @@ export {
587
490
  getProductEntitlement,
588
491
  guardResolution,
589
492
  isPlatformBillingHttpError,
590
- isPlatformHubErrorLike,
591
493
  isProductEntitled,
592
494
  isSeatBillingEnabled,
593
- isTangleBearerMissingError,
594
495
  normalizeTanglePlanTier,
595
496
  normalizeTangleSsoEmail,
596
497
  parseAdminEmails,
597
498
  readTangleTierState,
598
499
  resolveTangleSsoAccount,
599
- resolveUserTangleHubBearer,
600
- resolveUserTangleHubBearerForUser,
601
500
  seatCheckoutUrl,
602
501
  signSessionCookieValue,
603
502
  verifySignedSsoState
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/platform/hub.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/api-key-auth.ts"],"sourcesContent":["/**\n * Integrations-hub proxy routes: the app-side surface that forwards an\n * authenticated user's requests to the platform's `/v1/integrations/*` API\n * using their stored platform key. Auth, key lookup, and the wire client are\n * structural seams (`HubProxyContext`); error detection is by name + shape so\n * it survives bundlers duplicating module instances.\n */\n\nimport {\n resolveTangleDevOrUserKey,\n type TangleExecutionEnvironment,\n type TangleExecutionKeySource,\n} from '../runtime/model'\n\n/** Hub bearer provenance mirrors the execution-key source union. */\nexport type TangleHubBearerSource = TangleExecutionKeySource\n\n/** Represent a resolved bearer token with its associated TangleHub bearer source */\nexport interface ResolvedTangleHubBearer {\n bearer: string\n source: TangleHubBearerSource\n}\n\n/** Resolve options required to obtain a user's TangleHub bearer token including environment and API key retrieval */\nexport interface ResolveUserTangleHubBearerOptions {\n userId: string\n /** Deployment context. Only local development may use env credentials. */\n environment?: TangleExecutionEnvironment\n /** Env to read for the local-development bearer. */\n env?: Record<string, string | undefined>\n /** App-owned lookup for the caller's linked platform API key. */\n getUserApiKey: () => string | null | undefined | Promise<string | null | undefined>\n}\n\n/** Resolve options for retrieving a TangleHub bearer token for a specified user */\nexport interface ResolveUserTangleHubBearerForUserOptions<UserId = string> {\n userId: UserId\n environment?: TangleExecutionEnvironment\n env?: Record<string, string | undefined>\n getUserApiKey: (userId: UserId) => string | null | undefined | Promise<string | null | undefined>\n}\n\n/** Represent missing Tangle platform link error for a specified user ID */\nexport class TangleBearerMissingError extends Error {\n constructor(readonly userId: string) {\n super(`No Tangle platform link for user ${userId}`)\n this.name = 'TangleBearerMissingError'\n }\n}\n\n/**\n * Resolve the Tangle bearer used by the integration hub proxy.\n *\n * Local development may use a server env key so apps can exercise the hub\n * without completing cross-site SSO. Deployed contexts must use the caller's\n * linked platform key; this keeps integration ownership aligned with the user.\n */\nexport async function resolveUserTangleHubBearer(\n opts: ResolveUserTangleHubBearerOptions,\n): Promise<ResolvedTangleHubBearer> {\n const resolved = await resolveTangleDevOrUserKey({\n environment: opts.environment,\n env: opts.env,\n getUserApiKey: opts.getUserApiKey,\n })\n if (resolved) return { bearer: resolved.apiKey, source: resolved.source }\n\n throw new TangleBearerMissingError(opts.userId)\n}\n\n/** Resolve the TangleHub bearer token for a specified user based on provided options */\nexport async function resolveUserTangleHubBearerForUser<UserId = string>(\n opts: ResolveUserTangleHubBearerForUserOptions<UserId>,\n): Promise<ResolvedTangleHubBearer> {\n return resolveUserTangleHubBearer({\n userId: String(opts.userId),\n environment: opts.environment,\n env: opts.env,\n getUserApiKey: () => opts.getUserApiKey(opts.userId),\n })\n}\n\n/** Structural guard (name + userId shape) — robust when the error class is\n * constructed in a different module instance than the one checking it. */\nexport function isTangleBearerMissingError(error: unknown): error is TangleBearerMissingError {\n return (\n error instanceof Error &&\n error.name === 'TangleBearerMissingError' &&\n typeof (error as { userId?: unknown }).userId === 'string'\n )\n}\n\n/** Structural detection of the platform hub wire error (name + numeric status). */\nexport function isPlatformHubErrorLike(error: unknown): error is Error & { status: number; code?: string } {\n return (\n error instanceof Error &&\n error.name === 'PlatformHubError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Structural subset of the platform hub wire client — extra methods are fine. */\nexport interface HubClientLike {\n catalog(): Promise<unknown>\n listConnections(): Promise<unknown>\n revokeConnection(connectionId: string): Promise<unknown>\n startAuth(input: {\n providerId: string\n connectorId: string\n returnUrl: string\n requestedScopes?: string[]\n }): Promise<{ authorizationUrl: string; state: string }>\n listHealthchecks(): Promise<unknown>\n}\n\n/** Define methods to require user ID, get bearer token, and create a hub client bound to the bearer */\nexport interface HubProxyContext {\n /** Resolve the authenticated user id. Throw the app's own auth Response /\n * redirect to reject — it propagates untouched. */\n requireUserId(request: Request): Promise<string>\n /** The user's platform bearer; throw `TangleBearerMissingError` when unlinked. */\n getBearer(userId: string): Promise<string>\n /** A hub client bound to the bearer. */\n createHubClient(bearer: string): HubClientLike\n}\n\n/** Define arguments for configuring a proxy route with request and optional parameters */\nexport interface HubProxyRouteArgs {\n request: Request\n params?: Record<string, string | undefined>\n}\n\n/** Define routes for hub proxy handling catalog, connections, healthchecks, and authorization actions */\nexport interface HubProxyRoutes {\n /** GET → `{ catalog }`. */\n catalog(args: HubProxyRouteArgs): Promise<Response>\n /** GET → `{ connections }`. */\n connections(args: HubProxyRouteArgs): Promise<Response>\n /** DELETE → the platform revocation result verbatim; 405 otherwise. */\n connectionDelete(args: { request: Request; params: { connectionId: string } }): Promise<Response>\n /** GET → `{ healthchecks }`. */\n healthchecks(args: HubProxyRouteArgs): Promise<Response>\n /** POST `{ providerId, connectorId, returnUrl, requestedScopes? }` →\n * `{ authorizationUrl, state }`; 405 non-POST; 400 on bad JSON / missing fields. */\n authStart(args: HubProxyRouteArgs): Promise<Response>\n}\n\ninterface StartAuthBody {\n providerId?: string\n connectorId?: string\n returnUrl?: string\n requestedScopes?: string[]\n}\n\n/** Resolve hub proxy routes with authentication and error handling based on the given context */\nexport function createHubProxyRoutes(ctx: HubProxyContext): HubProxyRoutes {\n /** Auth runs OUTSIDE the proxy try/catch so the app's auth throw (redirect\n * Response etc.) is never swallowed; bearer + platform errors are mapped. */\n async function proxy(request: Request, call: (hub: HubClientLike) => Promise<Response>): Promise<Response> {\n const userId = await ctx.requireUserId(request)\n try {\n const bearer = await ctx.getBearer(userId)\n return await call(ctx.createHubClient(bearer))\n } catch (err) {\n if (isTangleBearerMissingError(err)) {\n return Response.json({ error: 'tangle_link_required' }, { status: 412 })\n }\n if (isPlatformHubErrorLike(err)) {\n return Response.json({ error: err.message, code: err.code }, { status: err.status })\n }\n throw err\n }\n }\n\n return {\n catalog: ({ request }) => proxy(request, async (hub) => Response.json({ catalog: await hub.catalog() })),\n\n connections: ({ request }) =>\n proxy(request, async (hub) => Response.json({ connections: await hub.listConnections() })),\n\n connectionDelete: async ({ request, params }) => {\n if (request.method !== 'DELETE') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n return proxy(request, async (hub) => Response.json(await hub.revokeConnection(params.connectionId)))\n },\n\n healthchecks: ({ request }) =>\n proxy(request, async (hub) => Response.json({ healthchecks: await hub.listHealthchecks() })),\n\n authStart: async ({ request }) => {\n if (request.method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const userId = await ctx.requireUserId(request)\n let body: StartAuthBody\n try {\n body = (await request.json()) as StartAuthBody\n } catch {\n return Response.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n if (!body.providerId || !body.connectorId || !body.returnUrl) {\n return Response.json({ error: 'providerId, connectorId, and returnUrl are required' }, { status: 400 })\n }\n try {\n const bearer = await ctx.getBearer(userId)\n const result = await ctx.createHubClient(bearer).startAuth({\n providerId: body.providerId,\n connectorId: body.connectorId,\n returnUrl: body.returnUrl,\n requestedScopes: body.requestedScopes,\n })\n return Response.json({ authorizationUrl: result.authorizationUrl, state: result.state })\n } catch (err) {\n if (isTangleBearerMissingError(err)) {\n return Response.json({ error: 'tangle_link_required' }, { status: 412 })\n }\n if (isPlatformHubErrorLike(err)) {\n return Response.json({ error: err.message, code: err.code }, { status: err.status })\n }\n throw err\n }\n },\n }\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\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 * 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): 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 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): 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) invalid()\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))\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 a finite Hub settings server boundary; existing Hub proxy routes are unaffected. */\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\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath) } 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","/** Verified key fields required to enter a product's private API routes. */\nexport interface RequestApiKey {\n keyId: string\n ownerId: string\n scopes: readonly string[]\n /** Unix epoch milliseconds. Private API credentials must expire. */\n expiresAt: number\n}\n\nexport interface ApiKeyRequestAuthOptions<Key extends RequestApiKey, Identity> {\n /** Verify against the existing key store, including revocation and spending limits. */\n verify(authorization: string): Promise<Key | null>\n /** Return one scope or all required scopes; null or an empty list denies the route. */\n requiredScope(request: Request): string | readonly string[] | null\n /** Load the owner from product storage; retain normal workspace and tenant authorization. */\n resolveIdentity(key: Key): Promise<Identity | null>\n /** Atomically enforce the existing key's request quotas before admitting the request. */\n claimRequest(key: Key, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\n/**\n * Adapt existing Bearer keys to private product routes without issuing sessions.\n * Only absent authorization returns null; supplied invalid credentials never\n * fall through to cookie authentication. Callers retain their ordinary RBAC.\n */\nexport function createApiKeyRequestAuth<Key extends RequestApiKey, Identity>(\n options: ApiKeyRequestAuthOptions<Key, Identity>,\n): (request: Request) => Promise<Identity | null> {\n return async (request) => {\n const authorization = request.headers.get('Authorization')\n if (authorization === null) return null\n const bearer = /^Bearer +(\\S+)$/i.exec(authorization)\n if (!bearer) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n const requiredScope = options.requiredScope(request)\n const requiredScopes = typeof requiredScope === 'string' ? [requiredScope] : Array.from(requiredScope ?? [])\n if (!requiredScopes?.length || !requiredScopes.every(scope => typeof scope === 'string' && scope.trim())) {\n throw denied(403, 'api_key.route_denied', 'API key access is not enabled for this route')\n }\n const key = await options.verify(`Bearer ${bearer[1]}`)\n if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'An unexpired API key with a finite expiry is required')\n }\n if (!Array.isArray(key.scopes) || !requiredScopes.every(scope => key.scopes.includes(scope))) {\n throw denied(403, 'api_key.insufficient_scope', `API key requires scopes: ${requiredScopes.join(', ')}`)\n }\n const identity = await options.resolveIdentity(key)\n if (!identity) throw denied(401, 'api_key.invalid_owner', 'API key owner is unavailable')\n const claim = await options.claimRequest(key, crypto.randomUUID())\n if (claim.allowed !== true) {\n const headers = new Headers()\n if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds! > 0) {\n headers.set('Retry-After', String(Math.ceil(claim.retryAfterSeconds!)))\n }\n throw denied(429, 'api_key.request_limit_exceeded', 'API key request limit exceeded', headers)\n }\n if (key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'API key expired during authorization')\n }\n return identity\n }\n}\n\nfunction denied(status: number, code: string, error: string, headers?: Headers): Response {\n return Response.json({ error, code }, { status, headers })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CO,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YAAqB,QAAgB;AACnC,UAAM,oCAAoC,MAAM,EAAE;AAD/B;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AASA,eAAsB,2BACpB,MACkC;AAClC,QAAM,WAAW,MAAM,0BAA0B;AAAA,IAC/C,aAAa,KAAK;AAAA,IAClB,KAAK,KAAK;AAAA,IACV,eAAe,KAAK;AAAA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kC,kCAAkC,OAAO;AAAA,IAC/F;AACA,QAAI,IAAI,aAAa,KAAK,IAAI,GAAG;AAC/B,YAAM,OAAO,KAAK,mBAAmB,sCAAsC;AAAA,IAC7E;AACA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,OAAO,QAAgB,MAAc,OAAe,SAA6B;AACxF,SAAO,SAAS,KAAK,EAAE,OAAO,KAAK,GAAG,EAAE,QAAQ,QAAQ,CAAC;AAC3D;","names":["body","body","body"]}
1
+ {"version":3,"sources":["../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/api-key-auth.ts"],"sourcesContent":["/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\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 * 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): 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 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): 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) invalid()\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))\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\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath) } 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","/** Verified key fields required to enter a product's private API routes. */\nexport interface RequestApiKey {\n keyId: string\n ownerId: string\n scopes: readonly string[]\n /** Unix epoch milliseconds. Private API credentials must expire. */\n expiresAt: number\n}\n\nexport interface ApiKeyRequestAuthOptions<Key extends RequestApiKey, Identity> {\n /** Verify against the existing key store, including revocation and spending limits. */\n verify(authorization: string): Promise<Key | null>\n /** Return one scope or all required scopes; null or an empty list denies the route. */\n requiredScope(request: Request): string | readonly string[] | null\n /** Load the owner from product storage; retain normal workspace and tenant authorization. */\n resolveIdentity(key: Key): Promise<Identity | null>\n /** Atomically enforce the existing key's request quotas before admitting the request. */\n claimRequest(key: Key, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\n/**\n * Adapt existing Bearer keys to private product routes without issuing sessions.\n * Only absent authorization returns null; supplied invalid credentials never\n * fall through to cookie authentication. Callers retain their ordinary RBAC.\n */\nexport function createApiKeyRequestAuth<Key extends RequestApiKey, Identity>(\n options: ApiKeyRequestAuthOptions<Key, Identity>,\n): (request: Request) => Promise<Identity | null> {\n return async (request) => {\n const authorization = request.headers.get('Authorization')\n if (authorization === null) return null\n const bearer = /^Bearer +(\\S+)$/i.exec(authorization)\n if (!bearer) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n const requiredScope = options.requiredScope(request)\n const requiredScopes = typeof requiredScope === 'string' ? [requiredScope] : Array.from(requiredScope ?? [])\n if (!requiredScopes?.length || !requiredScopes.every(scope => typeof scope === 'string' && scope.trim())) {\n throw denied(403, 'api_key.route_denied', 'API key access is not enabled for this route')\n }\n const key = await options.verify(`Bearer ${bearer[1]}`)\n if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'An unexpired API key with a finite expiry is required')\n }\n if (!Array.isArray(key.scopes) || !requiredScopes.every(scope => key.scopes.includes(scope))) {\n throw denied(403, 'api_key.insufficient_scope', `API key requires scopes: ${requiredScopes.join(', ')}`)\n }\n const identity = await options.resolveIdentity(key)\n if (!identity) throw denied(401, 'api_key.invalid_owner', 'API key owner is unavailable')\n const claim = await options.claimRequest(key, crypto.randomUUID())\n if (claim.allowed !== true) {\n const headers = new Headers()\n if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds! > 0) {\n headers.set('Retry-After', String(Math.ceil(claim.retryAfterSeconds!)))\n }\n throw denied(429, 'api_key.request_limit_exceeded', 'API key request limit exceeded', headers)\n }\n if (key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'API key expired during authorization')\n }\n return identity\n }\n}\n\nfunction denied(status: number, code: string, error: string, headers?: Headers): Response {\n return Response.json({ error, code }, { status, headers })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,KAAK,OAAgB,SAAS,KAAK,UAAkC,CAAC,GAAa;AAC1F,SAAO,SAAS,KAAK,OAAO,EAAE,QAAQ,SAAS,EAAE,iBAAiB,YAAY,GAAG,QAAQ,EAAE,CAAC;AAC9F;AAEA,SAAS,UAAiB;AAExB,QAAM,KAAK,EAAE,OAAO,gCAAgC,MAAM,oBAAoB,GAAG,GAAG;AACtF;AAEA,SAAS,OAAO,OAAyC;AACvD,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,SAAQ;AACjF,SAAO;AACT;AAEA,SAAS,SAAS,OAAgC,SAAkC;AAClF,MAAI,OAAO,KAAK,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,SAAS,GAAG,CAAC,EAAG,SAAQ;AACxE;AAEA,SAAS,KAAK,OAAgB,MAAM,KAAa;AAC/C,MAAI,OAAO,UAAU,Y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U,IAAI,QAAQ;AAC5B,UAAI,OAAO,SAAS,MAAM,iBAAiB,KAAK,MAAM,oBAAqB,GAAG;AAC5E,gBAAQ,IAAI,eAAe,OAAO,KAAK,KAAK,MAAM,iBAAkB,CAAC,CAAC;AAAA,MACxE;AACA,YAAM,OAAO,KAAK,kCAAkC,kCAAkC,OAAO;AAAA,IAC/F;AACA,QAAI,IAAI,aAAa,KAAK,IAAI,GAAG;AAC/B,YAAM,OAAO,KAAK,mBAAmB,sCAAsC;AAAA,IAC7E;AACA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,OAAO,QAAgB,MAAc,OAAe,SAA6B;AACxF,SAAO,SAAS,KAAK,EAAE,OAAO,KAAK,GAAG,EAAE,QAAQ,QAAQ,CAAC;AAC3D;","names":["body","body"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.50.33",
3
+ "version": "0.51.0",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1,107 +0,0 @@
1
- /**
2
- * Integrations-hub proxy routes: the app-side surface that forwards an
3
- * authenticated user's requests to the platform's `/v1/integrations/*` API
4
- * using their stored platform key. Auth, key lookup, and the wire client are
5
- * structural seams (`HubProxyContext`); error detection is by name + shape so
6
- * it survives bundlers duplicating module instances.
7
- */
8
- import { type TangleExecutionEnvironment, type TangleExecutionKeySource } from '../runtime/model';
9
- /** Hub bearer provenance mirrors the execution-key source union. */
10
- export type TangleHubBearerSource = TangleExecutionKeySource;
11
- /** Represent a resolved bearer token with its associated TangleHub bearer source */
12
- export interface ResolvedTangleHubBearer {
13
- bearer: string;
14
- source: TangleHubBearerSource;
15
- }
16
- /** Resolve options required to obtain a user's TangleHub bearer token including environment and API key retrieval */
17
- export interface ResolveUserTangleHubBearerOptions {
18
- userId: string;
19
- /** Deployment context. Only local development may use env credentials. */
20
- environment?: TangleExecutionEnvironment;
21
- /** Env to read for the local-development bearer. */
22
- env?: Record<string, string | undefined>;
23
- /** App-owned lookup for the caller's linked platform API key. */
24
- getUserApiKey: () => string | null | undefined | Promise<string | null | undefined>;
25
- }
26
- /** Resolve options for retrieving a TangleHub bearer token for a specified user */
27
- export interface ResolveUserTangleHubBearerForUserOptions<UserId = string> {
28
- userId: UserId;
29
- environment?: TangleExecutionEnvironment;
30
- env?: Record<string, string | undefined>;
31
- getUserApiKey: (userId: UserId) => string | null | undefined | Promise<string | null | undefined>;
32
- }
33
- /** Represent missing Tangle platform link error for a specified user ID */
34
- export declare class TangleBearerMissingError extends Error {
35
- readonly userId: string;
36
- constructor(userId: string);
37
- }
38
- /**
39
- * Resolve the Tangle bearer used by the integration hub proxy.
40
- *
41
- * Local development may use a server env key so apps can exercise the hub
42
- * without completing cross-site SSO. Deployed contexts must use the caller's
43
- * linked platform key; this keeps integration ownership aligned with the user.
44
- */
45
- export declare function resolveUserTangleHubBearer(opts: ResolveUserTangleHubBearerOptions): Promise<ResolvedTangleHubBearer>;
46
- /** Resolve the TangleHub bearer token for a specified user based on provided options */
47
- export declare function resolveUserTangleHubBearerForUser<UserId = string>(opts: ResolveUserTangleHubBearerForUserOptions<UserId>): Promise<ResolvedTangleHubBearer>;
48
- /** Structural guard (name + userId shape) — robust when the error class is
49
- * constructed in a different module instance than the one checking it. */
50
- export declare function isTangleBearerMissingError(error: unknown): error is TangleBearerMissingError;
51
- /** Structural detection of the platform hub wire error (name + numeric status). */
52
- export declare function isPlatformHubErrorLike(error: unknown): error is Error & {
53
- status: number;
54
- code?: string;
55
- };
56
- /** Structural subset of the platform hub wire client — extra methods are fine. */
57
- export interface HubClientLike {
58
- catalog(): Promise<unknown>;
59
- listConnections(): Promise<unknown>;
60
- revokeConnection(connectionId: string): Promise<unknown>;
61
- startAuth(input: {
62
- providerId: string;
63
- connectorId: string;
64
- returnUrl: string;
65
- requestedScopes?: string[];
66
- }): Promise<{
67
- authorizationUrl: string;
68
- state: string;
69
- }>;
70
- listHealthchecks(): Promise<unknown>;
71
- }
72
- /** Define methods to require user ID, get bearer token, and create a hub client bound to the bearer */
73
- export interface HubProxyContext {
74
- /** Resolve the authenticated user id. Throw the app's own auth Response /
75
- * redirect to reject — it propagates untouched. */
76
- requireUserId(request: Request): Promise<string>;
77
- /** The user's platform bearer; throw `TangleBearerMissingError` when unlinked. */
78
- getBearer(userId: string): Promise<string>;
79
- /** A hub client bound to the bearer. */
80
- createHubClient(bearer: string): HubClientLike;
81
- }
82
- /** Define arguments for configuring a proxy route with request and optional parameters */
83
- export interface HubProxyRouteArgs {
84
- request: Request;
85
- params?: Record<string, string | undefined>;
86
- }
87
- /** Define routes for hub proxy handling catalog, connections, healthchecks, and authorization actions */
88
- export interface HubProxyRoutes {
89
- /** GET → `{ catalog }`. */
90
- catalog(args: HubProxyRouteArgs): Promise<Response>;
91
- /** GET → `{ connections }`. */
92
- connections(args: HubProxyRouteArgs): Promise<Response>;
93
- /** DELETE → the platform revocation result verbatim; 405 otherwise. */
94
- connectionDelete(args: {
95
- request: Request;
96
- params: {
97
- connectionId: string;
98
- };
99
- }): Promise<Response>;
100
- /** GET → `{ healthchecks }`. */
101
- healthchecks(args: HubProxyRouteArgs): Promise<Response>;
102
- /** POST `{ providerId, connectorId, returnUrl, requestedScopes? }` →
103
- * `{ authorizationUrl, state }`; 405 non-POST; 400 on bad JSON / missing fields. */
104
- authStart(args: HubProxyRouteArgs): Promise<Response>;
105
- }
106
- /** Resolve hub proxy routes with authentication and error handling based on the given context */
107
- export declare function createHubProxyRoutes(ctx: HubProxyContext): HubProxyRoutes;