@opendatalabs/vana-sdk 3.22.0 → 3.23.0-pr.211.341f55d
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/dist/crypto/envelope/job.cjs +355 -0
- package/dist/crypto/envelope/job.cjs.map +1 -0
- package/dist/crypto/envelope/job.d.ts +123 -0
- package/dist/crypto/envelope/job.js +333 -0
- package/dist/crypto/envelope/job.js.map +1 -0
- package/dist/direct/access-request-client.cjs +4 -0
- package/dist/direct/access-request-client.cjs.map +1 -1
- package/dist/direct/access-request-client.js +4 -0
- package/dist/direct/access-request-client.js.map +1 -1
- package/dist/direct/connect-flow.cjs +43 -1
- package/dist/direct/connect-flow.cjs.map +1 -1
- package/dist/direct/connect-flow.d.ts +12 -0
- package/dist/direct/connect-flow.js +43 -1
- package/dist/direct/connect-flow.js.map +1 -1
- package/dist/direct/types.cjs.map +1 -1
- package/dist/direct/types.d.ts +7 -0
- package/dist/direct/types.js.map +1 -1
- package/dist/direct/use-direct-vana-connect.cjs +2 -1
- package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
- package/dist/direct/use-direct-vana-connect.d.ts +3 -1
- package/dist/direct/use-direct-vana-connect.js +2 -1
- package/dist/direct/use-direct-vana-connect.js.map +1 -1
- package/dist/errors.cjs +84 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +133 -0
- package/dist/errors.js +73 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.browser.d.ts +3 -0
- package/dist/index.browser.js +631 -24
- package/dist/index.browser.js.map +4 -4
- package/dist/index.node.cjs +1259 -111
- package/dist/index.node.cjs.map +4 -4
- package/dist/index.node.d.ts +4 -0
- package/dist/index.node.js +1223 -101
- package/dist/index.node.js.map +4 -4
- package/dist/protocol/identity.cjs +219 -0
- package/dist/protocol/identity.cjs.map +1 -0
- package/dist/protocol/identity.d.ts +193 -0
- package/dist/protocol/identity.js +183 -0
- package/dist/protocol/identity.js.map +1 -0
- package/dist/protocol/identity.test.d.ts +1 -0
- package/dist/protocol/identity.vector.test.d.ts +1 -0
- package/dist/protocol/jobs-client.cjs +540 -0
- package/dist/protocol/jobs-client.cjs.map +1 -0
- package/dist/protocol/jobs-client.d.ts +169 -0
- package/dist/protocol/jobs-client.js +547 -0
- package/dist/protocol/jobs-client.js.map +1 -0
- package/dist/protocol/jobs-client.test.d.ts +1 -0
- package/dist/protocol/jobs.cjs +64 -0
- package/dist/protocol/jobs.cjs.map +1 -0
- package/dist/protocol/jobs.d.ts +193 -0
- package/dist/protocol/jobs.js +31 -0
- package/dist/protocol/jobs.js.map +1 -0
- package/dist/protocol/jobs.test.d.ts +1 -0
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js.map +1 -1
- package/package.json +7 -1
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { sha256 } from "@noble/hashes/sha2";
|
|
2
|
+
import { bytesToHex, fromHex, isAddress, isHex, toHex } from "viem";
|
|
3
|
+
import { CURVE, FORMAT, MAC } from "../ecies/constants.js";
|
|
4
|
+
import {
|
|
5
|
+
deserializeECIES,
|
|
6
|
+
ECIESError,
|
|
7
|
+
serializeECIES
|
|
8
|
+
} from "../ecies/interface.js";
|
|
9
|
+
import {
|
|
10
|
+
JOB_OPERATIONS,
|
|
11
|
+
JOB_PROTOCOL_VERSION
|
|
12
|
+
} from "../../protocol/jobs.js";
|
|
13
|
+
import { fromBase64, toBase64 } from "../../utils/encoding.js";
|
|
14
|
+
const textDecoder = new TextDecoder();
|
|
15
|
+
const textEncoder = new TextEncoder();
|
|
16
|
+
const MAX_JOB_RESULT_HEADER_BYTES = 4096;
|
|
17
|
+
const JOB_RESULT_LENGTH_PREFIX_BYTES = 4;
|
|
18
|
+
class JobEnvelopeError extends Error {
|
|
19
|
+
constructor(message) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = "JobEnvelopeError";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function sortJsonKeys(value) {
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
return value.map(sortJsonKeys);
|
|
27
|
+
}
|
|
28
|
+
if (value !== null && typeof value === "object") {
|
|
29
|
+
return Object.fromEntries(
|
|
30
|
+
Object.keys(value).sort().map((key) => [
|
|
31
|
+
key,
|
|
32
|
+
sortJsonKeys(value[key])
|
|
33
|
+
])
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
function canonicalJsonBytes(value) {
|
|
39
|
+
return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));
|
|
40
|
+
}
|
|
41
|
+
function canonicalJobRequestBytes(request) {
|
|
42
|
+
validateJobRequest(request);
|
|
43
|
+
return canonicalJsonBytes(request);
|
|
44
|
+
}
|
|
45
|
+
function requestPlaintext(envelope) {
|
|
46
|
+
validateRequestEnvelope(envelope);
|
|
47
|
+
return canonicalJsonBytes(envelope);
|
|
48
|
+
}
|
|
49
|
+
function resultPlaintext(result) {
|
|
50
|
+
const header = textEncoder.encode(
|
|
51
|
+
JSON.stringify({
|
|
52
|
+
v: result.v,
|
|
53
|
+
jobId: result.jobId,
|
|
54
|
+
scope: result.scope,
|
|
55
|
+
version: result.version,
|
|
56
|
+
contentType: result.contentType
|
|
57
|
+
})
|
|
58
|
+
);
|
|
59
|
+
if (header.length > MAX_JOB_RESULT_HEADER_BYTES) {
|
|
60
|
+
throw new JobEnvelopeError(
|
|
61
|
+
`Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
const plaintext = new Uint8Array(
|
|
65
|
+
JOB_RESULT_LENGTH_PREFIX_BYTES + header.length + result.body.length
|
|
66
|
+
);
|
|
67
|
+
new DataView(plaintext.buffer).setUint32(0, header.length);
|
|
68
|
+
plaintext.set(header, JOB_RESULT_LENGTH_PREFIX_BYTES);
|
|
69
|
+
plaintext.set(result.body, JOB_RESULT_LENGTH_PREFIX_BYTES + header.length);
|
|
70
|
+
return plaintext;
|
|
71
|
+
}
|
|
72
|
+
function parseResultPlaintext(plaintext) {
|
|
73
|
+
if (plaintext.length < JOB_RESULT_LENGTH_PREFIX_BYTES) {
|
|
74
|
+
throw new JobEnvelopeError(
|
|
75
|
+
"Invalid job result: missing header length prefix"
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
const headerLength = new DataView(
|
|
79
|
+
plaintext.buffer,
|
|
80
|
+
plaintext.byteOffset,
|
|
81
|
+
JOB_RESULT_LENGTH_PREFIX_BYTES
|
|
82
|
+
).getUint32(0);
|
|
83
|
+
if (headerLength > MAX_JOB_RESULT_HEADER_BYTES) {
|
|
84
|
+
throw new JobEnvelopeError(
|
|
85
|
+
`Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
const remainingLength = plaintext.length - JOB_RESULT_LENGTH_PREFIX_BYTES;
|
|
89
|
+
if (headerLength > remainingLength) {
|
|
90
|
+
throw new JobEnvelopeError(
|
|
91
|
+
"Invalid job result: header length exceeds payload"
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
const headerEnd = JOB_RESULT_LENGTH_PREFIX_BYTES + headerLength;
|
|
95
|
+
const header = parseObject(
|
|
96
|
+
plaintext.subarray(JOB_RESULT_LENGTH_PREFIX_BYTES, headerEnd),
|
|
97
|
+
"job result header"
|
|
98
|
+
);
|
|
99
|
+
return validateResult({ ...header, body: plaintext.subarray(headerEnd) });
|
|
100
|
+
}
|
|
101
|
+
function encryptedBytesToBase64(encrypted) {
|
|
102
|
+
return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, "bytes"));
|
|
103
|
+
}
|
|
104
|
+
function encryptedToBytes(encrypted) {
|
|
105
|
+
const bytes = new Uint8Array(
|
|
106
|
+
encrypted.iv.length + encrypted.ephemPublicKey.length + encrypted.ciphertext.length + encrypted.mac.length
|
|
107
|
+
);
|
|
108
|
+
let offset = 0;
|
|
109
|
+
bytes.set(encrypted.iv, offset);
|
|
110
|
+
offset += encrypted.iv.length;
|
|
111
|
+
bytes.set(encrypted.ephemPublicKey, offset);
|
|
112
|
+
offset += encrypted.ephemPublicKey.length;
|
|
113
|
+
bytes.set(encrypted.ciphertext, offset);
|
|
114
|
+
offset += encrypted.ciphertext.length;
|
|
115
|
+
bytes.set(encrypted.mac, offset);
|
|
116
|
+
return bytes;
|
|
117
|
+
}
|
|
118
|
+
function bytesToEncrypted(bytes) {
|
|
119
|
+
const absoluteMinLength = FORMAT.IV_LENGTH + 1 + MAC.LENGTH + 1;
|
|
120
|
+
if (bytes.length < absoluteMinLength) {
|
|
121
|
+
throw new ECIESError(
|
|
122
|
+
`Invalid ECIES data: too short (${bytes.length} bytes, minimum ${absoluteMinLength} bytes required)`,
|
|
123
|
+
"DECRYPTION_FAILED"
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
const prefix = bytes[FORMAT.EPHEMERAL_KEY_OFFSET];
|
|
127
|
+
if (prefix !== CURVE.PREFIX.UNCOMPRESSED) {
|
|
128
|
+
throw new ECIESError(
|
|
129
|
+
`Invalid ephemeral public key: must be uncompressed format (0x04 prefix), got 0x${prefix.toString(16).padStart(2, "0")}`,
|
|
130
|
+
"DECRYPTION_FAILED"
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
const ephemKeySize = CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH;
|
|
134
|
+
const minLength = FORMAT.IV_LENGTH + ephemKeySize + MAC.LENGTH + 1;
|
|
135
|
+
if (bytes.length < minLength) {
|
|
136
|
+
throw new ECIESError(
|
|
137
|
+
`Invalid ECIES data: too short (${bytes.length} bytes, minimum ${minLength} bytes required)`,
|
|
138
|
+
"DECRYPTION_FAILED"
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
iv: bytes.subarray(FORMAT.IV_OFFSET, FORMAT.IV_OFFSET + FORMAT.IV_LENGTH),
|
|
143
|
+
ephemPublicKey: bytes.subarray(
|
|
144
|
+
FORMAT.EPHEMERAL_KEY_OFFSET,
|
|
145
|
+
FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize
|
|
146
|
+
),
|
|
147
|
+
ciphertext: bytes.subarray(
|
|
148
|
+
FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,
|
|
149
|
+
bytes.length - MAC.LENGTH
|
|
150
|
+
),
|
|
151
|
+
mac: bytes.subarray(bytes.length - MAC.LENGTH)
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function base64ToEncrypted(ciphertext) {
|
|
155
|
+
return deserializeECIES(toHex(fromBase64(ciphertext)));
|
|
156
|
+
}
|
|
157
|
+
function parseObject(plaintext, kind) {
|
|
158
|
+
try {
|
|
159
|
+
const value = JSON.parse(textDecoder.decode(plaintext));
|
|
160
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
161
|
+
throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);
|
|
162
|
+
}
|
|
163
|
+
return value;
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (error instanceof JobEnvelopeError) throw error;
|
|
166
|
+
throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function isPlainObject(value) {
|
|
170
|
+
if (value === null || typeof value !== "object") return false;
|
|
171
|
+
const prototype = Object.getPrototypeOf(value);
|
|
172
|
+
return prototype === Object.prototype || prototype === null;
|
|
173
|
+
}
|
|
174
|
+
function requirePlainObject(value, field, kind) {
|
|
175
|
+
if (!isPlainObject(value)) {
|
|
176
|
+
throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function requireExactKeys(value, expectedKeys, kind) {
|
|
180
|
+
for (const key of expectedKeys) {
|
|
181
|
+
if (!Object.hasOwn(value, key) || value[key] === void 0) {
|
|
182
|
+
throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const expected = new Set(expectedKeys);
|
|
186
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
187
|
+
if (!expected.has(key)) {
|
|
188
|
+
throw new JobEnvelopeError(
|
|
189
|
+
`Invalid ${kind}: unknown field ${String(key)}`
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function requireString(value, field, kind) {
|
|
195
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
196
|
+
throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function validateJobRequest(value) {
|
|
200
|
+
requirePlainObject(value, "request", "job request");
|
|
201
|
+
requireExactKeys(
|
|
202
|
+
value,
|
|
203
|
+
[
|
|
204
|
+
"v",
|
|
205
|
+
"jobId",
|
|
206
|
+
"owner",
|
|
207
|
+
"builder",
|
|
208
|
+
"builderPublicKey",
|
|
209
|
+
"grantId",
|
|
210
|
+
"scope",
|
|
211
|
+
"operation",
|
|
212
|
+
"pinnedVersion",
|
|
213
|
+
"deadline"
|
|
214
|
+
],
|
|
215
|
+
"job request"
|
|
216
|
+
);
|
|
217
|
+
if (value.v !== JOB_PROTOCOL_VERSION) {
|
|
218
|
+
throw new JobEnvelopeError(
|
|
219
|
+
`Unsupported job request version: ${String(value.v)}`
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
requireString(value.jobId, "jobId", "job request");
|
|
223
|
+
if (typeof value.owner !== "string" || !isAddress(value.owner)) {
|
|
224
|
+
throw new JobEnvelopeError("Invalid job request: invalid owner");
|
|
225
|
+
}
|
|
226
|
+
if (typeof value.builder !== "string" || !isAddress(value.builder)) {
|
|
227
|
+
throw new JobEnvelopeError("Invalid job request: invalid builder");
|
|
228
|
+
}
|
|
229
|
+
if (typeof value.builderPublicKey !== "string" || !isHex(value.builderPublicKey)) {
|
|
230
|
+
throw new JobEnvelopeError("Invalid job request: invalid builderPublicKey");
|
|
231
|
+
}
|
|
232
|
+
if (typeof value.grantId !== "string" || !isHex(value.grantId)) {
|
|
233
|
+
throw new JobEnvelopeError("Invalid job request: invalid grantId");
|
|
234
|
+
}
|
|
235
|
+
requireString(value.scope, "scope", "job request");
|
|
236
|
+
if (!JOB_OPERATIONS.includes(value.operation)) {
|
|
237
|
+
throw new JobEnvelopeError("Invalid job request: invalid operation");
|
|
238
|
+
}
|
|
239
|
+
if (value.pinnedVersion !== null && typeof value.pinnedVersion !== "string") {
|
|
240
|
+
throw new JobEnvelopeError("Invalid job request: missing pinnedVersion");
|
|
241
|
+
}
|
|
242
|
+
if (typeof value.deadline !== "string" || !Number.isFinite(Date.parse(value.deadline))) {
|
|
243
|
+
throw new JobEnvelopeError("Invalid job request: invalid deadline");
|
|
244
|
+
}
|
|
245
|
+
return value;
|
|
246
|
+
}
|
|
247
|
+
function validateRequestEnvelope(value) {
|
|
248
|
+
requirePlainObject(value, "envelope", "job request envelope");
|
|
249
|
+
requireExactKeys(value, ["request", "auth"], "job request envelope");
|
|
250
|
+
validateJobRequest(value.request);
|
|
251
|
+
requireString(value.auth, "auth", "job request envelope");
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
function validateResult(value) {
|
|
255
|
+
requirePlainObject(value, "result", "job result");
|
|
256
|
+
requireExactKeys(
|
|
257
|
+
value,
|
|
258
|
+
["v", "jobId", "scope", "version", "contentType", "body"],
|
|
259
|
+
"job result"
|
|
260
|
+
);
|
|
261
|
+
if (value.v !== JOB_PROTOCOL_VERSION) {
|
|
262
|
+
throw new JobEnvelopeError(
|
|
263
|
+
`Unsupported job result version: ${String(value.v)}`
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
for (const field of ["jobId", "scope", "contentType"]) {
|
|
267
|
+
requireString(value[field], field, "job result");
|
|
268
|
+
}
|
|
269
|
+
if (!(value.body instanceof Uint8Array)) {
|
|
270
|
+
throw new JobEnvelopeError("Invalid job result: missing body");
|
|
271
|
+
}
|
|
272
|
+
if (value.version !== null && typeof value.version !== "string") {
|
|
273
|
+
throw new JobEnvelopeError("Invalid job result: missing version");
|
|
274
|
+
}
|
|
275
|
+
return value;
|
|
276
|
+
}
|
|
277
|
+
async function sealJobRequest(envelope, enclavePublicKey, ecies) {
|
|
278
|
+
const encrypted = await ecies.encrypt(
|
|
279
|
+
fromHex(enclavePublicKey, "bytes"),
|
|
280
|
+
requestPlaintext(envelope)
|
|
281
|
+
);
|
|
282
|
+
return encryptedBytesToBase64(encrypted);
|
|
283
|
+
}
|
|
284
|
+
async function openJobRequest(ciphertext, privateKey, ecies) {
|
|
285
|
+
const plaintext = await ecies.decrypt(
|
|
286
|
+
privateKey,
|
|
287
|
+
base64ToEncrypted(ciphertext)
|
|
288
|
+
);
|
|
289
|
+
return validateRequestEnvelope(
|
|
290
|
+
parseObject(plaintext, "job request envelope")
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
async function sealJobResult(result, builderPublicKey, ecies) {
|
|
294
|
+
validateResult(result);
|
|
295
|
+
const encrypted = await ecies.encrypt(
|
|
296
|
+
fromHex(builderPublicKey, "bytes"),
|
|
297
|
+
resultPlaintext(result)
|
|
298
|
+
);
|
|
299
|
+
const bytes = encryptedToBytes(encrypted);
|
|
300
|
+
return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };
|
|
301
|
+
}
|
|
302
|
+
async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
|
|
303
|
+
const plaintext = await ecies.decrypt(
|
|
304
|
+
fromHex(builderPrivateKey, "bytes"),
|
|
305
|
+
bytesToEncrypted(sealedBytes)
|
|
306
|
+
);
|
|
307
|
+
const result = parseResultPlaintext(plaintext);
|
|
308
|
+
if (result.jobId !== expect.jobId) {
|
|
309
|
+
throw new JobEnvelopeError(
|
|
310
|
+
`Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
if (expect.scope !== void 0 && result.scope !== expect.scope) {
|
|
314
|
+
throw new JobEnvelopeError(
|
|
315
|
+
`Job result scope ${result.scope} does not match expected scope ${expect.scope}`
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
if (expect.version !== void 0 && result.version !== expect.version) {
|
|
319
|
+
throw new JobEnvelopeError(
|
|
320
|
+
`Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
return result;
|
|
324
|
+
}
|
|
325
|
+
export {
|
|
326
|
+
JobEnvelopeError,
|
|
327
|
+
canonicalJobRequestBytes,
|
|
328
|
+
openJobRequest,
|
|
329
|
+
openJobResult,
|
|
330
|
+
sealJobRequest,
|
|
331
|
+
sealJobResult
|
|
332
|
+
};
|
|
333
|
+
//# sourceMappingURL=job.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result plaintext is\n * `uint32be(header length) || JSON header || raw body`. The Request ciphertext\n * is base64 of `iv || ephemPub || ct || mac`, as specified\n * by the ECIES provider interface. Result ciphertext is the raw concatenated\n * byte sequence stored in object storage. The Gateway hashes raw ciphertext\n * bytes, not plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport { CURVE, FORMAT, MAC } from \"../ecies/constants\";\nimport {\n deserializeECIES,\n ECIESError,\n serializeECIES,\n type ECIESEncrypted,\n type ECIESProvider,\n} from \"../ecies/interface\";\nimport {\n JOB_OPERATIONS,\n JOB_PROTOCOL_VERSION,\n type JobOperation,\n type JobRequest,\n type JobRequestEnvelope,\n type JobResult,\n} from \"../../protocol/jobs\";\nimport { fromBase64, toBase64 } from \"../../utils/encoding\";\n\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\n/** Result metadata is only a few short fields; cap it before decoding attacker-reachable bytes. */\nconst MAX_JOB_RESULT_HEADER_BYTES = 4096;\nconst JOB_RESULT_LENGTH_PREFIX_BYTES = 4;\n\n/** A job envelope or result did not match the jobs protocol. */\nexport class JobEnvelopeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JobEnvelopeError\";\n }\n}\n\nfunction sortJsonKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJsonKeys);\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n sortJsonKeys((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n}\n\nfunction canonicalJsonBytes(value: unknown): Uint8Array {\n return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));\n}\n\n/**\n * Returns the canonical UTF-8 JSON bytes committed to by the auth body hash.\n *\n * @param request - Job request to validate and serialize canonically.\n * @returns Recursively key-sorted, whitespace-free UTF-8 JSON bytes.\n * @throws {JobEnvelopeError} If the request does not match the protocol schema.\n */\nexport function canonicalJobRequestBytes(request: JobRequest): Uint8Array {\n validateJobRequest(request);\n return canonicalJsonBytes(request);\n}\n\nfunction requestPlaintext(envelope: JobRequestEnvelope): Uint8Array {\n validateRequestEnvelope(envelope);\n return canonicalJsonBytes(envelope);\n}\n\nfunction resultPlaintext(result: JobResult): Uint8Array {\n const header = textEncoder.encode(\n JSON.stringify({\n v: result.v,\n jobId: result.jobId,\n scope: result.scope,\n version: result.version,\n contentType: result.contentType,\n }),\n );\n if (header.length > MAX_JOB_RESULT_HEADER_BYTES) {\n throw new JobEnvelopeError(\n `Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`,\n );\n }\n\n const plaintext = new Uint8Array(\n JOB_RESULT_LENGTH_PREFIX_BYTES + header.length + result.body.length,\n );\n new DataView(plaintext.buffer).setUint32(0, header.length);\n plaintext.set(header, JOB_RESULT_LENGTH_PREFIX_BYTES);\n plaintext.set(result.body, JOB_RESULT_LENGTH_PREFIX_BYTES + header.length);\n return plaintext;\n}\n\nfunction parseResultPlaintext(plaintext: Uint8Array): JobResult {\n if (plaintext.length < JOB_RESULT_LENGTH_PREFIX_BYTES) {\n throw new JobEnvelopeError(\n \"Invalid job result: missing header length prefix\",\n );\n }\n\n const headerLength = new DataView(\n plaintext.buffer,\n plaintext.byteOffset,\n JOB_RESULT_LENGTH_PREFIX_BYTES,\n ).getUint32(0);\n if (headerLength > MAX_JOB_RESULT_HEADER_BYTES) {\n throw new JobEnvelopeError(\n `Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`,\n );\n }\n const remainingLength = plaintext.length - JOB_RESULT_LENGTH_PREFIX_BYTES;\n if (headerLength > remainingLength) {\n throw new JobEnvelopeError(\n \"Invalid job result: header length exceeds payload\",\n );\n }\n\n const headerEnd = JOB_RESULT_LENGTH_PREFIX_BYTES + headerLength;\n const header = parseObject(\n plaintext.subarray(JOB_RESULT_LENGTH_PREFIX_BYTES, headerEnd),\n \"job result header\",\n );\n return validateResult({ ...header, body: plaintext.subarray(headerEnd) });\n}\n\nfunction encryptedBytesToBase64(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): string {\n return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\"));\n}\n\nfunction encryptedToBytes(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): Uint8Array {\n const bytes = new Uint8Array(\n encrypted.iv.length +\n encrypted.ephemPublicKey.length +\n encrypted.ciphertext.length +\n encrypted.mac.length,\n );\n let offset = 0;\n bytes.set(encrypted.iv, offset);\n offset += encrypted.iv.length;\n bytes.set(encrypted.ephemPublicKey, offset);\n offset += encrypted.ephemPublicKey.length;\n bytes.set(encrypted.ciphertext, offset);\n offset += encrypted.ciphertext.length;\n bytes.set(encrypted.mac, offset);\n return bytes;\n}\n\nfunction bytesToEncrypted(bytes: Uint8Array): ECIESEncrypted {\n const absoluteMinLength = FORMAT.IV_LENGTH + 1 + MAC.LENGTH + 1;\n if (bytes.length < absoluteMinLength) {\n throw new ECIESError(\n `Invalid ECIES data: too short (${bytes.length} bytes, minimum ${absoluteMinLength} bytes required)`,\n \"DECRYPTION_FAILED\",\n );\n }\n\n const prefix = bytes[FORMAT.EPHEMERAL_KEY_OFFSET];\n if (prefix !== CURVE.PREFIX.UNCOMPRESSED) {\n throw new ECIESError(\n `Invalid ephemeral public key: must be uncompressed format (0x04 prefix), got 0x${prefix.toString(16).padStart(2, \"0\")}`,\n \"DECRYPTION_FAILED\",\n );\n }\n\n const ephemKeySize = CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH;\n const minLength = FORMAT.IV_LENGTH + ephemKeySize + MAC.LENGTH + 1;\n if (bytes.length < minLength) {\n throw new ECIESError(\n `Invalid ECIES data: too short (${bytes.length} bytes, minimum ${minLength} bytes required)`,\n \"DECRYPTION_FAILED\",\n );\n }\n\n return {\n iv: bytes.subarray(FORMAT.IV_OFFSET, FORMAT.IV_OFFSET + FORMAT.IV_LENGTH),\n ephemPublicKey: bytes.subarray(\n FORMAT.EPHEMERAL_KEY_OFFSET,\n FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,\n ),\n ciphertext: bytes.subarray(\n FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,\n bytes.length - MAC.LENGTH,\n ),\n mac: bytes.subarray(bytes.length - MAC.LENGTH),\n };\n}\n\nfunction base64ToEncrypted(ciphertext: string) {\n return deserializeECIES(toHex(fromBase64(ciphertext)));\n}\n\nfunction parseObject(\n plaintext: Uint8Array,\n kind: string,\n): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(textDecoder.decode(plaintext));\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);\n }\n return value as Record<string, unknown>;\n } catch (error) {\n if (error instanceof JobEnvelopeError) throw error;\n throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction requirePlainObject(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);\n }\n}\n\nfunction requireExactKeys(\n value: Record<string, unknown>,\n expectedKeys: readonly string[],\n kind: string,\n): void {\n for (const key of expectedKeys) {\n if (!Object.hasOwn(value, key) || value[key] === undefined) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);\n }\n }\n const expected = new Set<PropertyKey>(expectedKeys);\n for (const key of Reflect.ownKeys(value)) {\n if (!expected.has(key)) {\n throw new JobEnvelopeError(\n `Invalid ${kind}: unknown field ${String(key)}`,\n );\n }\n }\n}\n\nfunction requireString(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);\n }\n}\n\nfunction validateJobRequest(value: unknown): JobRequest {\n requirePlainObject(value, \"request\", \"job request\");\n requireExactKeys(\n value,\n [\n \"v\",\n \"jobId\",\n \"owner\",\n \"builder\",\n \"builderPublicKey\",\n \"grantId\",\n \"scope\",\n \"operation\",\n \"pinnedVersion\",\n \"deadline\",\n ],\n \"job request\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job request version: ${String(value.v)}`,\n );\n }\n requireString(value.jobId, \"jobId\", \"job request\");\n if (typeof value.owner !== \"string\" || !isAddress(value.owner)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid owner\");\n }\n if (typeof value.builder !== \"string\" || !isAddress(value.builder)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builder\");\n }\n if (\n typeof value.builderPublicKey !== \"string\" ||\n !isHex(value.builderPublicKey)\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builderPublicKey\");\n }\n if (typeof value.grantId !== \"string\" || !isHex(value.grantId)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid grantId\");\n }\n requireString(value.scope, \"scope\", \"job request\");\n if (!JOB_OPERATIONS.includes(value.operation as JobOperation)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid operation\");\n }\n if (value.pinnedVersion !== null && typeof value.pinnedVersion !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job request: missing pinnedVersion\");\n }\n if (\n typeof value.deadline !== \"string\" ||\n !Number.isFinite(Date.parse(value.deadline))\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid deadline\");\n }\n return value as unknown as JobRequest;\n}\n\nfunction validateRequestEnvelope(value: unknown): JobRequestEnvelope {\n requirePlainObject(value, \"envelope\", \"job request envelope\");\n requireExactKeys(value, [\"request\", \"auth\"], \"job request envelope\");\n validateJobRequest(value.request);\n requireString(value.auth, \"auth\", \"job request envelope\");\n return value as unknown as JobRequestEnvelope;\n}\n\nfunction validateResult(value: unknown): JobResult {\n requirePlainObject(value, \"result\", \"job result\");\n requireExactKeys(\n value,\n [\"v\", \"jobId\", \"scope\", \"version\", \"contentType\", \"body\"],\n \"job result\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job result version: ${String(value.v)}`,\n );\n }\n for (const field of [\"jobId\", \"scope\", \"contentType\"]) {\n requireString(value[field], field, \"job result\");\n }\n if (!(value.body instanceof Uint8Array)) {\n throw new JobEnvelopeError(\"Invalid job result: missing body\");\n }\n if (value.version !== null && typeof value.version !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing version\");\n }\n return value as unknown as JobResult;\n}\n\n/**\n * Encrypts a validated job request envelope for a Personal Server enclave.\n *\n * The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext.\n *\n * @param envelope - Request and builder Web3Signed authorization to encrypt.\n * @param enclavePublicKey - Public key returned by `GET /v1/identity?owner=`.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext encoded as `iv || ephemPub || ct || mac`.\n * @throws {JobEnvelopeError} If the envelope or request is invalid.\n * @throws If ECIES encryption fails or the enclave public key is invalid.\n *\n * @example\n * ```ts\n * const identity = await fetch(`/v1/identity?owner=${owner}`).then((response) =>\n * response.json(),\n * );\n * const requestCiphertext = await sealJobRequest(\n * requestEnvelope,\n * identity.publicKey,\n * ecies,\n * );\n * await fetch(\"/v1/jobs\", {\n * method: \"POST\",\n * body: JSON.stringify({ ...submission, requestCiphertext }),\n * });\n * ```\n */\nexport async function sealJobRequest(\n envelope: JobRequestEnvelope,\n enclavePublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<string> {\n const encrypted = await ecies.encrypt(\n fromHex(enclavePublicKey, \"bytes\"),\n requestPlaintext(envelope),\n );\n return encryptedBytesToBase64(encrypted);\n}\n\n/**\n * Decrypts and validates a job request envelope inside the enclave.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param privateKey - Enclave key bytes, supplied as `Uint8Array` so the agent can zero them after use.\n * @param ecies - Injected ECIES implementation.\n * @returns The validated request envelope exactly as parsed from plaintext.\n * @throws {JobEnvelopeError} If plaintext is malformed or fails schema validation.\n * @throws If ciphertext decoding or ECIES decryption fails.\n */\nexport async function openJobRequest(\n ciphertext: string,\n privateKey: Uint8Array,\n ecies: ECIESProvider,\n): Promise<JobRequestEnvelope> {\n const plaintext = await ecies.decrypt(\n privateKey,\n base64ToEncrypted(ciphertext),\n );\n return validateRequestEnvelope(\n parseObject(plaintext, \"job request envelope\"),\n );\n}\n\n/**\n * Encrypts a validated job result for its builder and describes the ciphertext.\n *\n * `hash` is lowercase `0x` SHA-256 of the raw sealed bytes, not the `sha256:`\n * prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They\n * equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Raw sealed bytes plus their Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ bytes: Uint8Array; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const bytes = encryptedToBytes(encrypted);\n return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const sealedBytes = new Uint8Array(await response.arrayBuffer());\n * const result = await openJobResult(sealedBytes, key, ecies, {\n * jobId,\n * scope,\n * });\n * const text = new TextDecoder().decode(result.body);\n * ```\n */\nexport async function openJobResult(\n sealedBytes: Uint8Array,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n bytesToEncrypted(sealedBytes),\n );\n const result = parseResultPlaintext(plaintext);\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":"AAmBA,SAAS,cAAc;AACvB,SAAS,YAAY,SAAS,WAAW,OAAO,aAAuB;AACvE,SAAS,OAAO,QAAQ,WAAW;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,SAAS,YAAY,gBAAgB;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAEpC,MAAM,8BAA8B;AACpC,MAAM,iCAAiC;AAGhC,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,aAAa,OAAyB;AAC7C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,YAAY;AAAA,EAC/B;AACA,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO;AAAA,MACZ,OAAO,KAAK,KAAK,EACd,KAAK,EACL,IAAI,CAAC,QAAQ;AAAA,QACZ;AAAA,QACA,aAAc,MAAkC,GAAG,CAAC;AAAA,MACtD,CAAC;AAAA,IACL;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,mBAAmB,OAA4B;AACtD,SAAO,YAAY,OAAO,KAAK,UAAU,aAAa,KA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|
@@ -38,6 +38,9 @@ const VALID_STATUSES = [
|
|
|
38
38
|
function normalizeStatus(value) {
|
|
39
39
|
return VALID_STATUSES.includes(value) ? value : "pending";
|
|
40
40
|
}
|
|
41
|
+
function normalizeDelivery(value) {
|
|
42
|
+
return value === "enclave" || value === "personal_server" ? value : void 0;
|
|
43
|
+
}
|
|
41
44
|
function normalizeNetwork(value) {
|
|
42
45
|
return value === "mainnet" || value === "moksha" ? value : void 0;
|
|
43
46
|
}
|
|
@@ -258,6 +261,7 @@ function createDefaultAccessRequestClient(options) {
|
|
|
258
261
|
const scopes = body.scopes && body.scopes.length > 0 ? body.scopes : body.scope ? [body.scope] : void 0;
|
|
259
262
|
return {
|
|
260
263
|
status: normalizeStatus(body.status),
|
|
264
|
+
delivery: normalizeDelivery(body.delivery),
|
|
261
265
|
personalServerUrl: body.personalServerUrl,
|
|
262
266
|
grantId: body.grantId,
|
|
263
267
|
scope: body.scope ?? scopes?.[0],
|
|
@@ -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 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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAA+C;AAE/C,oBAA6C;AAC7C,oBAAkC;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,WAA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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,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 AccessRequestDelivery,\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 normalizeDelivery(value: unknown): AccessRequestDelivery | undefined {\n return value === \"enclave\" || value === \"personal_server\" ? value : undefined;\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 delivery?: unknown;\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 delivery: normalizeDelivery(body.delivery),\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;AAAA;AAsBA,mBAA+C;AAE/C,oBAA6C;AAC7C,oBAAkC;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,kBAAkB,OAAmD;AAC5E,SAAO,UAAU,aAAa,UAAU,oBAAoB,QAAQ;AACtE;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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M,IAAI,IAAI,UAAU;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -12,6 +12,9 @@ const VALID_STATUSES = [
|
|
|
12
12
|
function normalizeStatus(value) {
|
|
13
13
|
return VALID_STATUSES.includes(value) ? value : "pending";
|
|
14
14
|
}
|
|
15
|
+
function normalizeDelivery(value) {
|
|
16
|
+
return value === "enclave" || value === "personal_server" ? value : void 0;
|
|
17
|
+
}
|
|
15
18
|
function normalizeNetwork(value) {
|
|
16
19
|
return value === "mainnet" || value === "moksha" ? value : void 0;
|
|
17
20
|
}
|
|
@@ -232,6 +235,7 @@ function createDefaultAccessRequestClient(options) {
|
|
|
232
235
|
const scopes = body.scopes && body.scopes.length > 0 ? body.scopes : body.scope ? [body.scope] : void 0;
|
|
233
236
|
return {
|
|
234
237
|
status: normalizeStatus(body.status),
|
|
238
|
+
delivery: normalizeDelivery(body.delivery),
|
|
235
239
|
personalServerUrl: body.personalServerUrl,
|
|
236
240
|
grantId: body.grantId,
|
|
237
241
|
scope: body.scope ?? scopes?.[0],
|