@opendatalabs/vana-sdk 3.14.1 → 3.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -5
- package/dist/direct/access-request-client.cjs +31 -3
- package/dist/direct/access-request-client.cjs.map +1 -1
- package/dist/direct/access-request-client.d.ts +12 -1
- package/dist/direct/access-request-client.js +31 -3
- package/dist/direct/access-request-client.js.map +1 -1
- package/dist/direct/connect-flow.cjs +63 -6
- package/dist/direct/connect-flow.cjs.map +1 -1
- package/dist/direct/connect-flow.d.ts +30 -4
- package/dist/direct/connect-flow.js +63 -6
- package/dist/direct/connect-flow.js.map +1 -1
- package/dist/direct/controller.cjs +4 -1
- package/dist/direct/controller.cjs.map +1 -1
- package/dist/direct/controller.d.ts +11 -3
- package/dist/direct/controller.js +4 -1
- package/dist/direct/controller.js.map +1 -1
- package/dist/direct/types.cjs +28 -2
- package/dist/direct/types.cjs.map +1 -1
- package/dist/direct/types.d.ts +51 -0
- package/dist/direct/types.js +26 -1
- package/dist/direct/types.js.map +1 -1
- package/dist/direct/use-direct-vana-connect.cjs +3 -0
- package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
- package/dist/direct/use-direct-vana-connect.js +3 -0
- package/dist/direct/use-direct-vana-connect.js.map +1 -1
- package/dist/direct/use-direct-vana-connect.test.d.ts +1 -0
- package/dist/index.browser.d.ts +1 -0
- package/dist/index.browser.js +167 -2
- package/dist/index.browser.js.map +3 -3
- package/dist/index.node.cjs +175 -2
- package/dist/index.node.cjs.map +3 -3
- package/dist/index.node.d.ts +2 -1
- package/dist/index.node.js +167 -2
- package/dist/index.node.js.map +3 -3
- package/dist/protocol/gateway.cjs +16 -2
- package/dist/protocol/gateway.cjs.map +1 -1
- package/dist/protocol/gateway.d.ts +2 -0
- package/dist/protocol/gateway.js +16 -2
- package/dist/protocol/gateway.js.map +1 -1
- package/dist/protocol/scope-actions.cjs +185 -0
- package/dist/protocol/scope-actions.cjs.map +1 -0
- package/dist/protocol/scope-actions.d.ts +145 -0
- package/dist/protocol/scope-actions.js +154 -0
- package/dist/protocol/scope-actions.js.map +1 -0
- package/dist/protocol/scope-actions.test.d.ts +1 -0
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.ts +9 -2
- package/dist/react.js.map +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -195,7 +195,14 @@ private key, and handles `402 Payment Required`:
|
|
|
195
195
|
const request = await vana.createAccessRequest({
|
|
196
196
|
returnUrl: `${process.env.VANA_APP_URL}/connect/return`,
|
|
197
197
|
});
|
|
198
|
-
// -> {
|
|
198
|
+
// -> {
|
|
199
|
+
// requestId: "dcr_...",
|
|
200
|
+
// approvalUrl: "https://app.vana.org/...",
|
|
201
|
+
// appAddress: "0x...",
|
|
202
|
+
// network: "mainnet",
|
|
203
|
+
// expiresAt: "...",
|
|
204
|
+
// mobileContinuationUrl?: "https://open.vana.org/continue#<ticket>",
|
|
205
|
+
// }
|
|
199
206
|
|
|
200
207
|
// GET /api/vana/status?requestId=...
|
|
201
208
|
const status = await vana.getAccessRequestStatus(requestId);
|
|
@@ -252,10 +259,50 @@ export function ConnectSpotifyButton() {
|
|
|
252
259
|
}
|
|
253
260
|
```
|
|
254
261
|
|
|
255
|
-
The hook calls `createRequest`, opens the Vana
|
|
256
|
-
until the request is approved, then calls `readResult`.
|
|
257
|
-
|
|
258
|
-
|
|
262
|
+
The hook calls `createRequest`, opens the Vana destination, polls `getStatus`
|
|
263
|
+
until the request is approved, then calls `readResult`. Destination choice stays
|
|
264
|
+
inside the SDK, and it owns only the small mobile-versus-desktop split — it never
|
|
265
|
+
infers whether Vana is installed. Desktop browsers and light requests open the
|
|
266
|
+
HTTPS `approvalUrl` in a popup (`state.type === "awaiting_approval"`). Builders
|
|
267
|
+
should not add user-agent branches, app-install checks, deep-link construction,
|
|
268
|
+
or store-link logic.
|
|
269
|
+
|
|
270
|
+
If the popup is blocked, `state.popupBlocked` is `true`; render the HTTPS
|
|
271
|
+
`state.request.approvalUrl` as the universal manual "Open approval" link. Polling
|
|
272
|
+
continues either way, so a manual open still drives the flow to completion.
|
|
273
|
+
|
|
274
|
+
A deep Direct request on a mobile browser instead enters
|
|
275
|
+
`state.type === "ready_to_open"` and exposes a plain HTTPS
|
|
276
|
+
`state.mobileContinuationUrl` (`https://open[-dev].vana.org/continue#<ticket>`).
|
|
277
|
+
Because DCR creation is asynchronous, the SDK does **not** launch it
|
|
278
|
+
automatically — the original tap can no longer be trusted to retain iOS user
|
|
279
|
+
activation. Render it as an ordinary primary link the user taps themselves:
|
|
280
|
+
|
|
281
|
+
```tsx
|
|
282
|
+
<a href={state.mobileContinuationUrl} target="_blank" rel="noreferrer">
|
|
283
|
+
Open Vana
|
|
284
|
+
</a>
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Verified links (iOS Universal Links / Android App Links) deliver this URL to
|
|
288
|
+
Vana Mobile; if Vana is absent the same URL loads its web install/recovery
|
|
289
|
+
fallback. Polling continues in the originating tab, and the URL's short-lived
|
|
290
|
+
ticket may rotate to a fresh value between polls. This is capability routing, not
|
|
291
|
+
an assertion that the native app is installed.
|
|
292
|
+
|
|
293
|
+
The SDK owns no persistence. If the originating mobile tab is reloaded, evicted,
|
|
294
|
+
or replaced, the flow does not recover: the user restarts and creates a new DCR,
|
|
295
|
+
and the abandoned DCR expires. This restart-on-tab-loss behavior is an accepted
|
|
296
|
+
first-release tradeoff — do not build caller-side resume storage against it.
|
|
297
|
+
|
|
298
|
+
Server-side create calls accept an optional `idempotencyKey`. The default HTTP
|
|
299
|
+
client generates a fresh key for every create, because one shared controller
|
|
300
|
+
serves many users and identical-looking creates are still independent requests.
|
|
301
|
+
Retrying a create whose response was lost is therefore the caller's decision:
|
|
302
|
+
pass the same explicit `idempotencyKey` on the retry to avoid a duplicate DCR.
|
|
303
|
+
|
|
304
|
+
`react` is an optional peer dependency. The underlying
|
|
305
|
+
`createDirectConnectFlow` store is also exported for non-React frontends.
|
|
259
306
|
|
|
260
307
|
### Test with large sample data
|
|
261
308
|
|
|
@@ -23,6 +23,7 @@ __export(access_request_client_exports, {
|
|
|
23
23
|
createDefaultAccessRequestClient: () => createDefaultAccessRequestClient
|
|
24
24
|
});
|
|
25
25
|
module.exports = __toCommonJS(access_request_client_exports);
|
|
26
|
+
var import_types = require("./types");
|
|
26
27
|
const VALID_STATUSES = [
|
|
27
28
|
"pending",
|
|
28
29
|
"approved",
|
|
@@ -34,6 +35,20 @@ const VALID_STATUSES = [
|
|
|
34
35
|
function normalizeStatus(value) {
|
|
35
36
|
return VALID_STATUSES.includes(value) ? value : "pending";
|
|
36
37
|
}
|
|
38
|
+
function normalizeNetwork(value) {
|
|
39
|
+
return value === "mainnet" || value === "moksha" ? value : void 0;
|
|
40
|
+
}
|
|
41
|
+
function normalizeExpiresAt(value) {
|
|
42
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : void 0;
|
|
43
|
+
}
|
|
44
|
+
function defaultCreateIdempotencyKey() {
|
|
45
|
+
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
46
|
+
throw new Error(
|
|
47
|
+
"Secure randomUUID is unavailable. Pass createIdempotencyKey to createDefaultAccessRequestClient."
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return globalThis.crypto.randomUUID();
|
|
51
|
+
}
|
|
37
52
|
function stripTrailingSlash(url) {
|
|
38
53
|
return url.replace(/\/+$/, "");
|
|
39
54
|
}
|
|
@@ -82,13 +97,16 @@ function createDefaultAccessRequestClient(options) {
|
|
|
82
97
|
return {
|
|
83
98
|
async createAccessRequest(input) {
|
|
84
99
|
const path = "/api/data-connection-requests";
|
|
100
|
+
const idempotencyKey = input.idempotencyKey ?? (options.createIdempotencyKey ?? defaultCreateIdempotencyKey)();
|
|
85
101
|
const body = JSON.stringify({
|
|
86
102
|
appAddress: input.appAddress,
|
|
87
103
|
app: input.app,
|
|
88
104
|
source: input.source,
|
|
89
105
|
scopes: input.scopes,
|
|
90
106
|
returnUrl: input.returnUrl,
|
|
91
|
-
network: input.network
|
|
107
|
+
network: input.network,
|
|
108
|
+
...input.foregroundDelivery !== void 0 ? { foregroundDelivery: input.foregroundDelivery } : {},
|
|
109
|
+
idempotencyKey
|
|
92
110
|
});
|
|
93
111
|
const res = await fetchFn(`${base}${path}`, {
|
|
94
112
|
method: "POST",
|
|
@@ -115,7 +133,13 @@ function createDefaultAccessRequestClient(options) {
|
|
|
115
133
|
return {
|
|
116
134
|
requestId,
|
|
117
135
|
approvalUrl: responseBody.approvalUrl ?? buildApprovalUrl(options.approvalBaseUrl, requestId),
|
|
118
|
-
appAddress: responseBody.appAddress ?? input.appAddress
|
|
136
|
+
appAddress: responseBody.appAddress ?? input.appAddress,
|
|
137
|
+
network: normalizeNetwork(responseBody.network),
|
|
138
|
+
expiresAt: normalizeExpiresAt(responseBody.expiresAt),
|
|
139
|
+
mobileContinuationUrl: (0, import_types.normalizeMobileContinuationUrl)(
|
|
140
|
+
responseBody.mobileContinuationUrl,
|
|
141
|
+
options.env
|
|
142
|
+
)
|
|
119
143
|
};
|
|
120
144
|
},
|
|
121
145
|
async getAccessRequestStatus(requestId) {
|
|
@@ -140,7 +164,11 @@ function createDefaultAccessRequestClient(options) {
|
|
|
140
164
|
personalServerUrl: body.personalServerUrl,
|
|
141
165
|
grantId: body.grantId,
|
|
142
166
|
scope: body.scope ?? scopes?.[0],
|
|
143
|
-
scopes
|
|
167
|
+
scopes,
|
|
168
|
+
mobileContinuationUrl: (0, import_types.normalizeMobileContinuationUrl)(
|
|
169
|
+
body.mobileContinuationUrl,
|
|
170
|
+
options.env
|
|
171
|
+
)
|
|
144
172
|
};
|
|
145
173
|
},
|
|
146
174
|
async acknowledgeRead(requestId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/access-request-client.ts"],"sourcesContent":["/**\n * Default client for the Vana Account access-request API.\n *\n * @remarks\n * Calls the Vana Account endpoints that issue `dcr_*` ids and approval URLs and\n * report request status. Inject a custom {@link AccessRequestClient} on the\n * controller to point at a different deployment; pass `fetchFn` to supply a test\n * double for the HTTP layer.\n *\n * @category Direct\n * @module direct/access-request-client\n */\n\nimport type {\n AccessRequest,\n AccessRequestClient,\n AccessRequestStatus,\n AccessRequestStatusValue,\n} from \"./types\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\n\n/** Minimal `fetch` signature so the client is testable without a global fetch. */\nexport type FetchLike = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n statusText: string;\n json(): Promise<unknown>;\n text(): Promise<string>;\n}>;\n\n/** Options for {@link createDefaultAccessRequestClient}. */\nexport interface DefaultAccessRequestClientOptions {\n /** Base URL of the Vana Account access-request API. */\n baseUrl: string;\n /** Base URL the user is sent to for approval. */\n approvalBaseUrl: string;\n /** `fetch` implementation. Defaults to the global `fetch`. */\n fetchFn?: FetchLike;\n /** App identity address used for direct access-request authentication. */\n appAddress?: string;\n /** EIP-191 signer for direct access-request authentication. */\n signMessage?: Web3SignedSignFn;\n /** Clock source used for signed request timestamps. */\n now?: () => number;\n}\n\nconst VALID_STATUSES: readonly AccessRequestStatusValue[] = [\n \"pending\",\n \"approved\",\n \"ready_for_read\",\n \"completed\",\n \"denied\",\n \"expired\",\n];\n\nfunction normalizeStatus(value: unknown): AccessRequestStatusValue {\n return VALID_STATUSES.includes(value as AccessRequestStatusValue)\n ? (value as AccessRequestStatusValue)\n : \"pending\";\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\nconst DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX = \"Vana Direct Access Request v1\";\n\ninterface DirectAccessRequestAuthInput {\n body: string;\n method: string;\n path: string;\n timestamp: string;\n}\n\nexport function buildDirectAccessRequestAuthMessage(\n input: DirectAccessRequestAuthInput,\n): string {\n return [\n DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX,\n `method:${input.method.toUpperCase()}`,\n `path:${input.path}`,\n `timestamp:${input.timestamp}`,\n `body:${input.body}`,\n ].join(\"\\n\");\n}\n\nasync function buildDirectAccessRequestHeaders(\n options: DefaultAccessRequestClientOptions,\n input: Omit<DirectAccessRequestAuthInput, \"timestamp\">,\n): Promise<Record<string, string>> {\n if (!options.appAddress && !options.signMessage) {\n return {};\n }\n if (!options.appAddress || !options.signMessage) {\n throw new Error(\n \"Direct access-request authentication requires both `appAddress` and `signMessage`.\",\n );\n }\n\n const timestamp = String(options.now?.() ?? Date.now());\n const signature = await options.signMessage(\n buildDirectAccessRequestAuthMessage({ ...input, timestamp }),\n );\n\n return {\n \"X-Vana-App-Address\": options.appAddress,\n \"X-Vana-App-Signature\": signature,\n \"X-Vana-App-Timestamp\": timestamp,\n };\n}\n\n/**\n * Build an approval URL for a request id, matching the documented format\n * (`{app}/data-connection-requests/{requestId}?mode=page`).\n *\n * @param approvalBaseUrl - Base URL of the Vana approval app.\n * @param requestId - The `dcr_*` request id.\n * @returns The full approval URL.\n */\nexport function buildApprovalUrl(\n approvalBaseUrl: string,\n requestId: string,\n): string {\n return `${stripTrailingSlash(approvalBaseUrl)}/data-connection-requests/${encodeURIComponent(\n requestId,\n )}?mode=page`;\n}\n\n/**\n * Create the default {@link AccessRequestClient} for the Vana Account\n * access-request API.\n *\n * @param options - Base URLs and an optional `fetch` implementation.\n * @returns An {@link AccessRequestClient} backed by HTTP calls.\n */\nexport function createDefaultAccessRequestClient(\n options: DefaultAccessRequestClientOptions,\n): AccessRequestClient {\n const fetchFn = options.fetchFn ?? (globalThis.fetch as FetchLike);\n if (!fetchFn) {\n throw new Error(\n \"No fetch implementation available. Pass `fetchFn` to createDefaultAccessRequestClient.\",\n );\n }\n const base = stripTrailingSlash(options.baseUrl);\n\n return {\n async createAccessRequest(input): Promise<AccessRequest> {\n const path = \"/api/data-connection-requests\";\n const body = JSON.stringify({\n appAddress: input.appAddress,\n app: input.app,\n source: input.source,\n scopes: input.scopes,\n returnUrl: input.returnUrl,\n network: input.network,\n });\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(await buildDirectAccessRequestHeaders(options, {\n body,\n method: \"POST\",\n path,\n })),\n },\n body,\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const responseBody = (await res.json()) as {\n requestId?: string;\n id?: string;\n approvalUrl?: string;\n appAddress?: string;\n };\n const requestId = responseBody.requestId ?? responseBody.id;\n if (!requestId) {\n throw new Error(\"Access request service returned no requestId\");\n }\n return {\n requestId,\n approvalUrl:\n responseBody.approvalUrl ??\n buildApprovalUrl(options.approvalBaseUrl, requestId),\n appAddress: responseBody.appAddress ?? input.appAddress,\n };\n },\n\n async getAccessRequestStatus(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"GET\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"GET\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const body = (await res.json()) as {\n status?: string;\n personalServerUrl?: string;\n grantId?: string;\n scope?: string;\n scopes?: string[];\n };\n // `scopes` is the full approved set; `scope` is the first of them, kept\n // for callers (and deployments) that predate the array.\n const scopes =\n body.scopes && body.scopes.length > 0\n ? body.scopes\n : body.scope\n ? [body.scope]\n : undefined;\n return {\n status: normalizeStatus(body.status),\n personalServerUrl: body.personalServerUrl,\n grantId: body.grantId,\n scope: body.scope ?? scopes?.[0],\n scopes,\n };\n },\n\n async acknowledgeRead(requestId: string): Promise<void> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}/consumer-ack`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"POST\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request ack service error: ${res.status} ${res.statusText}`,\n );\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqDA,MAAM,iBAAsD;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,gBAAgB,OAA0C;AACjE,SAAO,eAAe,SAAS,KAAiC,IAC3D,QACD;AACN;AAEA,SAAS,mBAAmB,KAAqB;AAC/C,SAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;AAEA,MAAM,uCAAuC;AAStC,SAAS,oCACd,OACQ;AACR,SAAO;AAAA,IACL;AAAA,IACA,UAAU,MAAM,OAAO,YAAY,CAAC;AAAA,IACpC,QAAQ,MAAM,IAAI;AAAA,IAClB,aAAa,MAAM,SAAS;AAAA,IAC5B,QAAQ,MAAM,IAAI;AAAA,EACpB,EAAE,KAAK,IAAI;AACb;AAEA,eAAe,gCACb,SACA,OACiC;AACjC,MAAI,CAAC,QAAQ,cAAc,CAAC,QAAQ,aAAa;AAC/C,WAAO,CAAC;AAAA,EACV;AACA,MAAI,CAAC,QAAQ,cAAc,CAAC,QAAQ,aAAa;AAC/C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,YAAY,OAAO,QAAQ,MAAM,KAAK,KAAK,IAAI,CAAC;AACtD,QAAM,YAAY,MAAM,QAAQ;AAAA,IAC9B,oCAAoC,EAAE,GAAG,OAAO,UAAU,CAAC;AAAA,EAC7D;AAEA,SAAO;AAAA,IACL,sBAAsB,QAAQ;AAAA,IAC9B,wBAAwB;AAAA,IACxB,wBAAwB;AAAA,EAC1B;AACF;AAUO,SAAS,iBACd,iBACA,WACQ;AACR,SAAO,GAAG,mBAAmB,eAAe,CAAC,6BAA6B;AAAA,I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AAG,IAAI,IAAI;AAAA,QAC1C,QAAQ;AAAA,QACR,SAAS,MAAM,gCAAgC,SAAS;AAAA,UACtD,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AACD,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,IAAI;AAAA,UACR,iCAAiC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,QAC/D;AAAA,MACF;AACA,YAAM,OAAQ,MAAM,IAAI,KAAK;AAS7B,YAAM,SACJ,KAAK,UAAU,KAAK,OAAO,SAAS,IAChC,KAAK,SACL,KAAK,QACH,CAAC,KAAK,KAAK,IACX;AACR,aAAO;AAAA,QACL,QAAQ,gBAAgB,KAAK,MAAM;AAAA,QACnC,mBAAmB,KAAK;AAAA,QACxB,SAAS,KAAK;AAAA,QACd,OAAO,KAAK,SAAS,SAAS,CAAC;AAAA,QAC/B;AAAA,MACF;AAAA,IACF;AAAA,IAEA,MAAM,gBAAgB,WAAkC;AACtD,YAAM,OAAO,iCAAiC,mBAAmB,SAAS,CAAC;AAC3E,YAAM,MAAM,MAAM,QAAQ,GAAG,IAAI,GAAG,IAAI,IAAI;AAAA,QAC1C,QAAQ;AAAA,QACR,SAAS,MAAM,gCAAgC,SAAS;AAAA,UACtD,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AACD,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,IAAI;AAAA,UACR,qCAAqC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/direct/access-request-client.ts"],"sourcesContent":["/**\n * Default client for the Vana Account access-request API.\n *\n * @remarks\n * Calls the Vana Account endpoints that issue `dcr_*` ids and approval URLs and\n * report request status. Inject a custom {@link AccessRequestClient} on the\n * controller to point at a different deployment; pass `fetchFn` to supply a test\n * double for the HTTP layer.\n *\n * @category Direct\n * @module direct/access-request-client\n */\n\nimport type {\n AccessRequest,\n AccessRequestClient,\n AccessRequestStatus,\n AccessRequestStatusValue,\n DirectEnv,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\n\n/** Minimal `fetch` signature so the client is testable without a global fetch. */\nexport type FetchLike = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n statusText: string;\n json(): Promise<unknown>;\n text(): Promise<string>;\n}>;\n\n/** Options for {@link createDefaultAccessRequestClient}. */\nexport interface DefaultAccessRequestClientOptions {\n /** Base URL of the Vana Account access-request API. */\n baseUrl: string;\n /** Base URL the user is sent to for approval. */\n approvalBaseUrl: string;\n /**\n * Target environment. Pins the allowed mobile continuation link host\n * (`open.vana.org` for production, `open-dev.vana.org` for dev). When omitted,\n * both canonical hosts pass the structural continuation-URL check.\n */\n env?: DirectEnv;\n /** `fetch` implementation. Defaults to the global `fetch`. */\n fetchFn?: FetchLike;\n /** App identity address used for direct access-request authentication. */\n appAddress?: string;\n /** EIP-191 signer for direct access-request authentication. */\n signMessage?: Web3SignedSignFn;\n /** Clock source used for signed request timestamps. */\n now?: () => number;\n /**\n * Create the signed DCR idempotency key used when a create call omits one.\n * Called once per create. Injectable for deterministic tests.\n */\n createIdempotencyKey?: () => string;\n}\n\nconst VALID_STATUSES: readonly AccessRequestStatusValue[] = [\n \"pending\",\n \"approved\",\n \"ready_for_read\",\n \"completed\",\n \"denied\",\n \"expired\",\n];\n\nfunction normalizeStatus(value: unknown): AccessRequestStatusValue {\n return VALID_STATUSES.includes(value as AccessRequestStatusValue)\n ? (value as AccessRequestStatusValue)\n : \"pending\";\n}\n\nfunction normalizeNetwork(value: unknown): AccessRequest[\"network\"] {\n return value === \"mainnet\" || value === \"moksha\" ? value : undefined;\n}\n\nfunction normalizeExpiresAt(value: unknown): string | undefined {\n return typeof value === \"string\" && Number.isFinite(Date.parse(value))\n ? value\n : undefined;\n}\n\nfunction defaultCreateIdempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID !== \"function\") {\n throw new Error(\n \"Secure randomUUID is unavailable. Pass createIdempotencyKey to createDefaultAccessRequestClient.\",\n );\n }\n return globalThis.crypto.randomUUID();\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\nconst DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX = \"Vana Direct Access Request v1\";\n\ninterface DirectAccessRequestAuthInput {\n body: string;\n method: string;\n path: string;\n timestamp: string;\n}\n\nexport function buildDirectAccessRequestAuthMessage(\n input: DirectAccessRequestAuthInput,\n): string {\n return [\n DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX,\n `method:${input.method.toUpperCase()}`,\n `path:${input.path}`,\n `timestamp:${input.timestamp}`,\n `body:${input.body}`,\n ].join(\"\\n\");\n}\n\nasync function buildDirectAccessRequestHeaders(\n options: DefaultAccessRequestClientOptions,\n input: Omit<DirectAccessRequestAuthInput, \"timestamp\">,\n): Promise<Record<string, string>> {\n if (!options.appAddress && !options.signMessage) {\n return {};\n }\n if (!options.appAddress || !options.signMessage) {\n throw new Error(\n \"Direct access-request authentication requires both `appAddress` and `signMessage`.\",\n );\n }\n\n const timestamp = String(options.now?.() ?? Date.now());\n const signature = await options.signMessage(\n buildDirectAccessRequestAuthMessage({ ...input, timestamp }),\n );\n\n return {\n \"X-Vana-App-Address\": options.appAddress,\n \"X-Vana-App-Signature\": signature,\n \"X-Vana-App-Timestamp\": timestamp,\n };\n}\n\n/**\n * Build an approval URL for a request id, matching the documented format\n * (`{app}/data-connection-requests/{requestId}?mode=page`).\n *\n * @param approvalBaseUrl - Base URL of the Vana approval app.\n * @param requestId - The `dcr_*` request id.\n * @returns The full approval URL.\n */\nexport function buildApprovalUrl(\n approvalBaseUrl: string,\n requestId: string,\n): string {\n return `${stripTrailingSlash(approvalBaseUrl)}/data-connection-requests/${encodeURIComponent(\n requestId,\n )}?mode=page`;\n}\n\n/**\n * Create the default {@link AccessRequestClient} for the Vana Account\n * access-request API.\n *\n * @param options - Base URLs and an optional `fetch` implementation.\n * @returns An {@link AccessRequestClient} backed by HTTP calls.\n */\nexport function createDefaultAccessRequestClient(\n options: DefaultAccessRequestClientOptions,\n): AccessRequestClient {\n const fetchFn = options.fetchFn ?? (globalThis.fetch as FetchLike);\n if (!fetchFn) {\n throw new Error(\n \"No fetch implementation available. Pass `fetchFn` to createDefaultAccessRequestClient.\",\n );\n }\n const base = stripTrailingSlash(options.baseUrl);\n\n return {\n async createAccessRequest(input): Promise<AccessRequest> {\n const path = \"/api/data-connection-requests\";\n // Every call is an independent logical create, so it gets its own key.\n // The client cannot tell two look-alike creates apart — one shared backend\n // controller serves many users with the same app, scopes, and returnUrl —\n // so deriving a key from the input would let the service deduplicate two\n // users onto a single DCR. Retrying an uncertain create is the caller's\n // decision: pass the same `idempotencyKey` back in.\n const idempotencyKey =\n input.idempotencyKey ??\n (options.createIdempotencyKey ?? defaultCreateIdempotencyKey)();\n const body = JSON.stringify({\n appAddress: input.appAddress,\n app: input.app,\n source: input.source,\n scopes: input.scopes,\n returnUrl: input.returnUrl,\n network: input.network,\n ...(input.foregroundDelivery !== undefined\n ? { foregroundDelivery: input.foregroundDelivery }\n : {}),\n idempotencyKey,\n });\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(await buildDirectAccessRequestHeaders(options, {\n body,\n method: \"POST\",\n path,\n })),\n },\n body,\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const responseBody = (await res.json()) as {\n requestId?: string;\n id?: string;\n approvalUrl?: string;\n appAddress?: string;\n network?: unknown;\n expiresAt?: unknown;\n mobileContinuationUrl?: unknown;\n };\n const requestId = responseBody.requestId ?? responseBody.id;\n if (!requestId) {\n throw new Error(\"Access request service returned no requestId\");\n }\n return {\n requestId,\n approvalUrl:\n responseBody.approvalUrl ??\n buildApprovalUrl(options.approvalBaseUrl, requestId),\n appAddress: responseBody.appAddress ?? input.appAddress,\n network: normalizeNetwork(responseBody.network),\n expiresAt: normalizeExpiresAt(responseBody.expiresAt),\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n responseBody.mobileContinuationUrl,\n options.env,\n ),\n };\n },\n\n async getAccessRequestStatus(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"GET\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"GET\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const body = (await res.json()) as {\n status?: string;\n personalServerUrl?: string;\n grantId?: string;\n scope?: string;\n mobileContinuationUrl?: unknown;\n scopes?: string[];\n };\n // `scopes` is the full approved set; `scope` is the first of them, kept\n // for callers (and deployments) that predate the array.\n const scopes =\n body.scopes && body.scopes.length > 0\n ? body.scopes\n : body.scope\n ? [body.scope]\n : undefined;\n return {\n status: normalizeStatus(body.status),\n personalServerUrl: body.personalServerUrl,\n grantId: body.grantId,\n scope: body.scope ?? scopes?.[0],\n scopes,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n body.mobileContinuationUrl,\n options.env,\n ),\n };\n },\n\n async acknowledgeRead(requestId: string): Promise<void> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}/consumer-ack`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"POST\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request ack service error: ${res.status} ${res.statusText}`,\n );\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAI;AAAA,QAC1C,QAAQ;AAAA,QACR,SAAS,MAAM,gCAAgC,SAAS;AAAA,UACtD,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AACD,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,IAAI;AAAA,UACR,qCAAqC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* @category Direct
|
|
11
11
|
* @module direct/access-request-client
|
|
12
12
|
*/
|
|
13
|
-
import type { AccessRequestClient } from "./types.js";
|
|
13
|
+
import type { AccessRequestClient, DirectEnv } from "./types.js";
|
|
14
14
|
import type { Web3SignedSignFn } from "../auth/web3-signed-builder.js";
|
|
15
15
|
/** Minimal `fetch` signature so the client is testable without a global fetch. */
|
|
16
16
|
export type FetchLike = (input: string, init?: {
|
|
@@ -30,6 +30,12 @@ export interface DefaultAccessRequestClientOptions {
|
|
|
30
30
|
baseUrl: string;
|
|
31
31
|
/** Base URL the user is sent to for approval. */
|
|
32
32
|
approvalBaseUrl: string;
|
|
33
|
+
/**
|
|
34
|
+
* Target environment. Pins the allowed mobile continuation link host
|
|
35
|
+
* (`open.vana.org` for production, `open-dev.vana.org` for dev). When omitted,
|
|
36
|
+
* both canonical hosts pass the structural continuation-URL check.
|
|
37
|
+
*/
|
|
38
|
+
env?: DirectEnv;
|
|
33
39
|
/** `fetch` implementation. Defaults to the global `fetch`. */
|
|
34
40
|
fetchFn?: FetchLike;
|
|
35
41
|
/** App identity address used for direct access-request authentication. */
|
|
@@ -38,6 +44,11 @@ export interface DefaultAccessRequestClientOptions {
|
|
|
38
44
|
signMessage?: Web3SignedSignFn;
|
|
39
45
|
/** Clock source used for signed request timestamps. */
|
|
40
46
|
now?: () => number;
|
|
47
|
+
/**
|
|
48
|
+
* Create the signed DCR idempotency key used when a create call omits one.
|
|
49
|
+
* Called once per create. Injectable for deterministic tests.
|
|
50
|
+
*/
|
|
51
|
+
createIdempotencyKey?: () => string;
|
|
41
52
|
}
|
|
42
53
|
interface DirectAccessRequestAuthInput {
|
|
43
54
|
body: string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeMobileContinuationUrl } from "./types.js";
|
|
1
2
|
const VALID_STATUSES = [
|
|
2
3
|
"pending",
|
|
3
4
|
"approved",
|
|
@@ -9,6 +10,20 @@ const VALID_STATUSES = [
|
|
|
9
10
|
function normalizeStatus(value) {
|
|
10
11
|
return VALID_STATUSES.includes(value) ? value : "pending";
|
|
11
12
|
}
|
|
13
|
+
function normalizeNetwork(value) {
|
|
14
|
+
return value === "mainnet" || value === "moksha" ? value : void 0;
|
|
15
|
+
}
|
|
16
|
+
function normalizeExpiresAt(value) {
|
|
17
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : void 0;
|
|
18
|
+
}
|
|
19
|
+
function defaultCreateIdempotencyKey() {
|
|
20
|
+
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
21
|
+
throw new Error(
|
|
22
|
+
"Secure randomUUID is unavailable. Pass createIdempotencyKey to createDefaultAccessRequestClient."
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
return globalThis.crypto.randomUUID();
|
|
26
|
+
}
|
|
12
27
|
function stripTrailingSlash(url) {
|
|
13
28
|
return url.replace(/\/+$/, "");
|
|
14
29
|
}
|
|
@@ -57,13 +72,16 @@ function createDefaultAccessRequestClient(options) {
|
|
|
57
72
|
return {
|
|
58
73
|
async createAccessRequest(input) {
|
|
59
74
|
const path = "/api/data-connection-requests";
|
|
75
|
+
const idempotencyKey = input.idempotencyKey ?? (options.createIdempotencyKey ?? defaultCreateIdempotencyKey)();
|
|
60
76
|
const body = JSON.stringify({
|
|
61
77
|
appAddress: input.appAddress,
|
|
62
78
|
app: input.app,
|
|
63
79
|
source: input.source,
|
|
64
80
|
scopes: input.scopes,
|
|
65
81
|
returnUrl: input.returnUrl,
|
|
66
|
-
network: input.network
|
|
82
|
+
network: input.network,
|
|
83
|
+
...input.foregroundDelivery !== void 0 ? { foregroundDelivery: input.foregroundDelivery } : {},
|
|
84
|
+
idempotencyKey
|
|
67
85
|
});
|
|
68
86
|
const res = await fetchFn(`${base}${path}`, {
|
|
69
87
|
method: "POST",
|
|
@@ -90,7 +108,13 @@ function createDefaultAccessRequestClient(options) {
|
|
|
90
108
|
return {
|
|
91
109
|
requestId,
|
|
92
110
|
approvalUrl: responseBody.approvalUrl ?? buildApprovalUrl(options.approvalBaseUrl, requestId),
|
|
93
|
-
appAddress: responseBody.appAddress ?? input.appAddress
|
|
111
|
+
appAddress: responseBody.appAddress ?? input.appAddress,
|
|
112
|
+
network: normalizeNetwork(responseBody.network),
|
|
113
|
+
expiresAt: normalizeExpiresAt(responseBody.expiresAt),
|
|
114
|
+
mobileContinuationUrl: normalizeMobileContinuationUrl(
|
|
115
|
+
responseBody.mobileContinuationUrl,
|
|
116
|
+
options.env
|
|
117
|
+
)
|
|
94
118
|
};
|
|
95
119
|
},
|
|
96
120
|
async getAccessRequestStatus(requestId) {
|
|
@@ -115,7 +139,11 @@ function createDefaultAccessRequestClient(options) {
|
|
|
115
139
|
personalServerUrl: body.personalServerUrl,
|
|
116
140
|
grantId: body.grantId,
|
|
117
141
|
scope: body.scope ?? scopes?.[0],
|
|
118
|
-
scopes
|
|
142
|
+
scopes,
|
|
143
|
+
mobileContinuationUrl: normalizeMobileContinuationUrl(
|
|
144
|
+
body.mobileContinuationUrl,
|
|
145
|
+
options.env
|
|
146
|
+
)
|
|
119
147
|
};
|
|
120
148
|
},
|
|
121
149
|
async acknowledgeRead(requestId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/access-request-client.ts"],"sourcesContent":["/**\n * Default client for the Vana Account access-request API.\n *\n * @remarks\n * Calls the Vana Account endpoints that issue `dcr_*` ids and approval URLs and\n * report request status. Inject a custom {@link AccessRequestClient} on the\n * controller to point at a different deployment; pass `fetchFn` to supply a test\n * double for the HTTP layer.\n *\n * @category Direct\n * @module direct/access-request-client\n */\n\nimport type {\n AccessRequest,\n AccessRequestClient,\n AccessRequestStatus,\n AccessRequestStatusValue,\n} from \"./types\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\n\n/** Minimal `fetch` signature so the client is testable without a global fetch. */\nexport type FetchLike = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n statusText: string;\n json(): Promise<unknown>;\n text(): Promise<string>;\n}>;\n\n/** Options for {@link createDefaultAccessRequestClient}. */\nexport interface DefaultAccessRequestClientOptions {\n /** Base URL of the Vana Account access-request API. */\n baseUrl: string;\n /** Base URL the user is sent to for approval. */\n approvalBaseUrl: string;\n /** `fetch` implementation. Defaults to the global `fetch`. */\n fetchFn?: FetchLike;\n /** App identity address used for direct access-request authentication. */\n appAddress?: string;\n /** EIP-191 signer for direct access-request authentication. */\n signMessage?: Web3SignedSignFn;\n /** Clock source used for signed request timestamps. */\n now?: () => number;\n}\n\nconst VALID_STATUSES: readonly AccessRequestStatusValue[] = [\n \"pending\",\n \"approved\",\n \"ready_for_read\",\n \"completed\",\n \"denied\",\n \"expired\",\n];\n\nfunction normalizeStatus(value: unknown): AccessRequestStatusValue {\n return VALID_STATUSES.includes(value as AccessRequestStatusValue)\n ? (value as AccessRequestStatusValue)\n : \"pending\";\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\nconst DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX = \"Vana Direct Access Request v1\";\n\ninterface DirectAccessRequestAuthInput {\n body: string;\n method: string;\n path: string;\n timestamp: string;\n}\n\nexport function buildDirectAccessRequestAuthMessage(\n input: DirectAccessRequestAuthInput,\n): string {\n return [\n DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX,\n `method:${input.method.toUpperCase()}`,\n `path:${input.path}`,\n `timestamp:${input.timestamp}`,\n `body:${input.body}`,\n ].join(\"\\n\");\n}\n\nasync function buildDirectAccessRequestHeaders(\n options: DefaultAccessRequestClientOptions,\n input: Omit<DirectAccessRequestAuthInput, \"timestamp\">,\n): Promise<Record<string, string>> {\n if (!options.appAddress && !options.signMessage) {\n return {};\n }\n if (!options.appAddress || !options.signMessage) {\n throw new Error(\n \"Direct access-request authentication requires both `appAddress` and `signMessage`.\",\n );\n }\n\n const timestamp = String(options.now?.() ?? Date.now());\n const signature = await options.signMessage(\n buildDirectAccessRequestAuthMessage({ ...input, timestamp }),\n );\n\n return {\n \"X-Vana-App-Address\": options.appAddress,\n \"X-Vana-App-Signature\": signature,\n \"X-Vana-App-Timestamp\": timestamp,\n };\n}\n\n/**\n * Build an approval URL for a request id, matching the documented format\n * (`{app}/data-connection-requests/{requestId}?mode=page`).\n *\n * @param approvalBaseUrl - Base URL of the Vana approval app.\n * @param requestId - The `dcr_*` request id.\n * @returns The full approval URL.\n */\nexport function buildApprovalUrl(\n approvalBaseUrl: string,\n requestId: string,\n): string {\n return `${stripTrailingSlash(approvalBaseUrl)}/data-connection-requests/${encodeURIComponent(\n requestId,\n )}?mode=page`;\n}\n\n/**\n * Create the default {@link AccessRequestClient} for the Vana Account\n * access-request API.\n *\n * @param options - Base URLs and an optional `fetch` implementation.\n * @returns An {@link AccessRequestClient} backed by HTTP calls.\n */\nexport function createDefaultAccessRequestClient(\n options: DefaultAccessRequestClientOptions,\n): AccessRequestClient {\n const fetchFn = options.fetchFn ?? (globalThis.fetch as FetchLike);\n if (!fetchFn) {\n throw new Error(\n \"No fetch implementation available. Pass `fetchFn` to createDefaultAccessRequestClient.\",\n );\n }\n const base = stripTrailingSlash(options.baseUrl);\n\n return {\n async createAccessRequest(input): Promise<AccessRequest> {\n const path = \"/api/data-connection-requests\";\n const body = JSON.stringify({\n appAddress: input.appAddress,\n app: input.app,\n source: input.source,\n scopes: input.scopes,\n returnUrl: input.returnUrl,\n network: input.network,\n });\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(await buildDirectAccessRequestHeaders(options, {\n body,\n method: \"POST\",\n path,\n })),\n },\n body,\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const responseBody = (await res.json()) as {\n requestId?: string;\n id?: string;\n approvalUrl?: string;\n appAddress?: string;\n };\n const requestId = responseBody.requestId ?? responseBody.id;\n if (!requestId) {\n throw new Error(\"Access request service returned no requestId\");\n }\n return {\n requestId,\n approvalUrl:\n responseBody.approvalUrl ??\n buildApprovalUrl(options.approvalBaseUrl, requestId),\n appAddress: responseBody.appAddress ?? input.appAddress,\n };\n },\n\n async getAccessRequestStatus(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"GET\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"GET\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const body = (await res.json()) as {\n status?: string;\n personalServerUrl?: string;\n grantId?: string;\n scope?: string;\n scopes?: string[];\n };\n // `scopes` is the full approved set; `scope` is the first of them, kept\n // for callers (and deployments) that predate the array.\n const scopes =\n body.scopes && body.scopes.length > 0\n ? body.scopes\n : body.scope\n ? [body.scope]\n : undefined;\n return {\n status: normalizeStatus(body.status),\n personalServerUrl: body.personalServerUrl,\n grantId: body.grantId,\n scope: body.scope ?? scopes?.[0],\n scopes,\n };\n },\n\n async acknowledgeRead(requestId: string): Promise<void> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}/consumer-ack`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"POST\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request ack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CAAC;AACD,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,IAAI;AAAA,UACR,iCAAiC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,QAC/D;AAAA,MACF;AACA,YAAM,OAAQ,MAAM,IAAI,KAAK;AAS7B,YAAM,SACJ,KAAK,UAAU,KAAK,OAAO,SAAS,IAChC,KAAK,SACL,KAAK,QACH,CAAC,KAAK,KAAK,IACX;AACR,aAAO;AAAA,QACL,QAAQ,gBAAgB,KAAK,MAAM;AAAA,QACnC,mBAAmB,KAAK;AAAA,QACxB,SAAS,KAAK;AAAA,QACd,OAAO,KAAK,SAAS,SAAS,CAAC;AAAA,QAC/B;AAAA,MACF;AAAA,IACF;AAAA,IAEA,MAAM,gBAAgB,WAAkC;AACtD,YAAM,OAAO,iCAAiC,mBAAmB,SAAS,CAAC;AAC3E,YAAM,MAAM,MAAM,QAAQ,GAAG,IAAI,GAAG,IAAI,IAAI;AAAA,QAC1C,QAAQ;AAAA,QACR,SAAS,MAAM,gCAAgC,SAAS;AAAA,UACtD,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AACD,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,IAAI;AAAA,UACR,qCAAqC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/direct/access-request-client.ts"],"sourcesContent":["/**\n * Default client for the Vana Account access-request API.\n *\n * @remarks\n * Calls the Vana Account endpoints that issue `dcr_*` ids and approval URLs and\n * report request status. Inject a custom {@link AccessRequestClient} on the\n * controller to point at a different deployment; pass `fetchFn` to supply a test\n * double for the HTTP layer.\n *\n * @category Direct\n * @module direct/access-request-client\n */\n\nimport type {\n AccessRequest,\n AccessRequestClient,\n AccessRequestStatus,\n AccessRequestStatusValue,\n DirectEnv,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\n\n/** Minimal `fetch` signature so the client is testable without a global fetch. */\nexport type FetchLike = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n statusText: string;\n json(): Promise<unknown>;\n text(): Promise<string>;\n}>;\n\n/** Options for {@link createDefaultAccessRequestClient}. */\nexport interface DefaultAccessRequestClientOptions {\n /** Base URL of the Vana Account access-request API. */\n baseUrl: string;\n /** Base URL the user is sent to for approval. */\n approvalBaseUrl: string;\n /**\n * Target environment. Pins the allowed mobile continuation link host\n * (`open.vana.org` for production, `open-dev.vana.org` for dev). When omitted,\n * both canonical hosts pass the structural continuation-URL check.\n */\n env?: DirectEnv;\n /** `fetch` implementation. Defaults to the global `fetch`. */\n fetchFn?: FetchLike;\n /** App identity address used for direct access-request authentication. */\n appAddress?: string;\n /** EIP-191 signer for direct access-request authentication. */\n signMessage?: Web3SignedSignFn;\n /** Clock source used for signed request timestamps. */\n now?: () => number;\n /**\n * Create the signed DCR idempotency key used when a create call omits one.\n * Called once per create. Injectable for deterministic tests.\n */\n createIdempotencyKey?: () => string;\n}\n\nconst VALID_STATUSES: readonly AccessRequestStatusValue[] = [\n \"pending\",\n \"approved\",\n \"ready_for_read\",\n \"completed\",\n \"denied\",\n \"expired\",\n];\n\nfunction normalizeStatus(value: unknown): AccessRequestStatusValue {\n return VALID_STATUSES.includes(value as AccessRequestStatusValue)\n ? (value as AccessRequestStatusValue)\n : \"pending\";\n}\n\nfunction normalizeNetwork(value: unknown): AccessRequest[\"network\"] {\n return value === \"mainnet\" || value === \"moksha\" ? value : undefined;\n}\n\nfunction normalizeExpiresAt(value: unknown): string | undefined {\n return typeof value === \"string\" && Number.isFinite(Date.parse(value))\n ? value\n : undefined;\n}\n\nfunction defaultCreateIdempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID !== \"function\") {\n throw new Error(\n \"Secure randomUUID is unavailable. Pass createIdempotencyKey to createDefaultAccessRequestClient.\",\n );\n }\n return globalThis.crypto.randomUUID();\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\nconst DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX = \"Vana Direct Access Request v1\";\n\ninterface DirectAccessRequestAuthInput {\n body: string;\n method: string;\n path: string;\n timestamp: string;\n}\n\nexport function buildDirectAccessRequestAuthMessage(\n input: DirectAccessRequestAuthInput,\n): string {\n return [\n DIRECT_ACCESS_REQUEST_MESSAGE_PREFIX,\n `method:${input.method.toUpperCase()}`,\n `path:${input.path}`,\n `timestamp:${input.timestamp}`,\n `body:${input.body}`,\n ].join(\"\\n\");\n}\n\nasync function buildDirectAccessRequestHeaders(\n options: DefaultAccessRequestClientOptions,\n input: Omit<DirectAccessRequestAuthInput, \"timestamp\">,\n): Promise<Record<string, string>> {\n if (!options.appAddress && !options.signMessage) {\n return {};\n }\n if (!options.appAddress || !options.signMessage) {\n throw new Error(\n \"Direct access-request authentication requires both `appAddress` and `signMessage`.\",\n );\n }\n\n const timestamp = String(options.now?.() ?? Date.now());\n const signature = await options.signMessage(\n buildDirectAccessRequestAuthMessage({ ...input, timestamp }),\n );\n\n return {\n \"X-Vana-App-Address\": options.appAddress,\n \"X-Vana-App-Signature\": signature,\n \"X-Vana-App-Timestamp\": timestamp,\n };\n}\n\n/**\n * Build an approval URL for a request id, matching the documented format\n * (`{app}/data-connection-requests/{requestId}?mode=page`).\n *\n * @param approvalBaseUrl - Base URL of the Vana approval app.\n * @param requestId - The `dcr_*` request id.\n * @returns The full approval URL.\n */\nexport function buildApprovalUrl(\n approvalBaseUrl: string,\n requestId: string,\n): string {\n return `${stripTrailingSlash(approvalBaseUrl)}/data-connection-requests/${encodeURIComponent(\n requestId,\n )}?mode=page`;\n}\n\n/**\n * Create the default {@link AccessRequestClient} for the Vana Account\n * access-request API.\n *\n * @param options - Base URLs and an optional `fetch` implementation.\n * @returns An {@link AccessRequestClient} backed by HTTP calls.\n */\nexport function createDefaultAccessRequestClient(\n options: DefaultAccessRequestClientOptions,\n): AccessRequestClient {\n const fetchFn = options.fetchFn ?? (globalThis.fetch as FetchLike);\n if (!fetchFn) {\n throw new Error(\n \"No fetch implementation available. Pass `fetchFn` to createDefaultAccessRequestClient.\",\n );\n }\n const base = stripTrailingSlash(options.baseUrl);\n\n return {\n async createAccessRequest(input): Promise<AccessRequest> {\n const path = \"/api/data-connection-requests\";\n // Every call is an independent logical create, so it gets its own key.\n // The client cannot tell two look-alike creates apart — one shared backend\n // controller serves many users with the same app, scopes, and returnUrl —\n // so deriving a key from the input would let the service deduplicate two\n // users onto a single DCR. Retrying an uncertain create is the caller's\n // decision: pass the same `idempotencyKey` back in.\n const idempotencyKey =\n input.idempotencyKey ??\n (options.createIdempotencyKey ?? defaultCreateIdempotencyKey)();\n const body = JSON.stringify({\n appAddress: input.appAddress,\n app: input.app,\n source: input.source,\n scopes: input.scopes,\n returnUrl: input.returnUrl,\n network: input.network,\n ...(input.foregroundDelivery !== undefined\n ? { foregroundDelivery: input.foregroundDelivery }\n : {}),\n idempotencyKey,\n });\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(await buildDirectAccessRequestHeaders(options, {\n body,\n method: \"POST\",\n path,\n })),\n },\n body,\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const responseBody = (await res.json()) as {\n requestId?: string;\n id?: string;\n approvalUrl?: string;\n appAddress?: string;\n network?: unknown;\n expiresAt?: unknown;\n mobileContinuationUrl?: unknown;\n };\n const requestId = responseBody.requestId ?? responseBody.id;\n if (!requestId) {\n throw new Error(\"Access request service returned no requestId\");\n }\n return {\n requestId,\n approvalUrl:\n responseBody.approvalUrl ??\n buildApprovalUrl(options.approvalBaseUrl, requestId),\n appAddress: responseBody.appAddress ?? input.appAddress,\n network: normalizeNetwork(responseBody.network),\n expiresAt: normalizeExpiresAt(responseBody.expiresAt),\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n responseBody.mobileContinuationUrl,\n options.env,\n ),\n };\n },\n\n async getAccessRequestStatus(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"GET\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"GET\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request service error: ${res.status} ${res.statusText}`,\n );\n }\n const body = (await res.json()) as {\n status?: string;\n personalServerUrl?: string;\n grantId?: string;\n scope?: string;\n mobileContinuationUrl?: unknown;\n scopes?: string[];\n };\n // `scopes` is the full approved set; `scope` is the first of them, kept\n // for callers (and deployments) that predate the array.\n const scopes =\n body.scopes && body.scopes.length > 0\n ? body.scopes\n : body.scope\n ? [body.scope]\n : undefined;\n return {\n status: normalizeStatus(body.status),\n personalServerUrl: body.personalServerUrl,\n grantId: body.grantId,\n scope: body.scope ?? scopes?.[0],\n scopes,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n body.mobileContinuationUrl,\n options.env,\n ),\n };\n },\n\n async acknowledgeRead(requestId: string): Promise<void> {\n const path = `/api/data-connection-requests/${encodeURIComponent(requestId)}/consumer-ack`;\n const res = await fetchFn(`${base}${path}`, {\n method: \"POST\",\n headers: await buildDirectAccessRequestHeaders(options, {\n body: \"\",\n method: \"POST\",\n path,\n }),\n });\n if (!res.ok) {\n throw new Error(\n `Access request ack service error: ${res.status} ${res.statusText}`,\n );\n }\n },\n };\n}\n"],"mappings":"AAoBA,SAAS,sCAAsC;AA8C/C,MAAM,iBAAsD;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,gBAAgB,OAA0C;AACjE,SAAO,eAAe,SAAS,KAAiC,IAC3D,QACD;AACN;AAEA,SAAS,iBAAiB,O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C,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -21,6 +21,7 @@ __export(connect_flow_exports, {
|
|
|
21
21
|
createDirectConnectFlow: () => createDirectConnectFlow
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(connect_flow_exports);
|
|
24
|
+
var import_types = require("./types");
|
|
24
25
|
const DEFAULT_POLL_INTERVAL_MS = 1500;
|
|
25
26
|
const DEFAULT_TIMEOUT_MS = 3e5;
|
|
26
27
|
function toError(value) {
|
|
@@ -29,6 +30,16 @@ function toError(value) {
|
|
|
29
30
|
function isReadReadyStatus(status) {
|
|
30
31
|
return status === "approved" || status === "ready_for_read";
|
|
31
32
|
}
|
|
33
|
+
const MOBILE_USER_AGENT = /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;
|
|
34
|
+
function defaultBrowserPlatformPolicy() {
|
|
35
|
+
return {
|
|
36
|
+
current() {
|
|
37
|
+
if (typeof navigator === "undefined") return "desktop";
|
|
38
|
+
const isTouchCapableIpad = navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
|
|
39
|
+
return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad ? "mobile" : "desktop";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
32
43
|
function defaultOpenApprovalWindow() {
|
|
33
44
|
if (typeof window === "undefined" || !window.open) return null;
|
|
34
45
|
const opened = window.open("", "_blank");
|
|
@@ -89,7 +100,7 @@ function createDirectConnectFlow(transports, options = {}) {
|
|
|
89
100
|
}
|
|
90
101
|
}
|
|
91
102
|
function isRunningPhase() {
|
|
92
|
-
return state.type === "creating" || state.type === "awaiting_approval" || state.type === "reading";
|
|
103
|
+
return state.type === "creating" || state.type === "awaiting_approval" || state.type === "ready_to_open" || state.type === "reading";
|
|
93
104
|
}
|
|
94
105
|
async function readAndFinish(request) {
|
|
95
106
|
setState({ type: "reading", request });
|
|
@@ -109,6 +120,26 @@ function createDirectConnectFlow(transports, options = {}) {
|
|
|
109
120
|
void poll(request, deadline);
|
|
110
121
|
}, pollIntervalMs);
|
|
111
122
|
}
|
|
123
|
+
function requestDeadline(request) {
|
|
124
|
+
if (request.expiresAt !== void 0) {
|
|
125
|
+
const expiresAt = Date.parse(request.expiresAt);
|
|
126
|
+
if (Number.isFinite(expiresAt)) return expiresAt;
|
|
127
|
+
}
|
|
128
|
+
return now() + timeoutMs;
|
|
129
|
+
}
|
|
130
|
+
function startPolling(request, initialState) {
|
|
131
|
+
setState(initialState);
|
|
132
|
+
const deadline = requestDeadline(request);
|
|
133
|
+
if (now() >= deadline) {
|
|
134
|
+
running = false;
|
|
135
|
+
setState({
|
|
136
|
+
type: "error",
|
|
137
|
+
error: new Error("Access request expired")
|
|
138
|
+
});
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
scheduleNextPoll(request, deadline);
|
|
142
|
+
}
|
|
112
143
|
async function poll(request, deadline) {
|
|
113
144
|
if (!running) return;
|
|
114
145
|
if (now() >= deadline) {
|
|
@@ -129,6 +160,19 @@ function createDirectConnectFlow(transports, options = {}) {
|
|
|
129
160
|
return;
|
|
130
161
|
}
|
|
131
162
|
if (!running) return;
|
|
163
|
+
if (status.status === "pending" && state.type === "ready_to_open") {
|
|
164
|
+
const refreshed = (0, import_types.normalizeMobileContinuationUrl)(
|
|
165
|
+
status.mobileContinuationUrl
|
|
166
|
+
);
|
|
167
|
+
if (refreshed && refreshed !== state.mobileContinuationUrl) {
|
|
168
|
+
request = { ...request, mobileContinuationUrl: refreshed };
|
|
169
|
+
setState({
|
|
170
|
+
type: "ready_to_open",
|
|
171
|
+
request,
|
|
172
|
+
mobileContinuationUrl: refreshed
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
}
|
|
132
176
|
if (isReadReadyStatus(status.status)) {
|
|
133
177
|
clearPoll();
|
|
134
178
|
await readAndFinish(request);
|
|
@@ -156,8 +200,8 @@ function createDirectConnectFlow(transports, options = {}) {
|
|
|
156
200
|
if (running || isRunningPhase()) return;
|
|
157
201
|
running = true;
|
|
158
202
|
const runId = ++activeRunId;
|
|
159
|
-
const
|
|
160
|
-
const approvalWindow = openApprovalWindow();
|
|
203
|
+
const browserPlatform = (options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()).current();
|
|
204
|
+
const approvalWindow = browserPlatform === "desktop" ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)() : null;
|
|
161
205
|
openedWindow = approvalWindow;
|
|
162
206
|
setState({ type: "creating" });
|
|
163
207
|
let request;
|
|
@@ -177,17 +221,30 @@ function createDirectConnectFlow(transports, options = {}) {
|
|
|
177
221
|
approvalWindow?.close();
|
|
178
222
|
return;
|
|
179
223
|
}
|
|
224
|
+
request = {
|
|
225
|
+
...request,
|
|
226
|
+
mobileContinuationUrl: (0, import_types.normalizeMobileContinuationUrl)(
|
|
227
|
+
request.mobileContinuationUrl
|
|
228
|
+
)
|
|
229
|
+
};
|
|
230
|
+
const mobileContinuationUrl = browserPlatform === "mobile" ? request.mobileContinuationUrl : void 0;
|
|
231
|
+
if (mobileContinuationUrl) {
|
|
232
|
+
startPolling(request, {
|
|
233
|
+
type: "ready_to_open",
|
|
234
|
+
request,
|
|
235
|
+
mobileContinuationUrl
|
|
236
|
+
});
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
180
239
|
if (approvalWindow) {
|
|
181
240
|
approvalWindow.navigate(request.approvalUrl);
|
|
182
241
|
openedWindow = null;
|
|
183
242
|
}
|
|
184
|
-
|
|
243
|
+
startPolling(request, {
|
|
185
244
|
type: "awaiting_approval",
|
|
186
245
|
request,
|
|
187
246
|
popupBlocked: approvalWindow === null
|
|
188
247
|
});
|
|
189
|
-
const deadline = now() + timeoutMs;
|
|
190
|
-
scheduleNextPoll(request, deadline);
|
|
191
248
|
},
|
|
192
249
|
reset() {
|
|
193
250
|
running = false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /** Overall timeout in ms before giving up. Defaults to 300000 (5 min). */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the browser blocked the approval popup. The UI should\n * render `request.approvalUrl` as a visible \"Open approval\" link so the\n * user can open it manually instead of the flow silently hanging.\n */\n popupBlocked: boolean;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // Resolved lazily at start() (see below) so a custom opener swapped in after\n // construction is still honoured — matching the latest-callback pattern the\n // React hook uses for its transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n const runId = ++activeRunId;\n\n // Open the approval tab *synchronously*, while the click's transient\n // activation is still live. The approval URL isn't known yet (it comes\n // from createRequest below), so open a blank tab now and navigate it\n // once the URL arrives. Opening *after* the await — as this flow used to\n // — runs outside the gesture, so the browser suppresses it as an\n // unsolicited popup and the flow stalls forever (BUI-622).\n // Read the opener option *now* (not at construction) so a custom opener\n // swapped in after the flow was created is still used.\n const openApprovalWindow =\n options.openApprovalWindow ?? defaultOpenApprovalWindow;\n const approvalWindow = openApprovalWindow();\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n // `approvalWindow === null` means the popup was blocked. Surface it so\n // the UI renders request.approvalUrl as a visible \"Open approval\" link\n // instead of hanging. We poll either way, so a manual open still\n // resolves the flow, and the timeout still bounds the wait.\n setState({\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n\n const deadline = now() + timeoutMs;\n scheduleNextPoll(request, deadline);\n },\n\n reset(): void {\n running = false;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n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QAAQ,WAAW;AAE3C,uBAAe;AAAA,MACjB;AAKA,eAAS;AAAA,QACP,MAAM;AAAA,QACN;AAAA,QACA,cAAc,mBAAmB;AAAA,MACnC,CAAC;AAED,YAAM,WAAW,IAAI,IAAI;AACzB,uBAAiB,SAAS,QAAQ;AAAA,IACpC;AAAA,IAEA,QAAc;AACZ,gBAAU;AAGV;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Browser class used only to choose the destination returned by Vana. */\nexport type DirectBrowserPlatform = \"desktop\" | \"mobile\";\n\n/** Injectable browser-platform policy; it never asserts whether an app exists. */\nexport interface DirectBrowserPlatformPolicy {\n current(): DirectBrowserPlatform;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /**\n * Overall timeout in ms before giving up. Defaults to 300000 (5 min).\n * Used only when the access request does not carry an authoritative\n * `expiresAt` value.\n */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** SDK-owned mobile/desktop policy. Injectable for deterministic tests. */\n browserPlatformPolicy?: DirectBrowserPlatformPolicy;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n *\n * Desktop and light-data requests move through `\"awaiting_approval\"` (Vana Web\n * opens in a popup). A deep Direct request on a mobile browser moves through\n * `\"ready_to_open\"` instead: the SDK exposes a plain HTTPS\n * `mobileContinuationUrl` for the UI to render as a primary \"Open Vana\" link,\n * never launching it automatically, and keeps polling in memory.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the popup was blocked. The UI should render the universal\n * HTTPS `request.approvalUrl` as a manual \"Open approval\" link.\n */\n popupBlocked: boolean;\n }\n | {\n type: \"ready_to_open\";\n request: AccessRequest;\n /**\n * Validated HTTPS continuation URL the mobile UI renders as the primary\n * \"Open Vana\" tap. Polling continues while it is shown; its embedded\n * ticket may rotate to a fresh URL between polls.\n */\n mobileContinuationUrl: string;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\nconst MOBILE_USER_AGENT =\n /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;\n\nfunction defaultBrowserPlatformPolicy(): DirectBrowserPlatformPolicy {\n return {\n current() {\n if (typeof navigator === \"undefined\") return \"desktop\";\n const isTouchCapableIpad =\n navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1;\n return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad\n ? \"mobile\"\n : \"desktop\";\n },\n };\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // `openApprovalWindow` and `browserPlatformPolicy` are resolved lazily at\n // start() (see below) so options swapped in after construction are still\n // honoured — matching the latest-callback pattern the React hook uses for its\n // transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"ready_to_open\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n function requestDeadline(request: AccessRequest): number {\n if (request.expiresAt !== undefined) {\n const expiresAt = Date.parse(request.expiresAt);\n if (Number.isFinite(expiresAt)) return expiresAt;\n }\n return now() + timeoutMs;\n }\n\n /**\n * Enter the polling loop from the given initial state (either\n * `awaiting_approval` for desktop/light or `ready_to_open` for mobile-deep).\n * Errors out immediately if the request has already expired.\n */\n function startPolling(\n request: AccessRequest,\n initialState: DirectConnectState<T>,\n ): void {\n setState(initialState);\n const deadline = requestDeadline(request);\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Access request expired\"),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n // A pending deep-mobile status may rotate the continuation ticket. Adopt a\n // fresh, still-valid URL so the rendered \"Open Vana\" link always points at a\n // live ticket; ignore it on the desktop/light path.\n if (status.status === \"pending\" && state.type === \"ready_to_open\") {\n const refreshed = normalizeMobileContinuationUrl(\n status.mobileContinuationUrl,\n );\n if (refreshed && refreshed !== state.mobileContinuationUrl) {\n request = { ...request, mobileContinuationUrl: refreshed };\n setState({\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl: refreshed,\n });\n }\n }\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n const runId = ++activeRunId;\n // Read the platform policy at start time, like openApprovalWindow below,\n // so a policy swapped in after construction (a React rerender forwards\n // options through a ref) still decides this run's destination.\n const browserPlatform = (\n options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()\n ).current();\n\n // Desktop preserves the pre-mobile synchronous popup contract: open a\n // blank tab while the click's transient activation is live, then navigate\n // it once createRequest returns the approval URL (BUI-622). Mobile never\n // creates that transient tab; deep requests expose one explicit HTTPS\n // link, while light requests retain the manual approvalUrl fallback.\n // Read the opener option at start time so a swapped-in custom opener is\n // still honored for desktop flows.\n const approvalWindow =\n browserPlatform === \"desktop\"\n ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)()\n : null;\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n // Re-validate the continuation URL at the SDK boundary (defense in depth\n // for custom transports that bypass the default client).\n request = {\n ...request,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n request.mobileContinuationUrl,\n ),\n };\n\n // The SDK owns only the small mobile-versus-desktop destination choice.\n // A deep Direct request on mobile carries a validated continuation URL;\n // desktop keeps its popup contract, while mobile light exposes the HTTPS\n // approval URL as the existing manual fallback without opening a tab.\n const mobileContinuationUrl =\n browserPlatform === \"mobile\"\n ? request.mobileContinuationUrl\n : undefined;\n\n if (mobileContinuationUrl) {\n // Do not auto-launch: DCR creation is async, so the original Connect\n // gesture can no longer be trusted to retain iOS user activation. Let\n // the UI render an explicit primary \"Open Vana\" link; polling continues\n // in this tab.\n startPolling(request, {\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl,\n });\n return;\n }\n\n // Desktop/light: navigate the synchronously-opened tab to the HTTPS\n // approval URL. `approvalWindow === null` means the popup was blocked;\n // surface it so the UI renders request.approvalUrl as a visible manual\n // \"Open approval\" link instead of hanging. We poll either way, so a manual\n // open still resolves the flow, and the timeout still bounds the wait.\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n startPolling(request, {\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n },\n\n reset(): void {\n running = false;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a subsequent run.\n activeRunId++;\n clearPoll();\n closeUnnavigatedWindow();\n setState({ type: \"idle\" });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAA+C;AA2H/C,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAE3B,SAAS,QAAQ,OAAuB;AACtC,SAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;AAEA,SAAS,kBAAkB,QAA2C;AACpE,SAAO,WAAW,cAAc,WAAW;AAC7C;AAEA,MAAM,oBACJ;AAEF,SAAS,+BAA4D;AACnE,SAAO;AAAA,IACL,UAAU;AACR,UAAI,OAAO,cAAc,YAAa,QAAO;AAC7C,YAAM,qBACJ,UAAU,aAAa,cAAc,UAAU,iBAAiB;AAClE,aAAO,kBAAkB,KAAK,UAAU,SAAS,KAAK,qBAClD,WACA;AAAA,IACN;AAAA,EACF;AACF;AAOA,SAAS,4BAAkD;AACzD,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAM,QAAO;AAI1D,QAAM,SAAS,OAAO,KAAK,IAAI,QAAQ;AACvC,MAAI,CAAC,OAAQ,QAAO;AAGpB,MAAI;AACF,WAAO,SAAS;AAAA,EAClB,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,SAAS,KAAa;AAIpB,UAAI;AACF,cAAM,OAAO,OAAO,SAAS,cAAc,MAAM;AACjD,aAAK,OAAO;AACZ,aAAK,UAAU;AACf,SAAC,OAAO,SAAS,QAAQ,OAAO,SAAS,kBAAkB;AAAA,UACzD;AAAA,QACF;AAAA,MAC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