@tangle-network/agent-app 0.58.8 → 0.58.9

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.
@@ -1,6 +1,6 @@
1
1
  export { HubConnectCallbackPage, type HubConnectCallbackPageProps } from './callback';
2
2
  export { createHubIntegrationsClient, type HubIntegrationsClient, type HubIntegrationsIdentity, type HubSettingsRequest, type HubSettingsRequestFn } from './client';
3
- export { HubIntegrationsPanel, type HubIntegrationsPanelProps } from './panel';
3
+ export { HubIntegrationsPanel, type HubAccountStatus, type HubIntegrationsAccounts, type HubIntegrationsPanelProps } from './panel';
4
4
  export { HUB_CONNECT_CHANNEL, HUB_CONNECTED_MESSAGE_TYPE, HUB_CONNECT_FAILED_MESSAGE_TYPE, POPUP_TIMEOUT_MS } from './popup';
5
5
  export { useHubIntegrations, type HubWriteReceipt, type UseHubIntegrationsOptions } from './use-hub-integrations';
6
6
  export { type HubIntegrationCapabilities, type HubIntegrationCapability } from './projection';
@@ -307,9 +307,10 @@ import {
307
307
  ApiKeyConnectDialog,
308
308
  IntegrationConnectionDetail,
309
309
  IntegrationsCatalog,
310
- OAuthConnectionParameterDialog
310
+ OAuthConnectionParameterDialog,
311
+ ProviderIcon
311
312
  } from "@tangle-network/sandbox-ui/integrations";
312
- import { Button } from "@tangle-network/ui/primitives";
313
+ import { Button, StatusPill } from "@tangle-network/ui/primitives";
313
314
  import { useEffect as useEffect3, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
314
315
 
315
316
  // src/integrations-react/projection.ts
@@ -638,6 +639,82 @@ function catalogHref() {
638
639
  url.searchParams.delete("connection");
639
640
  return `${url.pathname}${url.search}${url.hash}`;
640
641
  }
642
+ function accountName(connection, providerTitle) {
643
+ return connection.accountDisplay?.trim() || connection.displayName?.trim() || providerTitle;
644
+ }
645
+ function AccountStatus({ connection, accounts }) {
646
+ const status = accounts.getStatus?.(connection);
647
+ return status ? /* @__PURE__ */ jsx2(StatusPill, { tone: status.tone ?? "neutral", size: "sm", className: "shrink-0", children: status.label }) : null;
648
+ }
649
+ function AccountPrimaryAction({ connection, accounts, busy }) {
650
+ const primary = accounts.getPrimaryAction?.(connection);
651
+ return primary ? /* @__PURE__ */ jsx2(
652
+ Button,
653
+ {
654
+ type: "button",
655
+ variant: "outline",
656
+ size: "sm",
657
+ disabled: busy || primary.disabled,
658
+ onClick: primary.onSelect,
659
+ children: primary.label
660
+ }
661
+ ) : null;
662
+ }
663
+ function HubAccountList({ accounts, connections, providers, loading, error, busy, onRetry, onManage, canManage }) {
664
+ const titles = new Map(providers.map((provider) => [provider.providerId, provider.title]));
665
+ const title = (connection) => titles.get(connection.providerId) ?? connection.displayName ?? connection.providerId;
666
+ const rows = connections.filter((connection) => connection.status !== "revoked").map((connection) => ({ connection, provider: title(connection), name: accountName(connection, title(connection)) })).sort((a, b) => a.provider.localeCompare(b.provider) || a.name.localeCompare(b.name) || a.connection.id.localeCompare(b.connection.id));
667
+ return /* @__PURE__ */ jsxs2("section", { className: "mb-8 min-w-0 space-y-3", "aria-labelledby": "hub-accounts-heading", "aria-busy": loading || void 0, children: [
668
+ /* @__PURE__ */ jsxs2("header", { children: [
669
+ /* @__PURE__ */ jsx2("h2", { id: "hub-accounts-heading", className: "text-lg font-semibold", children: accounts.title }),
670
+ accounts.description ? /* @__PURE__ */ jsx2("p", { className: "mt-1 text-sm text-muted-foreground", children: accounts.description }) : null
671
+ ] }),
672
+ error ? /* @__PURE__ */ jsxs2("div", { role: "alert", className: "flex flex-wrap items-center gap-3 rounded-xl border border-destructive/40 bg-card p-4 text-sm text-destructive", children: [
673
+ /* @__PURE__ */ jsx2("p", { className: "min-w-0 flex-1 break-words", children: error }),
674
+ /* @__PURE__ */ jsx2(Button, { type: "button", variant: "outline", size: "sm", onClick: onRetry, children: "Retry" })
675
+ ] }) : loading && rows.length === 0 ? /* @__PURE__ */ jsx2("p", { role: "status", className: "rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground", children: "Loading connected accounts\u2026" }) : rows.length === 0 ? /* @__PURE__ */ jsx2("p", { className: "rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground", children: accounts.emptyLabel ?? "No accounts connected yet. Connect one below." }) : /* @__PURE__ */ jsx2("ul", { className: "divide-y divide-border overflow-hidden rounded-xl border border-border bg-card", "aria-label": accounts.title, children: rows.map(({ connection, provider, name }) => {
676
+ const health = connection.status !== "active" ? connection.status.replaceAll("_", " ") : connection.health === "unhealthy" ? "needs attention" : null;
677
+ return /* @__PURE__ */ jsxs2(
678
+ "li",
679
+ {
680
+ "data-testid": `hub-account-${connection.id}`,
681
+ className: "flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3",
682
+ children: [
683
+ /* @__PURE__ */ jsxs2("div", { className: "flex min-w-0 flex-1 basis-56 items-center gap-3", children: [
684
+ /* @__PURE__ */ jsx2(ProviderIcon, { id: connection.providerId, displayName: provider, size: 32, className: "shrink-0 rounded-lg" }),
685
+ /* @__PURE__ */ jsxs2("div", { className: "min-w-0", children: [
686
+ /* @__PURE__ */ jsx2("p", { className: "truncate text-sm font-medium", title: name, children: name }),
687
+ /* @__PURE__ */ jsxs2("p", { className: "truncate text-xs text-muted-foreground", children: [
688
+ provider,
689
+ health ? ` \xB7 ${health}` : ""
690
+ ] })
691
+ ] })
692
+ ] }),
693
+ /* @__PURE__ */ jsxs2("div", { className: "flex min-w-0 flex-wrap items-center gap-2 sm:justify-end", children: [
694
+ /* @__PURE__ */ jsx2(AccountStatus, { connection, accounts }),
695
+ /* @__PURE__ */ jsxs2("div", { className: "flex shrink-0 items-center gap-1", children: [
696
+ /* @__PURE__ */ jsx2(AccountPrimaryAction, { connection, accounts, busy }),
697
+ canManage(connection) ? /* @__PURE__ */ jsx2(
698
+ Button,
699
+ {
700
+ type: "button",
701
+ variant: "ghost",
702
+ size: "sm",
703
+ "aria-label": `Manage ${provider} account ${name}`,
704
+ onClick: () => onManage(connection),
705
+ children: "Manage"
706
+ }
707
+ ) : null
708
+ ] })
709
+ ] })
710
+ ]
711
+ },
712
+ connection.id
713
+ );
714
+ }) }),
715
+ accounts.footer
716
+ ] });
717
+ }
641
718
  function HubIntegrationsPanel(props) {
642
719
  const hub = useHubIntegrations(props);
643
720
  const scope = contextKey(props.identity);
@@ -684,6 +761,9 @@ function HubIntegrationsPanel(props) {
684
761
  };
685
762
  });
686
763
  const selectedRow = rows.find((row) => row.providerId === hub.provider?.providerId);
764
+ const catalogRows2 = props.accounts ? rows.filter((row) => row.connections.length === 0) : rows;
765
+ const connectionList = hub.connections.status === "ready" ? hub.connections.value : [];
766
+ const selectedConnection = hub.connection;
687
767
  const detailError = hub.detail.status === "error" ? hub.detail.message : hub.detail.status === "ready" && hub.detail.value.truncated ? `Showing at most ${hub.detail.value.tools.length} actions. The provider catalog may be incomplete.` : null;
