@opendatalabs/vana-sdk 4.4.0 → 4.5.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 +176 -0
- package/dist/connect/account-origin.cjs +72 -0
- package/dist/connect/account-origin.cjs.map +1 -0
- package/dist/connect/account-origin.d.ts +92 -0
- package/dist/connect/account-origin.js +47 -0
- package/dist/connect/account-origin.js.map +1 -0
- package/dist/connect/account-origin.test.d.ts +1 -0
- package/dist/connect/chrome.cjs +284 -0
- package/dist/connect/chrome.cjs.map +1 -0
- package/dist/connect/chrome.d.ts +42 -0
- package/dist/connect/chrome.js +256 -0
- package/dist/connect/chrome.js.map +1 -0
- package/dist/connect/http-transports.cjs +100 -0
- package/dist/connect/http-transports.cjs.map +1 -0
- package/dist/connect/http-transports.d.ts +77 -0
- package/dist/connect/http-transports.js +75 -0
- package/dist/connect/http-transports.js.map +1 -0
- package/dist/connect/http-transports.test.d.ts +1 -0
- package/dist/connect/launcher.cjs +232 -0
- package/dist/connect/launcher.cjs.map +1 -0
- package/dist/connect/launcher.d.ts +129 -0
- package/dist/connect/launcher.js +220 -0
- package/dist/connect/launcher.js.map +1 -0
- package/dist/connect/launcher.test.d.ts +1 -0
- package/dist/connect/protocol.cjs +259 -0
- package/dist/connect/protocol.cjs.map +1 -0
- package/dist/connect/protocol.d.ts +331 -0
- package/dist/connect/protocol.js +215 -0
- package/dist/connect/protocol.js.map +1 -0
- package/dist/connect/protocol.test.d.ts +1 -0
- package/dist/connect.cjs +55 -0
- package/dist/connect.cjs.map +1 -0
- package/dist/connect.d.ts +35 -0
- package/dist/connect.js +34 -0
- package/dist/connect.js.map +1 -0
- package/dist/direct/connect-flow-sheet.test.d.ts +1 -0
- package/dist/direct/connect-flow.cjs +211 -1
- package/dist/direct/connect-flow.cjs.map +1 -1
- package/dist/direct/connect-flow.d.ts +75 -0
- package/dist/direct/connect-flow.js +213 -1
- package/dist/direct/connect-flow.js.map +1 -1
- package/dist/direct/connect-handler.cjs +493 -0
- package/dist/direct/connect-handler.cjs.map +1 -0
- package/dist/direct/connect-handler.d.ts +246 -0
- package/dist/direct/connect-handler.js +476 -0
- package/dist/direct/connect-handler.js.map +1 -0
- package/dist/direct/connect-handler.test.d.ts +1 -0
- package/dist/direct/controller.cjs +86 -17
- package/dist/direct/controller.cjs.map +1 -1
- package/dist/direct/controller.d.ts +101 -6
- package/dist/direct/controller.js +86 -16
- package/dist/direct/controller.js.map +1 -1
- package/dist/direct/endpoints.cjs +5 -2
- package/dist/direct/endpoints.cjs.map +1 -1
- package/dist/direct/endpoints.js +5 -2
- package/dist/direct/endpoints.js.map +1 -1
- package/dist/direct/request-authorization.cjs +65 -0
- package/dist/direct/request-authorization.cjs.map +1 -0
- package/dist/direct/request-authorization.d.ts +65 -0
- package/dist/direct/request-authorization.js +39 -0
- package/dist/direct/request-authorization.js.map +1 -0
- package/dist/direct/request-authorization.test.d.ts +1 -0
- package/dist/direct/types.cjs.map +1 -1
- package/dist/direct/types.d.ts +6 -0
- package/dist/direct/types.js.map +1 -1
- package/dist/direct/use-direct-vana-connect.cjs +18 -1
- package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
- package/dist/direct/use-direct-vana-connect.js +18 -1
- package/dist/direct/use-direct-vana-connect.js.map +1 -1
- package/dist/direct/use-vana-connect.cjs +84 -0
- package/dist/direct/use-vana-connect.cjs.map +1 -0
- package/dist/direct/use-vana-connect.d.ts +59 -0
- package/dist/direct/use-vana-connect.js +64 -0
- package/dist/direct/use-vana-connect.js.map +1 -0
- package/dist/direct/use-vana-connect.test.d.ts +1 -0
- package/dist/index.browser.d.ts +1 -0
- package/dist/index.browser.js +104 -0
- package/dist/index.browser.js.map +4 -4
- package/dist/index.node.cjs +112 -0
- package/dist/index.node.cjs.map +3 -3
- package/dist/index.node.d.ts +1 -0
- package/dist/index.node.js +104 -0
- package/dist/index.node.js.map +4 -4
- package/dist/protocol/fixtures/pdpp-scope-keys.json +133 -0
- package/dist/protocol/pdpp-scopes.cjs +134 -0
- package/dist/protocol/pdpp-scopes.cjs.map +1 -0
- package/dist/protocol/pdpp-scopes.d.ts +123 -0
- package/dist/protocol/pdpp-scopes.js +103 -0
- package/dist/protocol/pdpp-scopes.js.map +1 -0
- package/dist/protocol/pdpp-scopes.test.d.ts +1 -0
- package/dist/protocol/scopes.cjs +17 -0
- package/dist/protocol/scopes.cjs.map +1 -1
- package/dist/protocol/scopes.d.ts +1 -0
- package/dist/protocol/scopes.js +18 -0
- package/dist/protocol/scopes.js.map +1 -1
- package/dist/react.cjs +10 -2
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.ts +4 -1
- package/dist/react.js +11 -1
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +61 -2
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +16 -4
- package/dist/server.js +67 -3
- package/dist/server.js.map +1 -1
- package/package.json +11 -1
|
@@ -18,12 +18,17 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
var controller_exports = {};
|
|
20
20
|
__export(controller_exports, {
|
|
21
|
-
|
|
21
|
+
DIRECT_CONNECT_CAPABILITIES: () => DIRECT_CONNECT_CAPABILITIES,
|
|
22
|
+
createDirectDataController: () => createDirectDataController,
|
|
23
|
+
isConnectCapableController: () => isConnectCapableController,
|
|
24
|
+
missingConnectCapabilities: () => missingConnectCapabilities
|
|
22
25
|
});
|
|
23
26
|
module.exports = __toCommonJS(controller_exports);
|
|
24
27
|
var import_accounts = require("viem/accounts");
|
|
28
|
+
var import_viem = require("viem");
|
|
25
29
|
var import_scopes = require("../protocol/scopes");
|
|
26
30
|
var import_scope_actions = require("../protocol/scope-actions");
|
|
31
|
+
var import_pdpp_scopes = require("../protocol/pdpp-scopes");
|
|
27
32
|
var import_escrow = require("../protocol/escrow");
|
|
28
33
|
var import_gateway = require("../protocol/gateway");
|
|
29
34
|
var import_grant_union = require("./grant-union");
|
|
@@ -32,7 +37,22 @@ var import_access_request_client = require("./access-request-client");
|
|
|
32
37
|
var import_endpoints = require("./endpoints");
|
|
33
38
|
var import_errors = require("./errors.cjs");
|
|
34
39
|
var import_test_credit = require("./test-credit");
|
|
40
|
+
var import_request_authorization = require("./request-authorization");
|
|
35
41
|
var import_personal_server_read = require("./personal-server-read");
|
|
42
|
+
const DIRECT_CONNECT_CAPABILITIES = [
|
|
43
|
+
"authorizeRequestRead",
|
|
44
|
+
"getEndpoints",
|
|
45
|
+
"deriveSecret",
|
|
46
|
+
"getEnv"
|
|
47
|
+
];
|
|
48
|
+
function missingConnectCapabilities(controller) {
|
|
49
|
+
return DIRECT_CONNECT_CAPABILITIES.filter(
|
|
50
|
+
(name) => typeof controller[name] !== "function"
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
function isConnectCapableController(controller) {
|
|
54
|
+
return missingConnectCapabilities(controller).length === 0;
|
|
55
|
+
}
|
|
36
56
|
function isHexPrivateKey(value) {
|
|
37
57
|
return /^0x[0-9a-fA-F]{64}$/.test(value);
|
|
38
58
|
}
|
|
@@ -46,11 +66,24 @@ function createDirectDataController(config) {
|
|
|
46
66
|
"appPrivateKey must be a 0x-prefixed 32-byte hex string"
|
|
47
67
|
);
|
|
48
68
|
}
|
|
49
|
-
|
|
50
|
-
|
|
69
|
+
const scopes = (0, import_pdpp_scopes.grantRequestScopes)({
|
|
70
|
+
grants: config.grants,
|
|
71
|
+
scopes: config.scopes
|
|
72
|
+
});
|
|
73
|
+
if (scopes.length === 0) {
|
|
74
|
+
throw new import_errors.DirectConfigError(
|
|
75
|
+
"At least one scope or PDPP grant stream is required"
|
|
76
|
+
);
|
|
51
77
|
}
|
|
52
|
-
for (const entry of
|
|
53
|
-
|
|
78
|
+
for (const entry of scopes) {
|
|
79
|
+
const scope = (0, import_scope_actions.parseScopeEntry)(entry).scope;
|
|
80
|
+
(0, import_scopes.parseScope)(scope);
|
|
81
|
+
if (scope.startsWith(`${import_pdpp_scopes.PDPP_SCOPE_NAMESPACE}.`) && !(0, import_pdpp_scopes.isPdppScopeKey)(scope)) {
|
|
82
|
+
throw new import_errors.DirectConfigError(
|
|
83
|
+
`"${entry}" is in the reserved "${import_pdpp_scopes.PDPP_SCOPE_NAMESPACE}." namespace but is not a PDPP scope key. Request PDPP data with grants: [{ source_id, streams }].`,
|
|
84
|
+
{ entry }
|
|
85
|
+
);
|
|
86
|
+
}
|
|
54
87
|
}
|
|
55
88
|
const env = config.env ?? "production";
|
|
56
89
|
const network = config.network ?? (0, import_endpoints.getDirectDefaultNetwork)(env);
|
|
@@ -59,7 +92,8 @@ function createDirectDataController(config) {
|
|
|
59
92
|
const endpoints = {
|
|
60
93
|
...defaultEndpoints,
|
|
61
94
|
...config.endpoints,
|
|
62
|
-
chainId
|
|
95
|
+
chainId,
|
|
96
|
+
accountOrigin: config.endpoints?.accountOrigin ?? defaultEndpoints.accountOrigin
|
|
63
97
|
};
|
|
64
98
|
const account = (0, import_accounts.privateKeyToAccount)(privateKey);
|
|
65
99
|
const signMessage = (message) => account.signMessage({ message });
|
|
@@ -89,8 +123,8 @@ function createDirectDataController(config) {
|
|
|
89
123
|
let gateway = config.gateway;
|
|
90
124
|
async function resolveGrantUnion(owner, options) {
|
|
91
125
|
const requestedOnly = {
|
|
92
|
-
...(0, import_grant_union.unionGrantScopes)([],
|
|
93
|
-
scopes: [...
|
|
126
|
+
...(0, import_grant_union.unionGrantScopes)([], scopes, options.removeScopes),
|
|
127
|
+
scopes: [...scopes]
|
|
94
128
|
};
|
|
95
129
|
if (!options.merge) {
|
|
96
130
|
return { status: "disabled", ...requestedOnly };
|
|
@@ -104,7 +138,7 @@ function createDirectDataController(config) {
|
|
|
104
138
|
gateway,
|
|
105
139
|
owner,
|
|
106
140
|
appAddress: account.address,
|
|
107
|
-
scopes
|
|
141
|
+
scopes,
|
|
108
142
|
removeScopes: options.removeScopes
|
|
109
143
|
});
|
|
110
144
|
} catch (error) {
|
|
@@ -130,7 +164,7 @@ function createDirectDataController(config) {
|
|
|
130
164
|
},
|
|
131
165
|
async createAccessRequest(input) {
|
|
132
166
|
if (input.questions !== void 0) {
|
|
133
|
-
(0, import_access_request_client.validateAccessRequestQuestions)(input.questions,
|
|
167
|
+
(0, import_access_request_client.validateAccessRequestQuestions)(input.questions, scopes);
|
|
134
168
|
}
|
|
135
169
|
const removeScopes = input.removeScopes ?? [];
|
|
136
170
|
for (const entry of removeScopes) {
|
|
@@ -169,10 +203,10 @@ function createDirectDataController(config) {
|
|
|
169
203
|
requestTestCredit,
|
|
170
204
|
async readAllApprovedData(input) {
|
|
171
205
|
const status = await requireReadReady(input.requestId);
|
|
172
|
-
const
|
|
206
|
+
const scopes2 = approvedScopes(status);
|
|
173
207
|
const results = {};
|
|
174
208
|
const errors = {};
|
|
175
|
-
for (const scope of
|
|
209
|
+
for (const scope of scopes2) {
|
|
176
210
|
try {
|
|
177
211
|
results[scope] = await readScope(status, scope);
|
|
178
212
|
} catch (error) {
|
|
@@ -183,6 +217,38 @@ function createDirectDataController(config) {
|
|
|
183
217
|
await acknowledgeQuietly(input.requestId);
|
|
184
218
|
}
|
|
185
219
|
return { results, errors };
|
|
220
|
+
},
|
|
221
|
+
authorizeRequestRead(requestId) {
|
|
222
|
+
return (0, import_request_authorization.signRequestReadAuthorization)({
|
|
223
|
+
requestId,
|
|
224
|
+
appAddress: account.address,
|
|
225
|
+
signMessage
|
|
226
|
+
});
|
|
227
|
+
},
|
|
228
|
+
getEndpoints() {
|
|
229
|
+
return { ...endpoints };
|
|
230
|
+
},
|
|
231
|
+
getEnv() {
|
|
232
|
+
return env;
|
|
233
|
+
},
|
|
234
|
+
async deriveSecret(purpose) {
|
|
235
|
+
const ikm = await globalThis.crypto.subtle.importKey(
|
|
236
|
+
"raw",
|
|
237
|
+
new Uint8Array((0, import_viem.hexToBytes)(privateKey)),
|
|
238
|
+
"HKDF",
|
|
239
|
+
false,
|
|
240
|
+
["deriveBits"]
|
|
241
|
+
);
|
|
242
|
+
return globalThis.crypto.subtle.deriveBits(
|
|
243
|
+
{
|
|
244
|
+
name: "HKDF",
|
|
245
|
+
hash: "SHA-256",
|
|
246
|
+
salt: new TextEncoder().encode("vana-sdk/derived-secret/v1"),
|
|
247
|
+
info: new TextEncoder().encode(purpose)
|
|
248
|
+
},
|
|
249
|
+
ikm,
|
|
250
|
+
256
|
|
251
|
+
);
|
|
186
252
|
}
|
|
187
253
|
};
|
|
188
254
|
async function requireReadReady(requestId) {
|
|
@@ -206,12 +272,12 @@ function createDirectDataController(config) {
|
|
|
206
272
|
return status.scope ? [status.scope] : [];
|
|
207
273
|
}
|
|
208
274
|
function resolveRequestedScope(status, requested) {
|
|
209
|
-
const
|
|
210
|
-
if (requested === void 0) return
|
|
211
|
-
if (!
|
|
275
|
+
const scopes2 = approvedScopes(status);
|
|
276
|
+
if (requested === void 0) return scopes2[0];
|
|
277
|
+
if (!scopes2.includes(requested)) {
|
|
212
278
|
throw new import_errors.ScopeNotApprovedError(
|
|
213
279
|
`Scope "${requested}" is not approved on this request`,
|
|
214
|
-
{ requestedScope: requested, approvedScopes:
|
|
280
|
+
{ requestedScope: requested, approvedScopes: scopes2 }
|
|
215
281
|
);
|
|
216
282
|
}
|
|
217
283
|
return requested;
|
|
@@ -265,6 +331,9 @@ function createDirectDataController(config) {
|
|
|
265
331
|
}
|
|
266
332
|
// Annotate the CommonJS export names for ESM import in node:
|
|
267
333
|
0 && (module.exports = {
|
|
268
|
-
|
|
334
|
+
DIRECT_CONNECT_CAPABILITIES,
|
|
335
|
+
createDirectDataController,
|
|
336
|
+
isConnectCapableController,
|
|
337
|
+
missingConnectCapabilities
|
|
269
338
|
});
|
|
270
339
|
//# sourceMappingURL=controller.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/controller.ts"],"sourcesContent":["/**\n * Direct Data Controller — the server-side facade for the two-tab Data\n * Portability flow.\n *\n * @remarks\n * One controller owns an app's private key, source, scopes, app identity, and\n * payment flow. It exposes the three methods the builder guide documents:\n *\n * - {@link DirectDataController.createAccessRequest} — start an approval request.\n * - {@link DirectDataController.getAccessRequestStatus} — poll while the Vana tab is open.\n * - {@link DirectDataController.readApprovedData} — read from the Personal Server,\n * handling 402 Payment Required.\n *\n * Access requests are created through the Vana Account access-request API; the\n * Personal Server read uses Web3Signed auth; and payment uses the DPv2 escrow\n * surface (`protocol/escrow`) — when a read returns `402`, the controller signs\n * a `GenericPayment` with the app key, settles it through the escrow gateway,\n * and retries.\n *\n * @category Direct\n * @module direct/controller\n */\n\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport type { Hex } from \"viem\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\nimport { parseScope } from \"../protocol/scopes\";\nimport { parseScopeEntry } from \"../protocol/scope-actions\";\nimport { createEscrowGatewayClient } from \"../protocol/escrow\";\nimport { createGatewayClient } from \"../protocol/gateway\";\nimport {\n mergeWithLiveGrant,\n unionGrantScopes,\n type GrantUnionGateway,\n} from \"./grant-union\";\nimport { CONTRACTS } from \"../generated/addresses\";\nimport {\n createDefaultAccessRequestClient,\n validateAccessRequestQuestions,\n type FetchLike,\n} from \"./access-request-client\";\nimport {\n getDirectDefaultNetwork,\n getDirectEndpoints,\n getDirectNetworkChainId,\n} from \"./endpoints\";\nimport {\n AccessNotApprovedError,\n DirectConfigError,\n EscrowBalanceTooLowError,\n ScopeNotApprovedError,\n} from \"./errors\";\nimport {\n requestTestCredit as requestTestCreditFromAccount,\n type TestCreditResult,\n} from \"./test-credit\";\nimport {\n type EscrowPaymentConfig,\n type SignTypedDataFn,\n} from \"./escrow-payment\";\nimport {\n readPersonalServerData,\n type PersonalServerFetch,\n type PersonalServerTransportRetryOptions,\n} from \"./personal-server-read\";\nimport type {\n AccessRequest,\n AccessRequestClient,\n AccessRequestGrantUnion,\n AccessRequestQuestion,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n AppIdentity,\n DirectAppConfig,\n DirectEnv,\n DirectNetwork,\n DirectPaymentResponseMetadata,\n DirectServiceEndpoints,\n ForegroundDelivery,\n MultiScopeDataResult,\n} from \"./types\";\n\n/** Configuration for {@link createDirectDataController}. */\nexport interface DirectDataControllerConfig {\n /** Target environment. Defaults to `\"production\"`. */\n env?: DirectEnv;\n /**\n * Target Vana network for chain-aware defaults. Defaults to the selected\n * environment's historical network (`mainnet` for production, `moksha` for\n * dev). Use `network: \"moksha\"` with the default production env for\n * production app/API URLs on testnet.\n */\n network?: DirectNetwork;\n /**\n * The app private key (`0x`-prefixed, 32 bytes). Server-side only — this key\n * is the app's on-chain identity and is never exposed to the browser.\n */\n appPrivateKey?: string;\n /**\n * @deprecated Use {@link DirectDataControllerConfig.appPrivateKey}. Accepted as\n * a backwards-compatible alias; if both are set, `appPrivateKey` wins.\n */\n builderPrivateKey?: string;\n /** App identity advertised during approval. */\n app: DirectAppConfig;\n /** Data source key (e.g. `\"icloud_notes\"`). */\n source: string;\n /**\n * Grant scope entries to request. At least one required.\n *\n * Each entry is `[operation:]scope` (see `parseScopeEntry`): a bare entry\n * such as `\"icloud_notes.notes\"` requests read, and `\"write:coach.weekly\"`\n * requests write. The entries are carried through to the access request\n * verbatim and become the grant's `scopes`, so a request can mix both\n * (`[\"oura.sleep\", \"coach.weekly\", \"write:coach.weekly\"]`).\n *\n * The scope part must be a concrete `{source}.{category}[.{subcategory}]`\n * scope: this flow reads approved scopes back one by one, so wildcard\n * patterns (`chatgpt.*`, `write:chatgpt.*`) are not accepted here for\n * either operation.\n */\n scopes: string[];\n /**\n * Override the resolved service endpoints (partial). Useful for pointing at a\n * non-standard deployment.\n */\n endpoints?: Partial<DirectServiceEndpoints>;\n /**\n * Client for the Vana Account access-request API. Defaults to a client against\n * the resolved Vana Account endpoints; inject your own to point at a custom\n * deployment or to supply a test double.\n */\n accessRequestClient?: AccessRequestClient;\n /**\n * Escrow settlement config used when a Personal Server read returns `402`.\n *\n * @remarks\n * Wires the DPv2 escrow gateway (`protocol/escrow`). The controller supplies\n * the EIP-712 `signTypedData` from the app key automatically.\n *\n * When omitted (or partially omitted), the SDK derives defaults from the\n * per-network endpoints table and the contract registry:\n * - `client` defaults to a gateway client at `endpoints.escrowGatewayUrl`\n * - `escrowContract` defaults to `CONTRACTS.DataPortabilityEscrow.addresses[chainId]`\n * - `chainId` defaults to the controller's resolved chain id\n *\n * Provide this field only to override a specific default.\n */\n escrow?: Partial<DirectEscrowConfig>;\n /**\n * Gateway the controller reads the owner's live grant from when\n * `createAccessRequest` is given an `owner` (see\n * {@link DirectDataController.createAccessRequest}). Only public reads are\n * used: `listGrantsByUser` and `getBuilder`. Defaults to a gateway client at\n * `endpoints.escrowGatewayUrl`.\n */\n gateway?: GrantUnionGateway;\n /** `fetch` used by the default access-request client. Defaults to `globalThis.fetch`. */\n fetchFn?: FetchLike;\n /** `fetch` used for the Personal Server read. Defaults to `globalThis.fetch`. */\n personalServerFetch?: PersonalServerFetch;\n /**\n * Transport-retry knobs for the Personal Server read\n * ({@link PersonalServerTransportRetryOptions}). Defaults to 3 attempts with\n * exponential backoff. Retries fire only when fetch throws (the browser-PS\n * relay reconnect window), never on a received HTTP status, and never\n * re-sign a payment.\n */\n personalServerTransportRetry?: PersonalServerTransportRetryOptions;\n /**\n * Moksha test credit (testnet only).\n *\n * @remarks\n * With `autoTopUp: true` on `network: \"moksha\"`, a read refused because the\n * app's escrow is too low ({@link EscrowBalanceTooLowError}) asks Vana Account\n * for test credit, waits for it, and retries that read once. The refused\n * read charged nothing, so the retry cannot pay twice. Ignored on mainnet.\n */\n testCredit?: {\n autoTopUp?: boolean;\n /** Vana Account origin. Defaults to `https://account.vana.org`. */\n baseUrl?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n /** `fetch` for the Vana Account calls. Defaults to `globalThis.fetch`. */\n fetchFn?: typeof fetch;\n };\n}\n\n/**\n * Controller-level escrow config — the {@link EscrowPaymentConfig} minus the\n * `signTypedData` and `chainId` the controller injects itself.\n */\nexport interface DirectEscrowConfig extends Omit<\n EscrowPaymentConfig,\n \"signTypedData\" | \"chainId\"\n> {\n /**\n * Chain id for the EIP-712 domain. Defaults to the controller's environment\n * (1480 for mainnet, 14800 for moksha).\n */\n chainId?: number;\n}\n\n/**\n * Server-side controller for the direct Data Portability flow.\n *\n * @typeParam T - Shape of the data returned by {@link DirectDataController.readApprovedData}.\n */\nexport interface DirectDataController {\n /** The on-chain address of the app, derived from `appPrivateKey`. */\n readonly appAddress: string;\n\n /**\n * The app's on-chain address — the address to fund and inspect in the Builder\n * activity report. Equivalent to {@link DirectDataController.appAddress}.\n *\n * @returns The app's `0x`-prefixed address.\n */\n getAppAddress(): string;\n\n /**\n * The app's full identity: its configured id/name/homepage plus the derived\n * on-chain address. Useful for telling builders which app address to fund or\n * look up.\n *\n * @returns `{ id, name, homepageUrl, address }`.\n */\n getAppIdentity(): AppIdentity;\n\n /**\n * Create an access request the user can approve.\n *\n * @param input - The post-approval return URL and optional create retry key.\n * @returns The request id, HTTPS approval URL, and — for a pending deep Direct\n * request on mobile — an optional HTTPS `mobileContinuationUrl`.\n */\n createAccessRequest(input: {\n returnUrl: string;\n /** Optional foreground mobile delivery callback. */\n foregroundDelivery?: ForegroundDelivery;\n /**\n * Derivative questions to carry on the request (1 to 4). Each question\n * asks the user's Personal Server to compute its `derivedScope` from\n * `sourceScopes` the app never reads; the derived scope must also appear\n * in the controller's `scopes` as a bare read entry. Validated eagerly\n * against the configured scopes before the request is sent. See\n * {@link AccessRequestQuestion}.\n */\n questions?: AccessRequestQuestion[];\n /**\n * The data owner, when the app already knows who will approve (for\n * example from an earlier approval). With an owner, the controller reads\n * the owner's live grant for this app and includes its still-granted\n * scopes, so the new request extends the grant instead of replacing it.\n *\n * Without an owner nothing is read: the person is often anonymous until\n * they approve, and the Vana Web approval page signs the union of the\n * live grant and the request for whoever approves.\n */\n owner?: string;\n /**\n * Merge the owner's live grant into the request scopes. Defaults to\n * `true`; has no effect without `owner`. Pass `false` to send the\n * configured scopes verbatim.\n */\n mergeLiveGrant?: boolean;\n /**\n * Scope entries the app gives up from the owner's live grant. Removed\n * from the merged scopes here and sent on the request so the approval\n * page leaves them out of its own union. Matched verbatim\n * (`write:coach.weekly` and `coach.weekly` are separate entries).\n */\n removeScopes?: string[];\n /**\n * Stable retry key when the caller retries after an uncertain response.\n * Each create without one gets its own generated key.\n */\n idempotencyKey?: string;\n }): Promise<AccessRequest>;\n\n /**\n * Fetch the current status of an access request.\n *\n * @param requestId - The `dcr_*` id from {@link DirectDataController.createAccessRequest}.\n * @returns `{ status, personalServerUrl?, grantId?, scope?, scopes? }`.\n */\n getAccessRequestStatus(requestId: string): Promise<AccessRequestStatus>;\n\n /**\n * Read the approved data from the user's Personal Server.\n *\n * @remarks\n * Resolves the request to its grant + Personal Server and performs a Web3Signed\n * read. Hides the `402 Payment Required` flow by default: if a read needs\n * payment, it signs the Personal Server's payment challenge, retries with\n * `X-PAYMENT`, and attaches shape-validated but unauthenticated\n * {@link DirectPaymentResponseMetadata} under `payment` when the Personal\n * Server returns it. After a successful read, the controller acknowledges\n * the DCR so Vana Web can close/redirect the approval tab.\n *\n * A request can approve several scopes. This reads **one** of them — `scope`\n * when given, otherwise the first approved scope. Use\n * {@link DirectDataController.readAllApprovedData} to read them all.\n *\n * Acknowledging moves the DCR to `completed`, which is terminal and no longer\n * read-ready. To read several scopes with your own loop, pass\n * `acknowledge: false` on every call but the last.\n *\n * @param input - The `dcr_*` request id, the optional `scope` to read, and an\n * optional `acknowledge` flag (default `true`).\n * @returns `{ scope, data, payment? }`.\n * @throws {@link AccessNotApprovedError} if the request is not approved.\n * @throws {@link ScopeNotApprovedError} if `scope` is not an approved scope.\n * @throws {@link PaymentRequiredError} if payment is required but unsettled.\n */\n readApprovedData<T = unknown>(input: {\n requestId: string;\n scope?: string;\n acknowledge?: boolean;\n }): Promise<ApprovedDataResult<T>>;\n\n /**\n * Read every scope the user approved on a request.\n *\n * @remarks\n * Reads the scopes in approval order, then acknowledges the DCR **once**,\n * after the last read — acknowledging earlier would move the request to\n * `completed` and make the remaining scopes unreadable.\n *\n * Each scope is a separate Personal Server read that settles its own\n * `data_access` fee from escrow, so reading N scopes costs N times a\n * single-scope read. The one-off registration fee is charged per grant, not\n * per scope.\n *\n * A scope that fails does not abort the rest: successes land in `results` and\n * failures in `errors`, because the fees for earlier scopes are already spent.\n * If any scope fails the request is left unacknowledged, so the scopes that\n * failed stay retryable — read them with `readApprovedData({ scope })` and\n * acknowledge on the last one.\n *\n * @param input - The `dcr_*` request id to read.\n * @returns `{ results, errors }`, both keyed by scope.\n * @throws {@link AccessNotApprovedError} if the request is not approved.\n */\n readAllApprovedData<T = unknown>(input: {\n requestId: string;\n }): Promise<MultiScopeDataResult<T>>;\n /**\n * Ask Vana Account for Moksha test credit for this app's escrow and wait\n * until it is usable. Moksha only.\n *\n * @throws {@link DirectConfigError} on mainnet.\n * @throws TestCreditError if the request fails or does not finalize in time.\n */\n requestTestCredit(): Promise<TestCreditResult>;\n}\n\nfunction isHexPrivateKey(value: string): value is Hex {\n return /^0x[0-9a-fA-F]{64}$/.test(value);\n}\n\n// A DCR is read-ready only while the grant exists and the Personal Server is\n// still serving it: `approved` (durable PS) or `ready_for_read` (browser PS).\n// `completed` is terminal — the app already read and acknowledged, and the\n// browser PS may be gone — so it is deliberately excluded here.\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\n/**\n * Create a {@link DirectDataController}.\n *\n * @param config - Controller configuration (env, key, app identity, source, scopes).\n * @returns A ready-to-use controller.\n * @throws {@link DirectConfigError} when the key is missing or malformed, when\n * `scopes` is empty, or when no escrow contract can be resolved.\n * @throws InvalidScopeEntryError when a `scopes` entry does not fit the\n * `[operation:]scope` grammar (an unknown operation prefix such as `delete:`).\n * @throws ZodError when the scope part of an entry is not a valid scope.\n */\nexport function createDirectDataController(\n config: DirectDataControllerConfig,\n): DirectDataController {\n // `appPrivateKey` is the documented field; `builderPrivateKey` is a\n // deprecated alias kept for backwards compatibility.\n const privateKey = config.appPrivateKey ?? config.builderPrivateKey;\n if (!privateKey || !isHexPrivateKey(privateKey)) {\n throw new DirectConfigError(\n \"appPrivateKey must be a 0x-prefixed 32-byte hex string\",\n );\n }\n if (!config.scopes || config.scopes.length === 0) {\n throw new DirectConfigError(\"At least one scope is required\");\n }\n // Validate scopes eagerly so misconfiguration fails at construction. Each\n // element is a grant scope entry (`[operation:]scope`), so the operation\n // prefix is stripped first and only the scope part is checked against the\n // scope grammar — `write:coach.weekly` is a valid write-grant request, and\n // an unknown operation (`delete:x`) throws rather than being taken as read.\n // The entries themselves are passed through to the access request verbatim,\n // prefix included.\n for (const entry of config.scopes) {\n parseScope(parseScopeEntry(entry).scope);\n }\n\n const env: DirectEnv = config.env ?? \"production\";\n const network: DirectNetwork = config.network ?? getDirectDefaultNetwork(env);\n const defaultEndpoints = getDirectEndpoints(env);\n const chainId = config.endpoints?.chainId ?? getDirectNetworkChainId(network);\n const endpoints: DirectServiceEndpoints = {\n ...defaultEndpoints,\n ...config.endpoints,\n chainId,\n };\n\n const account = privateKeyToAccount(privateKey as Hex);\n const signMessage: Web3SignedSignFn = (message: string) =>\n account.signMessage({ message });\n // viem's account.signTypedData satisfies the structural SignTypedDataFn used\n // by the escrow GenericPayment signer.\n const signTypedData = account.signTypedData as unknown as SignTypedDataFn;\n const accessRequestClient: AccessRequestClient =\n config.accessRequestClient ??\n createDefaultAccessRequestClient({\n baseUrl: endpoints.accessRequestBaseUrl,\n approvalBaseUrl: endpoints.approvalAppBaseUrl,\n env,\n fetchFn: config.fetchFn,\n appAddress: account.address,\n signMessage,\n });\n\n // Build the escrow payment config, defaulting from the per-network endpoints\n // table and the contract registry when `config.escrow` is omitted or partial.\n const escrowChainId = config.escrow?.chainId ?? chainId;\n const defaultEscrowContract =\n CONTRACTS.DataPortabilityEscrow.addresses[\n escrowChainId as keyof typeof CONTRACTS.DataPortabilityEscrow.addresses\n ] ?? undefined;\n if (!config.escrow?.escrowContract && !defaultEscrowContract) {\n throw new DirectConfigError(\n `No DataPortabilityEscrow address found in the registry for chainId ${escrowChainId}. ` +\n `Provide an explicit escrow.escrowContract in the controller config.`,\n );\n }\n const escrow: EscrowPaymentConfig = {\n client:\n config.escrow?.client ??\n createEscrowGatewayClient(endpoints.escrowGatewayUrl),\n escrowContract:\n config.escrow?.escrowContract ?? (defaultEscrowContract as `0x${string}`),\n chainId: escrowChainId,\n nonceSource: config.escrow?.nonceSource,\n signTypedData,\n };\n\n let gateway: GrantUnionGateway | undefined = config.gateway;\n\n // Read the owner's live grant and union it with the configured scopes. A\n // failed read never blocks the request: it goes out with the configured\n // scopes, and the approval page's own union still keeps the live grant.\n async function resolveGrantUnion(\n owner: string | undefined,\n options: { merge: boolean; removeScopes: string[] },\n ): Promise<AccessRequestGrantUnion> {\n // Without a merged live grant the request carries the configured scopes\n // verbatim (duplicates and order included), so bodies and their\n // signatures match SDKs that predate the grant union.\n const requestedOnly = {\n ...unionGrantScopes([], config.scopes, options.removeScopes),\n scopes: [...config.scopes],\n };\n if (!options.merge) {\n return { status: \"disabled\", ...requestedOnly };\n }\n if (!owner) {\n return { status: \"owner_unknown\", ...requestedOnly };\n }\n gateway ??= createGatewayClient(endpoints.escrowGatewayUrl);\n try {\n return await mergeWithLiveGrant({\n gateway,\n owner,\n appAddress: account.address,\n scopes: config.scopes,\n removeScopes: options.removeScopes,\n });\n } catch (error) {\n return {\n status: \"unavailable\",\n reason: error instanceof Error ? error.message : String(error),\n ...requestedOnly,\n };\n }\n }\n\n return {\n appAddress: account.address,\n\n getAppAddress(): string {\n return account.address;\n },\n\n getAppIdentity(): AppIdentity {\n return {\n id: config.app.id,\n name: config.app.name,\n homepageUrl: config.app.homepageUrl,\n address: account.address,\n };\n },\n\n async createAccessRequest(input): Promise<AccessRequest> {\n // Fail fast even with an injected client: a malformed question would be\n // rejected by the access-request service anyway, after a signed round\n // trip.\n if (input.questions !== undefined) {\n validateAccessRequestQuestions(input.questions, config.scopes);\n }\n const removeScopes = input.removeScopes ?? [];\n for (const entry of removeScopes) {\n parseScopeEntry(entry);\n }\n const grantUnion = await resolveGrantUnion(input.owner, {\n merge: input.mergeLiveGrant !== false,\n removeScopes,\n });\n const created = await accessRequestClient.createAccessRequest({\n appAddress: account.address,\n app: config.app,\n source: config.source,\n scopes: grantUnion.scopes,\n ...(removeScopes.length > 0 ? { removeScopes } : {}),\n returnUrl: input.returnUrl,\n network,\n ...(input.foregroundDelivery !== undefined\n ? { foregroundDelivery: input.foregroundDelivery }\n : {}),\n ...(input.questions !== undefined\n ? { questions: input.questions }\n : {}),\n ...(input.idempotencyKey !== undefined\n ? { idempotencyKey: input.idempotencyKey }\n : {}),\n });\n return { ...created, scopes: grantUnion.scopes, grantUnion };\n },\n\n async getAccessRequestStatus(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n return accessRequestClient.getAccessRequestStatus(requestId);\n },\n\n async readApprovedData<T = unknown>(input: {\n requestId: string;\n scope?: string;\n acknowledge?: boolean;\n }): Promise<ApprovedDataResult<T>> {\n const status = await requireReadReady(input.requestId);\n const scope = resolveRequestedScope(status, input.scope);\n\n const result = await readScope<T>(status, scope);\n if (input.acknowledge !== false) {\n await acknowledgeQuietly(input.requestId);\n }\n return result;\n },\n\n requestTestCredit,\n\n async readAllApprovedData<T = unknown>(input: {\n requestId: string;\n }): Promise<MultiScopeDataResult<T>> {\n const status = await requireReadReady(input.requestId);\n const scopes = approvedScopes(status);\n\n const results: Record<string, ApprovedDataResult<T>> = {};\n const errors: Record<string, Error> = {};\n // Sequential, not parallel: each read settles its own escrow payment and\n // the default nonce source is process-local, so concurrent reads would\n // race on the payment nonce.\n for (const scope of scopes) {\n try {\n results[scope] = await readScope<T>(status, scope);\n } catch (error) {\n errors[scope] =\n error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Acknowledge only after the last read, and only if every scope read —\n // acking moves the DCR to `completed`, which is terminal and no longer\n // read-ready, so acking on a partial failure would make the scope that\n // failed impossible to retry.\n if (Object.keys(errors).length === 0) {\n await acknowledgeQuietly(input.requestId);\n }\n\n return { results, errors };\n },\n };\n\n async function requireReadReady(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n const status = await accessRequestClient.getAccessRequestStatus(requestId);\n // `scope` and `scopes` are both optional on the public status type, and a\n // client may return either one — require at least one approved scope rather\n // than the singular field specifically.\n if (\n !isReadReadyStatus(status.status) ||\n !status.personalServerUrl ||\n !status.grantId ||\n approvedScopes(status).length === 0\n ) {\n throw new AccessNotApprovedError(\n \"Request is not approved or is missing grantId/scope/personalServerUrl\",\n {\n requestId,\n status: status.status,\n hasPersonalServerUrl: Boolean(status.personalServerUrl),\n hasGrantId: Boolean(status.grantId),\n hasScope: approvedScopes(status).length > 0,\n },\n );\n }\n return status;\n }\n\n /** Approved scopes in approval order, falling back to the single `scope`. */\n function approvedScopes(status: AccessRequestStatus): string[] {\n if (status.scopes && status.scopes.length > 0) return status.scopes;\n return status.scope ? [status.scope] : [];\n }\n\n /**\n * Resolve which scope to read. Rejects an unapproved scope up front so it\n * never reaches the Personal Server and never settles a fee.\n */\n function resolveRequestedScope(\n status: AccessRequestStatus,\n requested?: string,\n ): string {\n const scopes = approvedScopes(status);\n if (requested === undefined) return scopes[0];\n if (!scopes.includes(requested)) {\n throw new ScopeNotApprovedError(\n `Scope \"${requested}\" is not approved on this request`,\n { requestedScope: requested, approvedScopes: scopes },\n );\n }\n return requested;\n }\n\n async function requestTestCredit(): Promise<TestCreditResult> {\n if (network !== \"moksha\") {\n throw new DirectConfigError(\"Test credit is only available on Moksha\");\n }\n return requestTestCreditFromAccount({\n signMessage,\n baseUrl: config.testCredit?.baseUrl,\n pollIntervalMs: config.testCredit?.pollIntervalMs,\n timeoutMs: config.testCredit?.timeoutMs,\n fetchFn: config.testCredit?.fetchFn,\n });\n }\n\n async function readScope<T>(\n status: AccessRequestStatus,\n scope: string,\n ): Promise<ApprovedDataResult<T>> {\n try {\n return await readScopeOnce<T>(status, scope);\n } catch (error) {\n const autoTopUp =\n network === \"moksha\" && config.testCredit?.autoTopUp === true;\n if (!(autoTopUp && error instanceof EscrowBalanceTooLowError)) {\n throw error;\n }\n const credit = await requestTestCredit();\n if (credit.status === \"refused\") {\n throw error;\n }\n return readScopeOnce<T>(status, scope);\n }\n }\n\n async function readScopeOnce<T>(\n status: AccessRequestStatus,\n scope: string,\n ): Promise<ApprovedDataResult<T>> {\n const result = await readPersonalServerData({\n personalServerUrl: status.personalServerUrl as string,\n scope,\n grantId: status.grantId as string,\n payerAddress: account.address,\n signMessage,\n escrow,\n fetchFn: config.personalServerFetch,\n transportRetry: config.personalServerTransportRetry,\n });\n return { scope, data: result.data as T, payment: result.payment };\n }\n\n async function acknowledgeQuietly(requestId: string): Promise<void> {\n try {\n await accessRequestClient.acknowledgeRead?.(requestId);\n } catch {\n // The read already succeeded; ack only drives Vana Web completion UX.\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBA,sBAAoC;AAGpC,oBAA2B;AAC3B,2BAAgC;AAChC,oBAA0C;AAC1C,qBAAoC;AACpC,yBAIO;AACP,uBAA0B;AAC1B,mCAIO;AACP,uBAIO;AACP,oBAKO;AACP,yBAGO;AAKP,kCAIO;AAuSP,SAAS,gBAAgB,OAA6B;AACpD,SAAO,sBAAsB,KAAK,KAAK;AACzC;AAMA,SAAS,kBAAkB,QAA2C;AACpE,SAAO,WAAW,cAAc,WAAW;AAC7C;AAaO,SAAS,2BACd,QACsB;AAGtB,QAAM,aAAa,OAAO,iBAAiB,OAAO;AAClD,MAAI,CAAC,cAAc,CAAC,gBAAgB,UAAU,GAAG;AAC/C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,MAAI,CAAC,OAAO,UAAU,OAAO,OAAO,WAAW,GAAG;AAChD,UAAM,IAAI,gCAAkB,gCAAgC;AAAA,EAC9D;AAQA,aAAW,SAAS,OAAO,QAAQ;AACjC,sCAAW,sCAAgB,KAAK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B,QAAQ,KAAK;AAAA,IAC7C,SAAS,OAAO;AACd,YAAM,YACJ,YAAY,YAAY,OAAO,YAAY,cAAc;AAC3D,UAAI,EAAE,aAAa,iBAAiB,yCAA2B;AAC7D,cAAM;AAAA,MACR;AACA,YAAM,SAAS,MAAM,kBAAkB;AACvC,UAAI,OAAO,WAAW,WAAW;AAC/B,cAAM;AAAA,MACR;AACA,aAAO,cAAiB,QAAQ,KAAK;AAAA,IACvC;AAAA,EACF;AAEA,iBAAe,cACb,QACA,OACgC;AAChC,UAAM,SAAS,UAAM,oDAAuB;AAAA,MAC1C,mBAAmB,OAAO;AAAA,MAC1B;AAAA,MACA,SAAS,OAAO;AAAA,MAChB,cAAc,QAAQ;AAAA,MACtB;AAAA,MACA;AAAA,MACA,SAAS,OAAO;AAAA,MAChB,gBAAgB,OAAO;AAAA,IACzB,CAAC;AACD,WAAO,EAAE,OAAO,MAAM,OAAO,MAAW,SAAS,OAAO,QAAQ;AAAA,EAClE;AAEA,iBAAe,mBAAmB,WAAkC;AAClE,QAAI;AACF,YAAM,oBAAoB,kBAAkB,SAAS;AAAA,IACvD,QAAQ;AAAA,IAER;AAAA,EACF;AACF;","names":["requestTestCreditFromAccount"]}
|
|
1
|
+
{"version":3,"sources":["../../src/direct/controller.ts"],"sourcesContent":["/**\n * Direct Data Controller — the server-side facade for the two-tab Data\n * Portability flow.\n *\n * @remarks\n * One controller owns an app's private key, source, scopes, app identity, and\n * payment flow. It exposes the three methods the builder guide documents:\n *\n * - {@link DirectDataController.createAccessRequest} — start an approval request.\n * - {@link DirectDataController.getAccessRequestStatus} — poll while the Vana tab is open.\n * - {@link DirectDataController.readApprovedData} — read from the Personal Server,\n * handling 402 Payment Required.\n *\n * Access requests are created through the Vana Account access-request API; the\n * Personal Server read uses Web3Signed auth; and payment uses the DPv2 escrow\n * surface (`protocol/escrow`) — when a read returns `402`, the controller signs\n * a `GenericPayment` with the app key, settles it through the escrow gateway,\n * and retries.\n *\n * @category Direct\n * @module direct/controller\n */\n\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { hexToBytes, type Hex } from \"viem\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\nimport { parseScope } from \"../protocol/scopes\";\nimport { parseScopeEntry } from \"../protocol/scope-actions\";\nimport {\n PDPP_SCOPE_NAMESPACE,\n grantRequestScopes,\n isPdppScopeKey,\n type PdppGrant,\n} from \"../protocol/pdpp-scopes\";\nimport { createEscrowGatewayClient } from \"../protocol/escrow\";\nimport { createGatewayClient } from \"../protocol/gateway\";\nimport {\n mergeWithLiveGrant,\n unionGrantScopes,\n type GrantUnionGateway,\n} from \"./grant-union\";\nimport { CONTRACTS } from \"../generated/addresses\";\nimport {\n createDefaultAccessRequestClient,\n validateAccessRequestQuestions,\n type FetchLike,\n} from \"./access-request-client\";\nimport {\n getDirectDefaultNetwork,\n getDirectEndpoints,\n getDirectNetworkChainId,\n} from \"./endpoints\";\nimport {\n AccessNotApprovedError,\n DirectConfigError,\n EscrowBalanceTooLowError,\n ScopeNotApprovedError,\n} from \"./errors\";\nimport {\n requestTestCredit as requestTestCreditFromAccount,\n type TestCreditResult,\n} from \"./test-credit\";\nimport {\n type EscrowPaymentConfig,\n type SignTypedDataFn,\n} from \"./escrow-payment\";\nimport { signRequestReadAuthorization } from \"./request-authorization\";\nimport type { RequestAuthorization } from \"../connect/protocol\";\nimport {\n readPersonalServerData,\n type PersonalServerFetch,\n type PersonalServerTransportRetryOptions,\n} from \"./personal-server-read\";\nimport type {\n AccessRequest,\n AccessRequestClient,\n AccessRequestGrantUnion,\n AccessRequestQuestion,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n AppIdentity,\n DirectAppConfig,\n DirectEnv,\n DirectNetwork,\n DirectPaymentResponseMetadata,\n DirectServiceEndpoints,\n ForegroundDelivery,\n MultiScopeDataResult,\n} from \"./types\";\n\n/** Configuration for {@link createDirectDataController}. */\nexport interface DirectDataControllerConfig {\n /** Target environment. Defaults to `\"production\"`. */\n env?: DirectEnv;\n /**\n * Target Vana network for chain-aware defaults. Defaults to the selected\n * environment's historical network (`mainnet` for production, `moksha` for\n * dev). Use `network: \"moksha\"` with the default production env for\n * production app/API URLs on testnet.\n */\n network?: DirectNetwork;\n /**\n * The app private key (`0x`-prefixed, 32 bytes). Server-side only — this key\n * is the app's on-chain identity and is never exposed to the browser.\n */\n appPrivateKey?: string;\n /**\n * @deprecated Use {@link DirectDataControllerConfig.appPrivateKey}. Accepted as\n * a backwards-compatible alias; if both are set, `appPrivateKey` wins.\n */\n builderPrivateKey?: string;\n /** App identity advertised during approval. */\n app: DirectAppConfig;\n /** Data source key (e.g. `\"icloud_notes\"`). */\n source: string;\n /**\n * PDPP grants to request: a registry `source_id` and the streams wanted\n * from it, e.g.\n * `[{ source_id: \"https://registry.pdpp.dev/sources/chatgpt\", streams: [\"conversations\", \"messages\"] }]`.\n *\n * Each stream is requested as the read scope `pdpp.<source>.<stream>` (see\n * `pdppScopeKey`), which is what the grant carries and what\n * `readApprovedData({ scope })` reads. Together with\n * {@link DirectDataControllerConfig.scopes} at least one entry is required;\n * when both are set the request is their union. An invalid `source_id` or\n * stream throws `InvalidPdppGrantError` at construction.\n */\n grants?: PdppGrant[];\n /**\n * Legacy grant scope entries to request. Optional when\n * {@link DirectDataControllerConfig.grants} names at least one stream;\n * otherwise at least one is required.\n *\n * Each entry is `[operation:]scope` (see `parseScopeEntry`): a bare entry\n * such as `\"icloud_notes.notes\"` requests read, and `\"write:coach.weekly\"`\n * requests write. The entries are carried through to the access request\n * verbatim and become the grant's `scopes`, so a request can mix both\n * (`[\"oura.sleep\", \"coach.weekly\", \"write:coach.weekly\"]`).\n *\n * The scope part must be a concrete `{source}.{category}[.{subcategory}]`\n * scope: this flow reads approved scopes back one by one, so wildcard\n * patterns (`chatgpt.*`, `write:chatgpt.*`) are not accepted here for\n * either operation.\n */\n scopes?: string[];\n /**\n * Override the resolved service endpoints (partial). Useful for pointing at a\n * non-standard deployment.\n */\n endpoints?: Partial<DirectServiceEndpoints>;\n /**\n * Client for the Vana Account access-request API. Defaults to a client against\n * the resolved Vana Account endpoints; inject your own to point at a custom\n * deployment or to supply a test double.\n */\n accessRequestClient?: AccessRequestClient;\n /**\n * Escrow settlement config used when a Personal Server read returns `402`.\n *\n * @remarks\n * Wires the DPv2 escrow gateway (`protocol/escrow`). The controller supplies\n * the EIP-712 `signTypedData` from the app key automatically.\n *\n * When omitted (or partially omitted), the SDK derives defaults from the\n * per-network endpoints table and the contract registry:\n * - `client` defaults to a gateway client at `endpoints.escrowGatewayUrl`\n * - `escrowContract` defaults to `CONTRACTS.DataPortabilityEscrow.addresses[chainId]`\n * - `chainId` defaults to the controller's resolved chain id\n *\n * Provide this field only to override a specific default.\n */\n escrow?: Partial<DirectEscrowConfig>;\n /**\n * Gateway the controller reads the owner's live grant from when\n * `createAccessRequest` is given an `owner` (see\n * {@link DirectDataController.createAccessRequest}). Only public reads are\n * used: `listGrantsByUser` and `getBuilder`. Defaults to a gateway client at\n * `endpoints.escrowGatewayUrl`.\n */\n gateway?: GrantUnionGateway;\n /** `fetch` used by the default access-request client. Defaults to `globalThis.fetch`. */\n fetchFn?: FetchLike;\n /** `fetch` used for the Personal Server read. Defaults to `globalThis.fetch`. */\n personalServerFetch?: PersonalServerFetch;\n /**\n * Transport-retry knobs for the Personal Server read\n * ({@link PersonalServerTransportRetryOptions}). Defaults to 3 attempts with\n * exponential backoff. Retries fire only when fetch throws (the browser-PS\n * relay reconnect window), never on a received HTTP status, and never\n * re-sign a payment.\n */\n personalServerTransportRetry?: PersonalServerTransportRetryOptions;\n /**\n * Moksha test credit (testnet only).\n *\n * @remarks\n * With `autoTopUp: true` on `network: \"moksha\"`, a read refused because the\n * app's escrow is too low ({@link EscrowBalanceTooLowError}) asks Vana Account\n * for test credit, waits for it, and retries that read once. The refused\n * read charged nothing, so the retry cannot pay twice. Ignored on mainnet.\n */\n testCredit?: {\n autoTopUp?: boolean;\n /** Vana Account origin. Defaults to `https://account.vana.org`. */\n baseUrl?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n /** `fetch` for the Vana Account calls. Defaults to `globalThis.fetch`. */\n fetchFn?: typeof fetch;\n };\n}\n\n/**\n * Controller-level escrow config — the {@link EscrowPaymentConfig} minus the\n * `signTypedData` and `chainId` the controller injects itself.\n */\nexport interface DirectEscrowConfig extends Omit<\n EscrowPaymentConfig,\n \"signTypedData\" | \"chainId\"\n> {\n /**\n * Chain id for the EIP-712 domain. Defaults to the controller's environment\n * (1480 for mainnet, 14800 for moksha).\n */\n chainId?: number;\n}\n\n/**\n * Server-side controller for the direct Data Portability flow.\n *\n * @typeParam T - Shape of the data returned by {@link DirectDataController.readApprovedData}.\n */\nexport interface DirectDataController extends Partial<DirectConnectCapabilities> {\n /** The on-chain address of the app, derived from `appPrivateKey`. */\n readonly appAddress: string;\n\n /**\n * The app's on-chain address — the address to fund and inspect in the Builder\n * activity report. Equivalent to {@link DirectDataController.appAddress}.\n *\n * @returns The app's `0x`-prefixed address.\n */\n getAppAddress(): string;\n\n /**\n * The app's full identity: its configured id/name/homepage plus the derived\n * on-chain address. Useful for telling builders which app address to fund or\n * look up.\n *\n * @returns `{ id, name, homepageUrl, address }`.\n */\n getAppIdentity(): AppIdentity;\n\n /**\n * Create an access request the user can approve.\n *\n * @param input - The post-approval return URL and optional create retry key.\n * @returns The request id, HTTPS approval URL, and — for a pending deep Direct\n * request on mobile — an optional HTTPS `mobileContinuationUrl`.\n */\n createAccessRequest(input: {\n returnUrl: string;\n /** Optional foreground mobile delivery callback. */\n foregroundDelivery?: ForegroundDelivery;\n /**\n * Derivative questions to carry on the request (1 to 4). Each question\n * asks the user's Personal Server to compute its `derivedScope` from\n * `sourceScopes` the app never reads; the derived scope must also appear\n * in the controller's `scopes` as a bare read entry. Validated eagerly\n * against the configured scopes before the request is sent. See\n * {@link AccessRequestQuestion}.\n */\n questions?: AccessRequestQuestion[];\n /**\n * The data owner, when the app already knows who will approve (for\n * example from an earlier approval). With an owner, the controller reads\n * the owner's live grant for this app and includes its still-granted\n * scopes, so the new request extends the grant instead of replacing it.\n *\n * Without an owner nothing is read: the person is often anonymous until\n * they approve, and the Vana Web approval page signs the union of the\n * live grant and the request for whoever approves.\n */\n owner?: string;\n /**\n * Merge the owner's live grant into the request scopes. Defaults to\n * `true`; has no effect without `owner`. Pass `false` to send the\n * configured scopes verbatim.\n */\n mergeLiveGrant?: boolean;\n /**\n * Scope entries the app gives up from the owner's live grant. Removed\n * from the merged scopes here and sent on the request so the approval\n * page leaves them out of its own union. Matched verbatim\n * (`write:coach.weekly` and `coach.weekly` are separate entries).\n */\n removeScopes?: string[];\n /**\n * Stable retry key when the caller retries after an uncertain response.\n * Each create without one gets its own generated key.\n */\n idempotencyKey?: string;\n }): Promise<AccessRequest>;\n\n /**\n * Fetch the current status of an access request.\n *\n * @param requestId - The `dcr_*` id from `createAccessRequest`.\n * @returns `{ status, personalServerUrl?, grantId?, scope?, scopes? }`.\n */\n getAccessRequestStatus(requestId: string): Promise<AccessRequestStatus>;\n\n /**\n * Read the approved data from the user's Personal Server.\n *\n * @remarks\n * Resolves the request to its grant + Personal Server and performs a Web3Signed\n * read. Hides the `402 Payment Required` flow by default: if a read needs\n * payment, it signs the Personal Server's payment challenge, retries with\n * `X-PAYMENT`, and attaches shape-validated but unauthenticated\n * {@link DirectPaymentResponseMetadata} under `payment` when the Personal\n * Server returns it. After a successful read, the controller acknowledges\n * the DCR so Vana Web can close/redirect the approval tab.\n *\n * A request can approve several scopes. This reads **one** of them — `scope`\n * when given, otherwise the first approved scope. Use\n * {@link DirectDataController.readAllApprovedData} to read them all.\n *\n * Acknowledging moves the DCR to `completed`, which is terminal and no longer\n * read-ready. To read several scopes with your own loop, pass\n * `acknowledge: false` on every call but the last.\n *\n * @param input - The `dcr_*` request id, the optional `scope` to read, and an\n * optional `acknowledge` flag (default `true`).\n * @returns `{ scope, data, payment? }`.\n * @throws {@link AccessNotApprovedError} if the request is not approved.\n * @throws {@link ScopeNotApprovedError} if `scope` is not an approved scope.\n * @throws {@link PaymentRequiredError} if payment is required but unsettled.\n */\n readApprovedData<T = unknown>(input: {\n requestId: string;\n scope?: string;\n acknowledge?: boolean;\n }): Promise<ApprovedDataResult<T>>;\n\n /**\n * Read every scope the user approved on a request.\n *\n * @remarks\n * Reads the scopes in approval order, then acknowledges the DCR **once**,\n * after the last read — acknowledging earlier would move the request to\n * `completed` and make the remaining scopes unreadable.\n *\n * Each scope is a separate Personal Server read that settles its own\n * `data_access` fee from escrow, so reading N scopes costs N times a\n * single-scope read. The one-off registration fee is charged per grant, not\n * per scope.\n *\n * A scope that fails does not abort the rest: successes land in `results` and\n * failures in `errors`, because the fees for earlier scopes are already spent.\n * If any scope fails the request is left unacknowledged, so the scopes that\n * failed stay retryable — read them with `readApprovedData({ scope })` and\n * acknowledge on the last one.\n *\n * @param input - The `dcr_*` request id to read.\n * @returns `{ results, errors }`, both keyed by scope.\n * @throws {@link AccessNotApprovedError} if the request is not approved.\n */\n readAllApprovedData<T = unknown>(input: {\n requestId: string;\n }): Promise<MultiScopeDataResult<T>>;\n /**\n * Ask Vana Account for Moksha test credit for this app's escrow and wait\n * until it is usable. Moksha only.\n *\n * @throws {@link DirectConfigError} on mainnet.\n * @throws TestCreditError if the request fails or does not finalize in time.\n */\n requestTestCredit(): Promise<TestCreditResult>;\n\n // Connect-sheet methods (authorizeRequestRead, getEndpoints, deriveSecret,\n // getEnv) come from DirectConnectCapabilities and are optional here, so a\n // hand-written controller keeps compiling. See isConnectCapableController.\n}\n\n/**\n * What the embedded connect sheet needs from a controller, on top of\n * {@link DirectDataController}.\n *\n * @remarks\n * `createDirectDataController` implements all of it. On the base interface\n * these methods are optional, so an existing hand-written\n * `DirectDataController` keeps compiling in this minor version;\n * `createVanaConnectHandler` checks for them with\n * {@link isConnectCapableController} and names any that are missing.\n */\nexport interface DirectConnectCapabilities {\n /**\n * Sign the short-lived read capability the embedded connect sheet needs to\n * show a request (`presentation: \"sheet\"`).\n *\n * @remarks\n * The same Direct SDK signature this controller sends when it polls the\n * request's status. It does not check whose request this is: call it only\n * for a request this browser created (`createVanaConnectHandler` binds them\n * with a signed cookie). Sign on each ask; Vana Account accepts it for\n * about five minutes.\n *\n * @param requestId - The `dcr_*` id from `createAccessRequest`.\n * @returns `{ appAddress, timestamp, signature }`.\n * @throws {@link DirectConfigError} when `requestId` is not a request id.\n */\n authorizeRequestRead(requestId: string): Promise<RequestAuthorization>;\n\n /**\n * The resolved service endpoints, including the Vana Account origin that\n * serves the connect sheet.\n *\n * @returns The endpoints this controller talks to.\n */\n getEndpoints(): DirectServiceEndpoints;\n\n /**\n * Derive a purpose-bound secret from the app key, without revealing it.\n *\n * @remarks\n * HKDF-SHA256 over the 32 key bytes, salt `\"vana-sdk/derived-secret/v1\"`,\n * `info` = `purpose`. Different purposes give independent secrets, so a\n * leaked derived secret never exposes the key or another purpose's secret.\n * `createVanaConnectHandler` keys its request-binding cookie with\n * `deriveSecret(\"vana-sdk/connect/request-binding/v1\")`.\n *\n * @param purpose - A label naming what the secret is for.\n * @returns 32 secret bytes.\n */\n deriveSecret(purpose: string): Promise<ArrayBuffer>;\n\n /**\n * The resolved deployment environment.\n *\n * @returns `\"production\"` or `\"dev\"`.\n */\n getEnv(): DirectEnv;\n}\n\n/** A controller that can back the embedded connect sheet. */\nexport type ConnectCapableDirectDataController = DirectDataController &\n DirectConnectCapabilities;\n\n/** The {@link DirectConnectCapabilities} method names, for checks and errors. */\nexport const DIRECT_CONNECT_CAPABILITIES = [\n \"authorizeRequestRead\",\n \"getEndpoints\",\n \"deriveSecret\",\n \"getEnv\",\n] as const satisfies readonly (keyof DirectConnectCapabilities)[];\n\n/**\n * The {@link DirectConnectCapabilities} methods a controller lacks.\n *\n * @param controller - Any {@link DirectDataController}.\n * @returns Missing method names; empty when it can back the sheet.\n */\nexport function missingConnectCapabilities(\n controller: DirectDataController,\n): (keyof DirectConnectCapabilities)[] {\n return DIRECT_CONNECT_CAPABILITIES.filter(\n (name) => typeof controller[name] !== \"function\",\n );\n}\n\n/**\n * Whether a controller implements every {@link DirectConnectCapabilities}\n * method (any controller from `createDirectDataController` does).\n *\n * @param controller - Any {@link DirectDataController}.\n * @returns `true` when it can back `createVanaConnectHandler`.\n */\nexport function isConnectCapableController(\n controller: DirectDataController,\n): controller is ConnectCapableDirectDataController {\n return missingConnectCapabilities(controller).length === 0;\n}\n\nfunction isHexPrivateKey(value: string): value is Hex {\n return /^0x[0-9a-fA-F]{64}$/.test(value);\n}\n\n// A DCR is read-ready only while the grant exists and the Personal Server is\n// still serving it: `approved` (durable PS) or `ready_for_read` (browser PS).\n// `completed` is terminal — the app already read and acknowledged, and the\n// browser PS may be gone — so it is deliberately excluded here.\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\n/**\n * Create a {@link DirectDataController}.\n *\n * @param config - Controller configuration (env, key, app identity, source, scopes).\n * @returns A ready-to-use controller.\n * @throws {@link DirectConfigError} when the key is missing or malformed, when\n * `scopes` and `grants` together request nothing, or when no escrow contract\n * can be resolved.\n * @throws InvalidPdppGrantError when a `grants` entry does not fit the PDPP\n * grant grammar.\n * @throws InvalidScopeEntryError when a `scopes` entry does not fit the\n * `[operation:]scope` grammar (an unknown operation prefix such as `delete:`).\n * @throws ZodError when the scope part of an entry is not a valid scope.\n */\nexport function createDirectDataController(\n config: DirectDataControllerConfig,\n): ConnectCapableDirectDataController {\n // `appPrivateKey` is the documented field; `builderPrivateKey` is a\n // deprecated alias kept for backwards compatibility.\n const privateKey = config.appPrivateKey ?? config.builderPrivateKey;\n if (!privateKey || !isHexPrivateKey(privateKey)) {\n throw new DirectConfigError(\n \"appPrivateKey must be a 0x-prefixed 32-byte hex string\",\n );\n }\n // The scopes every request starts from: legacy entries verbatim, then the\n // keys derived from PDPP grants.\n const scopes = grantRequestScopes({\n grants: config.grants,\n scopes: config.scopes,\n });\n if (scopes.length === 0) {\n throw new DirectConfigError(\n \"At least one scope or PDPP grant stream is required\",\n );\n }\n // Validate scopes eagerly so misconfiguration fails at construction. Each\n // element is a grant scope entry (`[operation:]scope`), so the operation\n // prefix is stripped first and only the scope part is checked against the\n // scope grammar — `write:coach.weekly` is a valid write-grant request, and\n // an unknown operation (`delete:x`) throws rather than being taken as read.\n // The entries themselves are passed through to the access request verbatim,\n // prefix included.\n for (const entry of scopes) {\n const scope = parseScopeEntry(entry).scope;\n parseScope(scope);\n // `pdpp.` is reserved for keys derived from PDPP grants; a hand-written\n // `pdpp.chatgpt` would read as one without being one.\n if (\n scope.startsWith(`${PDPP_SCOPE_NAMESPACE}.`) &&\n !isPdppScopeKey(scope)\n ) {\n throw new DirectConfigError(\n `\"${entry}\" is in the reserved \"${PDPP_SCOPE_NAMESPACE}.\" namespace but is not a PDPP scope key. Request PDPP data with grants: [{ source_id, streams }].`,\n { entry },\n );\n }\n }\n\n const env: DirectEnv = config.env ?? \"production\";\n const network: DirectNetwork = config.network ?? getDirectDefaultNetwork(env);\n const defaultEndpoints = getDirectEndpoints(env);\n const chainId = config.endpoints?.chainId ?? getDirectNetworkChainId(network);\n const endpoints: DirectServiceEndpoints = {\n ...defaultEndpoints,\n ...config.endpoints,\n chainId,\n accountOrigin:\n config.endpoints?.accountOrigin ?? defaultEndpoints.accountOrigin,\n };\n\n const account = privateKeyToAccount(privateKey as Hex);\n const signMessage: Web3SignedSignFn = (message: string) =>\n account.signMessage({ message });\n // viem's account.signTypedData satisfies the structural SignTypedDataFn used\n // by the escrow GenericPayment signer.\n const signTypedData = account.signTypedData as unknown as SignTypedDataFn;\n const accessRequestClient: AccessRequestClient =\n config.accessRequestClient ??\n createDefaultAccessRequestClient({\n baseUrl: endpoints.accessRequestBaseUrl,\n approvalBaseUrl: endpoints.approvalAppBaseUrl,\n env,\n fetchFn: config.fetchFn,\n appAddress: account.address,\n signMessage,\n });\n\n // Build the escrow payment config, defaulting from the per-network endpoints\n // table and the contract registry when `config.escrow` is omitted or partial.\n const escrowChainId = config.escrow?.chainId ?? chainId;\n const defaultEscrowContract =\n CONTRACTS.DataPortabilityEscrow.addresses[\n escrowChainId as keyof typeof CONTRACTS.DataPortabilityEscrow.addresses\n ] ?? undefined;\n if (!config.escrow?.escrowContract && !defaultEscrowContract) {\n throw new DirectConfigError(\n `No DataPortabilityEscrow address found in the registry for chainId ${escrowChainId}. ` +\n `Provide an explicit escrow.escrowContract in the controller config.`,\n );\n }\n const escrow: EscrowPaymentConfig = {\n client:\n config.escrow?.client ??\n createEscrowGatewayClient(endpoints.escrowGatewayUrl),\n escrowContract:\n config.escrow?.escrowContract ?? (defaultEscrowContract as `0x${string}`),\n chainId: escrowChainId,\n nonceSource: config.escrow?.nonceSource,\n signTypedData,\n };\n\n let gateway: GrantUnionGateway | undefined = config.gateway;\n\n // Read the owner's live grant and union it with the configured scopes. A\n // failed read never blocks the request: it goes out with the configured\n // scopes, and the approval page's own union still keeps the live grant.\n async function resolveGrantUnion(\n owner: string | undefined,\n options: { merge: boolean; removeScopes: string[] },\n ): Promise<AccessRequestGrantUnion> {\n // Without a merged live grant the request carries the configured scopes\n // verbatim (duplicates and order included), so bodies and their\n // signatures match SDKs that predate the grant union.\n const requestedOnly = {\n ...unionGrantScopes([], scopes, options.removeScopes),\n scopes: [...scopes],\n };\n if (!options.merge) {\n return { status: \"disabled\", ...requestedOnly };\n }\n if (!owner) {\n return { status: \"owner_unknown\", ...requestedOnly };\n }\n gateway ??= createGatewayClient(endpoints.escrowGatewayUrl);\n try {\n return await mergeWithLiveGrant({\n gateway,\n owner,\n appAddress: account.address,\n scopes,\n removeScopes: options.removeScopes,\n });\n } catch (error) {\n return {\n status: \"unavailable\",\n reason: error instanceof Error ? error.message : String(error),\n ...requestedOnly,\n };\n }\n }\n\n return {\n appAddress: account.address,\n\n getAppAddress(): string {\n return account.address;\n },\n\n getAppIdentity(): AppIdentity {\n return {\n id: config.app.id,\n name: config.app.name,\n homepageUrl: config.app.homepageUrl,\n address: account.address,\n };\n },\n\n async createAccessRequest(input): Promise<AccessRequest> {\n // Fail fast even with an injected client: a malformed question would be\n // rejected by the access-request service anyway, after a signed round\n // trip.\n if (input.questions !== undefined) {\n validateAccessRequestQuestions(input.questions, scopes);\n }\n const removeScopes = input.removeScopes ?? [];\n for (const entry of removeScopes) {\n parseScopeEntry(entry);\n }\n const grantUnion = await resolveGrantUnion(input.owner, {\n merge: input.mergeLiveGrant !== false,\n removeScopes,\n });\n const created = await accessRequestClient.createAccessRequest({\n appAddress: account.address,\n app: config.app,\n source: config.source,\n scopes: grantUnion.scopes,\n ...(removeScopes.length > 0 ? { removeScopes } : {}),\n returnUrl: input.returnUrl,\n network,\n ...(input.foregroundDelivery !== undefined\n ? { foregroundDelivery: input.foregroundDelivery }\n : {}),\n ...(input.questions !== undefined\n ? { questions: input.questions }\n : {}),\n ...(input.idempotencyKey !== undefined\n ? { idempotencyKey: input.idempotencyKey }\n : {}),\n });\n return { ...created, scopes: grantUnion.scopes, grantUnion };\n },\n\n async getAccessRequestStatus(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n return accessRequestClient.getAccessRequestStatus(requestId);\n },\n\n async readApprovedData<T = unknown>(input: {\n requestId: string;\n scope?: string;\n acknowledge?: boolean;\n }): Promise<ApprovedDataResult<T>> {\n const status = await requireReadReady(input.requestId);\n const scope = resolveRequestedScope(status, input.scope);\n\n const result = await readScope<T>(status, scope);\n if (input.acknowledge !== false) {\n await acknowledgeQuietly(input.requestId);\n }\n return result;\n },\n\n requestTestCredit,\n\n async readAllApprovedData<T = unknown>(input: {\n requestId: string;\n }): Promise<MultiScopeDataResult<T>> {\n const status = await requireReadReady(input.requestId);\n const scopes = approvedScopes(status);\n\n const results: Record<string, ApprovedDataResult<T>> = {};\n const errors: Record<string, Error> = {};\n // Sequential, not parallel: each read settles its own escrow payment and\n // the default nonce source is process-local, so concurrent reads would\n // race on the payment nonce.\n for (const scope of scopes) {\n try {\n results[scope] = await readScope<T>(status, scope);\n } catch (error) {\n errors[scope] =\n error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Acknowledge only after the last read, and only if every scope read —\n // acking moves the DCR to `completed`, which is terminal and no longer\n // read-ready, so acking on a partial failure would make the scope that\n // failed impossible to retry.\n if (Object.keys(errors).length === 0) {\n await acknowledgeQuietly(input.requestId);\n }\n\n return { results, errors };\n },\n\n authorizeRequestRead(requestId: string): Promise<RequestAuthorization> {\n return signRequestReadAuthorization({\n requestId,\n appAddress: account.address,\n signMessage,\n });\n },\n\n getEndpoints(): DirectServiceEndpoints {\n return { ...endpoints };\n },\n\n getEnv(): DirectEnv {\n return env;\n },\n\n async deriveSecret(purpose: string): Promise<ArrayBuffer> {\n const ikm = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new Uint8Array(hexToBytes(privateKey as Hex)),\n \"HKDF\",\n false,\n [\"deriveBits\"],\n );\n return globalThis.crypto.subtle.deriveBits(\n {\n name: \"HKDF\",\n hash: \"SHA-256\",\n salt: new TextEncoder().encode(\"vana-sdk/derived-secret/v1\"),\n info: new TextEncoder().encode(purpose),\n },\n ikm,\n 256,\n );\n },\n };\n\n async function requireReadReady(\n requestId: string,\n ): Promise<AccessRequestStatus> {\n const status = await accessRequestClient.getAccessRequestStatus(requestId);\n // `scope` and `scopes` are both optional on the public status type, and a\n // client may return either one — require at least one approved scope rather\n // than the singular field specifically.\n if (\n !isReadReadyStatus(status.status) ||\n !status.personalServerUrl ||\n !status.grantId ||\n approvedScopes(status).length === 0\n ) {\n throw new AccessNotApprovedError(\n \"Request is not approved or is missing grantId/scope/personalServerUrl\",\n {\n requestId,\n status: status.status,\n hasPersonalServerUrl: Boolean(status.personalServerUrl),\n hasGrantId: Boolean(status.grantId),\n hasScope: approvedScopes(status).length > 0,\n },\n );\n }\n return status;\n }\n\n /** Approved scopes in approval order, falling back to the single `scope`. */\n function approvedScopes(status: AccessRequestStatus): string[] {\n if (status.scopes && status.scopes.length > 0) return status.scopes;\n return status.scope ? [status.scope] : [];\n }\n\n /**\n * Resolve which scope to read. Rejects an unapproved scope up front so it\n * never reaches the Personal Server and never settles a fee.\n */\n function resolveRequestedScope(\n status: AccessRequestStatus,\n requested?: string,\n ): string {\n const scopes = approvedScopes(status);\n if (requested === undefined) return scopes[0];\n if (!scopes.includes(requested)) {\n throw new ScopeNotApprovedError(\n `Scope \"${requested}\" is not approved on this request`,\n { requestedScope: requested, approvedScopes: scopes },\n );\n }\n return requested;\n }\n\n async function requestTestCredit(): Promise<TestCreditResult> {\n if (network !== \"moksha\") {\n throw new DirectConfigError(\"Test credit is only available on Moksha\");\n }\n return requestTestCreditFromAccount({\n signMessage,\n baseUrl: config.testCredit?.baseUrl,\n pollIntervalMs: config.testCredit?.pollIntervalMs,\n timeoutMs: config.testCredit?.timeoutMs,\n fetchFn: config.testCredit?.fetchFn,\n });\n }\n\n async function readScope<T>(\n status: AccessRequestStatus,\n scope: string,\n ): Promise<ApprovedDataResult<T>> {\n try {\n return await readScopeOnce<T>(status, scope);\n } catch (error) {\n const autoTopUp =\n network === \"moksha\" && config.testCredit?.autoTopUp === true;\n if (!(autoTopUp && error instanceof EscrowBalanceTooLowError)) {\n throw error;\n }\n const credit = await requestTestCredit();\n if (credit.status === \"refused\") {\n throw error;\n }\n return readScopeOnce<T>(status, scope);\n }\n }\n\n async function readScopeOnce<T>(\n status: AccessRequestStatus,\n scope: string,\n ): Promise<ApprovedDataResult<T>> {\n const result = await readPersonalServerData({\n personalServerUrl: status.personalServerUrl as string,\n scope,\n grantId: status.grantId as string,\n payerAddress: account.address,\n signMessage,\n escrow,\n fetchFn: config.personalServerFetch,\n transportRetry: config.personalServerTransportRetry,\n });\n return { scope, data: result.data as T, payment: result.payment };\n }\n\n async function acknowledgeQuietly(requestId: string): Promise<void> {\n try {\n await accessRequestClient.acknowledgeRead?.(requestId);\n } catch {\n // The read already succeeded; ack only drives Vana Web completion UX.\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBA,sBAAoC;AACpC,k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AACF,YAAM,oBAAoB,kBAAkB,SAAS;AAAA,IACvD,QAAQ;AAAA,IAER;AAAA,EACF;AACF;","names":["scopes","requestTestCreditFromAccount"]}
|
|
@@ -20,10 +20,12 @@
|
|
|
20
20
|
* @category Direct
|
|
21
21
|
* @module direct/controller
|
|
22
22
|
*/
|
|
23
|
+
import { type PdppGrant } from "../protocol/pdpp-scopes.js";
|
|
23
24
|
import { type GrantUnionGateway } from "./grant-union.js";
|
|
24
25
|
import { type FetchLike } from "./access-request-client.js";
|
|
25
26
|
import { type TestCreditResult } from "./test-credit.js";
|
|
26
27
|
import { type EscrowPaymentConfig } from "./escrow-payment.js";
|
|
28
|
+
import type { RequestAuthorization } from "../connect/protocol.js";
|
|
27
29
|
import { type PersonalServerFetch, type PersonalServerTransportRetryOptions } from "./personal-server-read.js";
|
|
28
30
|
import type { AccessRequest, AccessRequestClient, AccessRequestQuestion, AccessRequestStatus, ApprovedDataResult, AppIdentity, DirectAppConfig, DirectEnv, DirectNetwork, DirectServiceEndpoints, ForegroundDelivery, MultiScopeDataResult } from "./types.js";
|
|
29
31
|
/** Configuration for {@link createDirectDataController}. */
|
|
@@ -52,7 +54,22 @@ export interface DirectDataControllerConfig {
|
|
|
52
54
|
/** Data source key (e.g. `"icloud_notes"`). */
|
|
53
55
|
source: string;
|
|
54
56
|
/**
|
|
55
|
-
*
|
|
57
|
+
* PDPP grants to request: a registry `source_id` and the streams wanted
|
|
58
|
+
* from it, e.g.
|
|
59
|
+
* `[{ source_id: "https://registry.pdpp.dev/sources/chatgpt", streams: ["conversations", "messages"] }]`.
|
|
60
|
+
*
|
|
61
|
+
* Each stream is requested as the read scope `pdpp.<source>.<stream>` (see
|
|
62
|
+
* `pdppScopeKey`), which is what the grant carries and what
|
|
63
|
+
* `readApprovedData({ scope })` reads. Together with
|
|
64
|
+
* {@link DirectDataControllerConfig.scopes} at least one entry is required;
|
|
65
|
+
* when both are set the request is their union. An invalid `source_id` or
|
|
66
|
+
* stream throws `InvalidPdppGrantError` at construction.
|
|
67
|
+
*/
|
|
68
|
+
grants?: PdppGrant[];
|
|
69
|
+
/**
|
|
70
|
+
* Legacy grant scope entries to request. Optional when
|
|
71
|
+
* {@link DirectDataControllerConfig.grants} names at least one stream;
|
|
72
|
+
* otherwise at least one is required.
|
|
56
73
|
*
|
|
57
74
|
* Each entry is `[operation:]scope` (see `parseScopeEntry`): a bare entry
|
|
58
75
|
* such as `"icloud_notes.notes"` requests read, and `"write:coach.weekly"`
|
|
@@ -65,7 +82,7 @@ export interface DirectDataControllerConfig {
|
|
|
65
82
|
* patterns (`chatgpt.*`, `write:chatgpt.*`) are not accepted here for
|
|
66
83
|
* either operation.
|
|
67
84
|
*/
|
|
68
|
-
scopes
|
|
85
|
+
scopes?: string[];
|
|
69
86
|
/**
|
|
70
87
|
* Override the resolved service endpoints (partial). Useful for pointing at a
|
|
71
88
|
* non-standard deployment.
|
|
@@ -148,7 +165,7 @@ export interface DirectEscrowConfig extends Omit<EscrowPaymentConfig, "signTyped
|
|
|
148
165
|
*
|
|
149
166
|
* @typeParam T - Shape of the data returned by {@link DirectDataController.readApprovedData}.
|
|
150
167
|
*/
|
|
151
|
-
export interface DirectDataController {
|
|
168
|
+
export interface DirectDataController extends Partial<DirectConnectCapabilities> {
|
|
152
169
|
/** The on-chain address of the app, derived from `appPrivateKey`. */
|
|
153
170
|
readonly appAddress: string;
|
|
154
171
|
/**
|
|
@@ -219,7 +236,7 @@ export interface DirectDataController {
|
|
|
219
236
|
/**
|
|
220
237
|
* Fetch the current status of an access request.
|
|
221
238
|
*
|
|
222
|
-
* @param requestId - The `dcr_*` id from
|
|
239
|
+
* @param requestId - The `dcr_*` id from `createAccessRequest`.
|
|
223
240
|
* @returns `{ status, personalServerUrl?, grantId?, scope?, scopes? }`.
|
|
224
241
|
*/
|
|
225
242
|
getAccessRequestStatus(requestId: string): Promise<AccessRequestStatus>;
|
|
@@ -290,15 +307,93 @@ export interface DirectDataController {
|
|
|
290
307
|
*/
|
|
291
308
|
requestTestCredit(): Promise<TestCreditResult>;
|
|
292
309
|
}
|
|
310
|
+
/**
|
|
311
|
+
* What the embedded connect sheet needs from a controller, on top of
|
|
312
|
+
* {@link DirectDataController}.
|
|
313
|
+
*
|
|
314
|
+
* @remarks
|
|
315
|
+
* `createDirectDataController` implements all of it. On the base interface
|
|
316
|
+
* these methods are optional, so an existing hand-written
|
|
317
|
+
* `DirectDataController` keeps compiling in this minor version;
|
|
318
|
+
* `createVanaConnectHandler` checks for them with
|
|
319
|
+
* {@link isConnectCapableController} and names any that are missing.
|
|
320
|
+
*/
|
|
321
|
+
export interface DirectConnectCapabilities {
|
|
322
|
+
/**
|
|
323
|
+
* Sign the short-lived read capability the embedded connect sheet needs to
|
|
324
|
+
* show a request (`presentation: "sheet"`).
|
|
325
|
+
*
|
|
326
|
+
* @remarks
|
|
327
|
+
* The same Direct SDK signature this controller sends when it polls the
|
|
328
|
+
* request's status. It does not check whose request this is: call it only
|
|
329
|
+
* for a request this browser created (`createVanaConnectHandler` binds them
|
|
330
|
+
* with a signed cookie). Sign on each ask; Vana Account accepts it for
|
|
331
|
+
* about five minutes.
|
|
332
|
+
*
|
|
333
|
+
* @param requestId - The `dcr_*` id from `createAccessRequest`.
|
|
334
|
+
* @returns `{ appAddress, timestamp, signature }`.
|
|
335
|
+
* @throws {@link DirectConfigError} when `requestId` is not a request id.
|
|
336
|
+
*/
|
|
337
|
+
authorizeRequestRead(requestId: string): Promise<RequestAuthorization>;
|
|
338
|
+
/**
|
|
339
|
+
* The resolved service endpoints, including the Vana Account origin that
|
|
340
|
+
* serves the connect sheet.
|
|
341
|
+
*
|
|
342
|
+
* @returns The endpoints this controller talks to.
|
|
343
|
+
*/
|
|
344
|
+
getEndpoints(): DirectServiceEndpoints;
|
|
345
|
+
/**
|
|
346
|
+
* Derive a purpose-bound secret from the app key, without revealing it.
|
|
347
|
+
*
|
|
348
|
+
* @remarks
|
|
349
|
+
* HKDF-SHA256 over the 32 key bytes, salt `"vana-sdk/derived-secret/v1"`,
|
|
350
|
+
* `info` = `purpose`. Different purposes give independent secrets, so a
|
|
351
|
+
* leaked derived secret never exposes the key or another purpose's secret.
|
|
352
|
+
* `createVanaConnectHandler` keys its request-binding cookie with
|
|
353
|
+
* `deriveSecret("vana-sdk/connect/request-binding/v1")`.
|
|
354
|
+
*
|
|
355
|
+
* @param purpose - A label naming what the secret is for.
|
|
356
|
+
* @returns 32 secret bytes.
|
|
357
|
+
*/
|
|
358
|
+
deriveSecret(purpose: string): Promise<ArrayBuffer>;
|
|
359
|
+
/**
|
|
360
|
+
* The resolved deployment environment.
|
|
361
|
+
*
|
|
362
|
+
* @returns `"production"` or `"dev"`.
|
|
363
|
+
*/
|
|
364
|
+
getEnv(): DirectEnv;
|
|
365
|
+
}
|
|
366
|
+
/** A controller that can back the embedded connect sheet. */
|
|
367
|
+
export type ConnectCapableDirectDataController = DirectDataController & DirectConnectCapabilities;
|
|
368
|
+
/** The {@link DirectConnectCapabilities} method names, for checks and errors. */
|
|
369
|
+
export declare const DIRECT_CONNECT_CAPABILITIES: readonly ["authorizeRequestRead", "getEndpoints", "deriveSecret", "getEnv"];
|
|
370
|
+
/**
|
|
371
|
+
* The {@link DirectConnectCapabilities} methods a controller lacks.
|
|
372
|
+
*
|
|
373
|
+
* @param controller - Any {@link DirectDataController}.
|
|
374
|
+
* @returns Missing method names; empty when it can back the sheet.
|
|
375
|
+
*/
|
|
376
|
+
export declare function missingConnectCapabilities(controller: DirectDataController): (keyof DirectConnectCapabilities)[];
|
|
377
|
+
/**
|
|
378
|
+
* Whether a controller implements every {@link DirectConnectCapabilities}
|
|
379
|
+
* method (any controller from `createDirectDataController` does).
|
|
380
|
+
*
|
|
381
|
+
* @param controller - Any {@link DirectDataController}.
|
|
382
|
+
* @returns `true` when it can back `createVanaConnectHandler`.
|
|
383
|
+
*/
|
|
384
|
+
export declare function isConnectCapableController(controller: DirectDataController): controller is ConnectCapableDirectDataController;
|
|
293
385
|
/**
|
|
294
386
|
* Create a {@link DirectDataController}.
|
|
295
387
|
*
|
|
296
388
|
* @param config - Controller configuration (env, key, app identity, source, scopes).
|
|
297
389
|
* @returns A ready-to-use controller.
|
|
298
390
|
* @throws {@link DirectConfigError} when the key is missing or malformed, when
|
|
299
|
-
* `scopes`
|
|
391
|
+
* `scopes` and `grants` together request nothing, or when no escrow contract
|
|
392
|
+
* can be resolved.
|
|
393
|
+
* @throws InvalidPdppGrantError when a `grants` entry does not fit the PDPP
|
|
394
|
+
* grant grammar.
|
|
300
395
|
* @throws InvalidScopeEntryError when a `scopes` entry does not fit the
|
|
301
396
|
* `[operation:]scope` grammar (an unknown operation prefix such as `delete:`).
|
|
302
397
|
* @throws ZodError when the scope part of an entry is not a valid scope.
|
|
303
398
|
*/
|
|
304
|
-
export declare function createDirectDataController(config: DirectDataControllerConfig):
|
|
399
|
+
export declare function createDirectDataController(config: DirectDataControllerConfig): ConnectCapableDirectDataController;
|