@opendatalabs/vana-sdk 3.22.0 → 3.23.0-pr.211.1da7c1b
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 +313 -0
- package/dist/crypto/envelope/job.cjs.map +1 -0
- package/dist/crypto/envelope/job.d.ts +122 -0
- package/dist/crypto/envelope/job.js +291 -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 +589 -24
- package/dist/index.browser.js.map +4 -4
- package/dist/index.node.cjs +1217 -111
- package/dist/index.node.cjs.map +4 -4
- package/dist/index.node.d.ts +4 -0
- package/dist/index.node.js +1181 -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 +192 -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,313 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var job_exports = {};
|
|
20
|
+
__export(job_exports, {
|
|
21
|
+
JobEnvelopeError: () => JobEnvelopeError,
|
|
22
|
+
canonicalJobRequestBytes: () => canonicalJobRequestBytes,
|
|
23
|
+
openJobRequest: () => openJobRequest,
|
|
24
|
+
openJobResult: () => openJobResult,
|
|
25
|
+
sealJobRequest: () => sealJobRequest,
|
|
26
|
+
sealJobResult: () => sealJobResult
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(job_exports);
|
|
29
|
+
var import_sha2 = require("@noble/hashes/sha2");
|
|
30
|
+
var import_viem = require("viem");
|
|
31
|
+
var import_constants = require("../ecies/constants");
|
|
32
|
+
var import_interface = require("../ecies/interface");
|
|
33
|
+
var import_jobs = require("../../protocol/jobs");
|
|
34
|
+
var import_encoding = require("../../utils/encoding");
|
|
35
|
+
const textDecoder = new TextDecoder();
|
|
36
|
+
const textEncoder = new TextEncoder();
|
|
37
|
+
class JobEnvelopeError extends Error {
|
|
38
|
+
constructor(message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = "JobEnvelopeError";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function sortJsonKeys(value) {
|
|
44
|
+
if (Array.isArray(value)) {
|
|
45
|
+
return value.map(sortJsonKeys);
|
|
46
|
+
}
|
|
47
|
+
if (value !== null && typeof value === "object") {
|
|
48
|
+
return Object.fromEntries(
|
|
49
|
+
Object.keys(value).sort().map((key) => [
|
|
50
|
+
key,
|
|
51
|
+
sortJsonKeys(value[key])
|
|
52
|
+
])
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
function canonicalJsonBytes(value) {
|
|
58
|
+
return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));
|
|
59
|
+
}
|
|
60
|
+
function canonicalJobRequestBytes(request) {
|
|
61
|
+
validateJobRequest(request);
|
|
62
|
+
return canonicalJsonBytes(request);
|
|
63
|
+
}
|
|
64
|
+
function requestPlaintext(envelope) {
|
|
65
|
+
validateRequestEnvelope(envelope);
|
|
66
|
+
return canonicalJsonBytes(envelope);
|
|
67
|
+
}
|
|
68
|
+
function resultPlaintext(result) {
|
|
69
|
+
return textEncoder.encode(
|
|
70
|
+
JSON.stringify({
|
|
71
|
+
v: result.v,
|
|
72
|
+
jobId: result.jobId,
|
|
73
|
+
scope: result.scope,
|
|
74
|
+
version: result.version,
|
|
75
|
+
contentType: result.contentType,
|
|
76
|
+
body: result.body
|
|
77
|
+
})
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
function encryptedBytesToBase64(encrypted) {
|
|
81
|
+
return (0, import_encoding.toBase64)((0, import_viem.fromHex)(`0x${(0, import_interface.serializeECIES)(encrypted)}`, "bytes"));
|
|
82
|
+
}
|
|
83
|
+
function encryptedToBytes(encrypted) {
|
|
84
|
+
const bytes = new Uint8Array(
|
|
85
|
+
encrypted.iv.length + encrypted.ephemPublicKey.length + encrypted.ciphertext.length + encrypted.mac.length
|
|
86
|
+
);
|
|
87
|
+
let offset = 0;
|
|
88
|
+
bytes.set(encrypted.iv, offset);
|
|
89
|
+
offset += encrypted.iv.length;
|
|
90
|
+
bytes.set(encrypted.ephemPublicKey, offset);
|
|
91
|
+
offset += encrypted.ephemPublicKey.length;
|
|
92
|
+
bytes.set(encrypted.ciphertext, offset);
|
|
93
|
+
offset += encrypted.ciphertext.length;
|
|
94
|
+
bytes.set(encrypted.mac, offset);
|
|
95
|
+
return bytes;
|
|
96
|
+
}
|
|
97
|
+
function bytesToEncrypted(bytes) {
|
|
98
|
+
const absoluteMinLength = import_constants.FORMAT.IV_LENGTH + 1 + import_constants.MAC.LENGTH + 1;
|
|
99
|
+
if (bytes.length < absoluteMinLength) {
|
|
100
|
+
throw new import_interface.ECIESError(
|
|
101
|
+
`Invalid ECIES data: too short (${bytes.length} bytes, minimum ${absoluteMinLength} bytes required)`,
|
|
102
|
+
"DECRYPTION_FAILED"
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
const prefix = bytes[import_constants.FORMAT.EPHEMERAL_KEY_OFFSET];
|
|
106
|
+
if (prefix !== import_constants.CURVE.PREFIX.UNCOMPRESSED) {
|
|
107
|
+
throw new import_interface.ECIESError(
|
|
108
|
+
`Invalid ephemeral public key: must be uncompressed format (0x04 prefix), got 0x${prefix.toString(16).padStart(2, "0")}`,
|
|
109
|
+
"DECRYPTION_FAILED"
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
const ephemKeySize = import_constants.CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH;
|
|
113
|
+
const minLength = import_constants.FORMAT.IV_LENGTH + ephemKeySize + import_constants.MAC.LENGTH + 1;
|
|
114
|
+
if (bytes.length < minLength) {
|
|
115
|
+
throw new import_interface.ECIESError(
|
|
116
|
+
`Invalid ECIES data: too short (${bytes.length} bytes, minimum ${minLength} bytes required)`,
|
|
117
|
+
"DECRYPTION_FAILED"
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
iv: bytes.subarray(import_constants.FORMAT.IV_OFFSET, import_constants.FORMAT.IV_OFFSET + import_constants.FORMAT.IV_LENGTH),
|
|
122
|
+
ephemPublicKey: bytes.subarray(
|
|
123
|
+
import_constants.FORMAT.EPHEMERAL_KEY_OFFSET,
|
|
124
|
+
import_constants.FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize
|
|
125
|
+
),
|
|
126
|
+
ciphertext: bytes.subarray(
|
|
127
|
+
import_constants.FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,
|
|
128
|
+
bytes.length - import_constants.MAC.LENGTH
|
|
129
|
+
),
|
|
130
|
+
mac: bytes.subarray(bytes.length - import_constants.MAC.LENGTH)
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function base64ToEncrypted(ciphertext) {
|
|
134
|
+
return (0, import_interface.deserializeECIES)((0, import_viem.toHex)((0, import_encoding.fromBase64)(ciphertext)));
|
|
135
|
+
}
|
|
136
|
+
function parseObject(plaintext, kind) {
|
|
137
|
+
try {
|
|
138
|
+
const value = JSON.parse(textDecoder.decode(plaintext));
|
|
139
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
140
|
+
throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);
|
|
141
|
+
}
|
|
142
|
+
return value;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (error instanceof JobEnvelopeError) throw error;
|
|
145
|
+
throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function isPlainObject(value) {
|
|
149
|
+
if (value === null || typeof value !== "object") return false;
|
|
150
|
+
const prototype = Object.getPrototypeOf(value);
|
|
151
|
+
return prototype === Object.prototype || prototype === null;
|
|
152
|
+
}
|
|
153
|
+
function requirePlainObject(value, field, kind) {
|
|
154
|
+
if (!isPlainObject(value)) {
|
|
155
|
+
throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function requireExactKeys(value, expectedKeys, kind) {
|
|
159
|
+
for (const key of expectedKeys) {
|
|
160
|
+
if (!Object.hasOwn(value, key) || value[key] === void 0) {
|
|
161
|
+
throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const expected = new Set(expectedKeys);
|
|
165
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
166
|
+
if (!expected.has(key)) {
|
|
167
|
+
throw new JobEnvelopeError(
|
|
168
|
+
`Invalid ${kind}: unknown field ${String(key)}`
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function requireString(value, field, kind) {
|
|
174
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
175
|
+
throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function validateJobRequest(value) {
|
|
179
|
+
requirePlainObject(value, "request", "job request");
|
|
180
|
+
requireExactKeys(
|
|
181
|
+
value,
|
|
182
|
+
[
|
|
183
|
+
"v",
|
|
184
|
+
"jobId",
|
|
185
|
+
"owner",
|
|
186
|
+
"builder",
|
|
187
|
+
"builderPublicKey",
|
|
188
|
+
"grantId",
|
|
189
|
+
"scope",
|
|
190
|
+
"operation",
|
|
191
|
+
"pinnedVersion",
|
|
192
|
+
"deadline"
|
|
193
|
+
],
|
|
194
|
+
"job request"
|
|
195
|
+
);
|
|
196
|
+
if (value.v !== import_jobs.JOB_PROTOCOL_VERSION) {
|
|
197
|
+
throw new JobEnvelopeError(
|
|
198
|
+
`Unsupported job request version: ${String(value.v)}`
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
requireString(value.jobId, "jobId", "job request");
|
|
202
|
+
if (typeof value.owner !== "string" || !(0, import_viem.isAddress)(value.owner)) {
|
|
203
|
+
throw new JobEnvelopeError("Invalid job request: invalid owner");
|
|
204
|
+
}
|
|
205
|
+
if (typeof value.builder !== "string" || !(0, import_viem.isAddress)(value.builder)) {
|
|
206
|
+
throw new JobEnvelopeError("Invalid job request: invalid builder");
|
|
207
|
+
}
|
|
208
|
+
if (typeof value.builderPublicKey !== "string" || !(0, import_viem.isHex)(value.builderPublicKey)) {
|
|
209
|
+
throw new JobEnvelopeError("Invalid job request: invalid builderPublicKey");
|
|
210
|
+
}
|
|
211
|
+
if (typeof value.grantId !== "string" || !(0, import_viem.isHex)(value.grantId)) {
|
|
212
|
+
throw new JobEnvelopeError("Invalid job request: invalid grantId");
|
|
213
|
+
}
|
|
214
|
+
requireString(value.scope, "scope", "job request");
|
|
215
|
+
if (!import_jobs.JOB_OPERATIONS.includes(value.operation)) {
|
|
216
|
+
throw new JobEnvelopeError("Invalid job request: invalid operation");
|
|
217
|
+
}
|
|
218
|
+
if (value.pinnedVersion !== null && typeof value.pinnedVersion !== "string") {
|
|
219
|
+
throw new JobEnvelopeError("Invalid job request: missing pinnedVersion");
|
|
220
|
+
}
|
|
221
|
+
if (typeof value.deadline !== "string" || !Number.isFinite(Date.parse(value.deadline))) {
|
|
222
|
+
throw new JobEnvelopeError("Invalid job request: invalid deadline");
|
|
223
|
+
}
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
function validateRequestEnvelope(value) {
|
|
227
|
+
requirePlainObject(value, "envelope", "job request envelope");
|
|
228
|
+
requireExactKeys(value, ["request", "auth"], "job request envelope");
|
|
229
|
+
validateJobRequest(value.request);
|
|
230
|
+
requireString(value.auth, "auth", "job request envelope");
|
|
231
|
+
return value;
|
|
232
|
+
}
|
|
233
|
+
function validateResult(value) {
|
|
234
|
+
requirePlainObject(value, "result", "job result");
|
|
235
|
+
requireExactKeys(
|
|
236
|
+
value,
|
|
237
|
+
["v", "jobId", "scope", "version", "contentType", "body"],
|
|
238
|
+
"job result"
|
|
239
|
+
);
|
|
240
|
+
if (value.v !== import_jobs.JOB_PROTOCOL_VERSION) {
|
|
241
|
+
throw new JobEnvelopeError(
|
|
242
|
+
`Unsupported job result version: ${String(value.v)}`
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
for (const field of ["jobId", "scope", "contentType"]) {
|
|
246
|
+
requireString(value[field], field, "job result");
|
|
247
|
+
}
|
|
248
|
+
if (typeof value.body !== "string") {
|
|
249
|
+
throw new JobEnvelopeError("Invalid job result: missing body");
|
|
250
|
+
}
|
|
251
|
+
if (value.version !== null && typeof value.version !== "string") {
|
|
252
|
+
throw new JobEnvelopeError("Invalid job result: missing version");
|
|
253
|
+
}
|
|
254
|
+
return value;
|
|
255
|
+
}
|
|
256
|
+
async function sealJobRequest(envelope, enclavePublicKey, ecies) {
|
|
257
|
+
const encrypted = await ecies.encrypt(
|
|
258
|
+
(0, import_viem.fromHex)(enclavePublicKey, "bytes"),
|
|
259
|
+
requestPlaintext(envelope)
|
|
260
|
+
);
|
|
261
|
+
return encryptedBytesToBase64(encrypted);
|
|
262
|
+
}
|
|
263
|
+
async function openJobRequest(ciphertext, privateKey, ecies) {
|
|
264
|
+
const plaintext = await ecies.decrypt(
|
|
265
|
+
privateKey,
|
|
266
|
+
base64ToEncrypted(ciphertext)
|
|
267
|
+
);
|
|
268
|
+
return validateRequestEnvelope(
|
|
269
|
+
parseObject(plaintext, "job request envelope")
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
async function sealJobResult(result, builderPublicKey, ecies) {
|
|
273
|
+
validateResult(result);
|
|
274
|
+
const encrypted = await ecies.encrypt(
|
|
275
|
+
(0, import_viem.fromHex)(builderPublicKey, "bytes"),
|
|
276
|
+
resultPlaintext(result)
|
|
277
|
+
);
|
|
278
|
+
const bytes = encryptedToBytes(encrypted);
|
|
279
|
+
return { bytes, hash: (0, import_viem.bytesToHex)((0, import_sha2.sha256)(bytes)), size: bytes.length };
|
|
280
|
+
}
|
|
281
|
+
async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
|
|
282
|
+
const plaintext = await ecies.decrypt(
|
|
283
|
+
(0, import_viem.fromHex)(builderPrivateKey, "bytes"),
|
|
284
|
+
bytesToEncrypted(sealedBytes)
|
|
285
|
+
);
|
|
286
|
+
const result = validateResult(parseObject(plaintext, "job result"));
|
|
287
|
+
if (result.jobId !== expect.jobId) {
|
|
288
|
+
throw new JobEnvelopeError(
|
|
289
|
+
`Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
if (expect.scope !== void 0 && result.scope !== expect.scope) {
|
|
293
|
+
throw new JobEnvelopeError(
|
|
294
|
+
`Job result scope ${result.scope} does not match expected scope ${expect.scope}`
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
if (expect.version !== void 0 && result.version !== expect.version) {
|
|
298
|
+
throw new JobEnvelopeError(
|
|
299
|
+
`Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
304
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
305
|
+
0 && (module.exports = {
|
|
306
|
+
JobEnvelopeError,
|
|
307
|
+
canonicalJobRequestBytes,
|
|
308
|
+
openJobRequest,
|
|
309
|
+
openJobResult,
|
|
310
|
+
sealJobRequest,
|
|
311
|
+
sealJobResult
|
|
312
|
+
});
|
|
313
|
+
//# sourceMappingURL=job.cjs.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 properties follow their interface order. The\n * Request ciphertext 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\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 return 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 body: result.body,\n }),\n );\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 (typeof value.body !== \"string\") {\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 body = fromBase64(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 = validateResult(parseObject(plaintext, \"job result\"));\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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,kBAAuB;AACvB,kBAAuE;AACvE,uBAAmC;AACnC,uBAMO;AACP,kBAOO;AACP,sBAAqC;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAG7B,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,KAAK,CAAC,CAAC;AAC/D;AASO,SAAS,yBAAyB,SAAiC;AACxE,qBAAmB,OAAO;AAC1B,SAAO,mBAAmB,OAAO;AACnC;AAEA,SAAS,iBAAiB,UAA0C;AAClE,0BAAwB,QAAQ;AAChC,SAAO,mBAAmB,QAAQ;AACpC;AAEA,SAAS,gBAAgB,QAA+B;AACtD,SAAO,YAAY;AAAA,IACjB,KAAK,UAAU;AAAA,MACb,GAAG,OAAO;AAAA,MACV,OAAO,OAAO;AAAA,MACd,OAAO,OAAO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AA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ECIES envelopes for encrypted job requests and results.
|
|
3
|
+
*
|
|
4
|
+
* Request plaintext is UTF-8 JSON with object keys sorted recursively and
|
|
5
|
+
* array order preserved. Result properties follow their interface order. The
|
|
6
|
+
* Request ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified
|
|
7
|
+
* by the ECIES provider interface. Result ciphertext is the raw concatenated
|
|
8
|
+
* byte sequence stored in object storage. The Gateway hashes raw ciphertext
|
|
9
|
+
* bytes, not plaintext.
|
|
10
|
+
* The builder verifies the decrypted result's job ID, scope, and version
|
|
11
|
+
* bindings. The PS worker verifies
|
|
12
|
+
* `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway
|
|
13
|
+
* never sees the plaintext. Flow: personal-server-ts
|
|
14
|
+
* `docs/260903-jobs-contract.md`, section 1.
|
|
15
|
+
*
|
|
16
|
+
* @category Cryptography
|
|
17
|
+
*/
|
|
18
|
+
import { type Hex } from "viem";
|
|
19
|
+
import { type ECIESProvider } from "../ecies/interface.js";
|
|
20
|
+
import { type JobRequest, type JobRequestEnvelope, type JobResult } from "../../protocol/jobs.js";
|
|
21
|
+
/** A job envelope or result did not match the jobs protocol. */
|
|
22
|
+
export declare class JobEnvelopeError extends Error {
|
|
23
|
+
constructor(message: string);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Returns the canonical UTF-8 JSON bytes committed to by the auth body hash.
|
|
27
|
+
*
|
|
28
|
+
* @param request - Job request to validate and serialize canonically.
|
|
29
|
+
* @returns Recursively key-sorted, whitespace-free UTF-8 JSON bytes.
|
|
30
|
+
* @throws {JobEnvelopeError} If the request does not match the protocol schema.
|
|
31
|
+
*/
|
|
32
|
+
export declare function canonicalJobRequestBytes(request: JobRequest): Uint8Array;
|
|
33
|
+
/**
|
|
34
|
+
* Encrypts a validated job request envelope for a Personal Server enclave.
|
|
35
|
+
*
|
|
36
|
+
* The PS worker verifies
|
|
37
|
+
* `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway
|
|
38
|
+
* never sees the plaintext.
|
|
39
|
+
*
|
|
40
|
+
* @param envelope - Request and builder Web3Signed authorization to encrypt.
|
|
41
|
+
* @param enclavePublicKey - Public key returned by `GET /v1/identity?owner=`.
|
|
42
|
+
* @param ecies - Injected ECIES implementation.
|
|
43
|
+
* @returns Base64 ciphertext encoded as `iv || ephemPub || ct || mac`.
|
|
44
|
+
* @throws {JobEnvelopeError} If the envelope or request is invalid.
|
|
45
|
+
* @throws If ECIES encryption fails or the enclave public key is invalid.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```ts
|
|
49
|
+
* const identity = await fetch(`/v1/identity?owner=${owner}`).then((response) =>
|
|
50
|
+
* response.json(),
|
|
51
|
+
* );
|
|
52
|
+
* const requestCiphertext = await sealJobRequest(
|
|
53
|
+
* requestEnvelope,
|
|
54
|
+
* identity.publicKey,
|
|
55
|
+
* ecies,
|
|
56
|
+
* );
|
|
57
|
+
* await fetch("/v1/jobs", {
|
|
58
|
+
* method: "POST",
|
|
59
|
+
* body: JSON.stringify({ ...submission, requestCiphertext }),
|
|
60
|
+
* });
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export declare function sealJobRequest(envelope: JobRequestEnvelope, enclavePublicKey: Hex, ecies: ECIESProvider): Promise<string>;
|
|
64
|
+
/**
|
|
65
|
+
* Decrypts and validates a job request envelope inside the enclave.
|
|
66
|
+
*
|
|
67
|
+
* @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.
|
|
68
|
+
* @param privateKey - Enclave key bytes, supplied as `Uint8Array` so the agent can zero them after use.
|
|
69
|
+
* @param ecies - Injected ECIES implementation.
|
|
70
|
+
* @returns The validated request envelope exactly as parsed from plaintext.
|
|
71
|
+
* @throws {JobEnvelopeError} If plaintext is malformed or fails schema validation.
|
|
72
|
+
* @throws If ciphertext decoding or ECIES decryption fails.
|
|
73
|
+
*/
|
|
74
|
+
export declare function openJobRequest(ciphertext: string, privateKey: Uint8Array, ecies: ECIESProvider): Promise<JobRequestEnvelope>;
|
|
75
|
+
/**
|
|
76
|
+
* Encrypts a validated job result for its builder and describes the ciphertext.
|
|
77
|
+
*
|
|
78
|
+
* `hash` is lowercase `0x` SHA-256 of the raw sealed bytes, not the `sha256:`
|
|
79
|
+
* prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They
|
|
80
|
+
* equal the Gateway's `resultHash` and `resultSize`.
|
|
81
|
+
*
|
|
82
|
+
* @param result - Job result to validate and encrypt.
|
|
83
|
+
* @param builderPublicKey - Builder wallet public key recorded in the request.
|
|
84
|
+
* @param ecies - Injected ECIES implementation.
|
|
85
|
+
* @returns Raw sealed bytes plus their Gateway-compatible hash and size.
|
|
86
|
+
* @throws {JobEnvelopeError} If the result does not match the protocol schema.
|
|
87
|
+
* @throws If ECIES encryption fails or the builder public key is invalid.
|
|
88
|
+
*/
|
|
89
|
+
export declare function sealJobResult(result: JobResult, builderPublicKey: Hex, ecies: ECIESProvider): Promise<{
|
|
90
|
+
bytes: Uint8Array;
|
|
91
|
+
hash: Hex;
|
|
92
|
+
size: number;
|
|
93
|
+
}>;
|
|
94
|
+
/**
|
|
95
|
+
* Decrypts a job result and verifies its builder-visible protocol bindings.
|
|
96
|
+
*
|
|
97
|
+
* The builder private key is a `Hex` wallet key. For `expect.version`,
|
|
98
|
+
* `undefined` skips the check while `null` requires a null result version.
|
|
99
|
+
*
|
|
100
|
+
* @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.
|
|
101
|
+
* @param builderPrivateKey - Builder's wallet private key as hex.
|
|
102
|
+
* @param ecies - Injected ECIES implementation.
|
|
103
|
+
* @param expect - Required job ID and optional scope and version bindings.
|
|
104
|
+
* @returns The validated result when every supplied binding matches.
|
|
105
|
+
* @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.
|
|
106
|
+
* @throws If ciphertext decoding or ECIES decryption fails.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* const sealedBytes = new Uint8Array(await response.arrayBuffer());
|
|
111
|
+
* const result = await openJobResult(sealedBytes, key, ecies, {
|
|
112
|
+
* jobId,
|
|
113
|
+
* scope,
|
|
114
|
+
* });
|
|
115
|
+
* const body = fromBase64(result.body);
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
export declare function openJobResult(sealedBytes: Uint8Array, builderPrivateKey: Hex, ecies: ECIESProvider, expect: {
|
|
119
|
+
jobId: string;
|
|
120
|
+
scope?: string;
|
|
121
|
+
version?: string | null;
|
|
122
|
+
}): Promise<JobResult>;
|