@opendatalabs/vana-sdk 3.20.1 → 3.22.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 +64 -0
- package/dist/direct/access-request-client.cjs +100 -2
- package/dist/direct/access-request-client.cjs.map +1 -1
- package/dist/direct/access-request-client.d.ts +23 -1
- package/dist/direct/access-request-client.js +98 -1
- package/dist/direct/access-request-client.js.map +1 -1
- package/dist/direct/controller.cjs +4 -0
- package/dist/direct/controller.cjs.map +1 -1
- package/dist/direct/controller.d.ts +10 -1
- package/dist/direct/controller.js +6 -1
- package/dist/direct/controller.js.map +1 -1
- package/dist/direct/types.cjs.map +1 -1
- package/dist/direct/types.d.ts +45 -0
- package/dist/direct/types.js.map +1 -1
- package/dist/index.browser.d.ts +2 -1
- package/dist/index.browser.js +186 -0
- package/dist/index.browser.js.map +4 -4
- package/dist/index.node.cjs +196 -0
- package/dist/index.node.cjs.map +4 -4
- package/dist/index.node.d.ts +2 -1
- package/dist/index.node.js +186 -0
- package/dist/index.node.js.map +4 -4
- package/dist/protocol/derivative-questions.cjs +22 -0
- package/dist/protocol/derivative-questions.cjs.map +1 -1
- package/dist/protocol/derivative-questions.d.ts +53 -0
- package/dist/protocol/derivative-questions.js +19 -0
- package/dist/protocol/derivative-questions.js.map +1 -1
- package/dist/protocol/derivative-status.cjs +209 -0
- package/dist/protocol/derivative-status.cjs.map +1 -0
- package/dist/protocol/derivative-status.d.ts +196 -0
- package/dist/protocol/derivative-status.js +190 -0
- package/dist/protocol/derivative-status.js.map +1 -0
- package/dist/protocol/derivative-status.test.d.ts +1 -0
- package/dist/server.cjs +4 -2
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.js +4 -2
- package/dist/server.js.map +1 -1
- package/dist/tests/mock-personal-server.d.ts +9 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -621,6 +621,70 @@ These helpers require `personal-server-ts` main `d91124d` or later, which is
|
|
|
621
621
|
where the query-in-the-signed-uri rule, the `nonce` claim, the 404 for an
|
|
622
622
|
unknown id and the full-view `recompute` answer landed.
|
|
623
623
|
|
|
624
|
+
### Watching a derived scope as the reader
|
|
625
|
+
|
|
626
|
+
The helpers above are the builder's: every one of them needs a write session,
|
|
627
|
+
which an app holding only a bare read entry on the derived scope cannot open.
|
|
628
|
+
That reader sees `GET /v1/data/<derivedScope>` answer 404 whether the compute
|
|
629
|
+
is running, retrying, or finished failing.
|
|
630
|
+
|
|
631
|
+
`getDerivativeStatus` is the reader's view of the same question. It
|
|
632
|
+
authenticates like a data read — a live grant covering the derived scope, or
|
|
633
|
+
the owner — and nothing is charged, so a priced grant raises no 402 here.
|
|
634
|
+
|
|
635
|
+
```typescript
|
|
636
|
+
import {
|
|
637
|
+
getDerivativeStatus,
|
|
638
|
+
waitForDerivativeStatus,
|
|
639
|
+
} from "@opendatalabs/vana-sdk";
|
|
640
|
+
|
|
641
|
+
const status = await getDerivativeStatus({
|
|
642
|
+
personalServerUrl: "https://ps.example.com",
|
|
643
|
+
derivedScope: "coach.weekly",
|
|
644
|
+
grantId,
|
|
645
|
+
signer,
|
|
646
|
+
});
|
|
647
|
+
// { derivedScope, status, lastComputedAt, derivedVersion,
|
|
648
|
+
// derivedCollectedAt, errorCode, retryAfterSeconds }
|
|
649
|
+
|
|
650
|
+
const settled = await waitForDerivativeStatus({
|
|
651
|
+
personalServerUrl: "https://ps.example.com",
|
|
652
|
+
derivedScope: "coach.weekly",
|
|
653
|
+
grantId,
|
|
654
|
+
signer,
|
|
655
|
+
timeoutMs: 60_000,
|
|
656
|
+
});
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
The view is lifecycle only: the question text, the source scopes, the question
|
|
660
|
+
id, the registrar and the server's raw `error` string stay owner-only.
|
|
661
|
+
`errorCode` is a closed vocabulary — `inference_unavailable`,
|
|
662
|
+
`source_missing`, `grant_invalid`, `internal` — and is `null` unless `status`
|
|
663
|
+
is `failed`.
|
|
664
|
+
|
|
665
|
+
`retryAfterSeconds` is what separates a failure that is still being worked on
|
|
666
|
+
from one that is over: `inference_unavailable` is the one transient class, and
|
|
667
|
+
the Personal Server retries it on its own schedule. `waitForDerivativeStatus`
|
|
668
|
+
returns as soon as the scope is `ready` or has failed with no retry pending,
|
|
669
|
+
keeps waiting through a retrying failure, and takes the server's
|
|
670
|
+
`retryAfterSeconds` as the cadence in place of `pollIntervalMs`, longer or
|
|
671
|
+
shorter — it is when the next compute actually happens, so asking sooner sees
|
|
672
|
+
nothing new and asking later sits on an answer that already exists. Once the
|
|
673
|
+
remaining budget cannot cover the next cadence it raises the timeout rather
|
|
674
|
+
than spending one more request that cannot carry new data. `signal` aborts
|
|
675
|
+
the wait and the request in flight with it. A failed status is returned, not thrown; branch
|
|
676
|
+
on `errorCode`. `isDerivativeStatusSettled` is the same predicate, exported
|
|
677
|
+
for callers that poll on their own.
|
|
678
|
+
|
|
679
|
+
When several questions write the same derived scope, the most optimistic true
|
|
680
|
+
state answers (`ready`, then `stale`, then `pending`, then `failed`), because
|
|
681
|
+
serving data is registration-agnostic: a duplicate that never wrote anything
|
|
682
|
+
must not report away an answer the scope has.
|
|
683
|
+
|
|
684
|
+
The status route needs a Personal Server that ships it; an older one answers
|
|
685
|
+
404 for the route itself, which arrives as `DerivativeQuestionNotFoundError`
|
|
686
|
+
— the same error as a covered scope with no question behind it.
|
|
687
|
+
|
|
624
688
|
## Networks
|
|
625
689
|
|
|
626
690
|
| Network | Chain ID | RPC URL |
|
|
@@ -20,10 +20,13 @@ var access_request_client_exports = {};
|
|
|
20
20
|
__export(access_request_client_exports, {
|
|
21
21
|
buildApprovalUrl: () => buildApprovalUrl,
|
|
22
22
|
buildDirectAccessRequestAuthMessage: () => buildDirectAccessRequestAuthMessage,
|
|
23
|
-
createDefaultAccessRequestClient: () => createDefaultAccessRequestClient
|
|
23
|
+
createDefaultAccessRequestClient: () => createDefaultAccessRequestClient,
|
|
24
|
+
validateAccessRequestQuestions: () => validateAccessRequestQuestions
|
|
24
25
|
});
|
|
25
26
|
module.exports = __toCommonJS(access_request_client_exports);
|
|
26
27
|
var import_types = require("./types");
|
|
28
|
+
var import_scopes = require("../protocol/scopes");
|
|
29
|
+
var import_errors = require("./errors");
|
|
27
30
|
const VALID_STATUSES = [
|
|
28
31
|
"pending",
|
|
29
32
|
"approved",
|
|
@@ -86,6 +89,96 @@ function buildApprovalUrl(approvalBaseUrl, requestId) {
|
|
|
86
89
|
requestId
|
|
87
90
|
)}?mode=page`;
|
|
88
91
|
}
|
|
92
|
+
const RECOMPUTE_VALUES = ["snapshot", "on-change"];
|
|
93
|
+
function parseConcreteScope(field, value) {
|
|
94
|
+
if (typeof value !== "string") {
|
|
95
|
+
throw new import_errors.DirectConfigError(`${field} must be a string`, { field });
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
return (0, import_scopes.parseScope)(value);
|
|
99
|
+
} catch {
|
|
100
|
+
throw new import_errors.DirectConfigError(
|
|
101
|
+
`${field} "${value}" is not a concrete scope. Use {source}.{category}[.{subcategory}] with no wildcard and no operation prefix.`,
|
|
102
|
+
{ field, value }
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function validateAccessRequestQuestions(questions, scopes) {
|
|
107
|
+
if (questions.length === 0 || questions.length > 4) {
|
|
108
|
+
throw new import_errors.DirectConfigError(
|
|
109
|
+
`questions must contain 1 to 4 entries when present, got ${questions.length}. Omit the field to send no questions.`,
|
|
110
|
+
{ count: questions.length }
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
const seenDerived = /* @__PURE__ */ new Set();
|
|
114
|
+
questions.forEach((question, index) => {
|
|
115
|
+
const label = `questions[${index}]`;
|
|
116
|
+
const derived = parseConcreteScope(
|
|
117
|
+
`${label}.derivedScope`,
|
|
118
|
+
question.derivedScope
|
|
119
|
+
);
|
|
120
|
+
if (seenDerived.has(question.derivedScope)) {
|
|
121
|
+
throw new import_errors.DirectConfigError(
|
|
122
|
+
`${label}.derivedScope "${question.derivedScope}" is already used by an earlier question. Each question must target its own derived scope.`,
|
|
123
|
+
{ derivedScope: question.derivedScope }
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
seenDerived.add(question.derivedScope);
|
|
127
|
+
if (!scopes.includes(question.derivedScope)) {
|
|
128
|
+
throw new import_errors.DirectConfigError(
|
|
129
|
+
`${label}.derivedScope "${question.derivedScope}" must also appear in scopes as a bare read entry, so the app can read the answer it asked for.`,
|
|
130
|
+
{ derivedScope: question.derivedScope, scopes: [...scopes] }
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
if (question.sourceScopes.length === 0 || question.sourceScopes.length > 16) {
|
|
134
|
+
throw new import_errors.DirectConfigError(
|
|
135
|
+
`${label}.sourceScopes must contain 1 to 16 entries, got ${question.sourceScopes.length}.`,
|
|
136
|
+
{ count: question.sourceScopes.length }
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const seenSources = /* @__PURE__ */ new Set();
|
|
140
|
+
for (const sourceScope of question.sourceScopes) {
|
|
141
|
+
const source = parseConcreteScope(`${label}.sourceScopes`, sourceScope);
|
|
142
|
+
if (seenSources.has(sourceScope)) {
|
|
143
|
+
throw new import_errors.DirectConfigError(
|
|
144
|
+
`${label}.sourceScopes contains "${sourceScope}" more than once. Deduplicate the source scopes.`,
|
|
145
|
+
{ sourceScope }
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
seenSources.add(sourceScope);
|
|
149
|
+
if (sourceScope === question.derivedScope) {
|
|
150
|
+
throw new import_errors.DirectConfigError(
|
|
151
|
+
`${label}.sourceScopes must not contain the derived scope "${question.derivedScope}".`,
|
|
152
|
+
{ sourceScope }
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (source.source === derived.source) {
|
|
156
|
+
throw new import_errors.DirectConfigError(
|
|
157
|
+
`${label}.derivedScope "${question.derivedScope}" must not share its first dot-segment "${derived.source}" with source scope "${sourceScope}". Name the derived scope under the app's own namespace.`,
|
|
158
|
+
{ derivedScope: question.derivedScope, sourceScope }
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (typeof question.question !== "string") {
|
|
163
|
+
throw new import_errors.DirectConfigError(`${label}.question must be a string`, {
|
|
164
|
+
field: `${label}.question`
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
const trimmedLength = question.question.trim().length;
|
|
168
|
+
if (trimmedLength === 0 || trimmedLength > 4e3) {
|
|
169
|
+
throw new import_errors.DirectConfigError(
|
|
170
|
+
`${label}.question must be 1 to 4000 characters after trimming, got ${trimmedLength}.`,
|
|
171
|
+
{ length: trimmedLength }
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
if (question.recompute !== void 0 && !RECOMPUTE_VALUES.includes(question.recompute)) {
|
|
175
|
+
throw new import_errors.DirectConfigError(
|
|
176
|
+
`${label}.recompute must be "snapshot" or "on-change" when present, got "${String(question.recompute)}".`,
|
|
177
|
+
{ recompute: question.recompute }
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
}
|
|
89
182
|
function createDefaultAccessRequestClient(options) {
|
|
90
183
|
const fetchFn = options.fetchFn ?? globalThis.fetch;
|
|
91
184
|
if (!fetchFn) {
|
|
@@ -96,6 +189,9 @@ function createDefaultAccessRequestClient(options) {
|
|
|
96
189
|
const base = stripTrailingSlash(options.baseUrl);
|
|
97
190
|
return {
|
|
98
191
|
async createAccessRequest(input) {
|
|
192
|
+
if (input.questions !== void 0) {
|
|
193
|
+
validateAccessRequestQuestions(input.questions, input.scopes);
|
|
194
|
+
}
|
|
99
195
|
const path = "/api/data-connection-requests";
|
|
100
196
|
const idempotencyKey = input.idempotencyKey ?? (options.createIdempotencyKey ?? defaultCreateIdempotencyKey)();
|
|
101
197
|
const body = JSON.stringify({
|
|
@@ -106,6 +202,7 @@ function createDefaultAccessRequestClient(options) {
|
|
|
106
202
|
returnUrl: input.returnUrl,
|
|
107
203
|
network: input.network,
|
|
108
204
|
...input.foregroundDelivery !== void 0 ? { foregroundDelivery: input.foregroundDelivery } : {},
|
|
205
|
+
...input.questions !== void 0 ? { questions: input.questions } : {},
|
|
109
206
|
idempotencyKey
|
|
110
207
|
});
|
|
111
208
|
const res = await fetchFn(`${base}${path}`, {
|
|
@@ -193,6 +290,7 @@ function createDefaultAccessRequestClient(options) {
|
|
|
193
290
|
0 && (module.exports = {
|
|
194
291
|
buildApprovalUrl,
|
|
195
292
|
buildDirectAccessRequestAuthMessage,
|
|
196
|
-
createDefaultAccessRequestClient
|
|
293
|
+
createDefaultAccessRequestClient,
|
|
294
|
+
validateAccessRequestQuestions
|
|
197
295
|
});
|
|
198
296
|
//# sourceMappingURL=access-request-client.cjs.map
|
|
@@ -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 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;AAoBA,mBAA+C;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,OAA0C;AAClE,SAAO,UAAU,aAAa,UAAU,WAAW,QAAQ;AAC7D;AAEA,SAAS,mBAAmB,OAAoC;AAC9D,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,MAAM,KAAK,CAAC,IACjE,QACA;AACN;AAEA,SAAS,8BAAsC;AAC7C,MAAI,OAAO,WAAW,QAAQ,eAAe,YAAY;AACvD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,WAAW,OAAO,WAAW;AACtC;AAEA,SAA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;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;AAU7B,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,QACA,2BAAuB;AAAA,UACrB,KAAK;AAAA,UACL,QAAQ;AAAA,QACV;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 AccessRequestQuestion,\n AccessRequestStatus,\n AccessRequestStatusValue,\n DirectEnv,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\nimport { parseScope, type ParsedScope } from \"../protocol/scopes\";\nimport { DirectConfigError } from \"./errors\";\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/** The `recompute` values the question contract defines today. */\nconst RECOMPUTE_VALUES: readonly string[] = [\"snapshot\", \"on-change\"];\n\nfunction parseConcreteScope(field: string, value: unknown): ParsedScope {\n if (typeof value !== \"string\") {\n throw new DirectConfigError(`${field} must be a string`, { field });\n }\n try {\n return parseScope(value);\n } catch {\n throw new DirectConfigError(\n `${field} \"${value}\" is not a concrete scope. Use {source}.{category}[.{subcategory}] with no wildcard and no operation prefix.`,\n { field, value },\n );\n }\n}\n\n/**\n * Validate the derivative questions on a create input against the request\n * scope entries.\n *\n * @remarks\n * Client-side mirror of the access-request service rules so builders fail\n * fast, before the create request is signed and sent; the service remains\n * authoritative. Rules: 1 to 4 questions; every `derivedScope` and every\n * `sourceScope` is a concrete scope (wildcards rejected); 1 to 16 source\n * scopes per question with no duplicates and none equal to the derived scope;\n * the first dot-segment of the derived scope differs from the first\n * dot-segment of every source scope; the derived scope appears verbatim in\n * `scopes` as a bare read entry; no two questions share a derived scope; the\n * question text is 1 to 4000 characters after trimming; `recompute`, when\n * present, is `\"snapshot\"` or `\"on-change\"`.\n *\n * @param questions - The `questions` array from the create input.\n * @param scopes - The request's grant scope entries, verbatim.\n * @throws {DirectConfigError} - When any rule is violated. The message names\n * the offending question index and field.\n */\nexport function validateAccessRequestQuestions(\n questions: readonly AccessRequestQuestion[],\n scopes: readonly string[],\n): void {\n if (questions.length === 0 || questions.length > 4) {\n throw new DirectConfigError(\n `questions must contain 1 to 4 entries when present, got ${questions.length}. Omit the field to send no questions.`,\n { count: questions.length },\n );\n }\n const seenDerived = new Set<string>();\n questions.forEach((question, index) => {\n const label = `questions[${index}]`;\n const derived = parseConcreteScope(\n `${label}.derivedScope`,\n question.derivedScope,\n );\n if (seenDerived.has(question.derivedScope)) {\n throw new DirectConfigError(\n `${label}.derivedScope \"${question.derivedScope}\" is already used by an earlier question. Each question must target its own derived scope.`,\n { derivedScope: question.derivedScope },\n );\n }\n seenDerived.add(question.derivedScope);\n // The bare entry (no operation prefix) is what makes the answer readable\n // by the app: `write:coach.weekly` alone would not grant the read back.\n if (!scopes.includes(question.derivedScope)) {\n throw new DirectConfigError(\n `${label}.derivedScope \"${question.derivedScope}\" must also appear in scopes as a bare read entry, so the app can read the answer it asked for.`,\n { derivedScope: question.derivedScope, scopes: [...scopes] },\n );\n }\n if (\n question.sourceScopes.length === 0 ||\n question.sourceScopes.length > 16\n ) {\n throw new DirectConfigError(\n `${label}.sourceScopes must contain 1 to 16 entries, got ${question.sourceScopes.length}.`,\n { count: question.sourceScopes.length },\n );\n }\n const seenSources = new Set<string>();\n for (const sourceScope of question.sourceScopes) {\n const source = parseConcreteScope(`${label}.sourceScopes`, sourceScope);\n if (seenSources.has(sourceScope)) {\n throw new DirectConfigError(\n `${label}.sourceScopes contains \"${sourceScope}\" more than once. Deduplicate the source scopes.`,\n { sourceScope },\n );\n }\n seenSources.add(sourceScope);\n if (sourceScope === question.derivedScope) {\n throw new DirectConfigError(\n `${label}.sourceScopes must not contain the derived scope \"${question.derivedScope}\".`,\n { sourceScope },\n );\n }\n if (source.source === derived.source) {\n throw new DirectConfigError(\n `${label}.derivedScope \"${question.derivedScope}\" must not share its first dot-segment \"${derived.source}\" with source scope \"${sourceScope}\". Name the derived scope under the app's own namespace.`,\n { derivedScope: question.derivedScope, sourceScope },\n );\n }\n }\n if (typeof question.question !== \"string\") {\n throw new DirectConfigError(`${label}.question must be a string`, {\n field: `${label}.question`,\n });\n }\n const trimmedLength = question.question.trim().length;\n if (trimmedLength === 0 || trimmedLength > 4000) {\n throw new DirectConfigError(\n `${label}.question must be 1 to 4000 characters after trimming, got ${trimmedLength}.`,\n { length: trimmedLength },\n );\n }\n if (\n question.recompute !== undefined &&\n !RECOMPUTE_VALUES.includes(question.recompute)\n ) {\n throw new DirectConfigError(\n `${label}.recompute must be \"snapshot\" or \"on-change\" when present, got \"${String(question.recompute)}\".`,\n { recompute: question.recompute },\n );\n }\n });\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 if (input.questions !== undefined) {\n validateAccessRequestQuestions(input.questions, input.scopes);\n }\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 ...(input.questions !== undefined\n ? { questions: input.questions }\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}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A,QACxB,SAAS,KAAK;AAAA,QACd,OAAO,KAAK,SAAS,SAAS,CAAC;AAAA,QAC/B;AAAA,QACA,2BAAuB;AAAA,UACrB,KAAK;AAAA,UACL,QAAQ;AAAA,QACV;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":[]}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* @category Direct
|
|
11
11
|
* @module direct/access-request-client
|
|
12
12
|
*/
|
|
13
|
-
import type { AccessRequestClient, DirectEnv } from "./types.js";
|
|
13
|
+
import type { AccessRequestClient, AccessRequestQuestion, 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?: {
|
|
@@ -66,6 +66,28 @@ export declare function buildDirectAccessRequestAuthMessage(input: DirectAccessR
|
|
|
66
66
|
* @returns The full approval URL.
|
|
67
67
|
*/
|
|
68
68
|
export declare function buildApprovalUrl(approvalBaseUrl: string, requestId: string): string;
|
|
69
|
+
/**
|
|
70
|
+
* Validate the derivative questions on a create input against the request
|
|
71
|
+
* scope entries.
|
|
72
|
+
*
|
|
73
|
+
* @remarks
|
|
74
|
+
* Client-side mirror of the access-request service rules so builders fail
|
|
75
|
+
* fast, before the create request is signed and sent; the service remains
|
|
76
|
+
* authoritative. Rules: 1 to 4 questions; every `derivedScope` and every
|
|
77
|
+
* `sourceScope` is a concrete scope (wildcards rejected); 1 to 16 source
|
|
78
|
+
* scopes per question with no duplicates and none equal to the derived scope;
|
|
79
|
+
* the first dot-segment of the derived scope differs from the first
|
|
80
|
+
* dot-segment of every source scope; the derived scope appears verbatim in
|
|
81
|
+
* `scopes` as a bare read entry; no two questions share a derived scope; the
|
|
82
|
+
* question text is 1 to 4000 characters after trimming; `recompute`, when
|
|
83
|
+
* present, is `"snapshot"` or `"on-change"`.
|
|
84
|
+
*
|
|
85
|
+
* @param questions - The `questions` array from the create input.
|
|
86
|
+
* @param scopes - The request's grant scope entries, verbatim.
|
|
87
|
+
* @throws {DirectConfigError} - When any rule is violated. The message names
|
|
88
|
+
* the offending question index and field.
|
|
89
|
+
*/
|
|
90
|
+
export declare function validateAccessRequestQuestions(questions: readonly AccessRequestQuestion[], scopes: readonly string[]): void;
|
|
69
91
|
/**
|
|
70
92
|
* Create the default {@link AccessRequestClient} for the Vana Account
|
|
71
93
|
* access-request API.
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { normalizeMobileContinuationUrl } from "./types.js";
|
|
2
|
+
import { parseScope } from "../protocol/scopes.js";
|
|
3
|
+
import { DirectConfigError } from "./errors.js";
|
|
2
4
|
const VALID_STATUSES = [
|
|
3
5
|
"pending",
|
|
4
6
|
"approved",
|
|
@@ -61,6 +63,96 @@ function buildApprovalUrl(approvalBaseUrl, requestId) {
|
|
|
61
63
|
requestId
|
|
62
64
|
)}?mode=page`;
|
|
63
65
|
}
|
|
66
|
+
const RECOMPUTE_VALUES = ["snapshot", "on-change"];
|
|
67
|
+
function parseConcreteScope(field, value) {
|
|
68
|
+
if (typeof value !== "string") {
|
|
69
|
+
throw new DirectConfigError(`${field} must be a string`, { field });
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return parseScope(value);
|
|
73
|
+
} catch {
|
|
74
|
+
throw new DirectConfigError(
|
|
75
|
+
`${field} "${value}" is not a concrete scope. Use {source}.{category}[.{subcategory}] with no wildcard and no operation prefix.`,
|
|
76
|
+
{ field, value }
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function validateAccessRequestQuestions(questions, scopes) {
|
|
81
|
+
if (questions.length === 0 || questions.length > 4) {
|
|
82
|
+
throw new DirectConfigError(
|
|
83
|
+
`questions must contain 1 to 4 entries when present, got ${questions.length}. Omit the field to send no questions.`,
|
|
84
|
+
{ count: questions.length }
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
const seenDerived = /* @__PURE__ */ new Set();
|
|
88
|
+
questions.forEach((question, index) => {
|
|
89
|
+
const label = `questions[${index}]`;
|
|
90
|
+
const derived = parseConcreteScope(
|
|
91
|
+
`${label}.derivedScope`,
|
|
92
|
+
question.derivedScope
|
|
93
|
+
);
|
|
94
|
+
if (seenDerived.has(question.derivedScope)) {
|
|
95
|
+
throw new DirectConfigError(
|
|
96
|
+
`${label}.derivedScope "${question.derivedScope}" is already used by an earlier question. Each question must target its own derived scope.`,
|
|
97
|
+
{ derivedScope: question.derivedScope }
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
seenDerived.add(question.derivedScope);
|
|
101
|
+
if (!scopes.includes(question.derivedScope)) {
|
|
102
|
+
throw new DirectConfigError(
|
|
103
|
+
`${label}.derivedScope "${question.derivedScope}" must also appear in scopes as a bare read entry, so the app can read the answer it asked for.`,
|
|
104
|
+
{ derivedScope: question.derivedScope, scopes: [...scopes] }
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
if (question.sourceScopes.length === 0 || question.sourceScopes.length > 16) {
|
|
108
|
+
throw new DirectConfigError(
|
|
109
|
+
`${label}.sourceScopes must contain 1 to 16 entries, got ${question.sourceScopes.length}.`,
|
|
110
|
+
{ count: question.sourceScopes.length }
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
const seenSources = /* @__PURE__ */ new Set();
|
|
114
|
+
for (const sourceScope of question.sourceScopes) {
|
|
115
|
+
const source = parseConcreteScope(`${label}.sourceScopes`, sourceScope);
|
|
116
|
+
if (seenSources.has(sourceScope)) {
|
|
117
|
+
throw new DirectConfigError(
|
|
118
|
+
`${label}.sourceScopes contains "${sourceScope}" more than once. Deduplicate the source scopes.`,
|
|
119
|
+
{ sourceScope }
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
seenSources.add(sourceScope);
|
|
123
|
+
if (sourceScope === question.derivedScope) {
|
|
124
|
+
throw new DirectConfigError(
|
|
125
|
+
`${label}.sourceScopes must not contain the derived scope "${question.derivedScope}".`,
|
|
126
|
+
{ sourceScope }
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
if (source.source === derived.source) {
|
|
130
|
+
throw new DirectConfigError(
|
|
131
|
+
`${label}.derivedScope "${question.derivedScope}" must not share its first dot-segment "${derived.source}" with source scope "${sourceScope}". Name the derived scope under the app's own namespace.`,
|
|
132
|
+
{ derivedScope: question.derivedScope, sourceScope }
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (typeof question.question !== "string") {
|
|
137
|
+
throw new DirectConfigError(`${label}.question must be a string`, {
|
|
138
|
+
field: `${label}.question`
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const trimmedLength = question.question.trim().length;
|
|
142
|
+
if (trimmedLength === 0 || trimmedLength > 4e3) {
|
|
143
|
+
throw new DirectConfigError(
|
|
144
|
+
`${label}.question must be 1 to 4000 characters after trimming, got ${trimmedLength}.`,
|
|
145
|
+
{ length: trimmedLength }
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
if (question.recompute !== void 0 && !RECOMPUTE_VALUES.includes(question.recompute)) {
|
|
149
|
+
throw new DirectConfigError(
|
|
150
|
+
`${label}.recompute must be "snapshot" or "on-change" when present, got "${String(question.recompute)}".`,
|
|
151
|
+
{ recompute: question.recompute }
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
64
156
|
function createDefaultAccessRequestClient(options) {
|
|
65
157
|
const fetchFn = options.fetchFn ?? globalThis.fetch;
|
|
66
158
|
if (!fetchFn) {
|
|
@@ -71,6 +163,9 @@ function createDefaultAccessRequestClient(options) {
|
|
|
71
163
|
const base = stripTrailingSlash(options.baseUrl);
|
|
72
164
|
return {
|
|
73
165
|
async createAccessRequest(input) {
|
|
166
|
+
if (input.questions !== void 0) {
|
|
167
|
+
validateAccessRequestQuestions(input.questions, input.scopes);
|
|
168
|
+
}
|
|
74
169
|
const path = "/api/data-connection-requests";
|
|
75
170
|
const idempotencyKey = input.idempotencyKey ?? (options.createIdempotencyKey ?? defaultCreateIdempotencyKey)();
|
|
76
171
|
const body = JSON.stringify({
|
|
@@ -81,6 +176,7 @@ function createDefaultAccessRequestClient(options) {
|
|
|
81
176
|
returnUrl: input.returnUrl,
|
|
82
177
|
network: input.network,
|
|
83
178
|
...input.foregroundDelivery !== void 0 ? { foregroundDelivery: input.foregroundDelivery } : {},
|
|
179
|
+
...input.questions !== void 0 ? { questions: input.questions } : {},
|
|
84
180
|
idempotencyKey
|
|
85
181
|
});
|
|
86
182
|
const res = await fetchFn(`${base}${path}`, {
|
|
@@ -167,6 +263,7 @@ function createDefaultAccessRequestClient(options) {
|
|
|
167
263
|
export {
|
|
168
264
|
buildApprovalUrl,
|
|
169
265
|
buildDirectAccessRequestAuthMessage,
|
|
170
|
-
createDefaultAccessRequestClient
|
|
266
|
+
createDefaultAccessRequestClient,
|
|
267
|
+
validateAccessRequestQuestions
|
|
171
268
|
};
|
|
172
269
|
//# sourceMappingURL=access-request-client.js.map
|
|
@@ -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 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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;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 AccessRequestQuestion,\n AccessRequestStatus,\n AccessRequestStatusValue,\n DirectEnv,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\nimport { parseScope, type ParsedScope } from \"../protocol/scopes\";\nimport { DirectConfigError } from \"./errors\";\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/** The `recompute` values the question contract defines today. */\nconst RECOMPUTE_VALUES: readonly string[] = [\"snapshot\", \"on-change\"];\n\nfunction parseConcreteScope(field: string, value: unknown): ParsedScope {\n if (typeof value !== \"string\") {\n throw new DirectConfigError(`${field} must be a string`, { field });\n }\n try {\n return parseScope(value);\n } catch {\n throw new DirectConfigError(\n `${field} \"${value}\" is not a concrete scope. Use {source}.{category}[.{subcategory}] with no wildcard and no operation prefix.`,\n { field, value },\n );\n }\n}\n\n/**\n * Validate the derivative questions on a create input against the request\n * scope entries.\n *\n * @remarks\n * Client-side mirror of the access-request service rules so builders fail\n * fast, before the create request is signed and sent; the service remains\n * authoritative. Rules: 1 to 4 questions; every `derivedScope` and every\n * `sourceScope` is a concrete scope (wildcards rejected); 1 to 16 source\n * scopes per question with no duplicates and none equal to the derived scope;\n * the first dot-segment of the derived scope differs from the first\n * dot-segment of every source scope; the derived scope appears verbatim in\n * `scopes` as a bare read entry; no two questions share a derived scope; the\n * question text is 1 to 4000 characters after trimming; `recompute`, when\n * present, is `\"snapshot\"` or `\"on-change\"`.\n *\n * @param questions - The `questions` array from the create input.\n * @param scopes - The request's grant scope entries, verbatim.\n * @throws {DirectConfigError} - When any rule is violated. The message names\n * the offending question index and field.\n */\nexport function validateAccessRequestQuestions(\n questions: readonly AccessRequestQuestion[],\n scopes: readonly string[],\n): void {\n if (questions.length === 0 || questions.length > 4) {\n throw new DirectConfigError(\n `questions must contain 1 to 4 entries when present, got ${questions.length}. Omit the field to send no questions.`,\n { count: questions.length },\n );\n }\n const seenDerived = new Set<string>();\n questions.forEach((question, index) => {\n const label = `questions[${index}]`;\n const derived = parseConcreteScope(\n `${label}.derivedScope`,\n question.derivedScope,\n );\n if (seenDerived.has(question.derivedScope)) {\n throw new DirectConfigError(\n `${label}.derivedScope \"${question.derivedScope}\" is already used by an earlier question. Each question must target its own derived scope.`,\n { derivedScope: question.derivedScope },\n );\n }\n seenDerived.add(question.derivedScope);\n // The bare entry (no operation prefix) is what makes the answer readable\n // by the app: `write:coach.weekly` alone would not grant the read back.\n if (!scopes.includes(question.derivedScope)) {\n throw new DirectConfigError(\n `${label}.derivedScope \"${question.derivedScope}\" must also appear in scopes as a bare read entry, so the app can read the answer it asked for.`,\n { derivedScope: question.derivedScope, scopes: [...scopes] },\n );\n }\n if (\n question.sourceScopes.length === 0 ||\n question.sourceScopes.length > 16\n ) {\n throw new DirectConfigError(\n `${label}.sourceScopes must contain 1 to 16 entries, got ${question.sourceScopes.length}.`,\n { count: question.sourceScopes.length },\n );\n }\n const seenSources = new Set<string>();\n for (const sourceScope of question.sourceScopes) {\n const source = parseConcreteScope(`${label}.sourceScopes`, sourceScope);\n if (seenSources.has(sourceScope)) {\n throw new DirectConfigError(\n `${label}.sourceScopes contains \"${sourceScope}\" more than once. Deduplicate the source scopes.`,\n { sourceScope },\n );\n }\n seenSources.add(sourceScope);\n if (sourceScope === question.derivedScope) {\n throw new DirectConfigError(\n `${label}.sourceScopes must not contain the derived scope \"${question.derivedScope}\".`,\n { sourceScope },\n );\n }\n if (source.source === derived.source) {\n throw new DirectConfigError(\n `${label}.derivedScope \"${question.derivedScope}\" must not share its first dot-segment \"${derived.source}\" with source scope \"${sourceScope}\". Name the derived scope under the app's own namespace.`,\n { derivedScope: question.derivedScope, sourceScope },\n );\n }\n }\n if (typeof question.question !== \"string\") {\n throw new DirectConfigError(`${label}.question must be a string`, {\n field: `${label}.question`,\n });\n }\n const trimmedLength = question.question.trim().length;\n if (trimmedLength === 0 || trimmedLength > 4000) {\n throw new DirectConfigError(\n `${label}.question must be 1 to 4000 characters after trimming, got ${trimmedLength}.`,\n { length: trimmedLength },\n );\n }\n if (\n question.recompute !== undefined &&\n !RECOMPUTE_VALUES.includes(question.recompute)\n ) {\n throw new DirectConfigError(\n `${label}.recompute must be \"snapshot\" or \"on-change\" when present, got \"${String(question.recompute)}\".`,\n { recompute: question.recompute },\n );\n }\n });\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 if (input.questions !== undefined) {\n validateAccessRequestQuestions(input.questions, input.scopes);\n }\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 ...(input.questions !== undefined\n ? { questions: input.questions }\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":"AAqBA,SAAS,sCAAsC;AAE/C,SAAS,kBAAoC;AAC7C,SAAS,yBAAyB;AA6ClC,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,OAA0C;AAClE,SAAO,UAAU,aAAa,UAAU,WAAW,QAAQ;AAC7D;AAEA,SAAS,mBAAmB,OAAoC;AAC9D,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,MAAM,KAAK,CAAC,IACjE,QACA;AACN;AAEA,SAAS,8BAAsC;AAC7C,MAAI,OAAO,WAAW,QAAQ,eAAe,YAAY;AACvD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,WAAW,OAAO,WAAW;AACtC;AAEA,SAAS,mBAAmB,KAAqB;AAC/C,SAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;AAEA,MAAM,uCAAuC;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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,iCAAiC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,QAC/D;AAAA,MACF;AACA,YAAM,OAAQ,MAAM,IAAI,KAAK;AAU7B,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,QACA,uBAAuB;AAAA,UACrB,KAAK;AAAA,UACL,QAAQ;AAAA,QACV;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":[]}
|
|
@@ -97,6 +97,9 @@ function createDirectDataController(config) {
|
|
|
97
97
|
};
|
|
98
98
|
},
|
|
99
99
|
async createAccessRequest(input) {
|
|
100
|
+
if (input.questions !== void 0) {
|
|
101
|
+
(0, import_access_request_client.validateAccessRequestQuestions)(input.questions, config.scopes);
|
|
102
|
+
}
|
|
100
103
|
return accessRequestClient.createAccessRequest({
|
|
101
104
|
appAddress: account.address,
|
|
102
105
|
app: config.app,
|
|
@@ -105,6 +108,7 @@ function createDirectDataController(config) {
|
|
|
105
108
|
returnUrl: input.returnUrl,
|
|
106
109
|
network,
|
|
107
110
|
...input.foregroundDelivery !== void 0 ? { foregroundDelivery: input.foregroundDelivery } : {},
|
|
111
|
+
...input.questions !== void 0 ? { questions: input.questions } : {},
|
|
108
112
|
...input.idempotencyKey !== void 0 ? { idempotencyKey: input.idempotencyKey } : {}
|
|
109
113
|
});
|
|
110
114
|
},
|