688
768
  const detailsByConnectionId = useMemo2(() => hub.connection ? {
689
769
  [hub.connection.id]: {
@@ -710,16 +790,33 @@ function HubIntegrationsPanel(props) {
710
790
  writeMessage ? /* @__PURE__ */ jsx2("p", { role: writeWarning ? "alert" : "status", children: writeMessage }) : null,
711
791
  hub.connectStatus.message && hub.provider ? /* @__PURE__ */ jsx2("p", { role: hub.connectStatus.status === "failed" ? "alert" : "status", children: hub.connectStatus.message }) : null,
712
792
  hub.provider ? /* @__PURE__ */ jsxs2(Fragment, { children: [
713
- selectedRow?.canConnect ? /* @__PURE__ */ jsx2("div", { className: "mb-4 flex justify-end", children: /* @__PURE__ */ jsx2(
714
- Button,
715
- {
716
- type: "button",
717
- variant: "outline",
718
- disabled: pending,
719
- onClick: () => hub.beginConnect(hub.provider),
720
- children: "Connect another account"
721
- }
722
- ) }) : null,
793
+ props.accounts && selectedConnection || selectedRow?.canConnect ? /* @__PURE__ */ jsxs2("div", { className: "mb-4 flex min-w-0 flex-wrap items-center gap-2", children: [
794
+ props.accounts && selectedConnection ? /* @__PURE__ */ jsxs2(
795
+ "div",
796
+ {
797
+ className: "flex min-w-0 flex-1 flex-wrap items-center gap-2",
798
+ "data-testid": "hub-account-access",
799
+ "aria-label": `Access for ${accountName(selectedConnection, hub.provider.title)}`,
800
+ role: "group",
801
+ children: [
802
+ /* @__PURE__ */ jsx2("span", { className: "min-w-0 max-w-full truncate text-sm font-medium", children: accountName(selectedConnection, hub.provider.title) }),
803
+ /* @__PURE__ */ jsx2(AccountStatus, { connection: selectedConnection, accounts: props.accounts }),
804
+ /* @__PURE__ */ jsx2(AccountPrimaryAction, { connection: selectedConnection, accounts: props.accounts, busy: pending })
805
+ ]
806
+ }
807
+ ) : null,
808
+ selectedRow?.canConnect ? /* @__PURE__ */ jsx2(
809
+ Button,
810
+ {
811
+ type: "button",
812
+ variant: "outline",
813
+ className: "ml-auto",
814
+ disabled: pending,
815
+ onClick: () => hub.beginConnect(hub.provider),
816
+ children: "Connect another account"
817
+ }
818
+ ) : null
819
+ ] }) : null,
723
820
  /* @__PURE__ */ jsx2(
724
821
  IntegrationConnectionDetail,
725
822
  {
@@ -747,39 +844,59 @@ function HubIntegrationsPanel(props) {
747
844
  }
748
845
  }
749
846
  )
750
- ] }) : /* @__PURE__ */ jsx2(
751
- IntegrationsCatalog,
752
- {
753
- title: props.title ?? "Integrations",
754
- rows,
755
- query,
756
- onQueryChange: setQuery,
757
- categoryFilter: category,
758
- onCategoryFilterChange: setCategory,
759
- sort,
760
- onSortChange: setSort,
761
- onSelectConnection: (providerId, connectionId) => setCatalogSelection((current) => ({
762
- scope,
763
- ids: { ...current.scope === scope ? current.ids : {}, [providerId]: connectionId }
764
- })),
765
- onConnect: (row) => {
766
- const provider = hub.providers.status === "ready" ? hub.providers.value.find((item) => item.providerId === row.providerId) : null;
767
- if (provider) hub.beginConnect(provider);
768
- },
769
- onManage: (connection, row) => hub.selectConnection(row.providerId, connection.id),
770
- onDisconnect: (connection) => {
771
- void hub.revoke(connection.id);
772
- },
773
- onRequestIntegration: props.onRequestIntegration,
774
- onRetry: () => hub.refresh(),
775
- loading: hub.providers.status === "loading" || hub.connections.status === "loading",
776
- error,
777
- actionError: mutationError,
778
- connectError: hub.connectStatus.status === "failed" ? hub.connectStatus.message : null,
779
- busyProviderId: hub.connectStatus.status === "pending" ? hub.connectStatus.providerId ?? null : null,
780
- reserveConnectionContext: true
781
- }
782
- ),
847
+ ] }) : /* @__PURE__ */ jsxs2(Fragment, { children: [
848
+ props.accounts ? /* @__PURE__ */ jsxs2(Fragment, { children: [
849
+ hub.connectStatus.status === "connected" && hub.connectStatus.message ? /* @__PURE__ */ jsx2("p", { role: "status", className: "mb-3 text-sm", children: hub.connectStatus.message }) : null,
850
+ /* @__PURE__ */ jsx2(
851
+ HubAccountList,
852
+ {
853
+ accounts: props.accounts,
854
+ connections: connectionList,
855
+ providers: hub.providers.status === "ready" ? hub.providers.value : [],
856
+ loading: hub.connections.status === "loading",
857
+ error: hub.connections.status === "error" ? hub.connections.message : null,
858
+ busy: pending,
859
+ onRetry: () => hub.refresh(),
860
+ onManage: (connection) => hub.selectConnection(connection.providerId, connection.id),
861
+ canManage: (connection) => props.can({ operation: "policies.list", connectionId: connection.id })
862
+ }
863
+ )
864
+ ] }) : null,
865
+ props.accounts && hub.connections.status === "error" ? null : /* @__PURE__ */ jsx2(
866
+ IntegrationsCatalog,
867
+ {
868
+ title: props.title ?? "Integrations",
869
+ rows: catalogRows2,
870
+ query,
871
+ onQueryChange: setQuery,
872
+ categoryFilter: category,
873
+ onCategoryFilterChange: setCategory,
874
+ sort,
875
+ onSortChange: setSort,
876
+ onSelectConnection: (providerId, connectionId) => setCatalogSelection((current) => ({
877
+ scope,
878
+ ids: { ...current.scope === scope ? current.ids : {}, [providerId]: connectionId }
879
+ })),
880
+ onConnect: (row) => {
881
+ const provider = hub.providers.status === "ready" ? hub.providers.value.find((item) => item.providerId === row.providerId) : null;
882
+ if (provider) hub.beginConnect(provider);
883
+ },
884
+ onManage: (connection, row) => hub.selectConnection(row.providerId, connection.id),
885
+ onDisconnect: (connection) => {
886
+ void hub.revoke(connection.id);
887
+ },
888
+ onRequestIntegration: props.onRequestIntegration,
889
+ onRetry: () => hub.refresh(),
890
+ loading: hub.providers.status === "loading" || hub.connections.status === "loading",
891
+ error,
892
+ actionError: mutationError,
893
+ connectError: hub.connectStatus.status === "failed" ? hub.connectStatus.message : null,
894
+ busyProviderId: hub.connectStatus.status === "pending" ? hub.connectStatus.providerId ?? null : null,
895
+ reserveConnectionContext: true,
896
+ emptyCatalogLabel: props.accounts && rows.length > 0 ? "Every available integration already has a connected account above." : void 0
897
+ }
898
+ )
899
+ ] }),
783
900
  hub.dialog?.kind === "api-key" ? /* @__PURE__ */ jsx2(
784
901
  ApiKeyConnectDialog,
785
902
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/integrations-react/callback.tsx","../../src/integrations-react/popup.ts","../../src/integrations-react/client.ts","../../src/integrations-react/panel.tsx","../../src/integrations-react/projection.ts","../../src/integrations-react/use-hub-integrations.ts"],"sourcesContent":["import { useEffect, useState } from 'react'\nimport { HUB_CONNECTED_MESSAGE_TYPE, HUB_CONNECT_CHANNEL, HUB_CONNECT_FAILED_MESSAGE_TYPE, localAppUrl } from './popup'\n\nexport interface HubConnectCallbackPageProps {\n /** Local settings destination owned by the consuming app. */\n returnHref: string\n}\n\n/** The callback only signals completion; the opener verifies fresh Hub state. */\nexport function HubConnectCallbackPage({ returnHref }: HubConnectCallbackPageProps) {\n const [phase, setPhase] = useState<'checking' | 'returned' | 'failed'>('checking')\n const [reason, setReason] = useState('')\n\n useEffect(() => {\n const params = new URLSearchParams(window.location.search)\n const provider = params.get('provider')\n const nonce = params.get('nonce')\n const context = params.get('context')\n if (!provider || !nonce || !context) { setReason('This connection callback is incomplete.'); setPhase('failed'); return }\n const failure = params.get('error_description') || params.get('error')\n try {\n const channel = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n channel.postMessage({ type: failure ? HUB_CONNECT_FAILED_MESSAGE_TYPE : HUB_CONNECTED_MESSAGE_TYPE, provider, nonce, context })\n channel.close()\n } catch { /* The opener also polls the authoritative connection list. */ }\n if (failure) { setReason(failure.slice(0, 200)); setPhase('failed'); return }\n window.close()\n const timer = window.setTimeout(() => setPhase('returned'), 150)\n return () => window.clearTimeout(timer)\n }, [])\n\n const destination = localAppUrl(returnHref)\n const localReturn = destination ? `${destination.pathname}${destination.search}${destination.hash}` : '/'\n return <main aria-live=\"polite\" style={{ maxWidth: 560, margin: '20vh auto', padding: 24, textAlign: 'center' }}>\n {phase === 'checking' ? <p>Checking your connection…</p> : phase === 'returned'\n ? <p>Return to the app to check your connection. You can close this window.</p>\n : <p>Could not complete the connection. {reason}</p>}\n <a href={localReturn}>Return to integrations</a>\n </main>\n}\n","import type { HubConnection } from '@tangle-network/hub-sdk'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\n\nexport const HUB_CONNECT_CHANNEL = 'tangle:hub-connect'\nexport const HUB_CONNECTED_MESSAGE_TYPE = 'tangle:hub-connected'\nexport const HUB_CONNECT_FAILED_MESSAGE_TYPE = 'tangle:hub-connect-failed'\nexport const POPUP_TIMEOUT_MS = 5 * 60 * 1000\nconst PRE_REDIRECT_TIMEOUT_MS = 30_000\nconst POLL_INTERVAL_MS = 2500\nconst POPUP_FEATURES = 'popup=yes,width=520,height=680'\n\nexport type PopupConnectResult = 'connected' | 'blocked' | 'cancelled' | 'unverified' | 'unavailable'\n\nexport function localAppUrl(path: string): URL | null {\n if (!path.startsWith('/') || path.startsWith('//')) return null\n try {\n const origin = typeof window === 'undefined' ? 'https://local.invalid' : window.location.origin\n const url = new URL(path, origin)\n return url.origin === origin && !url.username && !url.password ? url : null\n } catch { return null }\n}\n\nfunction updatedConnection(providerId: string, before: readonly HubConnection[], after: readonly HubConnection[]): boolean {\n const previous = new Map(before.filter(connection => connection.providerId === providerId).map(connection => [connection.id, connection]))\n return after.some(connection => {\n if (connection.providerId !== providerId || connection.status !== 'active' || connection.health === 'unhealthy') return false\n const old = previous.get(connection.id)\n return !old || old.updatedAt !== connection.updatedAt || old.status !== connection.status\n })\n}\n\nfunction closePopup(popup: Window): void {\n try { if (!popup.closed) popup.close() } catch { /* COOP may sever the handle. */ }\n}\n\nfunction withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) { reject(new DOMException('Aborted', 'AbortError')); return }\n const onAbort = () => reject(new DOMException('Aborted', 'AbortError'))\n signal.addEventListener('abort', onAbort, { once: true })\n promise.then(value => { signal.removeEventListener('abort', onAbort); resolve(value) }, error => { signal.removeEventListener('abort', onAbort); reject(error) })\n })\n}\n\nfunction waitForConnection(input: {\n popup: Window\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n nonce: string\n contextToken: string\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n return new Promise(resolve => {\n let settled = false\n let checking = false\n let pollId: number | undefined\n let timeoutId: number | undefined\n let channel: BroadcastChannel | undefined\n const finish = (result: PopupConnectResult) => {\n if (settled) return\n settled = true\n if (pollId !== undefined) window.clearTimeout(pollId)\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n input.signal.removeEventListener('abort', onAbort)\n channel?.close()\n closePopup(input.popup)\n resolve(result)\n }\n const onAbort = () => finish('cancelled')\n const check = async () => {\n if (settled || checking) return\n checking = true\n if (!input.isCurrent() || input.signal.aborted) { finish('cancelled'); return }\n try {\n const after = await input.client.connections(input.identity, input.signal)\n if (input.isCurrent() && updatedConnection(input.providerId, input.before, after)) { finish('connected'); return }\n } catch { /* A lost read is never evidence of a connection. Keep polling. */ }\n checking = false\n if (!settled) pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n }\n if (input.signal.aborted) { finish('cancelled'); return }\n input.signal.addEventListener('abort', onAbort, { once: true })\n try {\n const candidate = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n candidate.onmessage = event => {\n const message = event.data as Record<string, unknown> | null\n if (!message || message.provider !== input.providerId || message.nonce !== input.nonce || message.context !== input.contextToken) return\n if (message.type === HUB_CONNECT_FAILED_MESSAGE_TYPE) finish('cancelled')\n if (message.type === HUB_CONNECTED_MESSAGE_TYPE) {\n if (pollId !== undefined) window.clearTimeout(pollId)\n void check()\n }\n }\n channel = candidate\n } catch { /* Polling covers browsers without BroadcastChannel. */ }\n pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n timeoutId = window.setTimeout(() => finish('unverified'), POPUP_TIMEOUT_MS)\n })\n}\n\n/** Opens before the first await, preserving the initiating user gesture. */\nexport async function connectWithPopup(input: {\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n callbackPath: string\n connectionParameters?: Record<string, string>\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n const callback = localAppUrl(input.callbackPath)\n if (!callback) throw new TypeError('Callback path must be local.')\n const popup = window.open('', '_blank', POPUP_FEATURES)\n if (!popup) return 'blocked'\n // Keep the parent handle for navigation while removing the provider page's opener.\n try { popup.opener = null } catch { /* Some browsers make this read-only. */ }\n const nonce = crypto.randomUUID()\n const contextToken = crypto.randomUUID()\n callback.searchParams.set('provider', input.providerId)\n callback.searchParams.set('nonce', nonce)\n callback.searchParams.set('context', contextToken)\n const timeout = new AbortController()\n const onAbort = () => timeout.abort()\n input.signal.addEventListener('abort', onAbort, { once: true })\n const preRedirectId = window.setTimeout(() => timeout.abort(), PRE_REDIRECT_TIMEOUT_MS)\n try {\n if (!input.isCurrent()) return 'cancelled'\n const start = await withAbort(input.client.startOAuth(input.identity, input.providerId, {\n returnUrl: callback.href,\n ...(input.connectionParameters === undefined ? {} : { connectionParameters: input.connectionParameters }),\n }, timeout.signal), timeout.signal)\n if (!input.isCurrent() || input.signal.aborted) return 'cancelled'\n let redirect: URL\n try { redirect = new URL(start.redirectUrl) } catch { return 'unavailable' }\n if (redirect.protocol !== 'https:' || redirect.username || redirect.password) return 'unavailable'\n window.clearTimeout(preRedirectId)\n const waitController = new AbortController()\n const abortWait = () => waitController.abort()\n input.signal.addEventListener('abort', abortWait, { once: true })\n if (input.signal.aborted) abortWait()\n const waiting = waitForConnection({ ...input, popup, nonce, contextToken, signal: waitController.signal })\n try {\n popup.location.href = redirect.href\n return await waiting\n } catch {\n waitController.abort()\n await waiting\n return 'unavailable'\n } finally {\n input.signal.removeEventListener('abort', abortWait)\n }\n } catch {\n return input.signal.aborted || timeout.signal.aborted ? 'cancelled' : 'unavailable'\n } finally {\n window.clearTimeout(preRedirectId)\n input.signal.removeEventListener('abort', onAbort)\n closePopup(popup)\n }\n}\n","import type {\n HubApiKeyConnectionMetadata,\n HubConnection,\n HubConnectionHealthResponse,\n HubOAuthStartResponse,\n HubPolicy,\n HubPolicyDecision,\n HubProvider,\n HubTool,\n} from '@tangle-network/hub-sdk'\n\n/** The host must bind each request to this server-verified identity. */\nexport interface HubIntegrationsIdentity {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsRequest {\n readonly identity: HubIntegrationsIdentity\n readonly path: string\n readonly init: RequestInit\n}\n\n/**\n * The host supplies its authenticated fetch, CSRF protection and expected\n * identity check. The browser never receives a Hub credential or SDK client.\n */\nexport type HubSettingsRequestFn = (request: HubSettingsRequest) => Promise<Response>\n\nexport interface HubIntegrationsClient {\n providers(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubProvider[]>\n connections(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubConnection[]>\n startOAuth(identity: HubIntegrationsIdentity, providerId: string, input: { returnUrl: string; connectionParameters?: Record<string, string> }, signal?: AbortSignal): Promise<HubOAuthStartResponse>\n connectApiKey(identity: HubIntegrationsIdentity, providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata, signal?: AbortSignal): Promise<HubConnection>\n revoke(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnection>\n health(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnectionHealthResponse>\n actions(identity: HubIntegrationsIdentity, providerId: string, limit: number, signal?: AbortSignal): Promise<HubTool[]>\n policies(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubPolicy[]>\n setPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, decision: HubPolicyDecision, signal?: AbortSignal): Promise<HubPolicy>\n resetPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, signal?: AbortSignal): Promise<void>\n}\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value as Record<string, unknown>\n}\n\nfunction array(value: unknown): unknown[] {\n if (!Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value\n}\n\nfunction namedArray<T>(value: unknown, key: string): T[] {\n const rows = array(object(value)[key])\n if (rows.some(row => row === null || typeof row !== 'object' || Array.isArray(row))) throw new Error('Invalid Hub settings response.')\n return rows as T[]\n}\n\nfunction namedObject<T>(value: unknown, key: string): T {\n return object(object(value)[key]) as T\n}\n\nfunction segment(value: string): string {\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value)) throw new TypeError('Invalid Hub settings identifier.')\n return encodeURIComponent(value)\n}\n\n/** Finite browser transport for the server-owned `createHubSettingsRoutes` API. */\nexport function createHubIntegrationsClient(request: HubSettingsRequestFn, basePath = '/api/hub/settings'): HubIntegrationsClient {\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath.')\n\n async function call(identity: HubIntegrationsIdentity, path: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', signal?: AbortSignal, body?: object): Promise<unknown> {\n if (![identity.userId, identity.sessionId, identity.workspaceId].every(part => typeof part === 'string' && part.trim())) {\n throw new TypeError('Hub settings identity is required.')\n }\n const response = await request({\n identity,\n path: `${basePath}${path}`,\n init: { method, signal, ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) },\n })\n if (!response.ok) {\n let code: string | undefined\n try {\n const error = object(await response.json())\n if (typeof error.code === 'string') code = error.code\n } catch { /* Status remains authoritative when a response is unreadable. */ }\n throw new Error(`Hub settings request failed (${response.status}${code ? `, ${code}` : ''}).`)\n }\n return response.json()\n }\n\n return {\n async providers(identity, signal) { return namedArray<HubProvider>(await call(identity, '/providers', 'GET', signal), 'providers') },\n async connections(identity, signal) { return namedArray<HubConnection>(await call(identity, '/connections', 'GET', signal), 'connections') },\n async startOAuth(identity, providerId, input, signal) {\n const response = object(await call(identity, `/connections/${segment(providerId)}/start`, 'POST', signal, input))\n if (typeof response.redirectUrl !== 'string') throw new Error('Invalid Hub OAuth response.')\n return response as unknown as HubOAuthStartResponse\n },\n async connectApiKey(identity, providerId, apiKey, metadata, signal) {\n return namedObject<HubConnection>(await call(identity, `/connections/${segment(providerId)}/connect-key`, 'POST', signal, { apiKey, ...(metadata === undefined ? {} : { metadata }) }), 'connection')\n },\n async revoke(identity, connectionId, signal) { return namedObject<HubConnection>(await call(identity, `/connections/${segment(connectionId)}`, 'DELETE', signal), 'connection') },\n async health(identity, connectionId, signal) {\n const response = object(await call(identity, `/connections/${segment(connectionId)}/health`, 'POST', signal))\n object(response.connection)\n object(response.health)\n return response as unknown as HubConnectionHealthResponse\n },\n async actions(identity, providerId, limit, signal) {\n if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new TypeError('Hub action limit must be 1–200.')\n const search = new URLSearchParams({ query: '', limit: String(limit) })\n return namedArray<HubTool>(await call(identity, `/providers/${segment(providerId)}/actions?${search}`, 'GET', signal), 'tools')\n },\n async policies(identity, connectionId, signal) {\n const search = new URLSearchParams({ connectionId })\n return namedArray<HubPolicy>(await call(identity, `/policies?${search}`, 'GET', signal), 'policies')\n },\n async setPolicy(identity, connectionId, actionPath, decision, signal) {\n return namedObject<HubPolicy>(await call(identity, '/policies', 'PUT', signal, { connectionId, actionPath, decision }), 'policy')\n },\n async resetPolicy(identity, connectionId, actionPath, signal) {\n const response = object(await call(identity, '/policies', 'DELETE', signal, { connectionId, actionPath }))\n if (response.connectionId !== connectionId || response.actionPath !== actionPath || typeof response.deleted !== 'boolean') {\n throw new Error('Invalid Hub policy reset response.')\n }\n },\n }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubProvider } from '@tangle-network/hub-sdk'\nimport {\n ApiKeyConnectDialog,\n IntegrationConnectionDetail,\n IntegrationsCatalog,\n OAuthConnectionParameterDialog,\n type IntegrationDisplayAction,\n type IntegrationSort,\n} from '@tangle-network/sandbox-ui/integrations'\nimport { Button } from '@tangle-network/ui/primitives'\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { contextKey, displayProvider, type HubIntegrationCapabilities } from './projection'\nimport { useHubIntegrations } from './use-hub-integrations'\n\nexport interface HubIntegrationsPanelProps {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n can: HubIntegrationCapabilities\n callbackPath: string\n title?: string\n className?: string\n onRequestIntegration?: (prefill: string) => void\n onUnsupportedConnect?: (provider: HubProvider) => void\n /** Host-owned context and actions; the host authorizes and confirms their effects. */\n getConnectionContext?: (connection: HubConnection) => string | undefined\n getConnectionActions?: (connection: HubConnection) => readonly IntegrationDisplayAction[]\n /** Host-owned, transient fields for providers that require API-key metadata. */\n renderApiKeyMetadata?: (input: {\n provider: HubProvider\n value: HubApiKeyConnectionMetadata | undefined\n onChange: (value: HubApiKeyConnectionMetadata | undefined) => void\n }) => ReactNode\n}\n\nfunction catalogHref(): string {\n if (typeof window === 'undefined') return '/'\n const url = new URL(window.location.href)\n url.searchParams.delete('integration')\n url.searchParams.delete('connection')\n return `${url.pathname}${url.search}${url.hash}`\n}\n\n/** Embeddable settings surface. The app supplies authenticated transport and grants. */\nexport function HubIntegrationsPanel(props: HubIntegrationsPanelProps) {\n const hub = useHubIntegrations(props)\n const scope = contextKey(props.identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const activeDialog = useRef(hub.dialog)\n activeDialog.current = hub.dialog\n const [query, setQuery] = useState('')\n const [category, setCategory] = useState('')\n const [sort, setSort] = useState<IntegrationSort>('featured')\n const [catalogSelection, setCatalogSelection] = useState<{ scope: string; ids: Record<string, string | null> }>({ scope, ids: {} })\n const [keyInput, setKeyInput] = useState({ scope, value: '' })\n const apiKey = keyInput.scope === scope ? keyInput.value : ''\n const setApiKey = (value: string) => setKeyInput({ scope, value })\n const [metadataInput, setMetadataInput] = useState<{ scope: string; value: HubApiKeyConnectionMetadata | undefined }>({ scope, value: undefined })\n const metadata = metadataInput.scope === scope ? metadataInput.value : undefined\n const setMetadata = (value: HubApiKeyConnectionMetadata | undefined) => setMetadataInput({ scope, value })\n const [parameterInput, setParameterInput] = useState({ scope, values: {} as Record<string, string> })\n const parameters = parameterInput.scope === scope ? parameterInput.values : {}\n const setParameters = (values: Record<string, string>) => setParameterInput({ scope, values })\n\n useEffect(() => { setApiKey(''); setMetadata(undefined); setParameters({}) }, [scope])\n const pending = hub.writeState.status === 'pending' || hub.connectStatus.status === 'pending'\n const error = hub.providers.status === 'error' ? hub.providers.message\n : hub.connections.status === 'error' ? hub.connections.message : null\n const mutationError = hub.writeState.status === 'failed' ? hub.writeState.message : null\n const writeMessage = hub.writeState.status === 'succeeded' ? hub.writeState.value.message : null\n const writeWarning = hub.writeState.status === 'succeeded' && hub.writeState.value.reconciliation === 'refresh-failed'\n const rows = hub.rows.map(row => {\n const selectedId = catalogSelection.scope === scope ? catalogSelection.ids[row.providerId] : null\n return {\n ...row,\n selectedConnectionId: row.connections.some(connection => connection.id === selectedId) ? selectedId ?? null : null,\n connections: row.connections.map(connection => {\n const source = hub.connections.status === 'ready'\n ? hub.connections.value.find(item => item.id === connection.id) : undefined\n return source ? {\n ...connection,\n detail: props.getConnectionContext?.(source) ?? connection.detail,\n actions: props.getConnectionActions?.(source),\n } : connection\n }),\n }\n })\n const selectedRow = rows.find(row => row.providerId === hub.provider?.providerId)\n const detailError = hub.detail.status === 'error' ? hub.detail.message\n : hub.detail.status === 'ready' && hub.detail.value.truncated\n ? `Showing at most ${hub.detail.value.tools.length} actions. The provider catalog may be incomplete.` : null\n const detailsByConnectionId = useMemo(() => hub.connection ? {\n [hub.connection.id]: {\n ...hub.details,\n loading: hub.detail.status === 'loading',\n busy: pending,\n error: detailError,\n },\n } : {}, [hub.connection, hub.details, hub.detail.status, pending, detailError])\n\n const closeDialog = () => {\n if (hub.connectStatus.status === 'pending') hub.cancelConnect()\n else hub.setDialog(null)\n setApiKey(''); setMetadata(undefined); setParameters({})\n }\n\n return <section className={props.className}>\n {hub.connectStatus.status === 'pending' ? <div role=\"status\" className=\"mb-4 flex flex-wrap items-center gap-3\">\n <span>Finish connecting in the popup.</span>\n <Button type=\"button\" variant=\"outline\" onClick={hub.cancelConnect}>Cancel connection</Button>\n </div> : null}\n {hub.writeState.status === 'pending' ? <p role=\"status\">Saving Hub settings…</p> : null}\n {mutationError ? <p role=\"alert\">{mutationError}</p> : null}\n {writeMessage ? <p role={writeWarning ? 'alert' : 'status'}>{writeMessage}</p> : null}\n {hub.connectStatus.message && hub.provider ? <p role={hub.connectStatus.status === 'failed' ? 'alert' : 'status'}>{hub.connectStatus.message}</p> : null}\n {hub.provider ? <>\n {selectedRow?.canConnect ? <div className=\"mb-4 flex justify-end\"><Button type=\"button\" variant=\"outline\" disabled={pending}\n onClick={() => hub.beginConnect(hub.provider!)}>Connect another account</Button></div> : null}\n <IntegrationConnectionDetail\n provider={displayProvider(hub.provider)}\n connections={selectedRow?.connections ?? []}\n selectedConnectionId={hub.connection?.id ?? null}\n onSelectConnection={connectionId => hub.selectConnection(hub.provider!.providerId, connectionId)}\n detailsByConnectionId={detailsByConnectionId}\n loading={hub.connections.status === 'loading' || hub.detail.status === 'loading'}\n error={detailError}\n backHref={catalogHref()}\n onRetry={() => hub.refresh()}\n onTestConnection={connectionId => { void hub.test(connectionId) }}\n onDisconnect={connectionId => { void hub.revoke(connectionId) }}\n onDecisionChange={(connectionId, actionPath, decision) => {\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') return\n void hub.setDecision(connectionId, actionPath, decision)\n }}\n onResetDecision={(connectionId, actionPath) => { void hub.resetDecision(connectionId, actionPath) }}\n />\n </> : <IntegrationsCatalog\n title={props.title ?? 'Integrations'}\n rows={rows}\n query={query}\n onQueryChange={setQuery}\n categoryFilter={category}\n onCategoryFilterChange={setCategory}\n sort={sort}\n onSortChange={setSort}\n onSelectConnection={(providerId, connectionId) => setCatalogSelection(current => ({\n scope,\n ids: { ...(current.scope === scope ? current.ids : {}), [providerId]: connectionId },\n }))}\n onConnect={row => { const provider = hub.providers.status === 'ready' ? hub.providers.value.find(item => item.providerId === row.providerId) : null; if (provider) hub.beginConnect(provider) }}\n onManage={(connection, row) => hub.selectConnection(row.providerId, connection.id)}\n onDisconnect={connection => { void hub.revoke(connection.id) }}\n onRequestIntegration={props.onRequestIntegration}\n onRetry={() => hub.refresh()}\n loading={hub.providers.status === 'loading' || hub.connections.status === 'loading'}\n error={error}\n actionError={mutationError}\n connectError={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n busyProviderId={hub.connectStatus.status === 'pending' ? hub.connectStatus.providerId ?? null : null}\n reserveConnectionContext\n />}\n {hub.dialog?.kind === 'api-key' ? <ApiKeyConnectDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n description={hub.dialog.provider.authHint}\n value={apiKey}\n onValueChange={setApiKey}\n busy={pending}\n error={mutationError}\n canSubmit={apiKey.trim().length > 0 && !pending}\n onSubmit={() => {\n const secret = apiKey\n const target = hub.dialog?.provider.providerId\n const submittedDialog = hub.dialog\n setApiKey('')\n if (target) void hub.submitApiKey(target, secret, metadata).then(result => {\n if (result.succeeded && activeScope.current === scope && activeDialog.current === submittedDialog) {\n hub.setDialog(null); setMetadata(undefined)\n }\n })\n }}\n >{props.renderApiKeyMetadata?.({ provider: hub.dialog.provider, value: metadata, onChange: setMetadata })}</ApiKeyConnectDialog> : null}\n {hub.dialog?.kind === 'oauth' ? <OAuthConnectionParameterDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n parameters={hub.dialog.provider.connectionParameters ?? []}\n values={parameters}\n onValueChange={(key, value) => setParameters({ ...parameters, [key]: value })}\n busy={pending}\n error={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n canSubmit={!pending && (hub.dialog.provider.connectionParameters ?? []).every(field => !field.required || !!parameters[field.key]?.trim())}\n onSubmit={() => {\n const target = hub.dialog?.provider\n const submittedDialog = hub.dialog\n if (target) void hub.startOAuth(target, parameters).then(result => {\n if (result === 'connected' && activeScope.current === scope && activeDialog.current === submittedDialog) setParameters({})\n })\n }}\n /> : null}\n </section>\n}\n","import type { HubConnection, HubPolicy, HubProvider, HubTool } from '@tangle-network/hub-sdk'\nimport type {\n IntegrationConnectionDetails,\n IntegrationDisplayProvider,\n IntegrationPermissionDisplay,\n IntegrationPermissionGroup,\n IntegrationsProviderRow,\n} from '@tangle-network/sandbox-ui/integrations'\n\nexport type HubIntegrationCapability =\n | { operation: 'oauth.start' | 'api-key.connect'; providerId: string }\n | { operation: 'connection.revoke' | 'connection.health' | 'policies.list'; connectionId: string }\n | { operation: 'policy.set' | 'policy.reset'; connectionId: string; actionPath: string }\n\n/** Display hints only. `createHubSettingsRoutes.authorize` remains authoritative. */\nexport type HubIntegrationCapabilities = (intent: HubIntegrationCapability) => boolean\n\nexport const ACTION_LIMIT = 200\n\nexport function contextKey(identity: { userId: string; sessionId: string; workspaceId: string }): string {\n return JSON.stringify([identity.userId, identity.sessionId, identity.workspaceId])\n}\n\nexport function displayProvider(provider: HubProvider): IntegrationDisplayProvider {\n return { providerId: provider.providerId, title: provider.title, category: provider.category }\n}\n\nexport function catalogRows(\n providers: readonly HubProvider[],\n connections: readonly HubConnection[],\n selectedIds: Readonly<Record<string, string | null>>,\n can: HubIntegrationCapabilities,\n hasUnsupportedConnect = false,\n): IntegrationsProviderRow[] {\n return providers.map(provider => {\n const accounts = connections.filter(connection => connection.providerId === provider.providerId)\n return {\n ...displayProvider(provider),\n kind: 'provider',\n authKind: provider.authKind,\n selectedConnectionId: accounts.some(account => account.id === selectedIds[provider.providerId])\n ? selectedIds[provider.providerId] ?? null : null,\n canConnect: provider.authKind === 'oauth2'\n ? provider.configured && can({ operation: 'oauth.start', providerId: provider.providerId })\n : provider.authKind === 'api_key'\n ? provider.configured && can({ operation: 'api-key.connect', providerId: provider.providerId })\n : hasUnsupportedConnect,\n connections: accounts.map(connection => ({\n id: connection.id,\n accountDisplay: connection.accountDisplay ?? connection.displayName,\n statusLabel: connection.status === 'active' ? 'Connected' : connection.status.replaceAll('_', ' '),\n statusTone: connection.status === 'active' && connection.health !== 'unhealthy' ? 'success' : 'warning',\n detail: connection.providerAccountId ?? undefined,\n capabilities: {\n manage: can({ operation: 'policies.list', connectionId: connection.id }),\n disconnect: can({ operation: 'connection.revoke', connectionId: connection.id }),\n test: can({ operation: 'connection.health', connectionId: connection.id }),\n editPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n resetPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n },\n })),\n }\n })\n}\n\nconst OPTIONS = [\n { value: 'allow', label: 'Allow' },\n { value: 'ask', label: 'Ask' },\n { value: 'deny', label: 'Deny' },\n] as const\n\n/** Stored overrides are shown; app-specific effective policy is never guessed. */\nexport function permissionDetails(\n tools: readonly HubTool[],\n policies: readonly HubPolicy[],\n connectionId: string,\n can: HubIntegrationCapabilities,\n): IntegrationConnectionDetails {\n const overrides = new Map(policies.filter(policy => policy.connectionId === connectionId).map(policy => [policy.actionPath, policy.decision]))\n const groups: IntegrationPermissionGroup[] = [\n { id: 'writes', title: 'Write and unknown actions', rows: [] },\n { id: 'reads', title: 'Read actions', collapsed: true, rows: [] },\n ]\n const writes: IntegrationPermissionDisplay[] = []\n const reads: IntegrationPermissionDisplay[] = []\n for (const tool of tools) {\n const override = overrides.get(tool.path)\n const row = {\n actionPath: tool.path,\n title: tool.title ?? tool.path,\n riskLabel: tool.risk ?? 'unknown',\n riskTone: tool.risk === 'destructive' ? 'error' : tool.risk === 'write' || tool.risk === undefined ? 'warning' : 'neutral',\n decision: override ?? null,\n decisionOptions: OPTIONS,\n sourceLabel: override ? 'Stored override' : 'No stored override',\n canReset: override !== undefined && can({ operation: 'policy.reset', connectionId, actionPath: tool.path }),\n disabled: !can({ operation: 'policy.set', connectionId, actionPath: tool.path }),\n } as const\n if (tool.risk === 'read') reads.push(row)\n else writes.push(row)\n }\n writes.sort((a, b) => a.title.localeCompare(b.title))\n reads.sort((a, b) => a.title.localeCompare(b.title))\n groups[0] = { ...groups[0]!, rows: writes }\n groups[1] = { ...groups[1]!, rows: reads }\n return { permissionGroups: groups }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubPolicyDecision, HubProvider } from '@tangle-network/hub-sdk'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { confirmWrite, useAsyncResource, useConfirmedMutation } from '../web-react/async'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { connectWithPopup, type PopupConnectResult } from './popup'\nimport { ACTION_LIMIT, catalogRows, contextKey, permissionDetails, type HubIntegrationCapabilities } from './projection'\n\ntype Selection = { scope: string; providerId: string | null; connectionId: string | null }\ntype Dialog = { scope: string; kind: 'api-key' | 'oauth'; provider: HubProvider } | null\n\nexport interface UseHubIntegrationsOptions {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n /** Display only. The host server must authorize every exact operation. */\n can: HubIntegrationCapabilities\n /** Local app route that renders `HubConnectCallbackPage`. */\n callbackPath: string\n /** Optional host handler for custom/native signup. No Platform redirect is assumed. */\n onUnsupportedConnect?: (provider: HubProvider) => void\n}\n\ntype WriteInput =\n | { kind: 'api-key'; identity: HubIntegrationsIdentity; scope: string; providerId: string; apiKey: string; metadata?: HubApiKeyConnectionMetadata }\n | { kind: 'revoke'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'health'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'set'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string; decision: HubPolicyDecision }\n | { kind: 'reset'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string }\n\nexport interface HubWriteReceipt {\n scope: string\n kind: WriteInput['kind']\n reconciliation: 'verified' | 'refresh-failed'\n message: string\n}\n\nfunction initialSelection(scope: string): Selection {\n if (typeof window === 'undefined') return { scope, providerId: null, connectionId: null }\n const query = new URL(window.location.href).searchParams\n return { scope, providerId: query.get('integration'), connectionId: query.get('connection') }\n}\n\nfunction updateUrl(providerId: string | null, connectionId: string | null): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n if (providerId) url.searchParams.set('integration', providerId)\n else url.searchParams.delete('integration')\n if (connectionId) url.searchParams.set('connection', connectionId)\n else url.searchParams.delete('connection')\n window.history.pushState(window.history.state, '', url)\n}\n\n/** Identity-bound Hub settings controller; connection state is always server-read. */\nexport function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect }: UseHubIntegrationsOptions) {\n const scope = contextKey(identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const [selection, setSelection] = useState<Selection>(() => initialSelection(scope))\n const visibleSelection = selection.scope === scope ? selection : { scope, providerId: null, connectionId: null }\n const [dialog, setDialog] = useState<Dialog>(null)\n const visibleDialog = dialog?.scope === scope ? dialog : null\n const [connectStatus, setConnectStatus] = useState<{ scope: string; status: 'idle' | 'pending' | 'connected' | 'failed'; providerId?: string; message?: string }>({ scope, status: 'idle' })\n const [writeScope, setWriteScope] = useState(scope)\n const pendingPopup = useRef<AbortController | null>(null)\n\n useEffect(() => {\n const onPop = () => setSelection(initialSelection(scope))\n window.addEventListener('popstate', onPop)\n return () => window.removeEventListener('popstate', onPop)\n }, [scope])\n\n const providers = useAsyncResource({ load: ({ signal }) => client.providers(identity, signal), deps: [client, scope], isEmpty: () => false })\n const connections = useAsyncResource({ load: ({ signal }) => client.connections(identity, signal), deps: [client, scope], isEmpty: () => false })\n const providerList = providers.status === 'ready' ? providers.value : []\n const connectionList = connections.status === 'ready' ? connections.value : []\n const provider = providerList.find(item => item.providerId === visibleSelection.providerId) ?? null\n const connection = connectionList.find(item => item.id === visibleSelection.connectionId && item.providerId === provider?.providerId) ?? null\n const canReadPolicies = connection !== null && can({ operation: 'policies.list', connectionId: connection.id })\n const detail = useAsyncResource({\n enabled: canReadPolicies && connection?.status === 'active',\n deps: [client, scope, provider?.providerId, connection?.id, canReadPolicies],\n isEmpty: () => false,\n load: async ({ signal }) => {\n if (!provider || !connection) throw new Error('Choose a connection.')\n const [tools, policies] = await Promise.all([\n client.actions(identity, provider.providerId, ACTION_LIMIT, signal),\n client.policies(identity, connection.id, signal),\n ])\n if (tools.some(tool => !tool.path.startsWith(`${provider.providerId}.`)) || policies.some(policy => policy.connectionId !== connection.id)) {\n throw new Error('Hub settings response changed connection or provider.')\n }\n return { tools, policies, truncated: tools.length >= ACTION_LIMIT }\n },\n })\n\n const write = useConfirmedMutation<WriteInput, HubWriteReceipt>({\n concurrency: 'reject',\n mutate: async (input, { signal }) => {\n if (input.scope !== activeScope.current) throw new Error('Integration context changed. Retry in the current workspace.')\n const origin = input.identity\n const receipt = (reconciliation: HubWriteReceipt['reconciliation'], message: string) => confirmWrite<HubWriteReceipt>({ scope: input.scope, kind: input.kind, reconciliation, message })\n if (input.kind === 'api-key') {\n if (!can({ operation: 'api-key.connect', providerId: input.providerId })) throw new Error('Connection setup is unavailable.')\n const created = await client.connectApiKey(origin, input.providerId, input.apiKey, input.metadata, signal)\n if (created.providerId !== input.providerId || created.status !== 'active') throw new Error('Hub did not confirm the requested connection.')\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === created.id && item.status === 'active')\n ? receipt('verified', 'Connection saved and verified.') : receipt('refresh-failed', 'Connection saved; current account state could not be confirmed.')\n } catch { return receipt('refresh-failed', 'Connection saved; refresh failed.') }\n }\n if (input.kind === 'revoke') {\n if (!can({ operation: 'connection.revoke', connectionId: input.connectionId })) throw new Error('Disconnect is unavailable.')\n await client.revoke(origin, input.connectionId, signal)\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === input.connectionId && item.status === 'active')\n ? receipt('refresh-failed', 'Disconnected, but the current account state disagrees.') : receipt('verified', 'Connection disconnected and verified.')\n } catch { return receipt('refresh-failed', 'Disconnected; refresh failed.') }\n }\n if (input.kind === 'health') {\n if (!can({ operation: 'connection.health', connectionId: input.connectionId })) throw new Error('Connection test is unavailable.')\n const result = await client.health(origin, input.connectionId, signal)\n if (result.connection.id !== input.connectionId) throw new Error('Hub returned another connection.')\n return receipt('verified', `Connection test: ${result.health.status.replaceAll('_', ' ')}.`)\n }\n if (!can({ operation: input.kind === 'set' ? 'policy.set' : 'policy.reset', connectionId: input.connectionId, actionPath: input.actionPath })) {\n throw new Error('Permission editing is unavailable.')\n }\n if (input.kind === 'set') {\n const stored = await client.setPolicy(origin, input.connectionId, input.actionPath, input.decision, signal)\n if (stored.connectionId !== input.connectionId || stored.actionPath !== input.actionPath || stored.decision !== input.decision) {\n throw new Error('Hub did not confirm the requested permission.')\n }\n } else await client.resetPolicy(origin, input.connectionId, input.actionPath, signal)\n try {\n const current = await client.policies(origin, input.connectionId, signal)\n const override = current.find(policy => policy.actionPath === input.actionPath)\n const matches = input.kind === 'set' ? override?.decision === input.decision : override === undefined\n return matches\n ? receipt('verified', 'Permission saved and verified.') : receipt('refresh-failed', 'Permission write was accepted; current policy state disagrees.')\n } catch { return receipt('refresh-failed', 'Permission write was accepted; refresh failed.') }\n },\n onSucceeded: value => { if (value.scope === activeScope.current) { connections.retry(); detail.retry() } },\n })\n\n useEffect(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'idle' })\n setWriteScope(scope)\n write.reset()\n return () => { pendingPopup.current?.abort(); pendingPopup.current = null }\n }, [scope, client, write.reset])\n\n const selectProvider = useCallback((providerId: string | null) => {\n const next = { scope, providerId, connectionId: null }\n setSelection(next)\n updateUrl(providerId, null)\n }, [scope])\n\n const selectConnection = useCallback((providerId: string, connectionId: string | null) => {\n if (connectionId && !connectionList.some(item => item.id === connectionId && item.providerId === providerId)) return\n setSelection({ scope, providerId, connectionId })\n updateUrl(providerId, connectionId)\n }, [scope, connectionList])\n\n const startOAuth = useCallback(async (target: HubProvider, connectionParameters?: Record<string, string>): Promise<PopupConnectResult> => {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) return 'unavailable'\n if (connections.status !== 'ready') { setConnectStatus({ scope, status: 'failed', message: 'Load connections before connecting.' }); return 'unavailable' }\n pendingPopup.current?.abort()\n const controller = new AbortController()\n pendingPopup.current = controller\n setConnectStatus({ scope, status: 'pending', providerId: target.providerId })\n const result = await connectWithPopup({\n client, identity, providerId: target.providerId, before: connections.value,\n callbackPath, connectionParameters, signal: controller.signal,\n isCurrent: () => activeScope.current === scope && !controller.signal.aborted,\n })\n if (pendingPopup.current !== controller || activeScope.current !== scope) return result\n pendingPopup.current = null\n if (result === 'connected') {\n connections.retry()\n setDialog(null)\n setConnectStatus({ scope, status: 'connected', message: 'Connection verified.' })\n } else setConnectStatus({ scope, status: 'failed', message: result === 'blocked' ? 'Allow the popup and try again.' : result === 'unverified' ? 'Could not verify a new connection. Refresh and try again.' : result === 'cancelled' ? 'Connection was cancelled.' : 'This connection flow is unavailable.' })\n return result\n }, [can, connections, client, identity, callbackPath, scope])\n\n const beginConnect = useCallback((target: HubProvider) => {\n if (target.authKind !== 'api_key' && target.authKind !== 'oauth2') {\n if (onUnsupportedConnect) onUnsupportedConnect(target)\n else setConnectStatus({ scope, status: 'failed', message: 'This provider needs an app-specific connection flow.' })\n return\n }\n if (!target.configured) {\n setConnectStatus({ scope, status: 'failed', message: 'This provider is not configured for connection.' })\n return\n }\n if (target.authKind === 'api_key') {\n if (can({ operation: 'api-key.connect', providerId: target.providerId })) setDialog({ scope, kind: 'api-key', provider: target })\n else setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' })\n return\n }\n if (target.authKind === 'oauth2') {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) {\n setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' }); return\n }\n if (target.connectionParameters?.length) setDialog({ scope, kind: 'oauth', provider: target })\n else void startOAuth(target)\n return\n }\n }, [can, onUnsupportedConnect, scope, startOAuth])\n\n const cancelConnect = useCallback(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'failed', message: 'Connection was cancelled.' })\n }, [scope])\n\n const rows = useMemo(() => catalogRows(providerList, connectionList, visibleSelection.providerId && visibleSelection.connectionId\n ? { [visibleSelection.providerId]: visibleSelection.connectionId } : {}, can, !!onUnsupportedConnect),\n [providerList, connectionList, visibleSelection.providerId, visibleSelection.connectionId, can, onUnsupportedConnect])\n const details = detail.status === 'ready' && connection\n ? permissionDetails(detail.value.tools, detail.value.policies, connection.id, can) : undefined\n\n return {\n providers, connections, detail, rows, provider, connection, dialog: visibleDialog, setDialog,\n connectStatus: connectStatus.scope === scope ? connectStatus : { scope, status: 'idle' as const, providerId: undefined },\n selection: visibleSelection, selectProvider, selectConnection, beginConnect, startOAuth, cancelConnect,\n write, writeState: writeScope === scope ? write.state : { status: 'idle' as const }, details,\n refresh: () => { providers.retry(); connections.retry(); detail.retry() },\n submitApiKey: (providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata) => { setWriteScope(scope); return write.run({ kind: 'api-key', identity, scope, providerId, apiKey, metadata }) },\n revoke: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'revoke', identity, scope, connectionId }) },\n test: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'health', identity, scope, connectionId }) },\n setDecision: (connectionId: string, actionPath: string, decision: HubPolicyDecision) => { setWriteScope(scope); return write.run({ kind: 'set', identity, scope, connectionId, actionPath, decision }) },\n resetDecision: (connectionId: string, actionPath: string) => { setWriteScope(scope); return write.run({ kind: 'reset', identity, scope, connectionId, actionPath }) },\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,WAAW,gBAAgB;;;ACG7B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,kCAAkC;AACxC,IAAM,mBAAmB,IAAI,KAAK;AACzC,IAAM,0BAA0B;AAChC,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AAIhB,SAAS,YAAY,MAA0B;AACpD,MAAI,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,EAAG,QAAO;AAC3D,MAAI;AACF,UAAM,SAAS,OAAO,WAAW,cAAc,0BAA0B,OAAO,SAAS;AACzF,UAAM,MAAM,IAAI,IAAI,MAAM,MAAM;AAChC,WAAO,IAAI,WAAW,UAAU,CAAC,IAAI,YAAY,CAAC,IAAI,WAAW,MAAM;AAAA,EACzE,QAAQ;AAAE,WAAO;AAAA,EAAK;AACxB;AAEA,SAAS,kBAAkB,YAAoB,QAAkC,OAA0C;AACzH,QAAM,WAAW,IAAI,IAAI,OAAO,OAAO,gBAAc,WAAW,eAAe,UAAU,EAAE,IAAI,gBAAc,CAAC,WAAW,IAAI,UAAU,CAAC,CAAC;AACzI,SAAO,MAAM,KAAK,gBAAc;AAC9B,QAAI,WAAW,eAAe,cAAc,WAAW,WAAW,YAAY,WAAW,WAAW,YAAa,QAAO;AACxH,UAAM,MAAM,SAAS,IAAI,WAAW,EAAE;AACtC,WAAO,CAAC,OAAO,IAAI,cAAc,WAAW,aAAa,IAAI,WAAW,WAAW;AAAA,EACrF,CAAC;AACH;AAEA,SAAS,WAAW,OAAqB;AACvC,MAAI;AAAE,QAAI,CAAC,MAAM,OAAQ,OAAM,MAAM;AAAA,EAAE,QAAQ;AAAA,EAAmC;AACpF;AAEA,SAAS,UAAa,SAAqB,QAAiC;AAC1E,SAAO,IAAI,QAAQ,CAAC,SA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IAAE,IAAyB;AAAA,IAClI,IAAI,QAAQ,SAAS,UAAU,gBAAAA;AAAA,MAAC;AAAA;AAAA,QAC/B,MAAI;AAAA,QACJ,cAAc,UAAQ;AAAE,cAAI,CAAC,KAAM,aAAY;AAAA,QAAE;AAAA,QACjD,YAAY,IAAI,OAAO,SAAS;AAAA,QAChC,OAAO,IAAI,OAAO,SAAS;AAAA,QAC3B,YAAY,IAAI,OAAO,SAAS,wBAAwB,CAAC;AAAA,QACzD,QAAQ;AAAA,QACR,eAAe,CAAC,KAAK,UAAU,cAAc,EAAE,GAAG,YAAY,CAAC,GAAG,GAAG,MAAM,CAAC;AAAA,QAC5E,MAAM;AAAA,QACN,OAAO,IAAI,cAAc,WAAW,WAAW,IAAI,cAAc,UAAU;AAAA,QAC3E,WAAW,CAAC,YAAY,IAAI,OAAO,SAAS,wBAAwB,CAAC,GAAG,MAAM,WAAS,CAAC,MAAM,YAAY,CAAC,CAAC,WAAW,MAAM,GAAG,GAAG,KAAK,CAAC;AAAA,QACzI,UAAU,MAAM;AACd,gBAAM,SAAS,IAAI,QAAQ;AAC3B,gBAAM,kBAAkB,IAAI;AAC5B,cAAI,OAAQ,MAAK,IAAI,WAAW,QAAQ,UAAU,EAAE,KAAK,YAAU;AACjE,gBAAI,WAAW,eAAe,YAAY,YAAY,SAAS,aAAa,YAAY,gBAAiB,eAAc,CAAC,CAAC;AAAA,UAC3H,CAAC;AAAA,QACH;AAAA;AAAA,IACF,IAAK;AAAA,KACP;AACF;","names":["useEffect","useMemo","useRef","useState","useEffect","useState","useState","useEffect","jsx","jsxs","useRef","useState","useEffect","useMemo"]}
1
+ {"version":3,"sources":["../../src/integrations-react/callback.tsx","../../src/integrations-react/popup.ts","../../src/integrations-react/client.ts","../../src/integrations-react/panel.tsx","../../src/integrations-react/projection.ts","../../src/integrations-react/use-hub-integrations.ts"],"sourcesContent":["import { useEffect, useState } from 'react'\nimport { HUB_CONNECTED_MESSAGE_TYPE, HUB_CONNECT_CHANNEL, HUB_CONNECT_FAILED_MESSAGE_TYPE, localAppUrl } from './popup'\n\nexport interface HubConnectCallbackPageProps {\n /** Local settings destination owned by the consuming app. */\n returnHref: string\n}\n\n/** The callback only signals completion; the opener verifies fresh Hub state. */\nexport function HubConnectCallbackPage({ returnHref }: HubConnectCallbackPageProps) {\n const [phase, setPhase] = useState<'checking' | 'returned' | 'failed'>('checking')\n const [reason, setReason] = useState('')\n\n useEffect(() => {\n const params = new URLSearchParams(window.location.search)\n const provider = params.get('provider')\n const nonce = params.get('nonce')\n const context = params.get('context')\n if (!provider || !nonce || !context) { setReason('This connection callback is incomplete.'); setPhase('failed'); return }\n const failure = params.get('error_description') || params.get('error')\n try {\n const channel = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n channel.postMessage({ type: failure ? HUB_CONNECT_FAILED_MESSAGE_TYPE : HUB_CONNECTED_MESSAGE_TYPE, provider, nonce, context })\n channel.close()\n } catch { /* The opener also polls the authoritative connection list. */ }\n if (failure) { setReason(failure.slice(0, 200)); setPhase('failed'); return }\n window.close()\n const timer = window.setTimeout(() => setPhase('returned'), 150)\n return () => window.clearTimeout(timer)\n }, [])\n\n const destination = localAppUrl(returnHref)\n const localReturn = destination ? `${destination.pathname}${destination.search}${destination.hash}` : '/'\n return <main aria-live=\"polite\" style={{ maxWidth: 560, margin: '20vh auto', padding: 24, textAlign: 'center' }}>\n {phase === 'checking' ? <p>Checking your connection…</p> : phase === 'returned'\n ? <p>Return to the app to check your connection. You can close this window.</p>\n : <p>Could not complete the connection. {reason}</p>}\n <a href={localReturn}>Return to integrations</a>\n </main>\n}\n","import type { HubConnection } from '@tangle-network/hub-sdk'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\n\nexport const HUB_CONNECT_CHANNEL = 'tangle:hub-connect'\nexport const HUB_CONNECTED_MESSAGE_TYPE = 'tangle:hub-connected'\nexport const HUB_CONNECT_FAILED_MESSAGE_TYPE = 'tangle:hub-connect-failed'\nexport const POPUP_TIMEOUT_MS = 5 * 60 * 1000\nconst PRE_REDIRECT_TIMEOUT_MS = 30_000\nconst POLL_INTERVAL_MS = 2500\nconst POPUP_FEATURES = 'popup=yes,width=520,height=680'\n\nexport type PopupConnectResult = 'connected' | 'blocked' | 'cancelled' | 'unverified' | 'unavailable'\n\nexport function localAppUrl(path: string): URL | null {\n if (!path.startsWith('/') || path.startsWith('//')) return null\n try {\n const origin = typeof window === 'undefined' ? 'https://local.invalid' : window.location.origin\n const url = new URL(path, origin)\n return url.origin === origin && !url.username && !url.password ? url : null\n } catch { return null }\n}\n\nfunction updatedConnection(providerId: string, before: readonly HubConnection[], after: readonly HubConnection[]): boolean {\n const previous = new Map(before.filter(connection => connection.providerId === providerId).map(connection => [connection.id, connection]))\n return after.some(connection => {\n if (connection.providerId !== providerId || connection.status !== 'active' || connection.health === 'unhealthy') return false\n const old = previous.get(connection.id)\n return !old || old.updatedAt !== connection.updatedAt || old.status !== connection.status\n })\n}\n\nfunction closePopup(popup: Window): void {\n try { if (!popup.closed) popup.close() } catch { /* COOP may sever the handle. */ }\n}\n\nfunction withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) { reject(new DOMException('Aborted', 'AbortError')); return }\n const onAbort = () => reject(new DOMException('Aborted', 'AbortError'))\n signal.addEventListener('abort', onAbort, { once: true })\n promise.then(value => { signal.removeEventListener('abort', onAbort); resolve(value) }, error => { signal.removeEventListener('abort', onAbort); reject(error) })\n })\n}\n\nfunction waitForConnection(input: {\n popup: Window\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n nonce: string\n contextToken: string\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n return new Promise(resolve => {\n let settled = false\n let checking = false\n let pollId: number | undefined\n let timeoutId: number | undefined\n let channel: BroadcastChannel | undefined\n const finish = (result: PopupConnectResult) => {\n if (settled) return\n settled = true\n if (pollId !== undefined) window.clearTimeout(pollId)\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n input.signal.removeEventListener('abort', onAbort)\n channel?.close()\n closePopup(input.popup)\n resolve(result)\n }\n const onAbort = () => finish('cancelled')\n const check = async () => {\n if (settled || checking) return\n checking = true\n if (!input.isCurrent() || input.signal.aborted) { finish('cancelled'); return }\n try {\n const after = await input.client.connections(input.identity, input.signal)\n if (input.isCurrent() && updatedConnection(input.providerId, input.before, after)) { finish('connected'); return }\n } catch { /* A lost read is never evidence of a connection. Keep polling. */ }\n checking = false\n if (!settled) pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n }\n if (input.signal.aborted) { finish('cancelled'); return }\n input.signal.addEventListener('abort', onAbort, { once: true })\n try {\n const candidate = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n candidate.onmessage = event => {\n const message = event.data as Record<string, unknown> | null\n if (!message || message.provider !== input.providerId || message.nonce !== input.nonce || message.context !== input.contextToken) return\n if (message.type === HUB_CONNECT_FAILED_MESSAGE_TYPE) finish('cancelled')\n if (message.type === HUB_CONNECTED_MESSAGE_TYPE) {\n if (pollId !== undefined) window.clearTimeout(pollId)\n void check()\n }\n }\n channel = candidate\n } catch { /* Polling covers browsers without BroadcastChannel. */ }\n pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n timeoutId = window.setTimeout(() => finish('unverified'), POPUP_TIMEOUT_MS)\n })\n}\n\n/** Opens before the first await, preserving the initiating user gesture. */\nexport async function connectWithPopup(input: {\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n callbackPath: string\n connectionParameters?: Record<string, string>\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n const callback = localAppUrl(input.callbackPath)\n if (!callback) throw new TypeError('Callback path must be local.')\n const popup = window.open('', '_blank', POPUP_FEATURES)\n if (!popup) return 'blocked'\n // Keep the parent handle for navigation while removing the provider page's opener.\n try { popup.opener = null } catch { /* Some browsers make this read-only. */ }\n const nonce = crypto.randomUUID()\n const contextToken = crypto.randomUUID()\n callback.searchParams.set('provider', input.providerId)\n callback.searchParams.set('nonce', nonce)\n callback.searchParams.set('context', contextToken)\n const timeout = new AbortController()\n const onAbort = () => timeout.abort()\n input.signal.addEventListener('abort', onAbort, { once: true })\n const preRedirectId = window.setTimeout(() => timeout.abort(), PRE_REDIRECT_TIMEOUT_MS)\n try {\n if (!input.isCurrent()) return 'cancelled'\n const start = await withAbort(input.client.startOAuth(input.identity, input.providerId, {\n returnUrl: callback.href,\n ...(input.connectionParameters === undefined ? {} : { connectionParameters: input.connectionParameters }),\n }, timeout.signal), timeout.signal)\n if (!input.isCurrent() || input.signal.aborted) return 'cancelled'\n let redirect: URL\n try { redirect = new URL(start.redirectUrl) } catch { return 'unavailable' }\n if (redirect.protocol !== 'https:' || redirect.username || redirect.password) return 'unavailable'\n window.clearTimeout(preRedirectId)\n const waitController = new AbortController()\n const abortWait = () => waitController.abort()\n input.signal.addEventListener('abort', abortWait, { once: true })\n if (input.signal.aborted) abortWait()\n const waiting = waitForConnection({ ...input, popup, nonce, contextToken, signal: waitController.signal })\n try {\n popup.location.href = redirect.href\n return await waiting\n } catch {\n waitController.abort()\n await waiting\n return 'unavailable'\n } finally {\n input.signal.removeEventListener('abort', abortWait)\n }\n } catch {\n return input.signal.aborted || timeout.signal.aborted ? 'cancelled' : 'unavailable'\n } finally {\n window.clearTimeout(preRedirectId)\n input.signal.removeEventListener('abort', onAbort)\n closePopup(popup)\n }\n}\n","import type {\n HubApiKeyConnectionMetadata,\n HubConnection,\n HubConnectionHealthResponse,\n HubOAuthStartResponse,\n HubPolicy,\n HubPolicyDecision,\n HubProvider,\n HubTool,\n} from '@tangle-network/hub-sdk'\n\n/** The host must bind each request to this server-verified identity. */\nexport interface HubIntegrationsIdentity {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsRequest {\n readonly identity: HubIntegrationsIdentity\n readonly path: string\n readonly init: RequestInit\n}\n\n/**\n * The host supplies its authenticated fetch, CSRF protection and expected\n * identity check. The browser never receives a Hub credential or SDK client.\n */\nexport type HubSettingsRequestFn = (request: HubSettingsRequest) => Promise<Response>\n\nexport interface HubIntegrationsClient {\n providers(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubProvider[]>\n connections(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubConnection[]>\n startOAuth(identity: HubIntegrationsIdentity, providerId: string, input: { returnUrl: string; connectionParameters?: Record<string, string> }, signal?: AbortSignal): Promise<HubOAuthStartResponse>\n connectApiKey(identity: HubIntegrationsIdentity, providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata, signal?: AbortSignal): Promise<HubConnection>\n revoke(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnection>\n health(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnectionHealthResponse>\n actions(identity: HubIntegrationsIdentity, providerId: string, limit: number, signal?: AbortSignal): Promise<HubTool[]>\n policies(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubPolicy[]>\n setPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, decision: HubPolicyDecision, signal?: AbortSignal): Promise<HubPolicy>\n resetPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, signal?: AbortSignal): Promise<void>\n}\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value as Record<string, unknown>\n}\n\nfunction array(value: unknown): unknown[] {\n if (!Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value\n}\n\nfunction namedArray<T>(value: unknown, key: string): T[] {\n const rows = array(object(value)[key])\n if (rows.some(row => row === null || typeof row !== 'object' || Array.isArray(row))) throw new Error('Invalid Hub settings response.')\n return rows as T[]\n}\n\nfunction namedObject<T>(value: unknown, key: string): T {\n return object(object(value)[key]) as T\n}\n\nfunction segment(value: string): string {\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value)) throw new TypeError('Invalid Hub settings identifier.')\n return encodeURIComponent(value)\n}\n\n/** Finite browser transport for the server-owned `createHubSettingsRoutes` API. */\nexport function createHubIntegrationsClient(request: HubSettingsRequestFn, basePath = '/api/hub/settings'): HubIntegrationsClient {\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath.')\n\n async function call(identity: HubIntegrationsIdentity, path: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', signal?: AbortSignal, body?: object): Promise<unknown> {\n if (![identity.userId, identity.sessionId, identity.workspaceId].every(part => typeof part === 'string' && part.trim())) {\n throw new TypeError('Hub settings identity is required.')\n }\n const response = await request({\n identity,\n path: `${basePath}${path}`,\n init: { method, signal, ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) },\n })\n if (!response.ok) {\n let code: string | undefined\n try {\n const error = object(await response.json())\n if (typeof error.code === 'string') code = error.code\n } catch { /* Status remains authoritative when a response is unreadable. */ }\n throw new Error(`Hub settings request failed (${response.status}${code ? `, ${code}` : ''}).`)\n }\n return response.json()\n }\n\n return {\n async providers(identity, signal) { return namedArray<HubProvider>(await call(identity, '/providers', 'GET', signal), 'providers') },\n async connections(identity, signal) { return namedArray<HubConnection>(await call(identity, '/connections', 'GET', signal), 'connections') },\n async startOAuth(identity, providerId, input, signal) {\n const response = object(await call(identity, `/connections/${segment(providerId)}/start`, 'POST', signal, input))\n if (typeof response.redirectUrl !== 'string') throw new Error('Invalid Hub OAuth response.')\n return response as unknown as HubOAuthStartResponse\n },\n async connectApiKey(identity, providerId, apiKey, metadata, signal) {\n return namedObject<HubConnection>(await call(identity, `/connections/${segment(providerId)}/connect-key`, 'POST', signal, { apiKey, ...(metadata === undefined ? {} : { metadata }) }), 'connection')\n },\n async revoke(identity, connectionId, signal) { return namedObject<HubConnection>(await call(identity, `/connections/${segment(connectionId)}`, 'DELETE', signal), 'connection') },\n async health(identity, connectionId, signal) {\n const response = object(await call(identity, `/connections/${segment(connectionId)}/health`, 'POST', signal))\n object(response.connection)\n object(response.health)\n return response as unknown as HubConnectionHealthResponse\n },\n async actions(identity, providerId, limit, signal) {\n if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new TypeError('Hub action limit must be 1–200.')\n const search = new URLSearchParams({ query: '', limit: String(limit) })\n return namedArray<HubTool>(await call(identity, `/providers/${segment(providerId)}/actions?${search}`, 'GET', signal), 'tools')\n },\n async policies(identity, connectionId, signal) {\n const search = new URLSearchParams({ connectionId })\n return namedArray<HubPolicy>(await call(identity, `/policies?${search}`, 'GET', signal), 'policies')\n },\n async setPolicy(identity, connectionId, actionPath, decision, signal) {\n return namedObject<HubPolicy>(await call(identity, '/policies', 'PUT', signal, { connectionId, actionPath, decision }), 'policy')\n },\n async resetPolicy(identity, connectionId, actionPath, signal) {\n const response = object(await call(identity, '/policies', 'DELETE', signal, { connectionId, actionPath }))\n if (response.connectionId !== connectionId || response.actionPath !== actionPath || typeof response.deleted !== 'boolean') {\n throw new Error('Invalid Hub policy reset response.')\n }\n },\n }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubProvider } from '@tangle-network/hub-sdk'\nimport {\n ApiKeyConnectDialog,\n IntegrationConnectionDetail,\n IntegrationsCatalog,\n OAuthConnectionParameterDialog,\n ProviderIcon,\n type IntegrationDisplayAction,\n type IntegrationSort,\n} from '@tangle-network/sandbox-ui/integrations'\nimport { Button, StatusPill, type StatusTone } from '@tangle-network/ui/primitives'\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { contextKey, displayProvider, type HubIntegrationCapabilities } from './projection'\nimport { useHubIntegrations } from './use-hub-integrations'\n\n/** Host-owned access state for one account, such as whether this agent can use it. */\nexport interface HubAccountStatus {\n label: string\n tone?: StatusTone\n}\n\n/**\n * Lists each connected account once, with its host status and one inline host\n * control. The catalog below then offers only providers without an account;\n * Manage opens permissions, Test, Disconnect and Connect another account.\n */\nexport interface HubIntegrationsAccounts {\n title: string\n description?: string\n /** Shown before any account exists. The catalog below is its next action. */\n emptyLabel?: string\n getStatus?: (connection: HubConnection) => HubAccountStatus | undefined\n /** The host authorizes this control and supplies its new status only after its server confirms. */\n getPrimaryAction?: (connection: HubConnection) => IntegrationDisplayAction | undefined\n /** Host-owned rows rendered after the accounts, such as access to an account that is no longer connected. */\n footer?: ReactNode\n}\n\nexport interface HubIntegrationsPanelProps {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n can: HubIntegrationCapabilities\n callbackPath: string\n title?: string\n className?: string\n onRequestIntegration?: (prefill: string) => void\n onUnsupportedConnect?: (provider: HubProvider) => void\n /** Host-owned context and actions; the host authorizes and confirms their effects. */\n getConnectionContext?: (connection: HubConnection) => string | undefined\n getConnectionActions?: (connection: HubConnection) => readonly IntegrationDisplayAction[]\n accounts?: HubIntegrationsAccounts\n /** Host-owned, transient fields for providers that require API-key metadata. */\n renderApiKeyMetadata?: (input: {\n provider: HubProvider\n value: HubApiKeyConnectionMetadata | undefined\n onChange: (value: HubApiKeyConnectionMetadata | undefined) => void\n }) => ReactNode\n}\n\nfunction catalogHref(): string {\n if (typeof window === 'undefined') return '/'\n const url = new URL(window.location.href)\n url.searchParams.delete('integration')\n url.searchParams.delete('connection')\n return `${url.pathname}${url.search}${url.hash}`\n}\n\nfunction accountName(connection: HubConnection, providerTitle: string): string {\n return connection.accountDisplay?.trim() || connection.displayName?.trim() || providerTitle\n}\n\nfunction AccountStatus({ connection, accounts }: { connection: HubConnection; accounts: HubIntegrationsAccounts }) {\n const status = accounts.getStatus?.(connection)\n return status ? <StatusPill tone={status.tone ?? 'neutral'} size=\"sm\" className=\"shrink-0\">{status.label}</StatusPill> : null\n}\n\nfunction AccountPrimaryAction({ connection, accounts, busy }: { connection: HubConnection; accounts: HubIntegrationsAccounts; busy: boolean }) {\n const primary = accounts.getPrimaryAction?.(connection)\n return primary ? <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={busy || primary.disabled}\n onClick={primary.onSelect}>{primary.label}</Button> : null\n}\n\nfunction HubAccountList({ accounts, connections, providers, loading, error, busy, onRetry, onManage, canManage }: {\n accounts: HubIntegrationsAccounts\n connections: readonly HubConnection[]\n providers: readonly HubProvider[]\n loading: boolean\n error: string | null\n busy: boolean\n onRetry: () => void\n onManage: (connection: HubConnection) => void\n canManage: (connection: HubConnection) => boolean\n}) {\n const titles = new Map(providers.map(provider => [provider.providerId, provider.title]))\n const title = (connection: HubConnection) => titles.get(connection.providerId) ?? connection.displayName ?? connection.providerId\n const rows = connections.filter(connection => connection.status !== 'revoked')\n .map(connection => ({ connection, provider: title(connection), name: accountName(connection, title(connection)) }))\n .sort((a, b) => a.provider.localeCompare(b.provider) || a.name.localeCompare(b.name) || a.connection.id.localeCompare(b.connection.id))\n return <section className=\"mb-8 min-w-0 space-y-3\" aria-labelledby=\"hub-accounts-heading\" aria-busy={loading || undefined}>\n <header>\n <h2 id=\"hub-accounts-heading\" className=\"text-lg font-semibold\">{accounts.title}</h2>\n {accounts.description ? <p className=\"mt-1 text-sm text-muted-foreground\">{accounts.description}</p> : null}\n </header>\n {error ? <div role=\"alert\" className=\"flex flex-wrap items-center gap-3 rounded-xl border border-destructive/40 bg-card p-4 text-sm text-destructive\">\n <p className=\"min-w-0 flex-1 break-words\">{error}</p>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={onRetry}>Retry</Button>\n </div> : loading && rows.length === 0 ? <p role=\"status\" className=\"rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground\">Loading connected accounts…</p>\n : rows.length === 0 ? <p className=\"rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground\">{accounts.emptyLabel ?? 'No accounts connected yet. Connect one below.'}</p>\n : <ul className=\"divide-y divide-border overflow-hidden rounded-xl border border-border bg-card\" aria-label={accounts.title}>\n {rows.map(({ connection, provider, name }) => {\n const health = connection.status !== 'active' ? connection.status.replaceAll('_', ' ')\n : connection.health === 'unhealthy' ? 'needs attention' : null\n return <li key={connection.id} data-testid={`hub-account-${connection.id}`}\n className=\"flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3\">\n <div className=\"flex min-w-0 flex-1 basis-56 items-center gap-3\">\n <ProviderIcon id={connection.providerId} displayName={provider} size={32} className=\"shrink-0 rounded-lg\" />\n <div className=\"min-w-0\">\n <p className=\"truncate text-sm font-medium\" title={name}>{name}</p>\n <p className=\"truncate text-xs text-muted-foreground\">{provider}{health ? ` · ${health}` : ''}</p>\n </div>\n </div>\n <div className=\"flex min-w-0 flex-wrap items-center gap-2 sm:justify-end\">\n <AccountStatus connection={connection} accounts={accounts} />\n <div className=\"flex shrink-0 items-center gap-1\">\n <AccountPrimaryAction connection={connection} accounts={accounts} busy={busy} />\n {canManage(connection) ? <Button type=\"button\" variant=\"ghost\" size=\"sm\" aria-label={`Manage ${provider} account ${name}`}\n onClick={() => onManage(connection)}>Manage</Button> : null}\n </div>\n </div>\n </li>\n })}\n </ul>}\n {accounts.footer}\n </section>\n}\n\n/** Embeddable settings surface. The app supplies authenticated transport and grants. */\nexport function HubIntegrationsPanel(props: HubIntegrationsPanelProps) {\n const hub = useHubIntegrations(props)\n const scope = contextKey(props.identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const activeDialog = useRef(hub.dialog)\n activeDialog.current = hub.dialog\n const [query, setQuery] = useState('')\n const [category, setCategory] = useState('')\n const [sort, setSort] = useState<IntegrationSort>('featured')\n const [catalogSelection, setCatalogSelection] = useState<{ scope: string; ids: Record<string, string | null> }>({ scope, ids: {} })\n const [keyInput, setKeyInput] = useState({ scope, value: '' })\n const apiKey = keyInput.scope === scope ? keyInput.value : ''\n const setApiKey = (value: string) => setKeyInput({ scope, value })\n const [metadataInput, setMetadataInput] = useState<{ scope: string; value: HubApiKeyConnectionMetadata | undefined }>({ scope, value: undefined })\n const metadata = metadataInput.scope === scope ? metadataInput.value : undefined\n const setMetadata = (value: HubApiKeyConnectionMetadata | undefined) => setMetadataInput({ scope, value })\n const [parameterInput, setParameterInput] = useState({ scope, values: {} as Record<string, string> })\n const parameters = parameterInput.scope === scope ? parameterInput.values : {}\n const setParameters = (values: Record<string, string>) => setParameterInput({ scope, values })\n\n useEffect(() => { setApiKey(''); setMetadata(undefined); setParameters({}) }, [scope])\n const pending = hub.writeState.status === 'pending' || hub.connectStatus.status === 'pending'\n const error = hub.providers.status === 'error' ? hub.providers.message\n : hub.connections.status === 'error' ? hub.connections.message : null\n const mutationError = hub.writeState.status === 'failed' ? hub.writeState.message : null\n const writeMessage = hub.writeState.status === 'succeeded' ? hub.writeState.value.message : null\n const writeWarning = hub.writeState.status === 'succeeded' && hub.writeState.value.reconciliation === 'refresh-failed'\n const rows = hub.rows.map(row => {\n const selectedId = catalogSelection.scope === scope ? catalogSelection.ids[row.providerId] : null\n return {\n ...row,\n selectedConnectionId: row.connections.some(connection => connection.id === selectedId) ? selectedId ?? null : null,\n connections: row.connections.map(connection => {\n const source = hub.connections.status === 'ready'\n ? hub.connections.value.find(item => item.id === connection.id) : undefined\n return source ? {\n ...connection,\n detail: props.getConnectionContext?.(source) ?? connection.detail,\n actions: props.getConnectionActions?.(source),\n } : connection\n }),\n }\n })\n const selectedRow = rows.find(row => row.providerId === hub.provider?.providerId)\n // With an account list, the catalog only offers providers that have no account yet.\n const catalogRows = props.accounts ? rows.filter(row => row.connections.length === 0) : rows\n const connectionList = hub.connections.status === 'ready' ? hub.connections.value : []\n const selectedConnection = hub.connection\n const detailError = hub.detail.status === 'error' ? hub.detail.message\n : hub.detail.status === 'ready' && hub.detail.value.truncated\n ? `Showing at most ${hub.detail.value.tools.length} actions. The provider catalog may be incomplete.` : null\n const detailsByConnectionId = useMemo(() => hub.connection ? {\n [hub.connection.id]: {\n ...hub.details,\n loading: hub.detail.status === 'loading',\n busy: pending,\n error: detailError,\n },\n } : {}, [hub.connection, hub.details, hub.detail.status, pending, detailError])\n\n const closeDialog = () => {\n if (hub.connectStatus.status === 'pending') hub.cancelConnect()\n else hub.setDialog(null)\n setApiKey(''); setMetadata(undefined); setParameters({})\n }\n\n return <section className={props.className}>\n {hub.connectStatus.status === 'pending' ? <div role=\"status\" className=\"mb-4 flex flex-wrap items-center gap-3\">\n <span>Finish connecting in the popup.</span>\n <Button type=\"button\" variant=\"outline\" onClick={hub.cancelConnect}>Cancel connection</Button>\n </div> : null}\n {hub.writeState.status === 'pending' ? <p role=\"status\">Saving Hub settings…</p> : null}\n {mutationError ? <p role=\"alert\">{mutationError}</p> : null}\n {writeMessage ? <p role={writeWarning ? 'alert' : 'status'}>{writeMessage}</p> : null}\n {hub.connectStatus.message && hub.provider ? <p role={hub.connectStatus.status === 'failed' ? 'alert' : 'status'}>{hub.connectStatus.message}</p> : null}\n {hub.provider ? <>\n {(props.accounts && selectedConnection) || selectedRow?.canConnect ? <div className=\"mb-4 flex min-w-0 flex-wrap items-center gap-2\">\n {props.accounts && selectedConnection ? <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-2\" data-testid=\"hub-account-access\"\n aria-label={`Access for ${accountName(selectedConnection, hub.provider.title)}`} role=\"group\">\n <span className=\"min-w-0 max-w-full truncate text-sm font-medium\">{accountName(selectedConnection, hub.provider.title)}</span>\n <AccountStatus connection={selectedConnection} accounts={props.accounts} />\n <AccountPrimaryAction connection={selectedConnection} accounts={props.accounts} busy={pending} />\n </div> : null}\n {selectedRow?.canConnect ? <Button type=\"button\" variant=\"outline\" className=\"ml-auto\" disabled={pending}\n onClick={() => hub.beginConnect(hub.provider!)}>Connect another account</Button> : null}\n </div> : null}\n <IntegrationConnectionDetail\n provider={displayProvider(hub.provider)}\n connections={selectedRow?.connections ?? []}\n selectedConnectionId={hub.connection?.id ?? null}\n onSelectConnection={connectionId => hub.selectConnection(hub.provider!.providerId, connectionId)}\n detailsByConnectionId={detailsByConnectionId}\n loading={hub.connections.status === 'loading' || hub.detail.status === 'loading'}\n error={detailError}\n backHref={catalogHref()}\n onRetry={() => hub.refresh()}\n onTestConnection={connectionId => { void hub.test(connectionId) }}\n onDisconnect={connectionId => { void hub.revoke(connectionId) }}\n onDecisionChange={(connectionId, actionPath, decision) => {\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') return\n void hub.setDecision(connectionId, actionPath, decision)\n }}\n onResetDecision={(connectionId, actionPath) => { void hub.resetDecision(connectionId, actionPath) }}\n />\n </> : <>\n {props.accounts ? <>\n {hub.connectStatus.status === 'connected' && hub.connectStatus.message ? <p role=\"status\" className=\"mb-3 text-sm\">{hub.connectStatus.message}</p> : null}\n <HubAccountList accounts={props.accounts} connections={connectionList} providers={hub.providers.status === 'ready' ? hub.providers.value : []}\n loading={hub.connections.status === 'loading'} error={hub.connections.status === 'error' ? hub.connections.message : null} busy={pending}\n onRetry={() => hub.refresh()} onManage={connection => hub.selectConnection(connection.providerId, connection.id)}\n canManage={connection => props.can({ operation: 'policies.list', connectionId: connection.id })} />\n </> : null}\n {props.accounts && hub.connections.status === 'error' ? null : <IntegrationsCatalog\n title={props.title ?? 'Integrations'}\n rows={catalogRows}\n query={query}\n onQueryChange={setQuery}\n categoryFilter={category}\n onCategoryFilterChange={setCategory}\n sort={sort}\n onSortChange={setSort}\n onSelectConnection={(providerId, connectionId) => setCatalogSelection(current => ({\n scope,\n ids: { ...(current.scope === scope ? current.ids : {}), [providerId]: connectionId },\n }))}\n onConnect={row => { const provider = hub.providers.status === 'ready' ? hub.providers.value.find(item => item.providerId === row.providerId) : null; if (provider) hub.beginConnect(provider) }}\n onManage={(connection, row) => hub.selectConnection(row.providerId, connection.id)}\n onDisconnect={connection => { void hub.revoke(connection.id) }}\n onRequestIntegration={props.onRequestIntegration}\n onRetry={() => hub.refresh()}\n loading={hub.providers.status === 'loading' || hub.connections.status === 'loading'}\n error={error}\n actionError={mutationError}\n connectError={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n busyProviderId={hub.connectStatus.status === 'pending' ? hub.connectStatus.providerId ?? null : null}\n reserveConnectionContext\n emptyCatalogLabel={props.accounts && rows.length > 0 ? 'Every available integration already has a connected account above.' : undefined}\n />}\n </>}\n {hub.dialog?.kind === 'api-key' ? <ApiKeyConnectDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n description={hub.dialog.provider.authHint}\n value={apiKey}\n onValueChange={setApiKey}\n busy={pending}\n error={mutationError}\n canSubmit={apiKey.trim().length > 0 && !pending}\n onSubmit={() => {\n const secret = apiKey\n const target = hub.dialog?.provider.providerId\n const submittedDialog = hub.dialog\n setApiKey('')\n if (target) void hub.submitApiKey(target, secret, metadata).then(result => {\n if (result.succeeded && activeScope.current === scope && activeDialog.current === submittedDialog) {\n hub.setDialog(null); setMetadata(undefined)\n }\n })\n }}\n >{props.renderApiKeyMetadata?.({ provider: hub.dialog.provider, value: metadata, onChange: setMetadata })}</ApiKeyConnectDialog> : null}\n {hub.dialog?.kind === 'oauth' ? <OAuthConnectionParameterDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n parameters={hub.dialog.provider.connectionParameters ?? []}\n values={parameters}\n onValueChange={(key, value) => setParameters({ ...parameters, [key]: value })}\n busy={pending}\n error={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n canSubmit={!pending && (hub.dialog.provider.connectionParameters ?? []).every(field => !field.required || !!parameters[field.key]?.trim())}\n onSubmit={() => {\n const target = hub.dialog?.provider\n const submittedDialog = hub.dialog\n if (target) void hub.startOAuth(target, parameters).then(result => {\n if (result === 'connected' && activeScope.current === scope && activeDialog.current === submittedDialog) setParameters({})\n })\n }}\n /> : null}\n </section>\n}\n","import type { HubConnection, HubPolicy, HubProvider, HubTool } from '@tangle-network/hub-sdk'\nimport type {\n IntegrationConnectionDetails,\n IntegrationDisplayProvider,\n IntegrationPermissionDisplay,\n IntegrationPermissionGroup,\n IntegrationsProviderRow,\n} from '@tangle-network/sandbox-ui/integrations'\n\nexport type HubIntegrationCapability =\n | { operation: 'oauth.start' | 'api-key.connect'; providerId: string }\n | { operation: 'connection.revoke' | 'connection.health' | 'policies.list'; connectionId: string }\n | { operation: 'policy.set' | 'policy.reset'; connectionId: string; actionPath: string }\n\n/** Display hints only. `createHubSettingsRoutes.authorize` remains authoritative. */\nexport type HubIntegrationCapabilities = (intent: HubIntegrationCapability) => boolean\n\nexport const ACTION_LIMIT = 200\n\nexport function contextKey(identity: { userId: string; sessionId: string; workspaceId: string }): string {\n return JSON.stringify([identity.userId, identity.sessionId, identity.workspaceId])\n}\n\nexport function displayProvider(provider: HubProvider): IntegrationDisplayProvider {\n return { providerId: provider.providerId, title: provider.title, category: provider.category }\n}\n\nexport function catalogRows(\n providers: readonly HubProvider[],\n connections: readonly HubConnection[],\n selectedIds: Readonly<Record<string, string | null>>,\n can: HubIntegrationCapabilities,\n hasUnsupportedConnect = false,\n): IntegrationsProviderRow[] {\n return providers.map(provider => {\n const accounts = connections.filter(connection => connection.providerId === provider.providerId)\n return {\n ...displayProvider(provider),\n kind: 'provider',\n authKind: provider.authKind,\n selectedConnectionId: accounts.some(account => account.id === selectedIds[provider.providerId])\n ? selectedIds[provider.providerId] ?? null : null,\n canConnect: provider.authKind === 'oauth2'\n ? provider.configured && can({ operation: 'oauth.start', providerId: provider.providerId })\n : provider.authKind === 'api_key'\n ? provider.configured && can({ operation: 'api-key.connect', providerId: provider.providerId })\n : hasUnsupportedConnect,\n connections: accounts.map(connection => ({\n id: connection.id,\n accountDisplay: connection.accountDisplay ?? connection.displayName,\n statusLabel: connection.status === 'active' ? 'Connected' : connection.status.replaceAll('_', ' '),\n statusTone: connection.status === 'active' && connection.health !== 'unhealthy' ? 'success' : 'warning',\n detail: connection.providerAccountId ?? undefined,\n capabilities: {\n manage: can({ operation: 'policies.list', connectionId: connection.id }),\n disconnect: can({ operation: 'connection.revoke', connectionId: connection.id }),\n test: can({ operation: 'connection.health', connectionId: connection.id }),\n editPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n resetPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n },\n })),\n }\n })\n}\n\nconst OPTIONS = [\n { value: 'allow', label: 'Allow' },\n { value: 'ask', label: 'Ask' },\n { value: 'deny', label: 'Deny' },\n] as const\n\n/** Stored overrides are shown; app-specific effective policy is never guessed. */\nexport function permissionDetails(\n tools: readonly HubTool[],\n policies: readonly HubPolicy[],\n connectionId: string,\n can: HubIntegrationCapabilities,\n): IntegrationConnectionDetails {\n const overrides = new Map(policies.filter(policy => policy.connectionId === connectionId).map(policy => [policy.actionPath, policy.decision]))\n const groups: IntegrationPermissionGroup[] = [\n { id: 'writes', title: 'Write and unknown actions', rows: [] },\n { id: 'reads', title: 'Read actions', collapsed: true, rows: [] },\n ]\n const writes: IntegrationPermissionDisplay[] = []\n const reads: IntegrationPermissionDisplay[] = []\n for (const tool of tools) {\n const override = overrides.get(tool.path)\n const row = {\n actionPath: tool.path,\n title: tool.title ?? tool.path,\n riskLabel: tool.risk ?? 'unknown',\n riskTone: tool.risk === 'destructive' ? 'error' : tool.risk === 'write' || tool.risk === undefined ? 'warning' : 'neutral',\n decision: override ?? null,\n decisionOptions: OPTIONS,\n sourceLabel: override ? 'Stored override' : 'No stored override',\n canReset: override !== undefined && can({ operation: 'policy.reset', connectionId, actionPath: tool.path }),\n disabled: !can({ operation: 'policy.set', connectionId, actionPath: tool.path }),\n } as const\n if (tool.risk === 'read') reads.push(row)\n else writes.push(row)\n }\n writes.sort((a, b) => a.title.localeCompare(b.title))\n reads.sort((a, b) => a.title.localeCompare(b.title))\n groups[0] = { ...groups[0]!, rows: writes }\n groups[1] = { ...groups[1]!, rows: reads }\n return { permissionGroups: groups }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubPolicyDecision, HubProvider } from '@tangle-network/hub-sdk'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { confirmWrite, useAsyncResource, useConfirmedMutation } from '../web-react/async'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { connectWithPopup, type PopupConnectResult } from './popup'\nimport { ACTION_LIMIT, catalogRows, contextKey, permissionDetails, type HubIntegrationCapabilities } from './projection'\n\ntype Selection = { scope: string; providerId: string | null; connectionId: string | null }\ntype Dialog = { scope: string; kind: 'api-key' | 'oauth'; provider: HubProvider } | null\n\nexport interface UseHubIntegrationsOptions {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n /** Display only. The host server must authorize every exact operation. */\n can: HubIntegrationCapabilities\n /** Local app route that renders `HubConnectCallbackPage`. */\n callbackPath: string\n /** Optional host handler for custom/native signup. No Platform redirect is assumed. */\n onUnsupportedConnect?: (provider: HubProvider) => void\n}\n\ntype WriteInput =\n | { kind: 'api-key'; identity: HubIntegrationsIdentity; scope: string; providerId: string; apiKey: string; metadata?: HubApiKeyConnectionMetadata }\n | { kind: 'revoke'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'health'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'set'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string; decision: HubPolicyDecision }\n | { kind: 'reset'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string }\n\nexport interface HubWriteReceipt {\n scope: string\n kind: WriteInput['kind']\n reconciliation: 'verified' | 'refresh-failed'\n message: string\n}\n\nfunction initialSelection(scope: string): Selection {\n if (typeof window === 'undefined') return { scope, providerId: null, connectionId: null }\n const query = new URL(window.location.href).searchParams\n return { scope, providerId: query.get('integration'), connectionId: query.get('connection') }\n}\n\nfunction updateUrl(providerId: string | null, connectionId: string | null): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n if (providerId) url.searchParams.set('integration', providerId)\n else url.searchParams.delete('integration')\n if (connectionId) url.searchParams.set('connection', connectionId)\n else url.searchParams.delete('connection')\n window.history.pushState(window.history.state, '', url)\n}\n\n/** Identity-bound Hub settings controller; connection state is always server-read. */\nexport function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect }: UseHubIntegrationsOptions) {\n const scope = contextKey(identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const [selection, setSelection] = useState<Selection>(() => initialSelection(scope))\n const visibleSelection = selection.scope === scope ? selection : { scope, providerId: null, connectionId: null }\n const [dialog, setDialog] = useState<Dialog>(null)\n const visibleDialog = dialog?.scope === scope ? dialog : null\n const [connectStatus, setConnectStatus] = useState<{ scope: string; status: 'idle' | 'pending' | 'connected' | 'failed'; providerId?: string; message?: string }>({ scope, status: 'idle' })\n const [writeScope, setWriteScope] = useState(scope)\n const pendingPopup = useRef<AbortController | null>(null)\n\n useEffect(() => {\n const onPop = () => setSelection(initialSelection(scope))\n window.addEventListener('popstate', onPop)\n return () => window.removeEventListener('popstate', onPop)\n }, [scope])\n\n const providers = useAsyncResource({ load: ({ signal }) => client.providers(identity, signal), deps: [client, scope], isEmpty: () => false })\n const connections = useAsyncResource({ load: ({ signal }) => client.connections(identity, signal), deps: [client, scope], isEmpty: () => false })\n const providerList = providers.status === 'ready' ? providers.value : []\n const connectionList = connections.status === 'ready' ? connections.value : []\n const provider = providerList.find(item => item.providerId === visibleSelection.providerId) ?? null\n const connection = connectionList.find(item => item.id === visibleSelection.connectionId && item.providerId === provider?.providerId) ?? null\n const canReadPolicies = connection !== null && can({ operation: 'policies.list', connectionId: connection.id })\n const detail = useAsyncResource({\n enabled: canReadPolicies && connection?.status === 'active',\n deps: [client, scope, provider?.providerId, connection?.id, canReadPolicies],\n isEmpty: () => false,\n load: async ({ signal }) => {\n if (!provider || !connection) throw new Error('Choose a connection.')\n const [tools, policies] = await Promise.all([\n client.actions(identity, provider.providerId, ACTION_LIMIT, signal),\n client.policies(identity, connection.id, signal),\n ])\n if (tools.some(tool => !tool.path.startsWith(`${provider.providerId}.`)) || policies.some(policy => policy.connectionId !== connection.id)) {\n throw new Error('Hub settings response changed connection or provider.')\n }\n return { tools, policies, truncated: tools.length >= ACTION_LIMIT }\n },\n })\n\n const write = useConfirmedMutation<WriteInput, HubWriteReceipt>({\n concurrency: 'reject',\n mutate: async (input, { signal }) => {\n if (input.scope !== activeScope.current) throw new Error('Integration context changed. Retry in the current workspace.')\n const origin = input.identity\n const receipt = (reconciliation: HubWriteReceipt['reconciliation'], message: string) => confirmWrite<HubWriteReceipt>({ scope: input.scope, kind: input.kind, reconciliation, message })\n if (input.kind === 'api-key') {\n if (!can({ operation: 'api-key.connect', providerId: input.providerId })) throw new Error('Connection setup is unavailable.')\n const created = await client.connectApiKey(origin, input.providerId, input.apiKey, input.metadata, signal)\n if (created.providerId !== input.providerId || created.status !== 'active') throw new Error('Hub did not confirm the requested connection.')\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === created.id && item.status === 'active')\n ? receipt('verified', 'Connection saved and verified.') : receipt('refresh-failed', 'Connection saved; current account state could not be confirmed.')\n } catch { return receipt('refresh-failed', 'Connection saved; refresh failed.') }\n }\n if (input.kind === 'revoke') {\n if (!can({ operation: 'connection.revoke', connectionId: input.connectionId })) throw new Error('Disconnect is unavailable.')\n await client.revoke(origin, input.connectionId, signal)\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === input.connectionId && item.status === 'active')\n ? receipt('refresh-failed', 'Disconnected, but the current account state disagrees.') : receipt('verified', 'Connection disconnected and verified.')\n } catch { return receipt('refresh-failed', 'Disconnected; refresh failed.') }\n }\n if (input.kind === 'health') {\n if (!can({ operation: 'connection.health', connectionId: input.connectionId })) throw new Error('Connection test is unavailable.')\n const result = await client.health(origin, input.connectionId, signal)\n if (result.connection.id !== input.connectionId) throw new Error('Hub returned another connection.')\n return receipt('verified', `Connection test: ${result.health.status.replaceAll('_', ' ')}.`)\n }\n if (!can({ operation: input.kind === 'set' ? 'policy.set' : 'policy.reset', connectionId: input.connectionId, actionPath: input.actionPath })) {\n throw new Error('Permission editing is unavailable.')\n }\n if (input.kind === 'set') {\n const stored = await client.setPolicy(origin, input.connectionId, input.actionPath, input.decision, signal)\n if (stored.connectionId !== input.connectionId || stored.actionPath !== input.actionPath || stored.decision !== input.decision) {\n throw new Error('Hub did not confirm the requested permission.')\n }\n } else await client.resetPolicy(origin, input.connectionId, input.actionPath, signal)\n try {\n const current = await client.policies(origin, input.connectionId, signal)\n const override = current.find(policy => policy.actionPath === input.actionPath)\n const matches = input.kind === 'set' ? override?.decision === input.decision : override === undefined\n return matches\n ? receipt('verified', 'Permission saved and verified.') : receipt('refresh-failed', 'Permission write was accepted; current policy state disagrees.')\n } catch { return receipt('refresh-failed', 'Permission write was accepted; refresh failed.') }\n },\n onSucceeded: value => { if (value.scope === activeScope.current) { connections.retry(); detail.retry() } },\n })\n\n useEffect(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'idle' })\n setWriteScope(scope)\n write.reset()\n return () => { pendingPopup.current?.abort(); pendingPopup.current = null }\n }, [scope, client, write.reset])\n\n const selectProvider = useCallback((providerId: string | null) => {\n const next = { scope, providerId, connectionId: null }\n setSelection(next)\n updateUrl(providerId, null)\n }, [scope])\n\n const selectConnection = useCallback((providerId: string, connectionId: string | null) => {\n if (connectionId && !connectionList.some(item => item.id === connectionId && item.providerId === providerId)) return\n setSelection({ scope, providerId, connectionId })\n updateUrl(providerId, connectionId)\n }, [scope, connectionList])\n\n const startOAuth = useCallback(async (target: HubProvider, connectionParameters?: Record<string, string>): Promise<PopupConnectResult> => {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) return 'unavailable'\n if (connections.status !== 'ready') { setConnectStatus({ scope, status: 'failed', message: 'Load connections before connecting.' }); return 'unavailable' }\n pendingPopup.current?.abort()\n const controller = new AbortController()\n pendingPopup.current = controller\n setConnectStatus({ scope, status: 'pending', providerId: target.providerId })\n const result = await connectWithPopup({\n client, identity, providerId: target.providerId, before: connections.value,\n callbackPath, connectionParameters, signal: controller.signal,\n isCurrent: () => activeScope.current === scope && !controller.signal.aborted,\n })\n if (pendingPopup.current !== controller || activeScope.current !== scope) return result\n pendingPopup.current = null\n if (result === 'connected') {\n connections.retry()\n setDialog(null)\n setConnectStatus({ scope, status: 'connected', message: 'Connection verified.' })\n } else setConnectStatus({ scope, status: 'failed', message: result === 'blocked' ? 'Allow the popup and try again.' : result === 'unverified' ? 'Could not verify a new connection. Refresh and try again.' : result === 'cancelled' ? 'Connection was cancelled.' : 'This connection flow is unavailable.' })\n return result\n }, [can, connections, client, identity, callbackPath, scope])\n\n const beginConnect = useCallback((target: HubProvider) => {\n if (target.authKind !== 'api_key' && target.authKind !== 'oauth2') {\n if (onUnsupportedConnect) onUnsupportedConnect(target)\n else setConnectStatus({ scope, status: 'failed', message: 'This provider needs an app-specific connection flow.' })\n return\n }\n if (!target.configured) {\n setConnectStatus({ scope, status: 'failed', message: 'This provider is not configured for connection.' })\n return\n }\n if (target.authKind === 'api_key') {\n if (can({ operation: 'api-key.connect', providerId: target.providerId })) setDialog({ scope, kind: 'api-key', provider: target })\n else setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' })\n return\n }\n if (target.authKind === 'oauth2') {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) {\n setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' }); return\n }\n if (target.connectionParameters?.length) setDialog({ scope, kind: 'oauth', provider: target })\n else void startOAuth(target)\n return\n }\n }, [can, onUnsupportedConnect, scope, startOAuth])\n\n const cancelConnect = useCallback(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'failed', message: 'Connection was cancelled.' })\n }, [scope])\n\n const rows = useMemo(() => catalogRows(providerList, connectionList, visibleSelection.providerId && visibleSelection.connectionId\n ? { [visibleSelection.providerId]: visibleSelection.connectionId } : {}, can, !!onUnsupportedConnect),\n [providerList, connectionList, visibleSelection.providerId, visibleSelection.connectionId, can, onUnsupportedConnect])\n const details = detail.status === 'ready' && connection\n ? permissionDetails(detail.value.tools, detail.value.policies, connection.id, can) : undefined\n\n return {\n providers, connections, detail, rows, provider, connection, dialog: visibleDialog, setDialog,\n connectStatus: connectStatus.scope === scope ? connectStatus : { scope, status: 'idle' as const, providerId: undefined },\n selection: visibleSelection, selectProvider, selectConnection, beginConnect, startOAuth, cancelConnect,\n write, writeState: writeScope === scope ? write.state : { status: 'idle' as const }, details,\n refresh: () => { providers.retry(); connections.retry(); detail.retry() },\n submitApiKey: (providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata) => { setWriteScope(scope); return write.run({ kind: 'api-key', identity, scope, providerId, apiKey, metadata }) },\n revoke: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'revoke', identity, scope, connectionId }) },\n test: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'health', identity, scope, connectionId }) },\n setDecision: (connectionId: string, actionPath: string, decision: HubPolicyDecision) => { setWriteScope(scope); return write.run({ kind: 'set', identity, scope, connectionId, actionPath, decision }) },\n resetDecision: (connectionId: string, actionPath: string) => { setWriteScope(scope); return write.run({ kind: 'reset', identity, scope, connectionId, actionPath }) },\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,WAAW,gBAAgB;;;ACG7B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,kCAAkC;AACxC,IAAM,mBAAmB,IAAI,KAAK;AACzC,IAAM,0BAA0B;AAChC,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AAIhB,SAAS,YAAY,MAA0B;AACpD,MAAI,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,EAAG,QAAO;AAC3D,MAAI;AACF,UAAM,SAAS,OAAO,WAAW,cAAc,0BAA0B,OAAO,SAAS;AACzF,UAAM,MAAM,IAAI,IAAI,MAAM,MAAM;AAChC,WAAO,IAAI,WAAW,UAAU,CAAC,IAAI,YAAY,CAAC,IAAI,WAAW,MAAM;AAAA,EACzE,QAAQ;AAAE,WAAO;AAAA,EAAK;AACxB;AAEA,SA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iBAAiB;AACjG,kBAAI,UAAU,IAAI;AAAG,0BAAY,MAAS;AAAA,YAC5C;AAAA,UACF,CAAC;AAAA,QACH;AAAA,QACA,gBAAM,uBAAuB,EAAE,UAAU,IAAI,OAAO,UAAU,OAAO,UAAU,UAAU,YAAY,CAAC;AAAA;AAAA,IAAE,IAAyB;AAAA,IAClI,IAAI,QAAQ,SAAS,UAAU,gBAAAA;AAAA,MAAC;AAAA;AAAA,QAC/B,MAAI;AAAA,QACJ,cAAc,UAAQ;AAAE,cAAI,CAAC,KAAM,aAAY;AAAA,QAAE;AAAA,QACjD,YAAY,IAAI,OAAO,SAAS;AAAA,QAChC,OAAO,IAAI,OAAO,SAAS;AAAA,QAC3B,YAAY,IAAI,OAAO,SAAS,wBAAwB,CAAC;AAAA,QACzD,QAAQ;AAAA,QACR,eAAe,CAAC,KAAK,UAAU,cAAc,EAAE,GAAG,YAAY,CAAC,GAAG,GAAG,MAAM,CAAC;AAAA,QAC5E,MAAM;AAAA,QACN,OAAO,IAAI,cAAc,WAAW,WAAW,IAAI,cAAc,UAAU;AAAA,QAC3E,WAAW,CAAC,YAAY,IAAI,OAAO,SAAS,wBAAwB,CAAC,GAAG,MAAM,WAAS,CAAC,MAAM,YAAY,CAAC,CAAC,WAAW,MAAM,GAAG,GAAG,KAAK,CAAC;AAAA,QACzI,UAAU,MAAM;AACd,gBAAM,SAAS,IAAI,QAAQ;AAC3B,gBAAM,kBAAkB,IAAI;AAC5B,cAAI,OAAQ,MAAK,IAAI,WAAW,QAAQ,UAAU,EAAE,KAAK,YAAU;AACjE,gBAAI,WAAW,eAAe,YAAY,YAAY,SAAS,aAAa,YAAY,gBAAiB,eAAc,CAAC,CAAC;AAAA,UAC3H,CAAC;AAAA,QACH;AAAA;AAAA,IACF,IAAK;AAAA,KACP;AACF;","names":["useEffect","useMemo","useRef","useState","useEffect","useState","useState","useEffect","jsx","jsxs","useRef","useState","useEffect","catalogRows","useMemo"]}
@@ -1,8 +1,30 @@
1
1
  import type { HubApiKeyConnectionMetadata, HubConnection, HubProvider } from '@tangle-network/hub-sdk';
2
2
  import { type IntegrationDisplayAction } from '@tangle-network/sandbox-ui/integrations';
3
+ import { type StatusTone } from '@tangle-network/ui/primitives';
3
4
  import { type ReactNode } from 'react';
4
5
  import type { HubIntegrationsClient, HubIntegrationsIdentity } from './client';
5
6
  import { type HubIntegrationCapabilities } from './projection';
7
+ /** Host-owned access state for one account, such as whether this agent can use it. */
8
+ export interface HubAccountStatus {
9
+ label: string;
10
+ tone?: StatusTone;
11
+ }
12
+ /**
13
+ * Lists each connected account once, with its host status and one inline host
14
+ * control. The catalog below then offers only providers without an account;
15
+ * Manage opens permissions, Test, Disconnect and Connect another account.
16
+ */
17
+ export interface HubIntegrationsAccounts {
18
+ title: string;
19
+ description?: string;
20
+ /** Shown before any account exists. The catalog below is its next action. */
21
+ emptyLabel?: string;
22
+ getStatus?: (connection: HubConnection) => HubAccountStatus | undefined;
23
+ /** The host authorizes this control and supplies its new status only after its server confirms. */
24
+ getPrimaryAction?: (connection: HubConnection) => IntegrationDisplayAction | undefined;
25
+ /** Host-owned rows rendered after the accounts, such as access to an account that is no longer connected. */
26
+ footer?: ReactNode;
27
+ }
6
28
  export interface HubIntegrationsPanelProps {
7
29
  identity: HubIntegrationsIdentity;
8
30
  client: HubIntegrationsClient;
@@ -15,6 +37,7 @@ export interface HubIntegrationsPanelProps {
15
37
  /** Host-owned context and actions; the host authorizes and confirms their effects. */
16
38
  getConnectionContext?: (connection: HubConnection) => string | undefined;
17
39
  getConnectionActions?: (connection: HubConnection) => readonly IntegrationDisplayAction[];
40
+ accounts?: HubIntegrationsAccounts;
18
41
  /** Host-owned, transient fields for providers that require API-key metadata. */
19
42
  renderApiKeyMetadata?: (input: {
20
43
  provider: HubProvider;
@@ -0,0 +1,2 @@
1
+ /** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */
2
+ export declare function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean;
@@ -96,6 +96,12 @@ export interface HubSettingsClientBinding {
96
96
  export interface HubSettingsContext {
97
97
  /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */
98
98
  basePath?: string;
99
+ /**
100
+ * Local path of the page that renders `HubConnectCallbackPage`. When set, an
101
+ * OAuth start must return to exactly this path with the provider, nonce and
102
+ * context that the integrations panel adds, and nothing else.
103
+ */
104
+ oauthCallbackPath?: string;
99
105
  /**
100
106
  * Required on EVERY valid operation, including reads. Validate the current
101
107
  * session, CSRF protection, workspace role and exact target/decision here.
@@ -23,6 +23,17 @@ import {
23
23
  } from "../chunk-3NCPXNBZ.js";
24
24
  import "../chunk-TXD5HXLE.js";
25
25
 
26
+ // src/platform/hub-connect-callback.ts
27
+ var HUB_CONNECT_CALLBACK_PARAMS = ["provider", "nonce", "context"];
28
+ function isHubConnectCallbackUrl(returnUrl, callbackPath, provider) {
29
+ if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false;
30
+ const keys = [...returnUrl.searchParams.keys()];
31
+ if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false;
32
+ if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false;
33
+ const opaque = (value) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value);
34
+ return returnUrl.searchParams.get("provider") === provider && opaque(returnUrl.searchParams.get("nonce")) && opaque(returnUrl.searchParams.get("context"));
35
+ }
36
+
26
37
  // src/platform/hub-settings.ts
27
38
  function json(value, status = 200, headers = {}) {
28
39
  return Response.json(value, { status, headers: { "Cache-Control": "no-store", ...headers } });
@@ -65,7 +76,7 @@ function metadata(value) {
65
76
  return { id: text(listing.id), pms: text(listing.pms) };
66
77
  }) };
67
78
  }
68
- function oauthInput(body2, url) {
79
+ function oauthInput(body2, url, provider, callbackPath) {
69
80
  onlyKeys(body2, ["returnUrl", "connectionParameters"]);
70
81
  const returnUrl = text(body2.returnUrl, 2048);
71
82
  let destination;
@@ -75,6 +86,7 @@ function oauthInput(body2, url) {
75
86
  invalid();
76
87
  }
77
88
  if (!["https:", "http:"].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid();
89
+ if (callbackPath !== void 0 && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid();
78
90
  const input = { returnUrl };
79
91
  if (body2.connectionParameters !== void 0) {
80
92
  const parameters = record(body2.connectionParameters);
@@ -125,7 +137,7 @@ var ROUTES = [
125
137
  { kind: "actions", path: /^\/providers\/([^/]+)\/actions$/, methods: ["GET"] },
126
138
  { kind: "policies", path: /^\/policies$/, methods: ["GET", "PUT", "DELETE"] }
127
139
  ];
128
- async function prepare(request, basePath) {
140
+ async function prepare(request, basePath, callbackPath) {
129
141
  const url = new URL(request.url);
130
142
  if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: "Not found" }, 404);
131
143
  const path = url.pathname.slice(basePath.length);
@@ -181,7 +193,7 @@ async function prepare(request, basePath) {
181
193
  return { intent: { operation: "provider.actions", provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) };
182
194
  }
183
195
  if (route.kind === "oauth") {
184
- const input = freeze(oauthInput(await body(request), url));
196
+ const input = freeze(oauthInput(await body(request), url, id, callbackPath));
185
197
  return { intent: { operation: "oauth.start", provider: id, input }, call: (hub) => hub.connections.start(id, input) };
186
198
  }
187
199
  if (route.kind === "api-key") {
@@ -201,10 +213,12 @@ function createHubSettingsRoutes(ctx) {
201
213
  }
202
214
  const basePath = ctx.basePath ?? "/api/hub/settings";
203
215
  if (!/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError("Invalid Hub settings basePath");
216
+ const callbackPath = ctx.oauthCallbackPath;
217
+ if (callbackPath !== void 0 && !/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError("Invalid Hub OAuth callback path");
204
218
  return { async handle(request) {
205
219
  let prepared;
206
220
  try {
207
- prepared = await prepare(request, basePath);
221
+ prepared = await prepare(request, basePath, callbackPath);
208
222
  } catch (error) {
209
223
  if (error instanceof Response) return error;
210
224
  throw error;
@@ -1 +1 @@
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) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url))\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,K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AQ,IAAI,MAAM,KAAK,CAAC,eAAe,MAAM,WAAS,IAAI,OAAO,SAAS,KAAK,CAAC,GAAG;AAC5F,YAAM,OAAO,KAAK,8BAA8B,4BAA4B,eAAe,KAAK,IAAI,CAAC,EAAE;AAAA,IACzG;AACA,UAAM,WAAW,MAAM,QAAQ,gBAAgB,GAAG;AAClD,QAAI,CAAC,SAAU,OAAM,OAAO,KAAK,yBAAyB,8BAA8B;AACxF,UAAM,QAAQ,MAAM,QAAQ,aAAa,KAAK,OAAO,WAAW,CAAC;AACjE,QAAI,MAAM,YAAY,MAAM;AAC1B,YAAM,UAAU,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"]}
1
+ {"version":3,"sources":["../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/api-key-auth.ts"],"sourcesContent":["/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. */\n serviceToken: string | (() => string)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n","/** 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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAKA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,YAAM,OAAO,KAAK,mBAAmB,uDAAuD;AAAA,IAC9F;AACA,QAAI,CAAC,MAAM,QAAQ,IAAI,MAAM,KAAK,CAAC,eAAe,MAAM,WAAS,IAAI,OAAO,SAAS,KAAK,CAAC,GAAG;AAC5F,YAAM,OAAO,KAAK,8BAA8B,4BAA4B,eAAe,KAAK,IAAI,CAAC,EAAE;AAAA,IACzG;AACA,UAAM,WAAW,MAAM,QAAQ,gBAAgB,GAAG;AAClD,QAAI,CAAC,SAAU,OAAM,OAAO,KAAK,yBAAyB,8BAA8B;AACxF,UAAM,QAAQ,MAAM,QAAQ,aAAa,KAAK,OAAO,WAAW,CAAC;AACjE,QAAI,MAAM,YAAY,MAAM;AAC1B,YAAM,UAAU,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.58.8",
3
+ "version": "0.58.9",
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": [