@opendatalabs/vana-sdk 3.22.0 → 3.23.0-pr.211.3227174
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -0
- package/dist/auth/errors.cjs +1 -1
- package/dist/auth/web3-signed.cjs +1 -1
- package/dist/crypto/envelope/job-stream.test.d.ts +1 -0
- package/dist/crypto/envelope/job.cjs +818 -0
- package/dist/crypto/envelope/job.cjs.map +1 -0
- package/dist/crypto/envelope/job.d.ts +139 -0
- package/dist/crypto/envelope/job.js +792 -0
- package/dist/crypto/envelope/job.js.map +1 -0
- package/dist/direct/access-request-client.cjs +5 -1
- 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/controller.cjs +1 -1
- package/dist/direct/errors.cjs +1 -1
- package/dist/direct/personal-server-read.cjs +2 -2
- 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/error-entry-points.test.d.ts +1 -0
- 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 +1143 -434
- package/dist/index.browser.js.map +4 -4
- package/dist/index.node.cjs +1801 -631
- package/dist/index.node.cjs.map +4 -4
- package/dist/index.node.d.ts +4 -0
- package/dist/index.node.js +1762 -522
- package/dist/index.node.js.map +4 -4
- package/dist/protocol/data-point-deletion.cjs +1 -1
- package/dist/protocol/derivative-questions.cjs +1 -1
- package/dist/protocol/derivative-status.cjs +1 -1
- package/dist/protocol/fixtures/moksha-identity.json +20 -0
- package/dist/protocol/gateway.cjs +1 -1
- package/dist/protocol/identity.cjs +224 -0
- package/dist/protocol/identity.cjs.map +1 -0
- package/dist/protocol/identity.d.ts +193 -0
- package/dist/protocol/identity.js +188 -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 +551 -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 +558 -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/protocol/lineage.cjs +1 -1
- package/dist/protocol/personal-server-data.cjs +1 -1
- package/dist/protocol/personal-server-write.cjs +1 -1
- package/dist/protocol/write-request.cjs +1 -1
- package/dist/protocol/write-signer.cjs +1 -1
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js.map +1 -1
- package/dist/session-relay/client.cjs +1 -1
- package/dist/session-relay/errors.cjs +1 -1
- package/dist/session-relay/index.cjs +1 -1
- package/package.json +7 -1
package/dist/index.node.js
CHANGED
|
@@ -1147,289 +1147,8 @@ var init_browser2 = __esm({
|
|
|
1147
1147
|
}
|
|
1148
1148
|
});
|
|
1149
1149
|
|
|
1150
|
-
// src/
|
|
1151
|
-
|
|
1152
|
-
constructor(message, code) {
|
|
1153
|
-
super(message);
|
|
1154
|
-
this.code = code;
|
|
1155
|
-
this.name = this.constructor.name;
|
|
1156
|
-
if (Error.captureStackTrace) {
|
|
1157
|
-
Error.captureStackTrace(this, this.constructor);
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
code;
|
|
1161
|
-
};
|
|
1162
|
-
var RelayerError = class extends VanaError {
|
|
1163
|
-
constructor(message, statusCode, response) {
|
|
1164
|
-
super(message, "RELAYER_ERROR");
|
|
1165
|
-
this.statusCode = statusCode;
|
|
1166
|
-
this.response = response;
|
|
1167
|
-
}
|
|
1168
|
-
statusCode;
|
|
1169
|
-
response;
|
|
1170
|
-
};
|
|
1171
|
-
var UserRejectedRequestError = class extends VanaError {
|
|
1172
|
-
constructor(message = "User rejected the signature request") {
|
|
1173
|
-
super(message, "USER_REJECTED_REQUEST");
|
|
1174
|
-
}
|
|
1175
|
-
};
|
|
1176
|
-
var InvalidConfigurationError = class extends VanaError {
|
|
1177
|
-
constructor(message) {
|
|
1178
|
-
super(message, "INVALID_CONFIGURATION");
|
|
1179
|
-
}
|
|
1180
|
-
};
|
|
1181
|
-
var ContractNotFoundError = class extends VanaError {
|
|
1182
|
-
constructor(contractName, chainId) {
|
|
1183
|
-
super(
|
|
1184
|
-
`Contract ${contractName} not found on chain ${chainId}`,
|
|
1185
|
-
"CONTRACT_NOT_FOUND"
|
|
1186
|
-
);
|
|
1187
|
-
}
|
|
1188
|
-
};
|
|
1189
|
-
var BlockchainError = class extends VanaError {
|
|
1190
|
-
constructor(message, originalError) {
|
|
1191
|
-
super(message, "BLOCKCHAIN_ERROR");
|
|
1192
|
-
this.originalError = originalError;
|
|
1193
|
-
}
|
|
1194
|
-
originalError;
|
|
1195
|
-
};
|
|
1196
|
-
var SerializationError = class extends VanaError {
|
|
1197
|
-
constructor(message) {
|
|
1198
|
-
super(message, "SERIALIZATION_ERROR");
|
|
1199
|
-
}
|
|
1200
|
-
};
|
|
1201
|
-
var SignatureError = class extends VanaError {
|
|
1202
|
-
constructor(message, originalError) {
|
|
1203
|
-
super(message, "SIGNATURE_ERROR");
|
|
1204
|
-
this.originalError = originalError;
|
|
1205
|
-
}
|
|
1206
|
-
originalError;
|
|
1207
|
-
};
|
|
1208
|
-
var NetworkError = class extends VanaError {
|
|
1209
|
-
constructor(message, originalError) {
|
|
1210
|
-
super(message, "NETWORK_ERROR");
|
|
1211
|
-
this.originalError = originalError;
|
|
1212
|
-
}
|
|
1213
|
-
originalError;
|
|
1214
|
-
};
|
|
1215
|
-
var NonceError = class extends VanaError {
|
|
1216
|
-
constructor(message) {
|
|
1217
|
-
super(message, "NONCE_ERROR");
|
|
1218
|
-
}
|
|
1219
|
-
};
|
|
1220
|
-
var PersonalServerError = class extends VanaError {
|
|
1221
|
-
constructor(message, originalError) {
|
|
1222
|
-
super(message, "PERSONAL_SERVER_ERROR");
|
|
1223
|
-
this.originalError = originalError;
|
|
1224
|
-
}
|
|
1225
|
-
originalError;
|
|
1226
|
-
};
|
|
1227
|
-
var ServerUrlMismatchError = class extends VanaError {
|
|
1228
|
-
constructor(existingUrl, providedUrl, serverId) {
|
|
1229
|
-
super(
|
|
1230
|
-
`Server ${serverId} is already registered with URL "${existingUrl}". Cannot change to "${providedUrl}".`,
|
|
1231
|
-
"SERVER_URL_MISMATCH"
|
|
1232
|
-
);
|
|
1233
|
-
this.existingUrl = existingUrl;
|
|
1234
|
-
this.providedUrl = providedUrl;
|
|
1235
|
-
this.serverId = serverId;
|
|
1236
|
-
}
|
|
1237
|
-
existingUrl;
|
|
1238
|
-
providedUrl;
|
|
1239
|
-
serverId;
|
|
1240
|
-
};
|
|
1241
|
-
var PermissionError = class extends VanaError {
|
|
1242
|
-
constructor(message, originalError) {
|
|
1243
|
-
super(message, "PERMISSION_ERROR");
|
|
1244
|
-
this.originalError = originalError;
|
|
1245
|
-
}
|
|
1246
|
-
originalError;
|
|
1247
|
-
};
|
|
1248
|
-
var ReadOnlyError = class extends VanaError {
|
|
1249
|
-
constructor(operation, suggestion = "Initialize the SDK with a walletClient to perform this operation") {
|
|
1250
|
-
super(
|
|
1251
|
-
`Operation '${operation}' requires a wallet client. ${suggestion}`,
|
|
1252
|
-
"READ_ONLY_ERROR"
|
|
1253
|
-
);
|
|
1254
|
-
this.operation = operation;
|
|
1255
|
-
this.suggestion = suggestion;
|
|
1256
|
-
}
|
|
1257
|
-
/** The operation that was attempted */
|
|
1258
|
-
operation;
|
|
1259
|
-
/** Suggested solution for fixing the error */
|
|
1260
|
-
suggestion;
|
|
1261
|
-
};
|
|
1262
|
-
var TransactionPendingError = class extends VanaError {
|
|
1263
|
-
constructor(operationId, message, lastKnownStatus) {
|
|
1264
|
-
super(
|
|
1265
|
-
`Transaction operation pending: ${message} (operationId: ${operationId})`,
|
|
1266
|
-
"TRANSACTION_PENDING"
|
|
1267
|
-
);
|
|
1268
|
-
this.operationId = operationId;
|
|
1269
|
-
this.lastKnownStatus = lastKnownStatus;
|
|
1270
|
-
}
|
|
1271
|
-
operationId;
|
|
1272
|
-
lastKnownStatus;
|
|
1273
|
-
/**
|
|
1274
|
-
* Converts the error to a JSON-serializable format.
|
|
1275
|
-
*
|
|
1276
|
-
* @remarks
|
|
1277
|
-
* Useful for logging, storage, or transmission of error details.
|
|
1278
|
-
*
|
|
1279
|
-
* @returns JSON representation of the error
|
|
1280
|
-
*/
|
|
1281
|
-
toJSON() {
|
|
1282
|
-
return {
|
|
1283
|
-
name: this.name,
|
|
1284
|
-
code: this.code,
|
|
1285
|
-
message: this.message,
|
|
1286
|
-
operationId: this.operationId,
|
|
1287
|
-
lastKnownStatus: this.lastKnownStatus
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1290
|
-
};
|
|
1291
|
-
var PersonalServerWriteError = class extends VanaError {
|
|
1292
|
-
constructor(message, code, status, errorCode = null, details) {
|
|
1293
|
-
super(message, code);
|
|
1294
|
-
this.status = status;
|
|
1295
|
-
this.errorCode = errorCode;
|
|
1296
|
-
this.details = details;
|
|
1297
|
-
}
|
|
1298
|
-
status;
|
|
1299
|
-
errorCode;
|
|
1300
|
-
details;
|
|
1301
|
-
};
|
|
1302
|
-
var WriteRequestError = class extends PersonalServerWriteError {
|
|
1303
|
-
constructor(message, details) {
|
|
1304
|
-
super(message, "WRITE_INVALID_REQUEST", void 0, null, details);
|
|
1305
|
-
}
|
|
1306
|
-
};
|
|
1307
|
-
var WriteTransportError = class extends PersonalServerWriteError {
|
|
1308
|
-
constructor(message, attempts, cause) {
|
|
1309
|
-
super(message, "WRITE_TRANSPORT_ERROR", void 0, null, { attempts });
|
|
1310
|
-
this.attempts = attempts;
|
|
1311
|
-
this.cause = cause;
|
|
1312
|
-
}
|
|
1313
|
-
attempts;
|
|
1314
|
-
};
|
|
1315
|
-
var WriteSessionError = class extends PersonalServerWriteError {
|
|
1316
|
-
constructor(message, status, errorCode = null, details) {
|
|
1317
|
-
super(message, "WRITE_SESSION_REJECTED", status, errorCode, details);
|
|
1318
|
-
}
|
|
1319
|
-
};
|
|
1320
|
-
var WriteSessionExpiredError = class extends PersonalServerWriteError {
|
|
1321
|
-
constructor(message, details) {
|
|
1322
|
-
super(message, "WRITE_SESSION_EXPIRED", void 0, null, details);
|
|
1323
|
-
}
|
|
1324
|
-
};
|
|
1325
|
-
var WriteUnauthorizedError = class extends PersonalServerWriteError {
|
|
1326
|
-
constructor(message, errorCode = null, details) {
|
|
1327
|
-
super(message, "WRITE_UNAUTHORIZED", 401, errorCode, details);
|
|
1328
|
-
}
|
|
1329
|
-
};
|
|
1330
|
-
var WriteForbiddenError = class extends PersonalServerWriteError {
|
|
1331
|
-
constructor(message, errorCode = null, details) {
|
|
1332
|
-
super(message, "WRITE_FORBIDDEN", 403, errorCode, details);
|
|
1333
|
-
}
|
|
1334
|
-
};
|
|
1335
|
-
var WriteConflictError = class extends PersonalServerWriteError {
|
|
1336
|
-
constructor(message, errorCode = null, details) {
|
|
1337
|
-
super(message, "WRITE_CONFLICT", 409, errorCode, details);
|
|
1338
|
-
}
|
|
1339
|
-
};
|
|
1340
|
-
var WriteLineageError = class extends PersonalServerWriteError {
|
|
1341
|
-
constructor(message, status = 422, errorCode = null, details) {
|
|
1342
|
-
super(message, "WRITE_LINEAGE_REJECTED", status, errorCode, details);
|
|
1343
|
-
}
|
|
1344
|
-
};
|
|
1345
|
-
var WriteRejectedError = class extends PersonalServerWriteError {
|
|
1346
|
-
constructor(message, status, errorCode = null, details) {
|
|
1347
|
-
super(message, "WRITE_REJECTED", status, errorCode, details);
|
|
1348
|
-
}
|
|
1349
|
-
};
|
|
1350
|
-
var LineageReadError = class extends VanaError {
|
|
1351
|
-
constructor(message, status, errorCode = null, details) {
|
|
1352
|
-
super(message, "LINEAGE_READ_ERROR");
|
|
1353
|
-
this.status = status;
|
|
1354
|
-
this.errorCode = errorCode;
|
|
1355
|
-
this.details = details;
|
|
1356
|
-
}
|
|
1357
|
-
status;
|
|
1358
|
-
errorCode;
|
|
1359
|
-
details;
|
|
1360
|
-
};
|
|
1361
|
-
var DerivativeQuestionRejectedError = class extends PersonalServerWriteError {
|
|
1362
|
-
constructor(message, status, errorCode = null, details) {
|
|
1363
|
-
super(message, "DERIVATIVE_QUESTION_REJECTED", status, errorCode, details);
|
|
1364
|
-
}
|
|
1365
|
-
};
|
|
1366
|
-
var DerivativeQuestionInvalidError = class extends PersonalServerWriteError {
|
|
1367
|
-
constructor(message, status = 400, errorCode = null, details) {
|
|
1368
|
-
super(message, "DERIVATIVE_QUESTION_INVALID", status, errorCode, details);
|
|
1369
|
-
}
|
|
1370
|
-
};
|
|
1371
|
-
var DerivativeQuestionNotFoundError = class extends PersonalServerWriteError {
|
|
1372
|
-
constructor(message, errorCode = null, details) {
|
|
1373
|
-
super(message, "DERIVATIVE_QUESTION_NOT_FOUND", 404, errorCode, details);
|
|
1374
|
-
}
|
|
1375
|
-
};
|
|
1376
|
-
var DerivativeDerivedScopeRequiredError = class extends PersonalServerWriteError {
|
|
1377
|
-
constructor(message, errorCode = null, details) {
|
|
1378
|
-
super(
|
|
1379
|
-
message,
|
|
1380
|
-
"DERIVATIVE_DERIVED_SCOPE_REQUIRED",
|
|
1381
|
-
400,
|
|
1382
|
-
errorCode,
|
|
1383
|
-
details
|
|
1384
|
-
);
|
|
1385
|
-
}
|
|
1386
|
-
};
|
|
1387
|
-
var DerivativeSourceNotGrantedError = class extends PersonalServerWriteError {
|
|
1388
|
-
constructor(message, errorCode = null, details) {
|
|
1389
|
-
super(message, "DERIVATIVE_SOURCE_NOT_GRANTED", 403, errorCode, details);
|
|
1390
|
-
}
|
|
1391
|
-
};
|
|
1392
|
-
var DerivativeCycleError = class extends PersonalServerWriteError {
|
|
1393
|
-
constructor(message, errorCode = null, details) {
|
|
1394
|
-
super(message, "DERIVATIVE_CYCLE", 409, errorCode, details);
|
|
1395
|
-
}
|
|
1396
|
-
};
|
|
1397
|
-
var DerivativeComputeUnavailableError = class extends PersonalServerWriteError {
|
|
1398
|
-
constructor(message, errorCode = null, details) {
|
|
1399
|
-
super(message, "DERIVATIVE_COMPUTE_UNAVAILABLE", 503, errorCode, details);
|
|
1400
|
-
}
|
|
1401
|
-
};
|
|
1402
|
-
var DerivativeQuestionTimeoutError = class extends PersonalServerWriteError {
|
|
1403
|
-
constructor(message, details) {
|
|
1404
|
-
super(message, "DERIVATIVE_QUESTION_TIMEOUT", void 0, null, details);
|
|
1405
|
-
}
|
|
1406
|
-
};
|
|
1407
|
-
var DerivativeQuestionFailedError = class extends PersonalServerWriteError {
|
|
1408
|
-
constructor(message, details) {
|
|
1409
|
-
super(message, "DERIVATIVE_QUESTION_FAILED", void 0, null, details);
|
|
1410
|
-
}
|
|
1411
|
-
};
|
|
1412
|
-
var DataPointDeletedError = class extends VanaError {
|
|
1413
|
-
constructor(message, details = {}) {
|
|
1414
|
-
super(message, "DATA_POINT_DELETED");
|
|
1415
|
-
this.details = details;
|
|
1416
|
-
}
|
|
1417
|
-
details;
|
|
1418
|
-
};
|
|
1419
|
-
var DataPointNotFoundError = class extends VanaError {
|
|
1420
|
-
constructor(message, details = {}) {
|
|
1421
|
-
super(message, "DATA_POINT_NOT_FOUND");
|
|
1422
|
-
this.details = details;
|
|
1423
|
-
}
|
|
1424
|
-
details;
|
|
1425
|
-
};
|
|
1426
|
-
var DataPointVersionConflictError = class extends VanaError {
|
|
1427
|
-
constructor(message, details = {}) {
|
|
1428
|
-
super(message, "DATA_POINT_VERSION_CONFLICT");
|
|
1429
|
-
this.details = details;
|
|
1430
|
-
}
|
|
1431
|
-
details;
|
|
1432
|
-
};
|
|
1150
|
+
// src/index.node.ts
|
|
1151
|
+
export * from "./errors.js";
|
|
1433
1152
|
|
|
1434
1153
|
// src/contracts/contractController.ts
|
|
1435
1154
|
import {
|
|
@@ -31347,13 +31066,13 @@ var NodeCryptoAdapter = class {
|
|
|
31347
31066
|
*/
|
|
31348
31067
|
async generateKeyPair() {
|
|
31349
31068
|
try {
|
|
31350
|
-
const
|
|
31069
|
+
const secp256k15 = secp256k1Import2;
|
|
31351
31070
|
let privateKey;
|
|
31352
31071
|
do {
|
|
31353
31072
|
privateKey = randomBytes2(32);
|
|
31354
|
-
} while (!
|
|
31073
|
+
} while (!secp256k15.privateKeyVerify(privateKey));
|
|
31355
31074
|
const publicKey = Buffer.from(
|
|
31356
|
-
|
|
31075
|
+
secp256k15.publicKeyCreate(privateKey, true)
|
|
31357
31076
|
);
|
|
31358
31077
|
return {
|
|
31359
31078
|
privateKey: privateKey.toString("hex"),
|
|
@@ -31803,31 +31522,11 @@ async function decryptWithPassword(encrypted, password) {
|
|
|
31803
31522
|
|
|
31804
31523
|
// src/auth/web3-signed.ts
|
|
31805
31524
|
import { recoverMessageAddress as recoverMessageAddress2 } from "viem";
|
|
31806
|
-
|
|
31807
|
-
|
|
31808
|
-
|
|
31809
|
-
|
|
31810
|
-
|
|
31811
|
-
this.details = details;
|
|
31812
|
-
}
|
|
31813
|
-
details;
|
|
31814
|
-
};
|
|
31815
|
-
var InvalidSignatureError = class extends VanaError {
|
|
31816
|
-
constructor(details, message = "Invalid signature") {
|
|
31817
|
-
super(message, "INVALID_SIGNATURE");
|
|
31818
|
-
this.details = details;
|
|
31819
|
-
}
|
|
31820
|
-
details;
|
|
31821
|
-
};
|
|
31822
|
-
var ExpiredTokenError = class extends VanaError {
|
|
31823
|
-
constructor(details, message = "Token has expired") {
|
|
31824
|
-
super(message, "EXPIRED_TOKEN");
|
|
31825
|
-
this.details = details;
|
|
31826
|
-
}
|
|
31827
|
-
details;
|
|
31828
|
-
};
|
|
31829
|
-
|
|
31830
|
-
// src/auth/web3-signed.ts
|
|
31525
|
+
import {
|
|
31526
|
+
MissingAuthError,
|
|
31527
|
+
InvalidSignatureError,
|
|
31528
|
+
ExpiredTokenError
|
|
31529
|
+
} from "./auth/errors.js";
|
|
31831
31530
|
var WEB3_SIGNED_PREFIX = "Web3Signed ";
|
|
31832
31531
|
var CLOCK_SKEW_SECONDS = 60;
|
|
31833
31532
|
function base64urlDecode(input) {
|
|
@@ -31945,6 +31644,13 @@ async function verifyWeb3Signed(params) {
|
|
|
31945
31644
|
return { signer, payload };
|
|
31946
31645
|
}
|
|
31947
31646
|
|
|
31647
|
+
// src/index.node.ts
|
|
31648
|
+
import {
|
|
31649
|
+
MissingAuthError as MissingAuthError2,
|
|
31650
|
+
InvalidSignatureError as InvalidSignatureError2,
|
|
31651
|
+
ExpiredTokenError as ExpiredTokenError2
|
|
31652
|
+
} from "./auth/errors.js";
|
|
31653
|
+
|
|
31948
31654
|
// src/auth/pkce.ts
|
|
31949
31655
|
var PKCE_VERIFIER_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
|
|
31950
31656
|
var PKCE_VERIFIER_MIN_LENGTH = 43;
|
|
@@ -32363,9 +32069,1554 @@ var RECORD_DATA_ACCESS_TYPES = {
|
|
|
32363
32069
|
]
|
|
32364
32070
|
};
|
|
32365
32071
|
|
|
32072
|
+
// src/protocol/identity.ts
|
|
32073
|
+
init_interface();
|
|
32074
|
+
import * as secp256k14 from "@noble/secp256k1";
|
|
32075
|
+
import {
|
|
32076
|
+
concat as concat4,
|
|
32077
|
+
encodePacked,
|
|
32078
|
+
fromHex as fromHex5,
|
|
32079
|
+
getAddress,
|
|
32080
|
+
isAddressEqual,
|
|
32081
|
+
keccak256,
|
|
32082
|
+
recoverPublicKey,
|
|
32083
|
+
toBytes,
|
|
32084
|
+
toHex as toHex7
|
|
32085
|
+
} from "viem";
|
|
32086
|
+
import { publicKeyToAddress } from "viem/accounts";
|
|
32087
|
+
var ENCLAVE_IDENTITY_EVIDENCE_VERSION = 1;
|
|
32088
|
+
var USER_PS_ID_DOMAIN = "vana.ps-enclave.v1";
|
|
32089
|
+
var ENCLAVE_WALLET_PURPOSE = "vana.ps-enclave.wallet.v1";
|
|
32090
|
+
var MASTER_SIGNATURE_DELIVERY_VERSION = "vana.ps-enclave.delivery.v1";
|
|
32091
|
+
var MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS = 600;
|
|
32092
|
+
var SEALED_ENVELOPE_VERSION = 1;
|
|
32093
|
+
var VANA_MAINNET_CHAIN_ID = 1480;
|
|
32094
|
+
var MOKSHA_CHAIN_ID = 14800;
|
|
32095
|
+
var KMS_ISSUED_PREFIX = "dstack-kms-issued";
|
|
32096
|
+
var PREIMAGE_SEPARATOR = ":";
|
|
32097
|
+
var UNCOMPRESSED_PUBLIC_KEY_BYTES = 65;
|
|
32098
|
+
var UNCOMPRESSED_PUBLIC_KEY_PREFIX = "04";
|
|
32099
|
+
var EMPTY_HEX = "0x";
|
|
32100
|
+
function emptyAnchor() {
|
|
32101
|
+
return Object.freeze({
|
|
32102
|
+
kmsRootPubkey: EMPTY_HEX,
|
|
32103
|
+
appIds: Object.freeze([])
|
|
32104
|
+
});
|
|
32105
|
+
}
|
|
32106
|
+
var ENCLAVE_TRUST_ANCHORS = Object.freeze({
|
|
32107
|
+
// filled at fleet provisioning; verify fails closed while empty
|
|
32108
|
+
[VANA_MAINNET_CHAIN_ID]: emptyAnchor(),
|
|
32109
|
+
// Moksha workers share this dstack app and KMS root; the controller does not derive owner keys.
|
|
32110
|
+
[MOKSHA_CHAIN_ID]: Object.freeze({
|
|
32111
|
+
kmsRootPubkey: "0x0434c76e0c3f52ec64cbf9bbf5c910c272330166fd656c0a86bb330963e46910e1a0e6fa51bec74be2f9129342707636060d85856d102cee8290185409ecf7422f",
|
|
32112
|
+
appIds: Object.freeze([
|
|
32113
|
+
"0xec9a39de98c760e1ded9f1e97016dc5f0e357cf2"
|
|
32114
|
+
])
|
|
32115
|
+
})
|
|
32116
|
+
});
|
|
32117
|
+
function userPsId(chainId, ownerAddress) {
|
|
32118
|
+
const packed = encodePacked(
|
|
32119
|
+
["string", "uint256", "address"],
|
|
32120
|
+
[USER_PS_ID_DOMAIN, BigInt(chainId), getAddress(ownerAddress)]
|
|
32121
|
+
);
|
|
32122
|
+
return keccak256(packed);
|
|
32123
|
+
}
|
|
32124
|
+
function compressPublicKey(publicKey) {
|
|
32125
|
+
return secp256k14.ProjectivePoint.fromHex(
|
|
32126
|
+
fromHex5(publicKey, "bytes")
|
|
32127
|
+
).toRawBytes(true);
|
|
32128
|
+
}
|
|
32129
|
+
function sameKey(a, b) {
|
|
32130
|
+
return toHex7(compressPublicKey(a)) === toHex7(compressPublicKey(b));
|
|
32131
|
+
}
|
|
32132
|
+
function assertUncompressedKey(publicKey) {
|
|
32133
|
+
const hex = publicKey.slice(2);
|
|
32134
|
+
if (hex.length !== UNCOMPRESSED_PUBLIC_KEY_BYTES * 2 || !hex.startsWith(UNCOMPRESSED_PUBLIC_KEY_PREFIX) || !/^[0-9a-fA-F]+$/.test(hex)) {
|
|
32135
|
+
throw new Error("Public key must be a 65-byte uncompressed secp256k1 key");
|
|
32136
|
+
}
|
|
32137
|
+
}
|
|
32138
|
+
function appRootPreimage(purpose, publicKey) {
|
|
32139
|
+
const keyHex = toHex7(compressPublicKey(publicKey)).slice(2);
|
|
32140
|
+
return keccak256(toBytes(`${purpose}${PREIMAGE_SEPARATOR}${keyHex}`));
|
|
32141
|
+
}
|
|
32142
|
+
function kmsIssuedPreimage(appId, appRootPublicKey) {
|
|
32143
|
+
const prefix = concat4([
|
|
32144
|
+
toBytes(`${KMS_ISSUED_PREFIX}${PREIMAGE_SEPARATOR}`),
|
|
32145
|
+
fromHex5(appId, "bytes")
|
|
32146
|
+
]);
|
|
32147
|
+
const compressed = compressPublicKey(appRootPublicKey);
|
|
32148
|
+
return keccak256(concat4([prefix, compressed]));
|
|
32149
|
+
}
|
|
32150
|
+
async function recoverChainKey(hash, signature, link) {
|
|
32151
|
+
try {
|
|
32152
|
+
return (await recoverPublicKey({ hash, signature })).toLowerCase();
|
|
32153
|
+
} catch {
|
|
32154
|
+
throw new Error(`Invalid enclave signature chain link ${link}`);
|
|
32155
|
+
}
|
|
32156
|
+
}
|
|
32157
|
+
async function verifyEnclaveIdentityEvidence(evidence, anchors, expected) {
|
|
32158
|
+
if (evidence.v !== ENCLAVE_IDENTITY_EVIDENCE_VERSION) {
|
|
32159
|
+
throw new Error("Unsupported enclave identity evidence version");
|
|
32160
|
+
}
|
|
32161
|
+
if (!Number.isInteger(evidence.epoch) || evidence.epoch < 1) {
|
|
32162
|
+
throw new Error("Invalid enclave identity epoch");
|
|
32163
|
+
}
|
|
32164
|
+
if (evidence.chainId !== expected.chainId) {
|
|
32165
|
+
throw new Error(
|
|
32166
|
+
"Enclave identity chain ID does not match expected chain ID"
|
|
32167
|
+
);
|
|
32168
|
+
}
|
|
32169
|
+
if (!isAddressEqual(evidence.ownerAddress, expected.ownerAddress)) {
|
|
32170
|
+
throw new Error("Enclave identity owner does not match expected owner");
|
|
32171
|
+
}
|
|
32172
|
+
if (evidence.epoch !== expected.epoch) {
|
|
32173
|
+
throw new Error("Enclave identity epoch does not match expected epoch");
|
|
32174
|
+
}
|
|
32175
|
+
const expectedUserPsId = userPsId(expected.chainId, expected.ownerAddress);
|
|
32176
|
+
if (evidence.userPsId.toLowerCase() !== expectedUserPsId.toLowerCase()) {
|
|
32177
|
+
throw new Error("Enclave userPsId does not match expected identity");
|
|
32178
|
+
}
|
|
32179
|
+
if (evidence.purpose !== ENCLAVE_WALLET_PURPOSE) {
|
|
32180
|
+
throw new Error("Unexpected enclave wallet purpose");
|
|
32181
|
+
}
|
|
32182
|
+
if (anchors.kmsRootPubkey === EMPTY_HEX) {
|
|
32183
|
+
throw new Error("KMS root trust anchor is not provisioned");
|
|
32184
|
+
}
|
|
32185
|
+
assertUncompressedKey(evidence.publicKey);
|
|
32186
|
+
const derivedAddress = publicKeyToAddress(evidence.publicKey);
|
|
32187
|
+
if (getAddress(derivedAddress) !== getAddress(evidence.address)) {
|
|
32188
|
+
throw new Error("Enclave public key does not match its address");
|
|
32189
|
+
}
|
|
32190
|
+
const appRootPublicKey = await recoverChainKey(
|
|
32191
|
+
appRootPreimage(evidence.purpose, evidence.publicKey),
|
|
32192
|
+
evidence.signatureChain[0],
|
|
32193
|
+
0
|
|
32194
|
+
);
|
|
32195
|
+
const kmsRootPublicKey = await recoverChainKey(
|
|
32196
|
+
kmsIssuedPreimage(evidence.appId, appRootPublicKey),
|
|
32197
|
+
evidence.signatureChain[1],
|
|
32198
|
+
1
|
|
32199
|
+
);
|
|
32200
|
+
let matchesAnchor;
|
|
32201
|
+
try {
|
|
32202
|
+
matchesAnchor = sameKey(kmsRootPublicKey, anchors.kmsRootPubkey);
|
|
32203
|
+
} catch {
|
|
32204
|
+
throw new Error("KMS root trust anchor is malformed");
|
|
32205
|
+
}
|
|
32206
|
+
if (!matchesAnchor) {
|
|
32207
|
+
throw new Error("KMS root public key does not match the trust anchor");
|
|
32208
|
+
}
|
|
32209
|
+
if (keccak256(kmsRootPublicKey) !== evidence.kmsRootFingerprint.toLowerCase()) {
|
|
32210
|
+
throw new Error("KMS root fingerprint does not match the evidence");
|
|
32211
|
+
}
|
|
32212
|
+
const appId = evidence.appId.toLowerCase();
|
|
32213
|
+
if (!anchors.appIds.some((allowedAppId) => allowedAppId.toLowerCase() === appId)) {
|
|
32214
|
+
throw new Error("Enclave app ID is not trusted");
|
|
32215
|
+
}
|
|
32216
|
+
}
|
|
32217
|
+
async function buildMasterSignatureDelivery(evidence, masterSignature, now = Math.floor(Date.now() / 1e3)) {
|
|
32218
|
+
deriveMasterKey(masterSignature);
|
|
32219
|
+
const signerAddress = await recoverServerOwner(masterSignature);
|
|
32220
|
+
if (!isAddressEqual(signerAddress, evidence.ownerAddress)) {
|
|
32221
|
+
throw new Error("Master signature signer does not match evidence owner");
|
|
32222
|
+
}
|
|
32223
|
+
return {
|
|
32224
|
+
v: MASTER_SIGNATURE_DELIVERY_VERSION,
|
|
32225
|
+
userPsId: evidence.userPsId,
|
|
32226
|
+
epoch: evidence.epoch,
|
|
32227
|
+
enclaveAddress: evidence.address,
|
|
32228
|
+
ownerAddress: evidence.ownerAddress,
|
|
32229
|
+
masterSignature,
|
|
32230
|
+
issuedAt: now
|
|
32231
|
+
};
|
|
32232
|
+
}
|
|
32233
|
+
async function encryptMasterSignatureDelivery(delivery, publicKey, ecies) {
|
|
32234
|
+
assertUncompressedKey(publicKey);
|
|
32235
|
+
if (!isAddressEqual(publicKeyToAddress(publicKey), delivery.enclaveAddress)) {
|
|
32236
|
+
throw new Error(
|
|
32237
|
+
"Public key does not belong to the delivery's enclave address"
|
|
32238
|
+
);
|
|
32239
|
+
}
|
|
32240
|
+
const plaintext = toBytes(JSON.stringify(delivery));
|
|
32241
|
+
const encrypted = await ecies.encrypt(fromHex5(publicKey, "bytes"), plaintext);
|
|
32242
|
+
return `0x${serializeECIES(encrypted)}`;
|
|
32243
|
+
}
|
|
32244
|
+
|
|
32245
|
+
// src/protocol/jobs.ts
|
|
32246
|
+
var JOB_PROTOCOL_VERSION = 1;
|
|
32247
|
+
var JOB_OPERATIONS = ["raw_read", "inference"];
|
|
32248
|
+
var JOB_STATES = [
|
|
32249
|
+
"queued",
|
|
32250
|
+
"claimed",
|
|
32251
|
+
"running",
|
|
32252
|
+
"completed",
|
|
32253
|
+
"failed",
|
|
32254
|
+
"expired",
|
|
32255
|
+
"cancelled"
|
|
32256
|
+
];
|
|
32257
|
+
var DEFAULT_LEASE_SECONDS = 30;
|
|
32258
|
+
var MAX_LEASE_SECONDS = 300;
|
|
32259
|
+
var MAX_ATTEMPTS = 3;
|
|
32260
|
+
var MAX_WAIT_SECONDS = 25;
|
|
32261
|
+
var CLAIM_POLL_FLOOR_MS = 1e3;
|
|
32262
|
+
var DEFAULT_JOB_DEADLINE_SECONDS = 600;
|
|
32263
|
+
var MAX_JOB_DEADLINE_SECONDS = 3600;
|
|
32264
|
+
|
|
32265
|
+
// src/protocol/jobs-client.ts
|
|
32266
|
+
import { randomUUID } from "node:crypto";
|
|
32267
|
+
import { sha256 as sha2566 } from "@noble/hashes/sha2";
|
|
32268
|
+
import {
|
|
32269
|
+
bytesToHex as bytesToHex3,
|
|
32270
|
+
isAddress as isAddress2,
|
|
32271
|
+
isAddressEqual as isAddressEqual2,
|
|
32272
|
+
isHex as isHex2
|
|
32273
|
+
} from "viem";
|
|
32274
|
+
import { privateKeyToAccount, publicKeyToAddress as publicKeyToAddress2 } from "viem/accounts";
|
|
32275
|
+
|
|
32276
|
+
// src/crypto/envelope/job.ts
|
|
32277
|
+
init_constants();
|
|
32278
|
+
init_interface();
|
|
32279
|
+
import { sha256 as sha2565 } from "@noble/hashes/sha2";
|
|
32280
|
+
import { bytesToHex as bytesToHex2, fromHex as fromHex6, isAddress, isHex, toHex as toHex8 } from "viem";
|
|
32281
|
+
var textDecoder = new TextDecoder();
|
|
32282
|
+
var textEncoder = new TextEncoder();
|
|
32283
|
+
var MAX_JOB_RESULT_HEADER_BYTES = 4096;
|
|
32284
|
+
var WRAPPED_KEY_LENGTH_BYTES = 4;
|
|
32285
|
+
var FRAME_LENGTH_BYTES = 4;
|
|
32286
|
+
var FRAME_FLAGS_BYTES = 1;
|
|
32287
|
+
var AES_KEY_BYTES = 32;
|
|
32288
|
+
var AES_GCM_NONCE_BYTES = 12;
|
|
32289
|
+
var AES_GCM_TAG_BYTES = 16;
|
|
32290
|
+
var WRAPPED_METADATA_LENGTH_BYTES = 4;
|
|
32291
|
+
var WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES = AES_KEY_BYTES + AES_GCM_NONCE_BYTES + WRAPPED_METADATA_LENGTH_BYTES;
|
|
32292
|
+
var MAX_WRAPPED_KEY_BYTES = 8192;
|
|
32293
|
+
var FINAL_FRAME_FLAG = 1;
|
|
32294
|
+
var MAX_CHUNK_INDEX = 4294967295;
|
|
32295
|
+
var JOB_RESULT_FORMAT_VERSION = 2;
|
|
32296
|
+
var JOB_RESULT_CHUNK_BYTES = 1024 * 1024;
|
|
32297
|
+
var JobEnvelopeError = class extends Error {
|
|
32298
|
+
constructor(message) {
|
|
32299
|
+
super(message);
|
|
32300
|
+
this.name = "JobEnvelopeError";
|
|
32301
|
+
}
|
|
32302
|
+
};
|
|
32303
|
+
function sortJsonKeys(value) {
|
|
32304
|
+
if (Array.isArray(value)) {
|
|
32305
|
+
return value.map(sortJsonKeys);
|
|
32306
|
+
}
|
|
32307
|
+
if (value !== null && typeof value === "object") {
|
|
32308
|
+
return Object.fromEntries(
|
|
32309
|
+
Object.keys(value).sort().map((key) => [
|
|
32310
|
+
key,
|
|
32311
|
+
sortJsonKeys(value[key])
|
|
32312
|
+
])
|
|
32313
|
+
);
|
|
32314
|
+
}
|
|
32315
|
+
return value;
|
|
32316
|
+
}
|
|
32317
|
+
function canonicalJsonBytes(value) {
|
|
32318
|
+
return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));
|
|
32319
|
+
}
|
|
32320
|
+
function canonicalJobRequestBytes(request) {
|
|
32321
|
+
validateJobRequest(request);
|
|
32322
|
+
return canonicalJsonBytes(request);
|
|
32323
|
+
}
|
|
32324
|
+
function requestPlaintext(envelope) {
|
|
32325
|
+
validateRequestEnvelope(envelope);
|
|
32326
|
+
return canonicalJsonBytes(envelope);
|
|
32327
|
+
}
|
|
32328
|
+
function resultMetadata(result) {
|
|
32329
|
+
return {
|
|
32330
|
+
v: result.v,
|
|
32331
|
+
jobId: result.jobId,
|
|
32332
|
+
scope: result.scope,
|
|
32333
|
+
version: result.version,
|
|
32334
|
+
contentType: result.contentType
|
|
32335
|
+
};
|
|
32336
|
+
}
|
|
32337
|
+
function encryptedBytesToBase64(encrypted) {
|
|
32338
|
+
return toBase64(fromHex6(`0x${serializeECIES(encrypted)}`, "bytes"));
|
|
32339
|
+
}
|
|
32340
|
+
function encryptedToBytes(encrypted) {
|
|
32341
|
+
const bytes = new Uint8Array(
|
|
32342
|
+
encrypted.iv.length + encrypted.ephemPublicKey.length + encrypted.ciphertext.length + encrypted.mac.length
|
|
32343
|
+
);
|
|
32344
|
+
let offset = 0;
|
|
32345
|
+
bytes.set(encrypted.iv, offset);
|
|
32346
|
+
offset += encrypted.iv.length;
|
|
32347
|
+
bytes.set(encrypted.ephemPublicKey, offset);
|
|
32348
|
+
offset += encrypted.ephemPublicKey.length;
|
|
32349
|
+
bytes.set(encrypted.ciphertext, offset);
|
|
32350
|
+
offset += encrypted.ciphertext.length;
|
|
32351
|
+
bytes.set(encrypted.mac, offset);
|
|
32352
|
+
return bytes;
|
|
32353
|
+
}
|
|
32354
|
+
function bytesToEncrypted(bytes) {
|
|
32355
|
+
const absoluteMinLength = FORMAT.IV_LENGTH + 1 + MAC.LENGTH + 1;
|
|
32356
|
+
if (bytes.length < absoluteMinLength) {
|
|
32357
|
+
throw new ECIESError(
|
|
32358
|
+
`Invalid ECIES data: too short (${bytes.length} bytes, minimum ${absoluteMinLength} bytes required)`,
|
|
32359
|
+
"DECRYPTION_FAILED"
|
|
32360
|
+
);
|
|
32361
|
+
}
|
|
32362
|
+
const prefix = bytes[FORMAT.EPHEMERAL_KEY_OFFSET];
|
|
32363
|
+
if (prefix !== CURVE.PREFIX.UNCOMPRESSED) {
|
|
32364
|
+
throw new ECIESError(
|
|
32365
|
+
`Invalid ephemeral public key: must be uncompressed format (0x04 prefix), got 0x${prefix.toString(16).padStart(2, "0")}`,
|
|
32366
|
+
"DECRYPTION_FAILED"
|
|
32367
|
+
);
|
|
32368
|
+
}
|
|
32369
|
+
const ephemKeySize = CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH;
|
|
32370
|
+
const minLength = FORMAT.IV_LENGTH + ephemKeySize + MAC.LENGTH + 1;
|
|
32371
|
+
if (bytes.length < minLength) {
|
|
32372
|
+
throw new ECIESError(
|
|
32373
|
+
`Invalid ECIES data: too short (${bytes.length} bytes, minimum ${minLength} bytes required)`,
|
|
32374
|
+
"DECRYPTION_FAILED"
|
|
32375
|
+
);
|
|
32376
|
+
}
|
|
32377
|
+
return {
|
|
32378
|
+
iv: bytes.subarray(FORMAT.IV_OFFSET, FORMAT.IV_OFFSET + FORMAT.IV_LENGTH),
|
|
32379
|
+
ephemPublicKey: bytes.subarray(
|
|
32380
|
+
FORMAT.EPHEMERAL_KEY_OFFSET,
|
|
32381
|
+
FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize
|
|
32382
|
+
),
|
|
32383
|
+
ciphertext: bytes.subarray(
|
|
32384
|
+
FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,
|
|
32385
|
+
bytes.length - MAC.LENGTH
|
|
32386
|
+
),
|
|
32387
|
+
mac: bytes.subarray(bytes.length - MAC.LENGTH)
|
|
32388
|
+
};
|
|
32389
|
+
}
|
|
32390
|
+
function base64ToEncrypted(ciphertext) {
|
|
32391
|
+
return deserializeECIES(toHex8(fromBase64(ciphertext)));
|
|
32392
|
+
}
|
|
32393
|
+
function parseObject(plaintext, kind) {
|
|
32394
|
+
try {
|
|
32395
|
+
const value = JSON.parse(textDecoder.decode(plaintext));
|
|
32396
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
32397
|
+
throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);
|
|
32398
|
+
}
|
|
32399
|
+
return value;
|
|
32400
|
+
} catch (error) {
|
|
32401
|
+
if (error instanceof JobEnvelopeError) throw error;
|
|
32402
|
+
throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);
|
|
32403
|
+
}
|
|
32404
|
+
}
|
|
32405
|
+
function isPlainObject2(value) {
|
|
32406
|
+
if (value === null || typeof value !== "object") return false;
|
|
32407
|
+
const prototype = Object.getPrototypeOf(value);
|
|
32408
|
+
return prototype === Object.prototype || prototype === null;
|
|
32409
|
+
}
|
|
32410
|
+
function requirePlainObject(value, field, kind) {
|
|
32411
|
+
if (!isPlainObject2(value)) {
|
|
32412
|
+
throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);
|
|
32413
|
+
}
|
|
32414
|
+
}
|
|
32415
|
+
function requireExactKeys(value, expectedKeys, kind) {
|
|
32416
|
+
for (const key of expectedKeys) {
|
|
32417
|
+
if (!Object.hasOwn(value, key) || value[key] === void 0) {
|
|
32418
|
+
throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);
|
|
32419
|
+
}
|
|
32420
|
+
}
|
|
32421
|
+
const expected = new Set(expectedKeys);
|
|
32422
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
32423
|
+
if (!expected.has(key)) {
|
|
32424
|
+
throw new JobEnvelopeError(
|
|
32425
|
+
`Invalid ${kind}: unknown field ${String(key)}`
|
|
32426
|
+
);
|
|
32427
|
+
}
|
|
32428
|
+
}
|
|
32429
|
+
}
|
|
32430
|
+
function requireString(value, field, kind) {
|
|
32431
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
32432
|
+
throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);
|
|
32433
|
+
}
|
|
32434
|
+
}
|
|
32435
|
+
function validateJobRequest(value) {
|
|
32436
|
+
requirePlainObject(value, "request", "job request");
|
|
32437
|
+
requireExactKeys(
|
|
32438
|
+
value,
|
|
32439
|
+
[
|
|
32440
|
+
"v",
|
|
32441
|
+
"jobId",
|
|
32442
|
+
"owner",
|
|
32443
|
+
"builder",
|
|
32444
|
+
"builderPublicKey",
|
|
32445
|
+
"grantId",
|
|
32446
|
+
"scope",
|
|
32447
|
+
"operation",
|
|
32448
|
+
"pinnedVersion",
|
|
32449
|
+
"deadline"
|
|
32450
|
+
],
|
|
32451
|
+
"job request"
|
|
32452
|
+
);
|
|
32453
|
+
if (value.v !== JOB_PROTOCOL_VERSION) {
|
|
32454
|
+
throw new JobEnvelopeError(
|
|
32455
|
+
`Unsupported job request version: ${String(value.v)}`
|
|
32456
|
+
);
|
|
32457
|
+
}
|
|
32458
|
+
requireString(value.jobId, "jobId", "job request");
|
|
32459
|
+
if (typeof value.owner !== "string" || !isAddress(value.owner)) {
|
|
32460
|
+
throw new JobEnvelopeError("Invalid job request: invalid owner");
|
|
32461
|
+
}
|
|
32462
|
+
if (typeof value.builder !== "string" || !isAddress(value.builder)) {
|
|
32463
|
+
throw new JobEnvelopeError("Invalid job request: invalid builder");
|
|
32464
|
+
}
|
|
32465
|
+
if (typeof value.builderPublicKey !== "string" || !isHex(value.builderPublicKey)) {
|
|
32466
|
+
throw new JobEnvelopeError("Invalid job request: invalid builderPublicKey");
|
|
32467
|
+
}
|
|
32468
|
+
if (typeof value.grantId !== "string" || !isHex(value.grantId)) {
|
|
32469
|
+
throw new JobEnvelopeError("Invalid job request: invalid grantId");
|
|
32470
|
+
}
|
|
32471
|
+
requireString(value.scope, "scope", "job request");
|
|
32472
|
+
if (!JOB_OPERATIONS.includes(value.operation)) {
|
|
32473
|
+
throw new JobEnvelopeError("Invalid job request: invalid operation");
|
|
32474
|
+
}
|
|
32475
|
+
if (value.pinnedVersion !== null && typeof value.pinnedVersion !== "string") {
|
|
32476
|
+
throw new JobEnvelopeError("Invalid job request: missing pinnedVersion");
|
|
32477
|
+
}
|
|
32478
|
+
if (typeof value.deadline !== "string" || !Number.isFinite(Date.parse(value.deadline))) {
|
|
32479
|
+
throw new JobEnvelopeError("Invalid job request: invalid deadline");
|
|
32480
|
+
}
|
|
32481
|
+
return value;
|
|
32482
|
+
}
|
|
32483
|
+
function validateRequestEnvelope(value) {
|
|
32484
|
+
requirePlainObject(value, "envelope", "job request envelope");
|
|
32485
|
+
requireExactKeys(value, ["request", "auth"], "job request envelope");
|
|
32486
|
+
validateJobRequest(value.request);
|
|
32487
|
+
requireString(value.auth, "auth", "job request envelope");
|
|
32488
|
+
return value;
|
|
32489
|
+
}
|
|
32490
|
+
function validateResultMetadata(value) {
|
|
32491
|
+
requirePlainObject(value, "metadata", "job result");
|
|
32492
|
+
requireExactKeys(
|
|
32493
|
+
value,
|
|
32494
|
+
["v", "jobId", "scope", "version", "contentType"],
|
|
32495
|
+
"job result"
|
|
32496
|
+
);
|
|
32497
|
+
if (value.v !== JOB_PROTOCOL_VERSION) {
|
|
32498
|
+
throw new JobEnvelopeError(
|
|
32499
|
+
`Unsupported job result version: ${String(value.v)}`
|
|
32500
|
+
);
|
|
32501
|
+
}
|
|
32502
|
+
for (const field of ["jobId", "scope", "contentType"]) {
|
|
32503
|
+
requireString(value[field], field, "job result");
|
|
32504
|
+
}
|
|
32505
|
+
if (value.version !== null && typeof value.version !== "string") {
|
|
32506
|
+
throw new JobEnvelopeError("Invalid job result: missing version");
|
|
32507
|
+
}
|
|
32508
|
+
return value;
|
|
32509
|
+
}
|
|
32510
|
+
function validateResult(value) {
|
|
32511
|
+
requirePlainObject(value, "result", "job result");
|
|
32512
|
+
requireExactKeys(
|
|
32513
|
+
value,
|
|
32514
|
+
["v", "jobId", "scope", "version", "contentType", "body"],
|
|
32515
|
+
"job result"
|
|
32516
|
+
);
|
|
32517
|
+
validateResultMetadata(resultMetadata(value));
|
|
32518
|
+
if (!(value.body instanceof Uint8Array)) {
|
|
32519
|
+
throw new JobEnvelopeError("Invalid job result: missing body");
|
|
32520
|
+
}
|
|
32521
|
+
return value;
|
|
32522
|
+
}
|
|
32523
|
+
function webCrypto() {
|
|
32524
|
+
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.getRandomValues !== "function" || !globalThis.crypto.subtle) {
|
|
32525
|
+
throw new JobEnvelopeError(
|
|
32526
|
+
"Job result streaming requires the Web Crypto API"
|
|
32527
|
+
);
|
|
32528
|
+
}
|
|
32529
|
+
return globalThis.crypto;
|
|
32530
|
+
}
|
|
32531
|
+
function uint32(value) {
|
|
32532
|
+
const bytes = new Uint8Array(4);
|
|
32533
|
+
new DataView(bytes.buffer).setUint32(0, value);
|
|
32534
|
+
return bytes;
|
|
32535
|
+
}
|
|
32536
|
+
function readUint32(bytes, offset = 0) {
|
|
32537
|
+
return new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0);
|
|
32538
|
+
}
|
|
32539
|
+
function wrappedKeyPlaintext(contentKey, noncePrefix, metadataBytes) {
|
|
32540
|
+
const plaintext = new Uint8Array(
|
|
32541
|
+
WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES + metadataBytes.length
|
|
32542
|
+
);
|
|
32543
|
+
plaintext.set(contentKey, 0);
|
|
32544
|
+
plaintext.set(noncePrefix, AES_KEY_BYTES);
|
|
32545
|
+
new DataView(plaintext.buffer).setUint32(
|
|
32546
|
+
AES_KEY_BYTES + AES_GCM_NONCE_BYTES,
|
|
32547
|
+
metadataBytes.length
|
|
32548
|
+
);
|
|
32549
|
+
plaintext.set(metadataBytes, WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES);
|
|
32550
|
+
return plaintext;
|
|
32551
|
+
}
|
|
32552
|
+
function parseWrappedKeyPlaintext(plaintext) {
|
|
32553
|
+
if (plaintext.length < WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES) {
|
|
32554
|
+
throw new JobEnvelopeError("Invalid job result: wrapped key is truncated");
|
|
32555
|
+
}
|
|
32556
|
+
const metadataLength = readUint32(
|
|
32557
|
+
plaintext,
|
|
32558
|
+
AES_KEY_BYTES + AES_GCM_NONCE_BYTES
|
|
32559
|
+
);
|
|
32560
|
+
if (metadataLength > MAX_JOB_RESULT_HEADER_BYTES) {
|
|
32561
|
+
throw new JobEnvelopeError(
|
|
32562
|
+
`Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
|
|
32563
|
+
);
|
|
32564
|
+
}
|
|
32565
|
+
if (plaintext.length !== WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES + metadataLength) {
|
|
32566
|
+
throw new JobEnvelopeError(
|
|
32567
|
+
"Invalid job result: header length exceeds payload"
|
|
32568
|
+
);
|
|
32569
|
+
}
|
|
32570
|
+
const metadataBytes = plaintext.slice(WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES);
|
|
32571
|
+
const metadata = validateResultMetadata(
|
|
32572
|
+
parseObject(metadataBytes, "job result header")
|
|
32573
|
+
);
|
|
32574
|
+
return {
|
|
32575
|
+
contentKey: plaintext.slice(0, AES_KEY_BYTES),
|
|
32576
|
+
noncePrefix: plaintext.slice(
|
|
32577
|
+
AES_KEY_BYTES,
|
|
32578
|
+
AES_KEY_BYTES + AES_GCM_NONCE_BYTES
|
|
32579
|
+
),
|
|
32580
|
+
metadataBytes,
|
|
32581
|
+
metadata
|
|
32582
|
+
};
|
|
32583
|
+
}
|
|
32584
|
+
async function importAesKey(contentKey, usage) {
|
|
32585
|
+
return webCrypto().subtle.importKey(
|
|
32586
|
+
"raw",
|
|
32587
|
+
contentKey,
|
|
32588
|
+
{ name: "AES-GCM" },
|
|
32589
|
+
false,
|
|
32590
|
+
[usage]
|
|
32591
|
+
);
|
|
32592
|
+
}
|
|
32593
|
+
function chunkNonce(noncePrefix, chunkIndex) {
|
|
32594
|
+
if (chunkIndex > MAX_CHUNK_INDEX) {
|
|
32595
|
+
throw new JobEnvelopeError("Invalid job result: too many chunks");
|
|
32596
|
+
}
|
|
32597
|
+
const nonce = noncePrefix.slice();
|
|
32598
|
+
const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength);
|
|
32599
|
+
view.setUint32(8, view.getUint32(8) ^ chunkIndex);
|
|
32600
|
+
return nonce;
|
|
32601
|
+
}
|
|
32602
|
+
function chunkAad(metadataBytes, chunkIndex, final, plaintextLength) {
|
|
32603
|
+
const aad = new Uint8Array(14 + metadataBytes.length);
|
|
32604
|
+
aad[0] = JOB_RESULT_FORMAT_VERSION;
|
|
32605
|
+
aad.set(uint32(metadataBytes.length), 1);
|
|
32606
|
+
aad.set(metadataBytes, 5);
|
|
32607
|
+
aad.set(uint32(chunkIndex), 5 + metadataBytes.length);
|
|
32608
|
+
aad[9 + metadataBytes.length] = final ? FINAL_FRAME_FLAG : 0;
|
|
32609
|
+
aad.set(uint32(plaintextLength), 10 + metadataBytes.length);
|
|
32610
|
+
return aad;
|
|
32611
|
+
}
|
|
32612
|
+
async function encryptResultChunk(key, noncePrefix, metadataBytes, plaintext, chunkIndex, final) {
|
|
32613
|
+
const encrypted = new Uint8Array(
|
|
32614
|
+
await webCrypto().subtle.encrypt(
|
|
32615
|
+
{
|
|
32616
|
+
name: "AES-GCM",
|
|
32617
|
+
iv: chunkNonce(noncePrefix, chunkIndex),
|
|
32618
|
+
additionalData: chunkAad(
|
|
32619
|
+
metadataBytes,
|
|
32620
|
+
chunkIndex,
|
|
32621
|
+
final,
|
|
32622
|
+
plaintext.length
|
|
32623
|
+
),
|
|
32624
|
+
tagLength: AES_GCM_TAG_BYTES * 8
|
|
32625
|
+
},
|
|
32626
|
+
key,
|
|
32627
|
+
plaintext
|
|
32628
|
+
)
|
|
32629
|
+
);
|
|
32630
|
+
const frame = new Uint8Array(
|
|
32631
|
+
FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES + encrypted.length
|
|
32632
|
+
);
|
|
32633
|
+
new DataView(frame.buffer).setUint32(0, encrypted.length);
|
|
32634
|
+
frame[FRAME_LENGTH_BYTES] = final ? FINAL_FRAME_FLAG : 0;
|
|
32635
|
+
frame.set(encrypted, FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES);
|
|
32636
|
+
return frame;
|
|
32637
|
+
}
|
|
32638
|
+
function verifyResultBindings(metadata, expect) {
|
|
32639
|
+
if (metadata.jobId !== expect.jobId) {
|
|
32640
|
+
throw new JobEnvelopeError(
|
|
32641
|
+
`Job result ID ${metadata.jobId} does not match expected job ID ${expect.jobId}`
|
|
32642
|
+
);
|
|
32643
|
+
}
|
|
32644
|
+
if (expect.scope !== void 0 && metadata.scope !== expect.scope) {
|
|
32645
|
+
throw new JobEnvelopeError(
|
|
32646
|
+
`Job result scope ${metadata.scope} does not match expected scope ${expect.scope}`
|
|
32647
|
+
);
|
|
32648
|
+
}
|
|
32649
|
+
if (expect.version !== void 0 && metadata.version !== expect.version) {
|
|
32650
|
+
throw new JobEnvelopeError(
|
|
32651
|
+
`Job result version ${String(metadata.version)} does not match expected version ${String(expect.version)}`
|
|
32652
|
+
);
|
|
32653
|
+
}
|
|
32654
|
+
}
|
|
32655
|
+
var ByteStreamReader = class {
|
|
32656
|
+
reader;
|
|
32657
|
+
current;
|
|
32658
|
+
offset = 0;
|
|
32659
|
+
ended = false;
|
|
32660
|
+
constructor(stream) {
|
|
32661
|
+
this.reader = stream.getReader();
|
|
32662
|
+
}
|
|
32663
|
+
async ensureBytes() {
|
|
32664
|
+
while (!this.current || this.offset === this.current.length) {
|
|
32665
|
+
if (this.ended) return false;
|
|
32666
|
+
const next = await this.reader.read();
|
|
32667
|
+
if (next.done) {
|
|
32668
|
+
this.ended = true;
|
|
32669
|
+
this.current = void 0;
|
|
32670
|
+
return false;
|
|
32671
|
+
}
|
|
32672
|
+
if (!(next.value instanceof Uint8Array)) {
|
|
32673
|
+
throw new JobEnvelopeError(
|
|
32674
|
+
"Invalid job result: stream yielded non-byte data"
|
|
32675
|
+
);
|
|
32676
|
+
}
|
|
32677
|
+
this.current = next.value;
|
|
32678
|
+
this.offset = 0;
|
|
32679
|
+
}
|
|
32680
|
+
return true;
|
|
32681
|
+
}
|
|
32682
|
+
async readExactOrNull(length) {
|
|
32683
|
+
if (!await this.ensureBytes()) return null;
|
|
32684
|
+
const bytes = new Uint8Array(length);
|
|
32685
|
+
let written = 0;
|
|
32686
|
+
while (written < length) {
|
|
32687
|
+
if (!await this.ensureBytes()) {
|
|
32688
|
+
throw new JobEnvelopeError("Invalid job result: truncated payload");
|
|
32689
|
+
}
|
|
32690
|
+
const available = this.current.length - this.offset;
|
|
32691
|
+
const count = Math.min(available, length - written);
|
|
32692
|
+
bytes.set(
|
|
32693
|
+
this.current.subarray(this.offset, this.offset + count),
|
|
32694
|
+
written
|
|
32695
|
+
);
|
|
32696
|
+
this.offset += count;
|
|
32697
|
+
written += count;
|
|
32698
|
+
}
|
|
32699
|
+
return bytes;
|
|
32700
|
+
}
|
|
32701
|
+
async readExact(length) {
|
|
32702
|
+
const bytes = await this.readExactOrNull(length);
|
|
32703
|
+
if (!bytes) {
|
|
32704
|
+
throw new JobEnvelopeError("Invalid job result: truncated payload");
|
|
32705
|
+
}
|
|
32706
|
+
return bytes;
|
|
32707
|
+
}
|
|
32708
|
+
async hasRemaining() {
|
|
32709
|
+
return this.ensureBytes();
|
|
32710
|
+
}
|
|
32711
|
+
async cancel(reason) {
|
|
32712
|
+
await this.reader.cancel(reason);
|
|
32713
|
+
}
|
|
32714
|
+
};
|
|
32715
|
+
function normalizeChunkError(error) {
|
|
32716
|
+
if (error instanceof JobEnvelopeError) return error;
|
|
32717
|
+
return new JobEnvelopeError(
|
|
32718
|
+
`Invalid job result: chunk authentication failed${error instanceof Error ? `: ${error.message}` : ""}`
|
|
32719
|
+
);
|
|
32720
|
+
}
|
|
32721
|
+
async function sealJobRequest(envelope, enclavePublicKey, ecies) {
|
|
32722
|
+
const encrypted = await ecies.encrypt(
|
|
32723
|
+
fromHex6(enclavePublicKey, "bytes"),
|
|
32724
|
+
requestPlaintext(envelope)
|
|
32725
|
+
);
|
|
32726
|
+
return encryptedBytesToBase64(encrypted);
|
|
32727
|
+
}
|
|
32728
|
+
async function openJobRequest(ciphertext, privateKey, ecies) {
|
|
32729
|
+
const plaintext = await ecies.decrypt(
|
|
32730
|
+
privateKey,
|
|
32731
|
+
base64ToEncrypted(ciphertext)
|
|
32732
|
+
);
|
|
32733
|
+
return validateRequestEnvelope(
|
|
32734
|
+
parseObject(plaintext, "job request envelope")
|
|
32735
|
+
);
|
|
32736
|
+
}
|
|
32737
|
+
async function sealJobResultStream(metadataValue, builderPublicKey, ecies) {
|
|
32738
|
+
const metadata = validateResultMetadata(metadataValue);
|
|
32739
|
+
const metadataBytes = canonicalJsonBytes(metadata);
|
|
32740
|
+
if (metadataBytes.length > MAX_JOB_RESULT_HEADER_BYTES) {
|
|
32741
|
+
throw new JobEnvelopeError(
|
|
32742
|
+
`Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
|
|
32743
|
+
);
|
|
32744
|
+
}
|
|
32745
|
+
const crypto2 = webCrypto();
|
|
32746
|
+
const contentKey = crypto2.getRandomValues(new Uint8Array(AES_KEY_BYTES));
|
|
32747
|
+
const noncePrefix = crypto2.getRandomValues(
|
|
32748
|
+
new Uint8Array(AES_GCM_NONCE_BYTES)
|
|
32749
|
+
);
|
|
32750
|
+
const key = await importAesKey(contentKey, "encrypt");
|
|
32751
|
+
const keyPlaintext = wrappedKeyPlaintext(
|
|
32752
|
+
contentKey,
|
|
32753
|
+
noncePrefix,
|
|
32754
|
+
metadataBytes
|
|
32755
|
+
);
|
|
32756
|
+
const encryptedKey = await ecies.encrypt(
|
|
32757
|
+
fromHex6(builderPublicKey, "bytes"),
|
|
32758
|
+
keyPlaintext
|
|
32759
|
+
);
|
|
32760
|
+
contentKey.fill(0);
|
|
32761
|
+
keyPlaintext.fill(0);
|
|
32762
|
+
const wrappedKey = encryptedToBytes(encryptedKey);
|
|
32763
|
+
if (wrappedKey.length > MAX_WRAPPED_KEY_BYTES) {
|
|
32764
|
+
throw new JobEnvelopeError("Invalid job result: wrapped key is too large");
|
|
32765
|
+
}
|
|
32766
|
+
const header = new Uint8Array(
|
|
32767
|
+
1 + WRAPPED_KEY_LENGTH_BYTES + wrappedKey.length
|
|
32768
|
+
);
|
|
32769
|
+
header[0] = JOB_RESULT_FORMAT_VERSION;
|
|
32770
|
+
new DataView(header.buffer).setUint32(1, wrappedKey.length);
|
|
32771
|
+
header.set(wrappedKey, 1 + WRAPPED_KEY_LENGTH_BYTES);
|
|
32772
|
+
let pending = new Uint8Array(JOB_RESULT_CHUNK_BYTES);
|
|
32773
|
+
let pendingLength = 0;
|
|
32774
|
+
let chunkIndex = 0;
|
|
32775
|
+
const transform = new TransformStream({
|
|
32776
|
+
async transform(chunk, controller) {
|
|
32777
|
+
if (!(chunk instanceof Uint8Array)) {
|
|
32778
|
+
throw new JobEnvelopeError(
|
|
32779
|
+
"Invalid job result: stream yielded non-byte data"
|
|
32780
|
+
);
|
|
32781
|
+
}
|
|
32782
|
+
let offset = 0;
|
|
32783
|
+
while (offset < chunk.length) {
|
|
32784
|
+
if (pendingLength === JOB_RESULT_CHUNK_BYTES) {
|
|
32785
|
+
controller.enqueue(
|
|
32786
|
+
await encryptResultChunk(
|
|
32787
|
+
key,
|
|
32788
|
+
noncePrefix,
|
|
32789
|
+
metadataBytes,
|
|
32790
|
+
pending,
|
|
32791
|
+
chunkIndex,
|
|
32792
|
+
false
|
|
32793
|
+
)
|
|
32794
|
+
);
|
|
32795
|
+
chunkIndex += 1;
|
|
32796
|
+
pending = new Uint8Array(JOB_RESULT_CHUNK_BYTES);
|
|
32797
|
+
pendingLength = 0;
|
|
32798
|
+
}
|
|
32799
|
+
const count = Math.min(
|
|
32800
|
+
chunk.length - offset,
|
|
32801
|
+
JOB_RESULT_CHUNK_BYTES - pendingLength
|
|
32802
|
+
);
|
|
32803
|
+
pending.set(chunk.subarray(offset, offset + count), pendingLength);
|
|
32804
|
+
pendingLength += count;
|
|
32805
|
+
offset += count;
|
|
32806
|
+
}
|
|
32807
|
+
},
|
|
32808
|
+
async flush(controller) {
|
|
32809
|
+
controller.enqueue(
|
|
32810
|
+
await encryptResultChunk(
|
|
32811
|
+
key,
|
|
32812
|
+
noncePrefix,
|
|
32813
|
+
metadataBytes,
|
|
32814
|
+
pending.subarray(0, pendingLength),
|
|
32815
|
+
chunkIndex,
|
|
32816
|
+
true
|
|
32817
|
+
)
|
|
32818
|
+
);
|
|
32819
|
+
}
|
|
32820
|
+
});
|
|
32821
|
+
return { header, transform };
|
|
32822
|
+
}
|
|
32823
|
+
async function sealJobResult(result, builderPublicKey, ecies) {
|
|
32824
|
+
validateResult(result);
|
|
32825
|
+
const sealed = await sealJobResultStream(
|
|
32826
|
+
resultMetadata(result),
|
|
32827
|
+
builderPublicKey,
|
|
32828
|
+
ecies
|
|
32829
|
+
);
|
|
32830
|
+
const frameCount = Math.max(
|
|
32831
|
+
1,
|
|
32832
|
+
Math.ceil(result.body.length / JOB_RESULT_CHUNK_BYTES)
|
|
32833
|
+
);
|
|
32834
|
+
const size = sealed.header.length + result.body.length + frameCount * (FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES + AES_GCM_TAG_BYTES);
|
|
32835
|
+
const bytes = new Uint8Array(size);
|
|
32836
|
+
bytes.set(sealed.header, 0);
|
|
32837
|
+
let outputOffset = sealed.header.length;
|
|
32838
|
+
const reader = sealed.transform.readable.getReader();
|
|
32839
|
+
const drain = (async () => {
|
|
32840
|
+
for (; ; ) {
|
|
32841
|
+
const next = await reader.read();
|
|
32842
|
+
if (next.done) break;
|
|
32843
|
+
bytes.set(next.value, outputOffset);
|
|
32844
|
+
outputOffset += next.value.length;
|
|
32845
|
+
}
|
|
32846
|
+
})();
|
|
32847
|
+
const writer = sealed.transform.writable.getWriter();
|
|
32848
|
+
const fill = (async () => {
|
|
32849
|
+
for (let offset = 0; offset < result.body.length; offset += JOB_RESULT_CHUNK_BYTES) {
|
|
32850
|
+
await writer.write(
|
|
32851
|
+
result.body.subarray(offset, offset + JOB_RESULT_CHUNK_BYTES)
|
|
32852
|
+
);
|
|
32853
|
+
}
|
|
32854
|
+
await writer.close();
|
|
32855
|
+
})();
|
|
32856
|
+
await Promise.all([drain, fill]);
|
|
32857
|
+
if (outputOffset !== bytes.length) {
|
|
32858
|
+
throw new JobEnvelopeError("Invalid job result: sealed size mismatch");
|
|
32859
|
+
}
|
|
32860
|
+
return { bytes, hash: bytesToHex2(sha2565(bytes)), size };
|
|
32861
|
+
}
|
|
32862
|
+
async function openJobResultStream(bytesStream, builderPrivateKey, ecies, expect) {
|
|
32863
|
+
const reader = new ByteStreamReader(bytesStream);
|
|
32864
|
+
const headerPrefix = await reader.readExact(1 + WRAPPED_KEY_LENGTH_BYTES);
|
|
32865
|
+
const formatVersion = headerPrefix[0];
|
|
32866
|
+
if (formatVersion !== JOB_RESULT_FORMAT_VERSION) {
|
|
32867
|
+
throw new JobEnvelopeError(
|
|
32868
|
+
`Unsupported job result format: ${String(formatVersion)}`
|
|
32869
|
+
);
|
|
32870
|
+
}
|
|
32871
|
+
const wrappedKeyLength = readUint32(headerPrefix, 1);
|
|
32872
|
+
if (wrappedKeyLength === 0 || wrappedKeyLength > MAX_WRAPPED_KEY_BYTES) {
|
|
32873
|
+
throw new JobEnvelopeError(
|
|
32874
|
+
"Invalid job result: invalid wrapped key length"
|
|
32875
|
+
);
|
|
32876
|
+
}
|
|
32877
|
+
const wrappedKey = await reader.readExact(wrappedKeyLength);
|
|
32878
|
+
const keyPlaintext = await ecies.decrypt(
|
|
32879
|
+
fromHex6(builderPrivateKey, "bytes"),
|
|
32880
|
+
bytesToEncrypted(wrappedKey)
|
|
32881
|
+
);
|
|
32882
|
+
const parsed = parseWrappedKeyPlaintext(keyPlaintext);
|
|
32883
|
+
verifyResultBindings(parsed.metadata, expect);
|
|
32884
|
+
const key = await importAesKey(parsed.contentKey, "decrypt");
|
|
32885
|
+
parsed.contentKey.fill(0);
|
|
32886
|
+
keyPlaintext.fill(0);
|
|
32887
|
+
let chunkIndex = 0;
|
|
32888
|
+
let finished = false;
|
|
32889
|
+
const body = new ReadableStream({
|
|
32890
|
+
async pull(controller) {
|
|
32891
|
+
if (finished) {
|
|
32892
|
+
controller.close();
|
|
32893
|
+
return;
|
|
32894
|
+
}
|
|
32895
|
+
try {
|
|
32896
|
+
const frameHeader = await reader.readExactOrNull(
|
|
32897
|
+
FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES
|
|
32898
|
+
);
|
|
32899
|
+
if (!frameHeader) {
|
|
32900
|
+
throw new JobEnvelopeError("Invalid job result: missing final chunk");
|
|
32901
|
+
}
|
|
32902
|
+
const encryptedLength = readUint32(frameHeader);
|
|
32903
|
+
if (encryptedLength < AES_GCM_TAG_BYTES || encryptedLength > JOB_RESULT_CHUNK_BYTES + AES_GCM_TAG_BYTES) {
|
|
32904
|
+
throw new JobEnvelopeError(
|
|
32905
|
+
"Invalid job result: invalid chunk length"
|
|
32906
|
+
);
|
|
32907
|
+
}
|
|
32908
|
+
const flags = frameHeader[FRAME_LENGTH_BYTES];
|
|
32909
|
+
if (flags !== 0 && flags !== FINAL_FRAME_FLAG) {
|
|
32910
|
+
throw new JobEnvelopeError("Invalid job result: invalid chunk flags");
|
|
32911
|
+
}
|
|
32912
|
+
const final = flags === FINAL_FRAME_FLAG;
|
|
32913
|
+
const plaintextLength = encryptedLength - AES_GCM_TAG_BYTES;
|
|
32914
|
+
if (!final && plaintextLength !== JOB_RESULT_CHUNK_BYTES) {
|
|
32915
|
+
throw new JobEnvelopeError(
|
|
32916
|
+
"Invalid job result: short non-final chunk"
|
|
32917
|
+
);
|
|
32918
|
+
}
|
|
32919
|
+
const encrypted = await reader.readExact(encryptedLength);
|
|
32920
|
+
const plaintext = new Uint8Array(
|
|
32921
|
+
await webCrypto().subtle.decrypt(
|
|
32922
|
+
{
|
|
32923
|
+
name: "AES-GCM",
|
|
32924
|
+
iv: chunkNonce(parsed.noncePrefix, chunkIndex),
|
|
32925
|
+
additionalData: chunkAad(
|
|
32926
|
+
parsed.metadataBytes,
|
|
32927
|
+
chunkIndex,
|
|
32928
|
+
final,
|
|
32929
|
+
plaintextLength
|
|
32930
|
+
),
|
|
32931
|
+
tagLength: AES_GCM_TAG_BYTES * 8
|
|
32932
|
+
},
|
|
32933
|
+
key,
|
|
32934
|
+
encrypted
|
|
32935
|
+
)
|
|
32936
|
+
);
|
|
32937
|
+
if (plaintext.length !== plaintextLength) {
|
|
32938
|
+
throw new JobEnvelopeError(
|
|
32939
|
+
"Invalid job result: decrypted chunk length mismatch"
|
|
32940
|
+
);
|
|
32941
|
+
}
|
|
32942
|
+
chunkIndex += 1;
|
|
32943
|
+
if (final) {
|
|
32944
|
+
if (await reader.hasRemaining()) {
|
|
32945
|
+
throw new JobEnvelopeError(
|
|
32946
|
+
"Invalid job result: bytes follow final chunk"
|
|
32947
|
+
);
|
|
32948
|
+
}
|
|
32949
|
+
finished = true;
|
|
32950
|
+
}
|
|
32951
|
+
controller.enqueue(plaintext);
|
|
32952
|
+
if (finished) controller.close();
|
|
32953
|
+
} catch (error) {
|
|
32954
|
+
controller.error(normalizeChunkError(error));
|
|
32955
|
+
void reader.cancel(error).catch(() => void 0);
|
|
32956
|
+
}
|
|
32957
|
+
},
|
|
32958
|
+
cancel(reason) {
|
|
32959
|
+
return reader.cancel(reason);
|
|
32960
|
+
}
|
|
32961
|
+
});
|
|
32962
|
+
return { metadata: parsed.metadata, body };
|
|
32963
|
+
}
|
|
32964
|
+
function bufferedResultBodySize(sealedBytes) {
|
|
32965
|
+
if (sealedBytes.length < 1 + WRAPPED_KEY_LENGTH_BYTES) {
|
|
32966
|
+
throw new JobEnvelopeError("Invalid job result: truncated payload");
|
|
32967
|
+
}
|
|
32968
|
+
if (sealedBytes[0] !== JOB_RESULT_FORMAT_VERSION) {
|
|
32969
|
+
throw new JobEnvelopeError(
|
|
32970
|
+
`Unsupported job result format: ${String(sealedBytes[0])}`
|
|
32971
|
+
);
|
|
32972
|
+
}
|
|
32973
|
+
const wrappedKeyLength = readUint32(sealedBytes, 1);
|
|
32974
|
+
if (wrappedKeyLength === 0 || wrappedKeyLength > MAX_WRAPPED_KEY_BYTES) {
|
|
32975
|
+
throw new JobEnvelopeError(
|
|
32976
|
+
"Invalid job result: invalid wrapped key length"
|
|
32977
|
+
);
|
|
32978
|
+
}
|
|
32979
|
+
let offset = 1 + WRAPPED_KEY_LENGTH_BYTES + wrappedKeyLength;
|
|
32980
|
+
if (offset > sealedBytes.length) {
|
|
32981
|
+
throw new JobEnvelopeError("Invalid job result: truncated payload");
|
|
32982
|
+
}
|
|
32983
|
+
let bodySize = 0;
|
|
32984
|
+
let sawFinal = false;
|
|
32985
|
+
while (offset < sealedBytes.length) {
|
|
32986
|
+
if (sealedBytes.length - offset < FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES) {
|
|
32987
|
+
throw new JobEnvelopeError("Invalid job result: truncated payload");
|
|
32988
|
+
}
|
|
32989
|
+
const encryptedLength = readUint32(sealedBytes, offset);
|
|
32990
|
+
const flags = sealedBytes[offset + FRAME_LENGTH_BYTES];
|
|
32991
|
+
if (encryptedLength < AES_GCM_TAG_BYTES || encryptedLength > JOB_RESULT_CHUNK_BYTES + AES_GCM_TAG_BYTES || flags !== 0 && flags !== FINAL_FRAME_FLAG) {
|
|
32992
|
+
throw new JobEnvelopeError("Invalid job result: invalid chunk framing");
|
|
32993
|
+
}
|
|
32994
|
+
const plaintextLength = encryptedLength - AES_GCM_TAG_BYTES;
|
|
32995
|
+
if (flags === 0 && plaintextLength !== JOB_RESULT_CHUNK_BYTES) {
|
|
32996
|
+
throw new JobEnvelopeError("Invalid job result: short non-final chunk");
|
|
32997
|
+
}
|
|
32998
|
+
offset += FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES;
|
|
32999
|
+
if (encryptedLength > sealedBytes.length - offset) {
|
|
33000
|
+
throw new JobEnvelopeError("Invalid job result: truncated payload");
|
|
33001
|
+
}
|
|
33002
|
+
offset += encryptedLength;
|
|
33003
|
+
bodySize += plaintextLength;
|
|
33004
|
+
if (flags === FINAL_FRAME_FLAG) {
|
|
33005
|
+
sawFinal = true;
|
|
33006
|
+
if (offset !== sealedBytes.length) {
|
|
33007
|
+
throw new JobEnvelopeError(
|
|
33008
|
+
"Invalid job result: bytes follow final chunk"
|
|
33009
|
+
);
|
|
33010
|
+
}
|
|
33011
|
+
}
|
|
33012
|
+
}
|
|
33013
|
+
if (!sawFinal) {
|
|
33014
|
+
throw new JobEnvelopeError("Invalid job result: missing final chunk");
|
|
33015
|
+
}
|
|
33016
|
+
return bodySize;
|
|
33017
|
+
}
|
|
33018
|
+
async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
|
|
33019
|
+
const bodySize = bufferedResultBodySize(sealedBytes);
|
|
33020
|
+
const stream = new ReadableStream({
|
|
33021
|
+
start(controller) {
|
|
33022
|
+
controller.enqueue(sealedBytes);
|
|
33023
|
+
controller.close();
|
|
33024
|
+
}
|
|
33025
|
+
});
|
|
33026
|
+
const opened = await openJobResultStream(
|
|
33027
|
+
stream,
|
|
33028
|
+
builderPrivateKey,
|
|
33029
|
+
ecies,
|
|
33030
|
+
expect
|
|
33031
|
+
);
|
|
33032
|
+
const body = new Uint8Array(bodySize);
|
|
33033
|
+
let offset = 0;
|
|
33034
|
+
await opened.body.pipeTo(
|
|
33035
|
+
new WritableStream({
|
|
33036
|
+
write(chunk) {
|
|
33037
|
+
body.set(chunk, offset);
|
|
33038
|
+
offset += chunk.length;
|
|
33039
|
+
}
|
|
33040
|
+
})
|
|
33041
|
+
);
|
|
33042
|
+
if (offset !== body.length) {
|
|
33043
|
+
throw new JobEnvelopeError("Invalid job result: opened size mismatch");
|
|
33044
|
+
}
|
|
33045
|
+
return { ...opened.metadata, body };
|
|
33046
|
+
}
|
|
33047
|
+
|
|
33048
|
+
// src/protocol/jobs-client.ts
|
|
33049
|
+
import {
|
|
33050
|
+
BuilderUnknownError,
|
|
33051
|
+
GrantInvalidError,
|
|
33052
|
+
JobIdTakenError,
|
|
33053
|
+
JobNotFoundError,
|
|
33054
|
+
JobRejectedError,
|
|
33055
|
+
JobResultIntegrityError,
|
|
33056
|
+
JobRequestTooLargeError,
|
|
33057
|
+
JobTimeoutError,
|
|
33058
|
+
JobTransportError,
|
|
33059
|
+
OwnerNotReadyError
|
|
33060
|
+
} from "./errors.js";
|
|
33061
|
+
|
|
33062
|
+
// src/protocol/write-signer.ts
|
|
33063
|
+
import { WriteRequestError } from "./errors.js";
|
|
33064
|
+
function isRecord(value) {
|
|
33065
|
+
return value !== null && typeof value === "object";
|
|
33066
|
+
}
|
|
33067
|
+
function isViemWriteAccount(source) {
|
|
33068
|
+
return isRecord(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
|
|
33069
|
+
}
|
|
33070
|
+
function isViemWriteWalletClient(source) {
|
|
33071
|
+
return isRecord(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
|
|
33072
|
+
}
|
|
33073
|
+
function accountAddress(account) {
|
|
33074
|
+
return typeof account === "string" ? account : account.address;
|
|
33075
|
+
}
|
|
33076
|
+
function resolveWriteSigner(source, options = {}) {
|
|
33077
|
+
if (isViemWriteWalletClient(source)) {
|
|
33078
|
+
const account = options.account ?? source.account;
|
|
33079
|
+
if (account === void 0) {
|
|
33080
|
+
throw new WriteRequestError(
|
|
33081
|
+
"Viem wallet client requires an account option or account property"
|
|
33082
|
+
);
|
|
33083
|
+
}
|
|
33084
|
+
return {
|
|
33085
|
+
address: accountAddress(account),
|
|
33086
|
+
signMessage: (message) => source.signMessage({ account, message })
|
|
33087
|
+
};
|
|
33088
|
+
}
|
|
33089
|
+
if (isViemWriteAccount(source)) {
|
|
33090
|
+
return {
|
|
33091
|
+
address: source.address,
|
|
33092
|
+
signMessage: (message) => source.signMessage({ message })
|
|
33093
|
+
};
|
|
33094
|
+
}
|
|
33095
|
+
if (!isRecord(source) || typeof source.signMessage !== "function") {
|
|
33096
|
+
throw new WriteRequestError(
|
|
33097
|
+
"signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
|
|
33098
|
+
);
|
|
33099
|
+
}
|
|
33100
|
+
return source;
|
|
33101
|
+
}
|
|
33102
|
+
|
|
33103
|
+
// src/protocol/jobs-client.ts
|
|
33104
|
+
var IDENTITY_PATH = "/v1/identity";
|
|
33105
|
+
var JOBS_PATH = "/v1/jobs";
|
|
33106
|
+
var JOB_EXECUTE_PATH = "/v1/jobs/execute";
|
|
33107
|
+
var AUTHORIZATION_HEADER = "Authorization";
|
|
33108
|
+
var CONTENT_TYPE_HEADER = "Content-Type";
|
|
33109
|
+
var JSON_CONTENT_TYPE = "application/json";
|
|
33110
|
+
var GET_METHOD = "GET";
|
|
33111
|
+
var POST_METHOD = "POST";
|
|
33112
|
+
var RAW_READ_OPERATION = "raw_read";
|
|
33113
|
+
var SEALED_IDENTITY_STATE = "sealed";
|
|
33114
|
+
var HTTP_OK = 200;
|
|
33115
|
+
var HTTP_ACCEPTED = 202;
|
|
33116
|
+
var HTTP_UNAUTHORIZED = 401;
|
|
33117
|
+
var HTTP_FORBIDDEN = 403;
|
|
33118
|
+
var HTTP_NOT_FOUND = 404;
|
|
33119
|
+
var HTTP_CONFLICT = 409;
|
|
33120
|
+
var HTTP_PAYLOAD_TOO_LARGE = 413;
|
|
33121
|
+
var MILLISECONDS_PER_SECOND = 1e3;
|
|
33122
|
+
var DEFAULT_JOB_TIMEOUT_MS = 12e4;
|
|
33123
|
+
var DEFAULT_JOB_POLL_MS = CLAIM_POLL_FLOOR_MS;
|
|
33124
|
+
var TERMINAL_JOB_STATES = /* @__PURE__ */ new Set([
|
|
33125
|
+
"completed",
|
|
33126
|
+
"failed",
|
|
33127
|
+
"expired",
|
|
33128
|
+
"cancelled"
|
|
33129
|
+
]);
|
|
33130
|
+
function isRecord2(value) {
|
|
33131
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
33132
|
+
}
|
|
33133
|
+
function normalizeGateway(gatewayUrl) {
|
|
33134
|
+
try {
|
|
33135
|
+
const url = new URL(gatewayUrl);
|
|
33136
|
+
if (url.pathname !== "/" || url.search !== "" || url.hash !== "") {
|
|
33137
|
+
throw new JobRejectedError(
|
|
33138
|
+
"gatewayUrl must be an origin without a path, query, or fragment"
|
|
33139
|
+
);
|
|
33140
|
+
}
|
|
33141
|
+
return {
|
|
33142
|
+
baseUrl: url.origin,
|
|
33143
|
+
audience: url.origin
|
|
33144
|
+
};
|
|
33145
|
+
} catch (error) {
|
|
33146
|
+
if (error instanceof JobRejectedError) throw error;
|
|
33147
|
+
throw new JobRejectedError(
|
|
33148
|
+
"gatewayUrl must be an absolute URL",
|
|
33149
|
+
void 0,
|
|
33150
|
+
null,
|
|
33151
|
+
{
|
|
33152
|
+
cause: error instanceof Error ? error.message : String(error)
|
|
33153
|
+
}
|
|
33154
|
+
);
|
|
33155
|
+
}
|
|
33156
|
+
}
|
|
33157
|
+
function resolveFetch(fetchFn) {
|
|
33158
|
+
const resolved = fetchFn ?? globalThis.fetch;
|
|
33159
|
+
if (resolved === void 0) {
|
|
33160
|
+
throw new JobRejectedError("No fetch implementation available");
|
|
33161
|
+
}
|
|
33162
|
+
return resolved;
|
|
33163
|
+
}
|
|
33164
|
+
function sourcePublicKey(source) {
|
|
33165
|
+
if (isRecord2(source) && typeof source["publicKey"] === "string") {
|
|
33166
|
+
return source["publicKey"];
|
|
33167
|
+
}
|
|
33168
|
+
return void 0;
|
|
33169
|
+
}
|
|
33170
|
+
function resolveBuilder(options) {
|
|
33171
|
+
if (options.builderPrivateKey && options.builderAccount) {
|
|
33172
|
+
throw new JobRejectedError(
|
|
33173
|
+
"Provide builderPrivateKey or builderAccount, not both"
|
|
33174
|
+
);
|
|
33175
|
+
}
|
|
33176
|
+
let source;
|
|
33177
|
+
try {
|
|
33178
|
+
source = options.builderPrivateKey ? privateKeyToAccount(options.builderPrivateKey) : options.builderAccount;
|
|
33179
|
+
} catch (error) {
|
|
33180
|
+
throw new JobRejectedError("Invalid builder private key", void 0, null, {
|
|
33181
|
+
cause: error instanceof Error ? error.message : String(error)
|
|
33182
|
+
});
|
|
33183
|
+
}
|
|
33184
|
+
if (!source) {
|
|
33185
|
+
throw new JobRejectedError(
|
|
33186
|
+
"builderPrivateKey or builderAccount is required"
|
|
33187
|
+
);
|
|
33188
|
+
}
|
|
33189
|
+
let signer;
|
|
33190
|
+
try {
|
|
33191
|
+
signer = resolveWriteSigner(source);
|
|
33192
|
+
} catch (error) {
|
|
33193
|
+
throw new JobRejectedError("Invalid builder signer", void 0, null, {
|
|
33194
|
+
cause: error instanceof Error ? error.message : String(error)
|
|
33195
|
+
});
|
|
33196
|
+
}
|
|
33197
|
+
const publicKey = sourcePublicKey(source);
|
|
33198
|
+
if (!signer.address || !publicKey) {
|
|
33199
|
+
throw new JobRejectedError(
|
|
33200
|
+
"Builder signer must expose both address and publicKey"
|
|
33201
|
+
);
|
|
33202
|
+
}
|
|
33203
|
+
return {
|
|
33204
|
+
builder: {
|
|
33205
|
+
address: signer.address,
|
|
33206
|
+
publicKey,
|
|
33207
|
+
signMessage: signer.signMessage
|
|
33208
|
+
},
|
|
33209
|
+
...options.builderPrivateKey ? { privateKey: options.builderPrivateKey } : {}
|
|
33210
|
+
};
|
|
33211
|
+
}
|
|
33212
|
+
function clampInteger(value, fallback, minimum, maximum, field) {
|
|
33213
|
+
const resolved = value ?? fallback;
|
|
33214
|
+
if (!Number.isFinite(resolved)) {
|
|
33215
|
+
throw new JobRejectedError(`${field} must be a finite number`);
|
|
33216
|
+
}
|
|
33217
|
+
return Math.min(maximum, Math.max(minimum, Math.trunc(resolved)));
|
|
33218
|
+
}
|
|
33219
|
+
async function responseBody(response) {
|
|
33220
|
+
try {
|
|
33221
|
+
return await response.json();
|
|
33222
|
+
} catch {
|
|
33223
|
+
return null;
|
|
33224
|
+
}
|
|
33225
|
+
}
|
|
33226
|
+
function gatewayErrorBody(body, fallback) {
|
|
33227
|
+
if (!isRecord2(body)) return { code: null, message: fallback };
|
|
33228
|
+
const code = typeof body["code"] === "string" ? body["code"] : null;
|
|
33229
|
+
const message = typeof body["error"] === "string" ? body["error"] : typeof body["message"] === "string" ? body["message"] : fallback;
|
|
33230
|
+
const reason = typeof body["reason"] === "string" ? body["reason"] : void 0;
|
|
33231
|
+
const details = isRecord2(body["details"]) ? body["details"] : void 0;
|
|
33232
|
+
return {
|
|
33233
|
+
code,
|
|
33234
|
+
message,
|
|
33235
|
+
...reason ? { reason } : {},
|
|
33236
|
+
...details ? { details } : {}
|
|
33237
|
+
};
|
|
33238
|
+
}
|
|
33239
|
+
async function rejectedResponse(response, fallback) {
|
|
33240
|
+
const parsed = gatewayErrorBody(await responseBody(response), fallback);
|
|
33241
|
+
const details = response.status === HTTP_UNAUTHORIZED && parsed.reason ? { ...parsed.details, reason: parsed.reason } : parsed.details;
|
|
33242
|
+
const message = response.status === HTTP_UNAUTHORIZED && parsed.reason ? `${parsed.message}: ${parsed.reason}` : parsed.message;
|
|
33243
|
+
if (response.status === HTTP_FORBIDDEN) {
|
|
33244
|
+
if (parsed.code === "BUILDER_UNKNOWN") {
|
|
33245
|
+
return new BuilderUnknownError(parsed.message, details);
|
|
33246
|
+
}
|
|
33247
|
+
if (parsed.code === "GRANT_INVALID") {
|
|
33248
|
+
return new GrantInvalidError(parsed.message, details);
|
|
33249
|
+
}
|
|
33250
|
+
if (parsed.code === "OWNER_NOT_READY") {
|
|
33251
|
+
return new OwnerNotReadyError(parsed.message, details);
|
|
33252
|
+
}
|
|
33253
|
+
}
|
|
33254
|
+
if (response.status === HTTP_NOT_FOUND) {
|
|
33255
|
+
return new JobNotFoundError(parsed.message, details);
|
|
33256
|
+
}
|
|
33257
|
+
if (response.status === HTTP_CONFLICT && parsed.code === "JOB_ID_TAKEN") {
|
|
33258
|
+
return new JobIdTakenError(parsed.message, details);
|
|
33259
|
+
}
|
|
33260
|
+
if (response.status === HTTP_PAYLOAD_TOO_LARGE) {
|
|
33261
|
+
return new JobRequestTooLargeError(parsed.message, parsed.code, details);
|
|
33262
|
+
}
|
|
33263
|
+
return new JobRejectedError(message, response.status, parsed.code, details);
|
|
33264
|
+
}
|
|
33265
|
+
function requireStatus(value, status) {
|
|
33266
|
+
if (!isRecord2(value) || !isNonEmptyString(value["jobId"]) || typeof value["state"] !== "string" || !JOB_STATES.includes(value["state"]) || !isNonEmptyString(value["owner"]) || !isNonEmptyString(value["grantId"]) || !isNonEmptyString(value["scope"]) || !isNonEmptyString(value["operation"]) || !JOB_OPERATIONS.includes(value["operation"]) || value["state"] === "completed" && !isResultHandle(value["result"])) {
|
|
33267
|
+
throw new JobRejectedError(
|
|
33268
|
+
"Gateway response did not contain a job status",
|
|
33269
|
+
status
|
|
33270
|
+
);
|
|
33271
|
+
}
|
|
33272
|
+
return value;
|
|
33273
|
+
}
|
|
33274
|
+
function isNonEmptyString(value) {
|
|
33275
|
+
return typeof value === "string" && value.length > 0;
|
|
33276
|
+
}
|
|
33277
|
+
function isResultHandle(value) {
|
|
33278
|
+
if (!isRecord2(value) || !isNonEmptyString(value["objectKey"]) || !isNonEmptyString(value["url"]) || typeof value["size"] !== "number" || !Number.isInteger(value["size"]) || value["size"] < 0 || typeof value["hash"] !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(value["hash"]) || typeof value["expiresAt"] !== "string" || Number.isNaN(Date.parse(value["expiresAt"]))) {
|
|
33279
|
+
return false;
|
|
33280
|
+
}
|
|
33281
|
+
try {
|
|
33282
|
+
const url = new URL(value["url"]);
|
|
33283
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
33284
|
+
} catch {
|
|
33285
|
+
return false;
|
|
33286
|
+
}
|
|
33287
|
+
}
|
|
33288
|
+
function hasMatchingIdentityKey(value) {
|
|
33289
|
+
const address = value["address"];
|
|
33290
|
+
const publicKey = value["publicKey"];
|
|
33291
|
+
if (typeof address !== "string" || !isAddress2(address) || typeof publicKey !== "string" || !isHex2(publicKey)) {
|
|
33292
|
+
return false;
|
|
33293
|
+
}
|
|
33294
|
+
try {
|
|
33295
|
+
return publicKeyToAddress2(publicKey).toLowerCase() === address.toLowerCase();
|
|
33296
|
+
} catch {
|
|
33297
|
+
return false;
|
|
33298
|
+
}
|
|
33299
|
+
}
|
|
33300
|
+
function hasExpectedIdentity(value, owner, chainId) {
|
|
33301
|
+
const identityOwner = value["ownerAddress"];
|
|
33302
|
+
const identityChainId = value["chainId"];
|
|
33303
|
+
const identityUserPsId = value["userPsId"];
|
|
33304
|
+
if (!hasMatchingIdentityKey(value) || typeof identityOwner !== "string" || !isAddress2(identityOwner) || typeof identityChainId !== "number" || typeof identityUserPsId !== "string" || !isHex2(identityUserPsId)) {
|
|
33305
|
+
return false;
|
|
33306
|
+
}
|
|
33307
|
+
return isAddressEqual2(identityOwner, owner) && identityChainId === chainId && identityUserPsId.toLowerCase() === userPsId(chainId, owner).toLowerCase();
|
|
33308
|
+
}
|
|
33309
|
+
function sleep2(ms) {
|
|
33310
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
33311
|
+
}
|
|
33312
|
+
function requireFiniteDuration(value, field) {
|
|
33313
|
+
if (!Number.isFinite(value)) {
|
|
33314
|
+
throw new JobRejectedError(`${field} must be a finite number`);
|
|
33315
|
+
}
|
|
33316
|
+
return Math.max(0, value);
|
|
33317
|
+
}
|
|
33318
|
+
function createJobsClient(options) {
|
|
33319
|
+
const { baseUrl, audience } = normalizeGateway(options.gatewayUrl);
|
|
33320
|
+
const fetchFn = resolveFetch(options.fetch);
|
|
33321
|
+
const { builder, privateKey } = resolveBuilder(options);
|
|
33322
|
+
const ecies = options.ecies ?? new NodeECIESUint8Provider();
|
|
33323
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
33324
|
+
async function request(url, init, description) {
|
|
33325
|
+
try {
|
|
33326
|
+
return await fetchFn(url, init);
|
|
33327
|
+
} catch (error) {
|
|
33328
|
+
throw new JobTransportError(
|
|
33329
|
+
`${description} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
33330
|
+
error
|
|
33331
|
+
);
|
|
33332
|
+
}
|
|
33333
|
+
}
|
|
33334
|
+
async function getIdentity(owner) {
|
|
33335
|
+
const query = new URLSearchParams({
|
|
33336
|
+
owner,
|
|
33337
|
+
chainId: String(options.chainId)
|
|
33338
|
+
});
|
|
33339
|
+
const response = await request(
|
|
33340
|
+
`${baseUrl}${IDENTITY_PATH}?${query.toString()}`,
|
|
33341
|
+
{ method: GET_METHOD },
|
|
33342
|
+
"Owner identity lookup"
|
|
33343
|
+
);
|
|
33344
|
+
if (response.status === HTTP_NOT_FOUND) {
|
|
33345
|
+
const parsed = gatewayErrorBody(
|
|
33346
|
+
await responseBody(response),
|
|
33347
|
+
"Owner identity not found"
|
|
33348
|
+
);
|
|
33349
|
+
throw new OwnerNotReadyError(parsed.message, parsed.details);
|
|
33350
|
+
}
|
|
33351
|
+
if (!response.ok) {
|
|
33352
|
+
throw await rejectedResponse(response, "Owner identity lookup rejected");
|
|
33353
|
+
}
|
|
33354
|
+
const body = await responseBody(response);
|
|
33355
|
+
if (!isRecord2(body) || body["state"] !== SEALED_IDENTITY_STATE || !isRecord2(body["identity"])) {
|
|
33356
|
+
throw new OwnerNotReadyError("Owner identity is not sealed", {
|
|
33357
|
+
state: isRecord2(body) ? body["state"] : void 0
|
|
33358
|
+
});
|
|
33359
|
+
}
|
|
33360
|
+
if (!hasExpectedIdentity(body["identity"], owner, options.chainId)) {
|
|
33361
|
+
throw new JobRejectedError(
|
|
33362
|
+
"Gateway returned a malformed or mismatched owner identity",
|
|
33363
|
+
response.status
|
|
33364
|
+
);
|
|
33365
|
+
}
|
|
33366
|
+
return body["identity"];
|
|
33367
|
+
}
|
|
33368
|
+
const client = {
|
|
33369
|
+
async submitRawRead(params) {
|
|
33370
|
+
const identity = await getIdentity(params.owner);
|
|
33371
|
+
const deadlineSeconds = clampInteger(
|
|
33372
|
+
params.deadlineSeconds,
|
|
33373
|
+
DEFAULT_JOB_DEADLINE_SECONDS,
|
|
33374
|
+
1,
|
|
33375
|
+
MAX_JOB_DEADLINE_SECONDS,
|
|
33376
|
+
"deadlineSeconds"
|
|
33377
|
+
);
|
|
33378
|
+
const wait = clampInteger(params.wait, 0, 0, MAX_WAIT_SECONDS, "wait");
|
|
33379
|
+
const jobId = randomUUID();
|
|
33380
|
+
const nowMs = now().getTime();
|
|
33381
|
+
if (!Number.isFinite(nowMs)) {
|
|
33382
|
+
throw new JobRejectedError("now must return a valid Date");
|
|
33383
|
+
}
|
|
33384
|
+
const deadline = new Date(
|
|
33385
|
+
nowMs + deadlineSeconds * MILLISECONDS_PER_SECOND
|
|
33386
|
+
).toISOString();
|
|
33387
|
+
const requestBody = {
|
|
33388
|
+
v: JOB_PROTOCOL_VERSION,
|
|
33389
|
+
jobId,
|
|
33390
|
+
owner: params.owner,
|
|
33391
|
+
builder: builder.address,
|
|
33392
|
+
builderPublicKey: builder.publicKey,
|
|
33393
|
+
grantId: params.grantId,
|
|
33394
|
+
scope: params.scope,
|
|
33395
|
+
operation: RAW_READ_OPERATION,
|
|
33396
|
+
pinnedVersion: params.pinnedVersion ?? null,
|
|
33397
|
+
deadline
|
|
33398
|
+
};
|
|
33399
|
+
const auth = await buildWeb3SignedHeader({
|
|
33400
|
+
signMessage: builder.signMessage,
|
|
33401
|
+
aud: audience,
|
|
33402
|
+
method: POST_METHOD,
|
|
33403
|
+
uri: JOB_EXECUTE_PATH,
|
|
33404
|
+
bodyHash: computeBodyHash(canonicalJobRequestBytes(requestBody)),
|
|
33405
|
+
nonce: randomUUID()
|
|
33406
|
+
});
|
|
33407
|
+
const requestCiphertext = await sealJobRequest(
|
|
33408
|
+
{ request: requestBody, auth },
|
|
33409
|
+
identity.publicKey,
|
|
33410
|
+
ecies
|
|
33411
|
+
);
|
|
33412
|
+
const submission = {
|
|
33413
|
+
owner: requestBody.owner,
|
|
33414
|
+
grantId: requestBody.grantId,
|
|
33415
|
+
scope: requestBody.scope,
|
|
33416
|
+
operation: requestBody.operation,
|
|
33417
|
+
idempotencyKey: randomUUID(),
|
|
33418
|
+
jobId,
|
|
33419
|
+
deadline,
|
|
33420
|
+
requestCiphertext
|
|
33421
|
+
};
|
|
33422
|
+
const bodyBytes = new TextEncoder().encode(JSON.stringify(submission));
|
|
33423
|
+
const authorization = await buildWeb3SignedHeader({
|
|
33424
|
+
signMessage: builder.signMessage,
|
|
33425
|
+
aud: audience,
|
|
33426
|
+
method: POST_METHOD,
|
|
33427
|
+
uri: JOBS_PATH,
|
|
33428
|
+
body: bodyBytes,
|
|
33429
|
+
nonce: randomUUID()
|
|
33430
|
+
});
|
|
33431
|
+
const response = await request(
|
|
33432
|
+
`${baseUrl}${JOBS_PATH}?wait=${wait}`,
|
|
33433
|
+
{
|
|
33434
|
+
method: POST_METHOD,
|
|
33435
|
+
headers: {
|
|
33436
|
+
[AUTHORIZATION_HEADER]: authorization,
|
|
33437
|
+
[CONTENT_TYPE_HEADER]: JSON_CONTENT_TYPE
|
|
33438
|
+
},
|
|
33439
|
+
body: bodyBytes
|
|
33440
|
+
},
|
|
33441
|
+
"Job submission"
|
|
33442
|
+
);
|
|
33443
|
+
if (!response.ok) {
|
|
33444
|
+
throw await rejectedResponse(response, "Job submission rejected");
|
|
33445
|
+
}
|
|
33446
|
+
const body = await responseBody(response);
|
|
33447
|
+
if (response.status === HTTP_OK && isRecord2(body)) {
|
|
33448
|
+
const job = requireStatus(body["job"], response.status);
|
|
33449
|
+
if (job.jobId !== jobId) {
|
|
33450
|
+
throw new JobRejectedError(
|
|
33451
|
+
"Gateway returned a job id that does not match the submission",
|
|
33452
|
+
response.status
|
|
33453
|
+
);
|
|
33454
|
+
}
|
|
33455
|
+
return { jobId, state: job.state, job };
|
|
33456
|
+
}
|
|
33457
|
+
if (response.status === HTTP_ACCEPTED && isRecord2(body) && body["jobId"] === jobId && typeof body["state"] === "string" && JOB_STATES.includes(body["state"])) {
|
|
33458
|
+
return { jobId, state: body["state"] };
|
|
33459
|
+
}
|
|
33460
|
+
throw new JobRejectedError(
|
|
33461
|
+
"Gateway returned an undocumented job submission response",
|
|
33462
|
+
response.status
|
|
33463
|
+
);
|
|
33464
|
+
},
|
|
33465
|
+
async getJob(jobId) {
|
|
33466
|
+
const path = `${JOBS_PATH}/${encodeURIComponent(jobId)}`;
|
|
33467
|
+
const authorization = await buildWeb3SignedHeader({
|
|
33468
|
+
signMessage: builder.signMessage,
|
|
33469
|
+
aud: audience,
|
|
33470
|
+
method: GET_METHOD,
|
|
33471
|
+
uri: path,
|
|
33472
|
+
nonce: randomUUID()
|
|
33473
|
+
});
|
|
33474
|
+
const response = await request(
|
|
33475
|
+
`${baseUrl}${path}`,
|
|
33476
|
+
{
|
|
33477
|
+
method: GET_METHOD,
|
|
33478
|
+
headers: { [AUTHORIZATION_HEADER]: authorization }
|
|
33479
|
+
},
|
|
33480
|
+
"Job status read"
|
|
33481
|
+
);
|
|
33482
|
+
if (!response.ok) {
|
|
33483
|
+
throw await rejectedResponse(response, "Job status read rejected");
|
|
33484
|
+
}
|
|
33485
|
+
const body = await responseBody(response);
|
|
33486
|
+
return requireStatus(
|
|
33487
|
+
isRecord2(body) ? body["job"] : void 0,
|
|
33488
|
+
response.status
|
|
33489
|
+
);
|
|
33490
|
+
},
|
|
33491
|
+
async waitForJob(jobId, waitOptions = {}) {
|
|
33492
|
+
const timeoutMs = requireFiniteDuration(
|
|
33493
|
+
waitOptions.timeoutMs ?? DEFAULT_JOB_TIMEOUT_MS,
|
|
33494
|
+
"timeoutMs"
|
|
33495
|
+
);
|
|
33496
|
+
const pollMs = Math.max(
|
|
33497
|
+
CLAIM_POLL_FLOOR_MS,
|
|
33498
|
+
requireFiniteDuration(
|
|
33499
|
+
waitOptions.pollMs ?? DEFAULT_JOB_POLL_MS,
|
|
33500
|
+
"pollMs"
|
|
33501
|
+
)
|
|
33502
|
+
);
|
|
33503
|
+
const startedAt = Date.now();
|
|
33504
|
+
const callerDeadline = startedAt + timeoutMs;
|
|
33505
|
+
let latest;
|
|
33506
|
+
for (; ; ) {
|
|
33507
|
+
if (Date.now() >= callerDeadline) {
|
|
33508
|
+
throw new JobTimeoutError(
|
|
33509
|
+
`Timed out waiting for terminal job ${jobId}`,
|
|
33510
|
+
{
|
|
33511
|
+
jobId,
|
|
33512
|
+
timeoutMs,
|
|
33513
|
+
state: latest?.state
|
|
33514
|
+
}
|
|
33515
|
+
);
|
|
33516
|
+
}
|
|
33517
|
+
latest = await client.getJob(jobId);
|
|
33518
|
+
if (TERMINAL_JOB_STATES.has(latest.state)) return latest;
|
|
33519
|
+
const remaining = callerDeadline - Date.now();
|
|
33520
|
+
if (remaining <= 0) {
|
|
33521
|
+
throw new JobTimeoutError(
|
|
33522
|
+
`Timed out waiting for terminal job ${jobId}`,
|
|
33523
|
+
{
|
|
33524
|
+
jobId,
|
|
33525
|
+
timeoutMs,
|
|
33526
|
+
state: latest.state
|
|
33527
|
+
}
|
|
33528
|
+
);
|
|
33529
|
+
}
|
|
33530
|
+
await sleep2(Math.min(pollMs, remaining));
|
|
33531
|
+
}
|
|
33532
|
+
},
|
|
33533
|
+
async openResult(handle, openOptions) {
|
|
33534
|
+
if (!privateKey) {
|
|
33535
|
+
throw new JobRejectedError(
|
|
33536
|
+
"openResult requires createJobsClient({ builderPrivateKey })"
|
|
33537
|
+
);
|
|
33538
|
+
}
|
|
33539
|
+
const response = await request(
|
|
33540
|
+
handle.url,
|
|
33541
|
+
{ method: GET_METHOD },
|
|
33542
|
+
"Job result fetch"
|
|
33543
|
+
);
|
|
33544
|
+
if (!response.ok) {
|
|
33545
|
+
throw await rejectedResponse(response, "Job result fetch rejected");
|
|
33546
|
+
}
|
|
33547
|
+
let bytes;
|
|
33548
|
+
try {
|
|
33549
|
+
bytes = new Uint8Array(await response.arrayBuffer());
|
|
33550
|
+
} catch (error) {
|
|
33551
|
+
throw new JobTransportError(
|
|
33552
|
+
`Job result fetch failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
33553
|
+
error
|
|
33554
|
+
);
|
|
33555
|
+
}
|
|
33556
|
+
const actualHash = bytesToHex3(sha2566(bytes));
|
|
33557
|
+
if (actualHash.toLowerCase() !== handle.hash.toLowerCase()) {
|
|
33558
|
+
throw new JobResultIntegrityError(
|
|
33559
|
+
"Fetched job result hash does not match its handle",
|
|
33560
|
+
{
|
|
33561
|
+
objectKey: handle.objectKey,
|
|
33562
|
+
expectedHash: handle.hash,
|
|
33563
|
+
actualHash
|
|
33564
|
+
}
|
|
33565
|
+
);
|
|
33566
|
+
}
|
|
33567
|
+
if (bytes.length !== handle.size) {
|
|
33568
|
+
throw new JobResultIntegrityError(
|
|
33569
|
+
"Fetched job result size does not match its handle",
|
|
33570
|
+
{
|
|
33571
|
+
objectKey: handle.objectKey,
|
|
33572
|
+
expectedSize: handle.size,
|
|
33573
|
+
actualSize: bytes.length
|
|
33574
|
+
}
|
|
33575
|
+
);
|
|
33576
|
+
}
|
|
33577
|
+
return openJobResult(bytes, privateKey, ecies, openOptions.expect);
|
|
33578
|
+
},
|
|
33579
|
+
async readRaw(params) {
|
|
33580
|
+
const submitted = await client.submitRawRead(params);
|
|
33581
|
+
const job = submitted.job && TERMINAL_JOB_STATES.has(submitted.job.state) ? submitted.job : await client.waitForJob(submitted.jobId, {
|
|
33582
|
+
timeoutMs: params.timeoutMs,
|
|
33583
|
+
pollMs: params.pollMs
|
|
33584
|
+
});
|
|
33585
|
+
if (job.state !== "completed") {
|
|
33586
|
+
throw new JobRejectedError(
|
|
33587
|
+
`Job ${job.jobId} ended in state ${job.state}${job.failureReason ? `: ${job.failureReason}` : ""}`,
|
|
33588
|
+
void 0,
|
|
33589
|
+
null,
|
|
33590
|
+
{
|
|
33591
|
+
jobId: job.jobId,
|
|
33592
|
+
state: job.state,
|
|
33593
|
+
...job.failureReason ? { failureReason: job.failureReason } : {}
|
|
33594
|
+
}
|
|
33595
|
+
);
|
|
33596
|
+
}
|
|
33597
|
+
if (!job.result) {
|
|
33598
|
+
throw new JobRejectedError(
|
|
33599
|
+
"Completed job status does not include a result handle",
|
|
33600
|
+
void 0,
|
|
33601
|
+
null,
|
|
33602
|
+
{ jobId: job.jobId, state: job.state }
|
|
33603
|
+
);
|
|
33604
|
+
}
|
|
33605
|
+
return client.openResult(job.result, {
|
|
33606
|
+
expect: {
|
|
33607
|
+
jobId: submitted.jobId,
|
|
33608
|
+
scope: params.scope,
|
|
33609
|
+
...params.pinnedVersion !== void 0 && params.pinnedVersion !== null ? { version: params.pinnedVersion } : {}
|
|
33610
|
+
}
|
|
33611
|
+
});
|
|
33612
|
+
}
|
|
33613
|
+
};
|
|
33614
|
+
return client;
|
|
33615
|
+
}
|
|
33616
|
+
|
|
32366
33617
|
// src/protocol/personal-server-registration.ts
|
|
32367
33618
|
import {
|
|
32368
|
-
isAddress
|
|
33619
|
+
isAddress as isAddress3
|
|
32369
33620
|
} from "viem";
|
|
32370
33621
|
var PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID = vanaMainnet2.id;
|
|
32371
33622
|
var PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT = getContractAddress(
|
|
@@ -32373,7 +33624,7 @@ var PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT = getContractAddress
|
|
|
32373
33624
|
"DataPortabilityServers"
|
|
32374
33625
|
);
|
|
32375
33626
|
function assertAddress(value, name) {
|
|
32376
|
-
if (!
|
|
33627
|
+
if (!isAddress3(value)) {
|
|
32377
33628
|
throw new Error(`${name} must be a valid EVM address`);
|
|
32378
33629
|
}
|
|
32379
33630
|
}
|
|
@@ -32460,13 +33711,13 @@ var registerPersonalServerSignature = buildPersonalServerRegistrationSignature;
|
|
|
32460
33711
|
|
|
32461
33712
|
// src/personal-server-lite/owner-binding.ts
|
|
32462
33713
|
import {
|
|
32463
|
-
isAddress as
|
|
33714
|
+
isAddress as isAddress4
|
|
32464
33715
|
} from "viem";
|
|
32465
33716
|
var PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION = "vana.ps-lite.owner-binding.v1";
|
|
32466
33717
|
var PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE = "ps-lite-owner";
|
|
32467
33718
|
var PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX = `${PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION}:${PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE}:`;
|
|
32468
33719
|
function assertAddress2(value, name) {
|
|
32469
|
-
if (!
|
|
33720
|
+
if (!isAddress4(value)) {
|
|
32470
33721
|
throw new Error(`${name} must be a valid EVM address`);
|
|
32471
33722
|
}
|
|
32472
33723
|
}
|
|
@@ -32516,7 +33767,7 @@ async function buildPersonalServerLiteOwnerBindingSignature(input) {
|
|
|
32516
33767
|
var signPersonalServerLiteOwnerBinding = buildPersonalServerLiteOwnerBindingSignature;
|
|
32517
33768
|
|
|
32518
33769
|
// src/account/personal-server-registration.ts
|
|
32519
|
-
import { isAddress as
|
|
33770
|
+
import { isAddress as isAddress5 } from "viem";
|
|
32520
33771
|
var ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT = "personal_server.server_registration.v1";
|
|
32521
33772
|
var AccountPersonalServerRegistrationError = class extends Error {
|
|
32522
33773
|
status;
|
|
@@ -32535,7 +33786,7 @@ function trimTrailingSlash(value) {
|
|
|
32535
33786
|
return value.replace(/\/+$/, "");
|
|
32536
33787
|
}
|
|
32537
33788
|
function assertAddress3(value, name) {
|
|
32538
|
-
if (!
|
|
33789
|
+
if (!isAddress5(value)) {
|
|
32539
33790
|
throw new Error(`${name} must be a valid EVM address`);
|
|
32540
33791
|
}
|
|
32541
33792
|
}
|
|
@@ -32556,7 +33807,7 @@ function accountErrorMessage(status, body) {
|
|
|
32556
33807
|
if (nestedMessage) {
|
|
32557
33808
|
return nestedMessage;
|
|
32558
33809
|
}
|
|
32559
|
-
if (
|
|
33810
|
+
if (isRecord3(body) && typeof body.message === "string") {
|
|
32560
33811
|
return body.message;
|
|
32561
33812
|
}
|
|
32562
33813
|
const code = accountErrorCode(body);
|
|
@@ -32570,7 +33821,7 @@ function accountErrorCode(body) {
|
|
|
32570
33821
|
if (nestedCode) {
|
|
32571
33822
|
return nestedCode;
|
|
32572
33823
|
}
|
|
32573
|
-
if (
|
|
33824
|
+
if (isRecord3(body)) {
|
|
32574
33825
|
if (typeof body.code === "string") {
|
|
32575
33826
|
return body.code;
|
|
32576
33827
|
}
|
|
@@ -32581,13 +33832,13 @@ function accountErrorCode(body) {
|
|
|
32581
33832
|
return void 0;
|
|
32582
33833
|
}
|
|
32583
33834
|
function nestedAccountErrorField(body, field) {
|
|
32584
|
-
if (!
|
|
33835
|
+
if (!isRecord3(body) || !isRecord3(body.error)) {
|
|
32585
33836
|
return void 0;
|
|
32586
33837
|
}
|
|
32587
33838
|
const value = body.error[field];
|
|
32588
33839
|
return typeof value === "string" ? value : void 0;
|
|
32589
33840
|
}
|
|
32590
|
-
function
|
|
33841
|
+
function isRecord3(value) {
|
|
32591
33842
|
return typeof value === "object" && value !== null;
|
|
32592
33843
|
}
|
|
32593
33844
|
function normalizeAccountResponse(response) {
|
|
@@ -33061,22 +34312,24 @@ function buildMarkDataPointUnavailableRequest(config, input) {
|
|
|
33061
34312
|
|
|
33062
34313
|
// src/protocol/data-point-deletion.ts
|
|
33063
34314
|
import {
|
|
33064
|
-
isAddress as
|
|
33065
|
-
keccak256 as
|
|
34315
|
+
isAddress as isAddress7,
|
|
34316
|
+
keccak256 as keccak2563,
|
|
33066
34317
|
maxUint256,
|
|
33067
34318
|
stringToBytes as stringToBytes3
|
|
33068
34319
|
} from "viem";
|
|
34320
|
+
import { DataPointDeletedError, DataPointNotFoundError } from "./errors.js";
|
|
33069
34321
|
|
|
33070
34322
|
// src/protocol/lineage.ts
|
|
33071
34323
|
import {
|
|
33072
34324
|
encodeAbiParameters,
|
|
33073
|
-
isAddress as
|
|
33074
|
-
keccak256
|
|
34325
|
+
isAddress as isAddress6,
|
|
34326
|
+
keccak256 as keccak2562
|
|
33075
34327
|
} from "viem";
|
|
33076
34328
|
import { z } from "zod";
|
|
34329
|
+
import { LineageReadError, WriteRequestError as WriteRequestError2 } from "./errors.js";
|
|
33077
34330
|
|
|
33078
34331
|
// src/protocol/personal-server-error-body.ts
|
|
33079
|
-
function
|
|
34332
|
+
function isRecord4(value) {
|
|
33080
34333
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
33081
34334
|
}
|
|
33082
34335
|
async function readPersonalServerErrorBody(response) {
|
|
@@ -33086,8 +34339,8 @@ async function readPersonalServerErrorBody(response) {
|
|
|
33086
34339
|
} catch {
|
|
33087
34340
|
return { errorCode: null, message: null };
|
|
33088
34341
|
}
|
|
33089
|
-
if (!
|
|
33090
|
-
const nested =
|
|
34342
|
+
if (!isRecord4(body)) return { errorCode: null, message: null };
|
|
34343
|
+
const nested = isRecord4(body.error) ? body.error : null;
|
|
33091
34344
|
const gatewayShape = typeof body.error === "string" && typeof body.code === "string";
|
|
33092
34345
|
const code = nested?.errorCode ?? nested?.code ?? body.errorCode ?? (gatewayShape ? body.code : void 0) ?? (typeof body.error === "string" ? body.error : void 0) ?? body.code;
|
|
33093
34346
|
const message = nested?.message ?? body.message ?? (gatewayShape ? body.error : void 0);
|
|
@@ -33100,62 +34353,22 @@ async function readPersonalServerErrorBody(response) {
|
|
|
33100
34353
|
return {
|
|
33101
34354
|
errorCode: typeof code === "string" ? code : null,
|
|
33102
34355
|
message: typeof message === "string" ? message : null,
|
|
33103
|
-
...
|
|
34356
|
+
...isRecord4(details) ? { details } : {}
|
|
33104
34357
|
};
|
|
33105
34358
|
}
|
|
33106
34359
|
|
|
33107
|
-
// src/protocol/write-signer.ts
|
|
33108
|
-
function isRecord3(value) {
|
|
33109
|
-
return value !== null && typeof value === "object";
|
|
33110
|
-
}
|
|
33111
|
-
function isViemWriteAccount(source) {
|
|
33112
|
-
return isRecord3(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
|
|
33113
|
-
}
|
|
33114
|
-
function isViemWriteWalletClient(source) {
|
|
33115
|
-
return isRecord3(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
|
|
33116
|
-
}
|
|
33117
|
-
function accountAddress(account) {
|
|
33118
|
-
return typeof account === "string" ? account : account.address;
|
|
33119
|
-
}
|
|
33120
|
-
function resolveWriteSigner(source, options = {}) {
|
|
33121
|
-
if (isViemWriteWalletClient(source)) {
|
|
33122
|
-
const account = options.account ?? source.account;
|
|
33123
|
-
if (account === void 0) {
|
|
33124
|
-
throw new WriteRequestError(
|
|
33125
|
-
"Viem wallet client requires an account option or account property"
|
|
33126
|
-
);
|
|
33127
|
-
}
|
|
33128
|
-
return {
|
|
33129
|
-
address: accountAddress(account),
|
|
33130
|
-
signMessage: (message) => source.signMessage({ account, message })
|
|
33131
|
-
};
|
|
33132
|
-
}
|
|
33133
|
-
if (isViemWriteAccount(source)) {
|
|
33134
|
-
return {
|
|
33135
|
-
address: source.address,
|
|
33136
|
-
signMessage: (message) => source.signMessage({ message })
|
|
33137
|
-
};
|
|
33138
|
-
}
|
|
33139
|
-
if (!isRecord3(source) || typeof source.signMessage !== "function") {
|
|
33140
|
-
throw new WriteRequestError(
|
|
33141
|
-
"signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
|
|
33142
|
-
);
|
|
33143
|
-
}
|
|
33144
|
-
return source;
|
|
33145
|
-
}
|
|
33146
|
-
|
|
33147
34360
|
// src/protocol/lineage.ts
|
|
33148
34361
|
var DATA_POINT_ID_PATTERN = /^0x[0-9a-fA-F]{64}$/;
|
|
33149
34362
|
function isDataPointId(value) {
|
|
33150
34363
|
return typeof value === "string" && DATA_POINT_ID_PATTERN.test(value);
|
|
33151
34364
|
}
|
|
33152
34365
|
function deriveDataPointId(ownerAddress, scope) {
|
|
33153
|
-
if (!
|
|
34366
|
+
if (!isAddress6(ownerAddress, { strict: false })) {
|
|
33154
34367
|
throw new Error(
|
|
33155
34368
|
`ownerAddress is not an EVM address: ${String(ownerAddress)}`
|
|
33156
34369
|
);
|
|
33157
34370
|
}
|
|
33158
|
-
return
|
|
34371
|
+
return keccak2562(
|
|
33159
34372
|
encodeAbiParameters(
|
|
33160
34373
|
[
|
|
33161
34374
|
{ name: "ownerAddress", type: "address" },
|
|
@@ -33185,7 +34398,7 @@ function derivedScopeViolatesNaming(derivedScope, sourceScope) {
|
|
|
33185
34398
|
function assertDerivedScopeNaming(derivedScope, sourceScopes) {
|
|
33186
34399
|
for (const sourceScope of sourceScopes) {
|
|
33187
34400
|
if (derivedScopeViolatesNaming(derivedScope, sourceScope)) {
|
|
33188
|
-
throw new
|
|
34401
|
+
throw new WriteRequestError2(
|
|
33189
34402
|
`Derived scope ${derivedScope} must not share its first segment with source scope ${sourceScope}; put derivatives in the app's own namespace`,
|
|
33190
34403
|
{ scope: derivedScope, sourceScope }
|
|
33191
34404
|
);
|
|
@@ -33245,7 +34458,7 @@ function gatewayLineagePath(dataPointId, version) {
|
|
|
33245
34458
|
function normalizeBaseUrl(url) {
|
|
33246
34459
|
return url.replace(/\/+$/, "");
|
|
33247
34460
|
}
|
|
33248
|
-
function
|
|
34461
|
+
function resolveFetch2(fetchFn) {
|
|
33249
34462
|
const resolved = fetchFn ?? globalThis.fetch;
|
|
33250
34463
|
if (resolved === void 0) {
|
|
33251
34464
|
throw new LineageReadError("No fetch implementation available");
|
|
@@ -33286,7 +34499,7 @@ async function parseLineageGraph(source, response) {
|
|
|
33286
34499
|
{ cause: err instanceof Error ? err.message : String(err) }
|
|
33287
34500
|
);
|
|
33288
34501
|
}
|
|
33289
|
-
const envelope =
|
|
34502
|
+
const envelope = isRecord4(body) && isRecord4(body.data) ? body : void 0;
|
|
33290
34503
|
const parsed = LineageGraphSchema.safeParse(envelope?.data ?? body);
|
|
33291
34504
|
if (!parsed.success) {
|
|
33292
34505
|
throw new LineageReadError(
|
|
@@ -33296,7 +34509,7 @@ async function parseLineageGraph(source, response) {
|
|
|
33296
34509
|
{ issues: parsed.error.issues }
|
|
33297
34510
|
);
|
|
33298
34511
|
}
|
|
33299
|
-
const proof =
|
|
34512
|
+
const proof = isRecord4(envelope?.proof) ? envelope.proof : void 0;
|
|
33300
34513
|
return proof === void 0 ? parsed.data : { ...parsed.data, proof };
|
|
33301
34514
|
}
|
|
33302
34515
|
async function sendLineageRead(source, fetchFn, url, headers) {
|
|
@@ -33317,7 +34530,7 @@ async function sendLineageRead(source, fetchFn, url, headers) {
|
|
|
33317
34530
|
return parseLineageGraph(source, response);
|
|
33318
34531
|
}
|
|
33319
34532
|
async function getPersonalServerLineage(params) {
|
|
33320
|
-
const fetchFn =
|
|
34533
|
+
const fetchFn = resolveFetch2(params.fetch);
|
|
33321
34534
|
const baseUrl = normalizeBaseUrl(params.personalServerUrl);
|
|
33322
34535
|
const audience = params.audience ?? baseUrl;
|
|
33323
34536
|
const signer = resolveWriteSigner(params.signer, { account: params.account });
|
|
@@ -33352,7 +34565,7 @@ async function getGatewayLineage(params) {
|
|
|
33352
34565
|
{ dataPointId: params.dataPointId }
|
|
33353
34566
|
);
|
|
33354
34567
|
}
|
|
33355
|
-
const fetchFn =
|
|
34568
|
+
const fetchFn = resolveFetch2(params.fetch);
|
|
33356
34569
|
const baseUrl = normalizeBaseUrl(params.gatewayUrl);
|
|
33357
34570
|
const signer = resolveWriteSigner(params.signer, { account: params.account });
|
|
33358
34571
|
const uri = gatewayLineagePath(
|
|
@@ -33382,7 +34595,7 @@ var TOMBSTONE_METADATA_HASH_PREIMAGE = "vana.data-point.tombstone.metadata.v1";
|
|
|
33382
34595
|
var TOMBSTONE_DATA_HASH = "0x30c45ee72fe56d1927701316925ab7ceacd3b6f9267061735d59396f075c6222";
|
|
33383
34596
|
var TOMBSTONE_METADATA_HASH = "0xc5255a141acd6a2ae55971b62c0a85977c2511989dc114ad2abc2b7644f57d90";
|
|
33384
34597
|
function computeTombstoneHash(preimage) {
|
|
33385
|
-
return
|
|
34598
|
+
return keccak2563(stringToBytes3(preimage));
|
|
33386
34599
|
}
|
|
33387
34600
|
function isTombstoneHashes(dataHash, metadataHash) {
|
|
33388
34601
|
return typeof dataHash === "string" && typeof metadataHash === "string" && dataHash.toLowerCase() === TOMBSTONE_DATA_HASH && metadataHash.toLowerCase() === TOMBSTONE_METADATA_HASH;
|
|
@@ -33401,7 +34614,7 @@ function tombstoneDeletedAt(value) {
|
|
|
33401
34614
|
return typeof deletedAt === "string" ? deletedAt : null;
|
|
33402
34615
|
}
|
|
33403
34616
|
function assertAddress4(value, name) {
|
|
33404
|
-
if (!
|
|
34617
|
+
if (!isAddress7(value)) {
|
|
33405
34618
|
throw new Error(`${name} must be a valid EVM address`);
|
|
33406
34619
|
}
|
|
33407
34620
|
}
|
|
@@ -33543,6 +34756,9 @@ async function deleteDataPoint(input) {
|
|
|
33543
34756
|
}
|
|
33544
34757
|
}
|
|
33545
34758
|
|
|
34759
|
+
// src/protocol/personal-server-data.ts
|
|
34760
|
+
import { DataPointDeletedError as DataPointDeletedError2 } from "./errors.js";
|
|
34761
|
+
|
|
33546
34762
|
// src/protocol/data-file.ts
|
|
33547
34763
|
import { z as z2 } from "zod";
|
|
33548
34764
|
var DataFileEnvelopeSchema = z2.object({
|
|
@@ -33601,7 +34817,7 @@ async function readPersonalServerData(params) {
|
|
|
33601
34817
|
const request = await buildPersonalServerDataReadRequest(params);
|
|
33602
34818
|
const response = await fetchFn(request);
|
|
33603
34819
|
if (response.status === 410) {
|
|
33604
|
-
throw new
|
|
34820
|
+
throw new DataPointDeletedError2(
|
|
33605
34821
|
`Personal Server scope '${params.scope}' has been deleted`,
|
|
33606
34822
|
{
|
|
33607
34823
|
scope: params.scope,
|
|
@@ -33616,7 +34832,7 @@ async function readPersonalServerData(params) {
|
|
|
33616
34832
|
}
|
|
33617
34833
|
const body = await response.json();
|
|
33618
34834
|
if (isDataPointTombstone(body)) {
|
|
33619
|
-
throw new
|
|
34835
|
+
throw new DataPointDeletedError2(
|
|
33620
34836
|
`Personal Server scope '${params.scope}' has been deleted`,
|
|
33621
34837
|
{ scope: params.scope, deletedAt: tombstoneDeletedAt(body) }
|
|
33622
34838
|
);
|
|
@@ -33816,20 +35032,31 @@ function tryGrantPermissions(scopes) {
|
|
|
33816
35032
|
}
|
|
33817
35033
|
|
|
33818
35034
|
// src/protocol/personal-server-write.ts
|
|
33819
|
-
import { sha256 as
|
|
33820
|
-
import { bytesToHex as
|
|
35035
|
+
import { sha256 as sha2568 } from "@noble/hashes/sha2";
|
|
35036
|
+
import { bytesToHex as bytesToHex5, isAddress as isAddress8 } from "viem";
|
|
33821
35037
|
import { z as z4 } from "zod";
|
|
35038
|
+
import {
|
|
35039
|
+
WriteConflictError,
|
|
35040
|
+
WriteForbiddenError,
|
|
35041
|
+
WriteLineageError,
|
|
35042
|
+
WriteRejectedError,
|
|
35043
|
+
WriteRequestError as WriteRequestError4,
|
|
35044
|
+
WriteSessionError,
|
|
35045
|
+
WriteSessionExpiredError,
|
|
35046
|
+
WriteUnauthorizedError
|
|
35047
|
+
} from "./errors.js";
|
|
33822
35048
|
|
|
33823
35049
|
// src/protocol/write-request.ts
|
|
33824
|
-
import { sha256 as
|
|
33825
|
-
import { bytesToHex as
|
|
35050
|
+
import { sha256 as sha2567 } from "@noble/hashes/sha2";
|
|
35051
|
+
import { bytesToHex as bytesToHex4 } from "viem";
|
|
35052
|
+
import { WriteRequestError as WriteRequestError3, WriteTransportError } from "./errors.js";
|
|
33826
35053
|
function normalizeBaseUrl2(url) {
|
|
33827
35054
|
return url.replace(/\/+$/, "");
|
|
33828
35055
|
}
|
|
33829
|
-
function
|
|
35056
|
+
function resolveFetch3(fetchFn) {
|
|
33830
35057
|
const resolved = fetchFn ?? globalThis.fetch;
|
|
33831
35058
|
if (resolved === void 0) {
|
|
33832
|
-
throw new
|
|
35059
|
+
throw new WriteRequestError3("No fetch implementation available");
|
|
33833
35060
|
}
|
|
33834
35061
|
return resolved;
|
|
33835
35062
|
}
|
|
@@ -33839,7 +35066,7 @@ function errorMessage(err) {
|
|
|
33839
35066
|
function finiteOr(value, fallback) {
|
|
33840
35067
|
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
33841
35068
|
}
|
|
33842
|
-
function
|
|
35069
|
+
function sleep3(ms) {
|
|
33843
35070
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
33844
35071
|
}
|
|
33845
35072
|
var issuedProofIats = /* @__PURE__ */ new Map();
|
|
@@ -33881,30 +35108,30 @@ function nextProofIat(proofKey) {
|
|
|
33881
35108
|
setIssuedProofIat(proofKey, iat, last);
|
|
33882
35109
|
const waitSec = iat - nowSec - PROOF_IAT_MAX_AHEAD_SECONDS;
|
|
33883
35110
|
if (waitSec <= 0) return Promise.resolve(iat);
|
|
33884
|
-
return
|
|
35111
|
+
return sleep3(waitSec * 1e3).then(() => iat);
|
|
33885
35112
|
}
|
|
33886
35113
|
function freshProofNonce() {
|
|
33887
|
-
const
|
|
33888
|
-
if (typeof
|
|
33889
|
-
return
|
|
35114
|
+
const webCrypto2 = globalThis.crypto;
|
|
35115
|
+
if (typeof webCrypto2?.randomUUID === "function") {
|
|
35116
|
+
return webCrypto2.randomUUID();
|
|
33890
35117
|
}
|
|
33891
|
-
if (typeof
|
|
33892
|
-
return
|
|
35118
|
+
if (typeof webCrypto2?.getRandomValues === "function") {
|
|
35119
|
+
return bytesToHex4(webCrypto2.getRandomValues(new Uint8Array(16)));
|
|
33893
35120
|
}
|
|
33894
|
-
throw new
|
|
35121
|
+
throw new WriteRequestError3(
|
|
33895
35122
|
"No secure random source available to build a proof nonce; provide a crypto global"
|
|
33896
35123
|
);
|
|
33897
35124
|
}
|
|
33898
35125
|
function proofKeyFor(parts) {
|
|
33899
|
-
return
|
|
33900
|
-
|
|
35126
|
+
return bytesToHex4(
|
|
35127
|
+
sha2567(
|
|
33901
35128
|
new TextEncoder().encode(
|
|
33902
35129
|
JSON.stringify([
|
|
33903
35130
|
parts.aud,
|
|
33904
35131
|
parts.method,
|
|
33905
35132
|
parts.uri,
|
|
33906
35133
|
parts.grantId,
|
|
33907
|
-
parts.signedBytes ?
|
|
35134
|
+
parts.signedBytes ? bytesToHex4(sha2567(parts.signedBytes)) : ""
|
|
33908
35135
|
])
|
|
33909
35136
|
)
|
|
33910
35137
|
)
|
|
@@ -33922,7 +35149,7 @@ async function sendWithFreshProof(label, fetchFn, options, proofKey, build) {
|
|
|
33922
35149
|
lastError = err;
|
|
33923
35150
|
}
|
|
33924
35151
|
if (attempt < attempts - 1) {
|
|
33925
|
-
await
|
|
35152
|
+
await sleep3(delayMs);
|
|
33926
35153
|
delayMs *= 2;
|
|
33927
35154
|
}
|
|
33928
35155
|
}
|
|
@@ -33961,7 +35188,7 @@ function dataPath(scope) {
|
|
|
33961
35188
|
return `/v1/data/${encodeURIComponent(scope)}`;
|
|
33962
35189
|
}
|
|
33963
35190
|
async function openWriteSession(params) {
|
|
33964
|
-
const fetchFn =
|
|
35191
|
+
const fetchFn = resolveFetch3(params.fetch);
|
|
33965
35192
|
const personalServerUrl = normalizeBaseUrl2(params.personalServerUrl);
|
|
33966
35193
|
const audience = params.audience ?? personalServerUrl;
|
|
33967
35194
|
const signer = resolveWriteSigner(params.signer, { account: params.account });
|
|
@@ -34041,13 +35268,13 @@ async function openWriteSession(params) {
|
|
|
34041
35268
|
};
|
|
34042
35269
|
}
|
|
34043
35270
|
function isWriteSession(value) {
|
|
34044
|
-
if (!
|
|
35271
|
+
if (!isRecord4(value)) return false;
|
|
34045
35272
|
const signer = value.signer;
|
|
34046
|
-
return typeof value.personalServerUrl === "string" && typeof value.audience === "string" && typeof value.grantId === "string" && typeof value.accessToken === "string" && value.accessToken.length > 0 && typeof value.expiresAt === "number" && Number.isFinite(value.expiresAt) && Array.isArray(value.writeScopes) && value.writeScopes.every((scope) => typeof scope === "string") &&
|
|
35273
|
+
return typeof value.personalServerUrl === "string" && typeof value.audience === "string" && typeof value.grantId === "string" && typeof value.accessToken === "string" && value.accessToken.length > 0 && typeof value.expiresAt === "number" && Number.isFinite(value.expiresAt) && Array.isArray(value.writeScopes) && value.writeScopes.every((scope) => typeof scope === "string") && isRecord4(signer) && typeof signer.signMessage === "function";
|
|
34047
35274
|
}
|
|
34048
35275
|
function sessionCoversScope(session, scope) {
|
|
34049
|
-
if (!
|
|
34050
|
-
throw new
|
|
35276
|
+
if (!isRecord4(session) || !Array.isArray(session.writeScopes) || !session.writeScopes.every((pattern) => typeof pattern === "string")) {
|
|
35277
|
+
throw new WriteRequestError4("session must come from openWriteSession");
|
|
34051
35278
|
}
|
|
34052
35279
|
return session.writeScopes.some(
|
|
34053
35280
|
(pattern) => scopeMatchesPattern(scope, pattern)
|
|
@@ -34072,12 +35299,12 @@ function encodeWriteMetadataHeader(metadata) {
|
|
|
34072
35299
|
try {
|
|
34073
35300
|
json = JSON.stringify(metadata);
|
|
34074
35301
|
} catch (err) {
|
|
34075
|
-
throw new
|
|
35302
|
+
throw new WriteRequestError4(
|
|
34076
35303
|
`metadata is not JSON-serialisable: ${errorMessage(err)}`
|
|
34077
35304
|
);
|
|
34078
35305
|
}
|
|
34079
35306
|
if (typeof json !== "string") {
|
|
34080
|
-
throw new
|
|
35307
|
+
throw new WriteRequestError4("metadata must serialise to JSON");
|
|
34081
35308
|
}
|
|
34082
35309
|
return json.replace(
|
|
34083
35310
|
/[\u007f-\uffff]/g,
|
|
@@ -34091,7 +35318,7 @@ function binaryWriteSignedBytes(input) {
|
|
|
34091
35318
|
mimeType: normalizeBinaryMimeType(input.contentType),
|
|
34092
35319
|
...input.filename ? { filename: input.filename } : {},
|
|
34093
35320
|
sizeBytes: input.bytes.length,
|
|
34094
|
-
contentHash:
|
|
35321
|
+
contentHash: bytesToHex5(sha2568(input.bytes)),
|
|
34095
35322
|
encoding: "base64",
|
|
34096
35323
|
content: toBase64(input.bytes),
|
|
34097
35324
|
...metadata !== void 0 ? { metadata } : {}
|
|
@@ -34112,7 +35339,7 @@ function setFilenameHeader(headers, filename) {
|
|
|
34112
35339
|
function assertNoReservedKeys(value, where) {
|
|
34113
35340
|
for (const key of RESERVED_WRITE_KEYS) {
|
|
34114
35341
|
if (Object.prototype.hasOwnProperty.call(value, key)) {
|
|
34115
|
-
throw new
|
|
35342
|
+
throw new WriteRequestError4(
|
|
34116
35343
|
`${where} must not contain the reserved ${key} key; the Personal Server stamps it`,
|
|
34117
35344
|
{ key }
|
|
34118
35345
|
);
|
|
@@ -34120,14 +35347,14 @@ function assertNoReservedKeys(value, where) {
|
|
|
34120
35347
|
}
|
|
34121
35348
|
}
|
|
34122
35349
|
function isLineagePair(value) {
|
|
34123
|
-
return
|
|
35350
|
+
return isRecord4(value) && typeof value.ownerAddress === "string" && typeof value.scope === "string";
|
|
34124
35351
|
}
|
|
34125
35352
|
function normalizeLineage(lineage, derivedScope) {
|
|
34126
35353
|
if (!Array.isArray(lineage)) {
|
|
34127
|
-
throw new
|
|
35354
|
+
throw new WriteRequestError4("lineage must be an array of data point ids");
|
|
34128
35355
|
}
|
|
34129
35356
|
if (lineage.length > MAX_LINEAGE_SOURCES) {
|
|
34130
|
-
throw new
|
|
35357
|
+
throw new WriteRequestError4(
|
|
34131
35358
|
`lineage lists ${lineage.length} sources; the maximum is ${MAX_LINEAGE_SOURCES}`,
|
|
34132
35359
|
{ max: MAX_LINEAGE_SOURCES, count: lineage.length }
|
|
34133
35360
|
);
|
|
@@ -34139,14 +35366,14 @@ function normalizeLineage(lineage, derivedScope) {
|
|
|
34139
35366
|
for (const entry of lineage) {
|
|
34140
35367
|
let id;
|
|
34141
35368
|
if (isLineagePair(entry)) {
|
|
34142
|
-
if (!
|
|
34143
|
-
throw new
|
|
35369
|
+
if (!isAddress8(entry.ownerAddress, { strict: false })) {
|
|
35370
|
+
throw new WriteRequestError4(
|
|
34144
35371
|
"lineage source ownerAddress must be an EVM address",
|
|
34145
35372
|
{ ownerAddress: entry.ownerAddress }
|
|
34146
35373
|
);
|
|
34147
35374
|
}
|
|
34148
35375
|
if (entry.scope.length === 0) {
|
|
34149
|
-
throw new
|
|
35376
|
+
throw new WriteRequestError4("lineage source scope is required");
|
|
34150
35377
|
}
|
|
34151
35378
|
id = deriveDataPointId(entry.ownerAddress, entry.scope);
|
|
34152
35379
|
sourceScopes.push(entry.scope);
|
|
@@ -34154,14 +35381,14 @@ function normalizeLineage(lineage, derivedScope) {
|
|
|
34154
35381
|
} else if (isDataPointId(entry)) {
|
|
34155
35382
|
id = entry;
|
|
34156
35383
|
} else {
|
|
34157
|
-
throw new
|
|
35384
|
+
throw new WriteRequestError4(
|
|
34158
35385
|
"lineage entries must be 32-byte hex data point ids or { ownerAddress, scope } pairs",
|
|
34159
35386
|
{ entry }
|
|
34160
35387
|
);
|
|
34161
35388
|
}
|
|
34162
35389
|
const normalized = id.toLowerCase();
|
|
34163
35390
|
if (seen.has(normalized)) {
|
|
34164
|
-
throw new
|
|
35391
|
+
throw new WriteRequestError4("lineage must not repeat a data point id", {
|
|
34165
35392
|
dataPointId: normalized
|
|
34166
35393
|
});
|
|
34167
35394
|
}
|
|
@@ -34170,7 +35397,7 @@ function normalizeLineage(lineage, derivedScope) {
|
|
|
34170
35397
|
}
|
|
34171
35398
|
for (const own of ownIds) {
|
|
34172
35399
|
if (seen.has(own)) {
|
|
34173
|
-
throw new
|
|
35400
|
+
throw new WriteRequestError4(
|
|
34174
35401
|
"lineage must not cite the record's own data point",
|
|
34175
35402
|
{ dataPointId: own, scope: derivedScope }
|
|
34176
35403
|
);
|
|
@@ -34181,15 +35408,15 @@ function normalizeLineage(lineage, derivedScope) {
|
|
|
34181
35408
|
}
|
|
34182
35409
|
function assertNoLineageField(value, where) {
|
|
34183
35410
|
if (Object.prototype.hasOwnProperty.call(value, LINEAGE_FIELD)) {
|
|
34184
|
-
throw new
|
|
35411
|
+
throw new WriteRequestError4(
|
|
34185
35412
|
`${where}.${LINEAGE_FIELD} is reserved; pass sources through the lineage option`
|
|
34186
35413
|
);
|
|
34187
35414
|
}
|
|
34188
35415
|
}
|
|
34189
35416
|
function buildMetadataHeader(metadata, sources) {
|
|
34190
35417
|
if (metadata !== void 0) {
|
|
34191
|
-
if (!
|
|
34192
|
-
throw new
|
|
35418
|
+
if (!isRecord4(metadata)) {
|
|
35419
|
+
throw new WriteRequestError4("metadata must be a plain object");
|
|
34193
35420
|
}
|
|
34194
35421
|
assertNoReservedKeys(metadata, "metadata");
|
|
34195
35422
|
assertNoLineageField(metadata, "metadata");
|
|
@@ -34202,24 +35429,24 @@ function buildMetadataHeader(metadata, sources) {
|
|
|
34202
35429
|
}
|
|
34203
35430
|
function prepareWrite(params) {
|
|
34204
35431
|
if (params.binary !== void 0 && params.data !== void 0) {
|
|
34205
|
-
throw new
|
|
35432
|
+
throw new WriteRequestError4("Pass either data or binary, not both");
|
|
34206
35433
|
}
|
|
34207
35434
|
const rawLineage = params.lineage;
|
|
34208
35435
|
const sources = rawLineage === void 0 || rawLineage === null ? void 0 : normalizeLineage(rawLineage, params.scope);
|
|
34209
35436
|
if (params.binary !== void 0) {
|
|
34210
35437
|
const { bytes, contentType, filename } = params.binary;
|
|
34211
35438
|
if (!(bytes instanceof Uint8Array)) {
|
|
34212
|
-
throw new
|
|
35439
|
+
throw new WriteRequestError4("binary.bytes must be a Uint8Array");
|
|
34213
35440
|
}
|
|
34214
35441
|
if (typeof contentType !== "string" || contentType.trim() === "") {
|
|
34215
|
-
throw new
|
|
35442
|
+
throw new WriteRequestError4("binary.contentType is required");
|
|
34216
35443
|
}
|
|
34217
35444
|
if (filename !== void 0) {
|
|
34218
35445
|
if (typeof filename !== "string") {
|
|
34219
|
-
throw new
|
|
35446
|
+
throw new WriteRequestError4("binary.filename must be a string");
|
|
34220
35447
|
}
|
|
34221
35448
|
if (filename !== filename.trim()) {
|
|
34222
|
-
throw new
|
|
35449
|
+
throw new WriteRequestError4(
|
|
34223
35450
|
"binary.filename must not have leading or trailing whitespace"
|
|
34224
35451
|
);
|
|
34225
35452
|
}
|
|
@@ -34239,13 +35466,13 @@ function prepareWrite(params) {
|
|
|
34239
35466
|
};
|
|
34240
35467
|
}
|
|
34241
35468
|
if (params.data === void 0) {
|
|
34242
|
-
throw new
|
|
35469
|
+
throw new WriteRequestError4("Pass data (a JSON object) or binary");
|
|
34243
35470
|
}
|
|
34244
|
-
if (!
|
|
34245
|
-
throw new
|
|
35471
|
+
if (!isRecord4(params.data)) {
|
|
35472
|
+
throw new WriteRequestError4("data must be a plain JSON object");
|
|
34246
35473
|
}
|
|
34247
35474
|
if (params.metadata !== void 0) {
|
|
34248
|
-
throw new
|
|
35475
|
+
throw new WriteRequestError4(
|
|
34249
35476
|
"metadata applies to binary writes; put fields to store inside data"
|
|
34250
35477
|
);
|
|
34251
35478
|
}
|
|
@@ -34256,12 +35483,12 @@ function prepareWrite(params) {
|
|
|
34256
35483
|
try {
|
|
34257
35484
|
text = JSON.stringify(record);
|
|
34258
35485
|
} catch (err) {
|
|
34259
|
-
throw new
|
|
35486
|
+
throw new WriteRequestError4(
|
|
34260
35487
|
`data is not JSON-serialisable: ${errorMessage(err)}`
|
|
34261
35488
|
);
|
|
34262
35489
|
}
|
|
34263
35490
|
if (typeof text !== "string" || !text.startsWith("{")) {
|
|
34264
|
-
throw new
|
|
35491
|
+
throw new WriteRequestError4("data must serialise to a JSON object");
|
|
34265
35492
|
}
|
|
34266
35493
|
const body = new TextEncoder().encode(text);
|
|
34267
35494
|
return {
|
|
@@ -34290,11 +35517,11 @@ async function writeErrorFromResponse(response) {
|
|
|
34290
35517
|
async function writeData(params) {
|
|
34291
35518
|
const { session } = params;
|
|
34292
35519
|
if (!isWriteSession(session)) {
|
|
34293
|
-
throw new
|
|
35520
|
+
throw new WriteRequestError4("session must come from openWriteSession");
|
|
34294
35521
|
}
|
|
34295
|
-
const fetchFn =
|
|
35522
|
+
const fetchFn = resolveFetch3(params.fetch);
|
|
34296
35523
|
if (typeof params.scope !== "string" || params.scope.length === 0) {
|
|
34297
|
-
throw new
|
|
35524
|
+
throw new WriteRequestError4("scope is required");
|
|
34298
35525
|
}
|
|
34299
35526
|
const prepared = prepareWrite(params);
|
|
34300
35527
|
if (Date.now() >= session.expiresAt) {
|
|
@@ -34390,6 +35617,21 @@ async function writePersonalServerData(params) {
|
|
|
34390
35617
|
|
|
34391
35618
|
// src/protocol/derivative-questions.ts
|
|
34392
35619
|
import { z as z5 } from "zod";
|
|
35620
|
+
import {
|
|
35621
|
+
DerivativeComputeUnavailableError,
|
|
35622
|
+
DerivativeCycleError,
|
|
35623
|
+
DerivativeDerivedScopeRequiredError,
|
|
35624
|
+
DerivativeQuestionFailedError,
|
|
35625
|
+
DerivativeQuestionInvalidError,
|
|
35626
|
+
DerivativeQuestionNotFoundError,
|
|
35627
|
+
DerivativeQuestionRejectedError,
|
|
35628
|
+
DerivativeQuestionTimeoutError,
|
|
35629
|
+
DerivativeSourceNotGrantedError,
|
|
35630
|
+
WriteConflictError as WriteConflictError2,
|
|
35631
|
+
WriteForbiddenError as WriteForbiddenError2,
|
|
35632
|
+
WriteRequestError as WriteRequestError5,
|
|
35633
|
+
WriteUnauthorizedError as WriteUnauthorizedError2
|
|
35634
|
+
} from "./errors.js";
|
|
34393
35635
|
var DERIVATIVE_QUESTIONS_PATH = "/v1/derivatives/questions";
|
|
34394
35636
|
var MAX_QUESTION_SOURCE_SCOPES = 16;
|
|
34395
35637
|
var MAX_QUESTION_CHARS = 8e3;
|
|
@@ -34472,19 +35714,19 @@ function fetchIdOf(fetchFn) {
|
|
|
34472
35714
|
}
|
|
34473
35715
|
function resolveRequest(params) {
|
|
34474
35716
|
if (typeof params.personalServerUrl !== "string" || params.personalServerUrl.length === 0) {
|
|
34475
|
-
throw new
|
|
35717
|
+
throw new WriteRequestError5("personalServerUrl is required");
|
|
34476
35718
|
}
|
|
34477
35719
|
if (typeof params.grantId !== "string" || params.grantId.length === 0) {
|
|
34478
|
-
throw new
|
|
35720
|
+
throw new WriteRequestError5(
|
|
34479
35721
|
"grantId is required; a question call runs under the grant carrying write:<derivedScope>"
|
|
34480
35722
|
);
|
|
34481
35723
|
}
|
|
34482
35724
|
if (params.signer === null || typeof params.signer !== "object") {
|
|
34483
|
-
throw new
|
|
35725
|
+
throw new WriteRequestError5(
|
|
34484
35726
|
"signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
|
|
34485
35727
|
);
|
|
34486
35728
|
}
|
|
34487
|
-
const fetchFn =
|
|
35729
|
+
const fetchFn = resolveFetch3(params.fetch);
|
|
34488
35730
|
const baseUrl = normalizeBaseUrl2(params.personalServerUrl);
|
|
34489
35731
|
const audience = params.audience ?? baseUrl;
|
|
34490
35732
|
return {
|
|
@@ -34556,13 +35798,13 @@ async function questionErrorFromResponse(response, body) {
|
|
|
34556
35798
|
}
|
|
34557
35799
|
switch (response.status) {
|
|
34558
35800
|
case 401:
|
|
34559
|
-
return new
|
|
35801
|
+
return new WriteUnauthorizedError2(text, errorCode, details);
|
|
34560
35802
|
case 403:
|
|
34561
|
-
return new
|
|
35803
|
+
return new WriteForbiddenError2(text, errorCode, details);
|
|
34562
35804
|
case 404:
|
|
34563
35805
|
return new DerivativeQuestionNotFoundError(text, errorCode, details);
|
|
34564
35806
|
case 409:
|
|
34565
|
-
return new
|
|
35807
|
+
return new WriteConflictError2(text, errorCode, details);
|
|
34566
35808
|
default:
|
|
34567
35809
|
return new DerivativeQuestionRejectedError(
|
|
34568
35810
|
text,
|
|
@@ -34664,22 +35906,22 @@ async function sendQuestionRequest(params, spec, schema) {
|
|
|
34664
35906
|
}
|
|
34665
35907
|
function assertQuestionId(questionId) {
|
|
34666
35908
|
if (typeof questionId !== "string" || questionId.length === 0) {
|
|
34667
|
-
throw new
|
|
35909
|
+
throw new WriteRequestError5("questionId is required");
|
|
34668
35910
|
}
|
|
34669
35911
|
return `${DERIVATIVE_QUESTIONS_PATH}/${encodeURIComponent(questionId)}`;
|
|
34670
35912
|
}
|
|
34671
35913
|
function registrationBody(params) {
|
|
34672
35914
|
const { derivedScope, question } = params;
|
|
34673
35915
|
if (typeof derivedScope !== "string" || derivedScope.length === 0) {
|
|
34674
|
-
throw new
|
|
35916
|
+
throw new WriteRequestError5("derivedScope is required");
|
|
34675
35917
|
}
|
|
34676
35918
|
if (!Array.isArray(params.sourceScopes) || params.sourceScopes.length === 0) {
|
|
34677
|
-
throw new
|
|
35919
|
+
throw new WriteRequestError5(
|
|
34678
35920
|
"sourceScopes must be a non-empty array of scopes"
|
|
34679
35921
|
);
|
|
34680
35922
|
}
|
|
34681
35923
|
if (params.sourceScopes.length > MAX_QUESTION_SOURCE_SCOPES) {
|
|
34682
|
-
throw new
|
|
35924
|
+
throw new WriteRequestError5(
|
|
34683
35925
|
`sourceScopes lists ${params.sourceScopes.length} scopes; the maximum is ${MAX_QUESTION_SOURCE_SCOPES}`,
|
|
34684
35926
|
{ max: MAX_QUESTION_SOURCE_SCOPES, count: params.sourceScopes.length }
|
|
34685
35927
|
);
|
|
@@ -34687,15 +35929,15 @@ function registrationBody(params) {
|
|
|
34687
35929
|
const sourceScopes = [];
|
|
34688
35930
|
for (const scope of params.sourceScopes) {
|
|
34689
35931
|
if (typeof scope !== "string" || scope.length === 0) {
|
|
34690
|
-
throw new
|
|
35932
|
+
throw new WriteRequestError5("sourceScopes entries must be scope strings");
|
|
34691
35933
|
}
|
|
34692
35934
|
if (sourceScopes.includes(scope)) {
|
|
34693
|
-
throw new
|
|
35935
|
+
throw new WriteRequestError5("sourceScopes must not repeat a scope", {
|
|
34694
35936
|
duplicate: scope
|
|
34695
35937
|
});
|
|
34696
35938
|
}
|
|
34697
35939
|
if (scope === derivedScope) {
|
|
34698
|
-
throw new
|
|
35940
|
+
throw new WriteRequestError5(
|
|
34699
35941
|
"derivedScope cannot be one of its own sources",
|
|
34700
35942
|
{ scope }
|
|
34701
35943
|
);
|
|
@@ -34703,17 +35945,17 @@ function registrationBody(params) {
|
|
|
34703
35945
|
sourceScopes.push(scope);
|
|
34704
35946
|
}
|
|
34705
35947
|
if (typeof question !== "string" || question.trim() === "") {
|
|
34706
|
-
throw new
|
|
35948
|
+
throw new WriteRequestError5("question must be a non-empty string");
|
|
34707
35949
|
}
|
|
34708
35950
|
if (question.length > MAX_QUESTION_CHARS) {
|
|
34709
|
-
throw new
|
|
35951
|
+
throw new WriteRequestError5(
|
|
34710
35952
|
`question is ${question.length} characters; the maximum is ${MAX_QUESTION_CHARS}`,
|
|
34711
35953
|
{ max: MAX_QUESTION_CHARS, length: question.length }
|
|
34712
35954
|
);
|
|
34713
35955
|
}
|
|
34714
35956
|
if (params.model !== void 0) {
|
|
34715
35957
|
if (typeof params.model !== "string" || params.model.length > MAX_QUESTION_MODEL_CHARS || !MODEL_ID_PATTERN.test(params.model)) {
|
|
34716
|
-
throw new
|
|
35958
|
+
throw new WriteRequestError5("model must be a provider model id", {
|
|
34717
35959
|
model: params.model
|
|
34718
35960
|
});
|
|
34719
35961
|
}
|
|
@@ -34749,7 +35991,7 @@ async function getQuestion(params) {
|
|
|
34749
35991
|
}
|
|
34750
35992
|
async function listQuestions(params) {
|
|
34751
35993
|
if (typeof params.derivedScope !== "string" || params.derivedScope.length === 0) {
|
|
34752
|
-
throw new
|
|
35994
|
+
throw new WriteRequestError5(
|
|
34753
35995
|
"derivedScope is required; a builder may only list its own questions on a scope it may write"
|
|
34754
35996
|
);
|
|
34755
35997
|
}
|
|
@@ -34817,7 +36059,7 @@ async function waitForQuestion(params) {
|
|
|
34817
36059
|
}
|
|
34818
36060
|
);
|
|
34819
36061
|
}
|
|
34820
|
-
await
|
|
36062
|
+
await sleep3(Math.min(pollIntervalMs, remaining));
|
|
34821
36063
|
}
|
|
34822
36064
|
}
|
|
34823
36065
|
async function askPersonalServer(params) {
|
|
@@ -34854,6 +36096,12 @@ async function askPersonalServer(params) {
|
|
|
34854
36096
|
|
|
34855
36097
|
// src/protocol/derivative-status.ts
|
|
34856
36098
|
import { z as z6 } from "zod";
|
|
36099
|
+
import {
|
|
36100
|
+
DerivativeQuestionRejectedError as DerivativeQuestionRejectedError2,
|
|
36101
|
+
DerivativeQuestionTimeoutError as DerivativeQuestionTimeoutError2,
|
|
36102
|
+
WriteRequestError as WriteRequestError6,
|
|
36103
|
+
WriteTransportError as WriteTransportError2
|
|
36104
|
+
} from "./errors.js";
|
|
34857
36105
|
var DERIVATIVE_STATUS_PATH = "/v1/derivatives/status";
|
|
34858
36106
|
var DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS = 12e4;
|
|
34859
36107
|
var DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS = 2e3;
|
|
@@ -34881,20 +36129,20 @@ function derivativeStatusTarget(derivedScope) {
|
|
|
34881
36129
|
function normalizeBaseUrl3(url) {
|
|
34882
36130
|
return url.replace(/\/+$/, "");
|
|
34883
36131
|
}
|
|
34884
|
-
function
|
|
36132
|
+
function resolveFetch4(fetchFn) {
|
|
34885
36133
|
const resolved = fetchFn ?? globalThis.fetch;
|
|
34886
36134
|
if (resolved === void 0) {
|
|
34887
|
-
throw new
|
|
36135
|
+
throw new WriteRequestError6("No fetch implementation available");
|
|
34888
36136
|
}
|
|
34889
36137
|
return resolved;
|
|
34890
36138
|
}
|
|
34891
36139
|
function requireDerivedScope(derivedScope) {
|
|
34892
36140
|
if (typeof derivedScope !== "string" || derivedScope.length === 0) {
|
|
34893
|
-
throw new
|
|
36141
|
+
throw new WriteRequestError6("derivedScope is required");
|
|
34894
36142
|
}
|
|
34895
36143
|
return derivedScope;
|
|
34896
36144
|
}
|
|
34897
|
-
function
|
|
36145
|
+
function sleep4(ms, signal) {
|
|
34898
36146
|
if (ms <= 0) return Promise.resolve();
|
|
34899
36147
|
return new Promise((resolve, reject) => {
|
|
34900
36148
|
const timer = setTimeout(() => {
|
|
@@ -34909,7 +36157,7 @@ function sleep3(ms, signal) {
|
|
|
34909
36157
|
});
|
|
34910
36158
|
}
|
|
34911
36159
|
function timeoutError(latest, timeoutMs) {
|
|
34912
|
-
return new
|
|
36160
|
+
return new DerivativeQuestionTimeoutError2(
|
|
34913
36161
|
`Derived scope ${latest.derivedScope} was still ${latest.status} after ${timeoutMs}ms`,
|
|
34914
36162
|
{
|
|
34915
36163
|
derivedScope: latest.derivedScope,
|
|
@@ -34922,7 +36170,7 @@ function timeoutError(latest, timeoutMs) {
|
|
|
34922
36170
|
}
|
|
34923
36171
|
function abortError2(signal) {
|
|
34924
36172
|
const reason = signal?.reason;
|
|
34925
|
-
return reason instanceof Error ? reason : new
|
|
36173
|
+
return reason instanceof Error ? reason : new WriteRequestError6("Derivative status wait was aborted");
|
|
34926
36174
|
}
|
|
34927
36175
|
function isDerivativeStatusSettled(status) {
|
|
34928
36176
|
if (status.status === "ready") return true;
|
|
@@ -34930,7 +36178,7 @@ function isDerivativeStatusSettled(status) {
|
|
|
34930
36178
|
}
|
|
34931
36179
|
async function getDerivativeStatus(params) {
|
|
34932
36180
|
const derivedScope = requireDerivedScope(params.derivedScope);
|
|
34933
|
-
const fetchFn =
|
|
36181
|
+
const fetchFn = resolveFetch4(params.fetch);
|
|
34934
36182
|
const baseUrl = normalizeBaseUrl3(params.personalServerUrl);
|
|
34935
36183
|
const signer = resolveWriteSigner(params.signer, { account: params.account });
|
|
34936
36184
|
const headers = new Headers(params.headers);
|
|
@@ -34955,7 +36203,7 @@ async function getDerivativeStatus(params) {
|
|
|
34955
36203
|
}
|
|
34956
36204
|
);
|
|
34957
36205
|
} catch (err) {
|
|
34958
|
-
throw new
|
|
36206
|
+
throw new WriteTransportError2(
|
|
34959
36207
|
`Derivative status read failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
34960
36208
|
1,
|
|
34961
36209
|
err
|
|
@@ -34970,7 +36218,7 @@ async function getDerivativeStatus(params) {
|
|
|
34970
36218
|
try {
|
|
34971
36219
|
body = await response.json();
|
|
34972
36220
|
} catch (err) {
|
|
34973
|
-
throw new
|
|
36221
|
+
throw new DerivativeQuestionRejectedError2(
|
|
34974
36222
|
"Derivative status response is not JSON",
|
|
34975
36223
|
response.status,
|
|
34976
36224
|
null,
|
|
@@ -34979,7 +36227,7 @@ async function getDerivativeStatus(params) {
|
|
|
34979
36227
|
}
|
|
34980
36228
|
const parsed = DerivativeStatusSchema.safeParse(body);
|
|
34981
36229
|
if (!parsed.success) {
|
|
34982
|
-
throw new
|
|
36230
|
+
throw new DerivativeQuestionRejectedError2(
|
|
34983
36231
|
"Derivative status response is not a status view",
|
|
34984
36232
|
response.status,
|
|
34985
36233
|
null,
|
|
@@ -35008,11 +36256,16 @@ async function waitForDerivativeStatus(params) {
|
|
|
35008
36256
|
if (waitMs > remaining) {
|
|
35009
36257
|
throw timeoutError(latest, timeoutMs);
|
|
35010
36258
|
}
|
|
35011
|
-
await
|
|
36259
|
+
await sleep4(waitMs, params.signal);
|
|
35012
36260
|
}
|
|
35013
36261
|
}
|
|
35014
36262
|
|
|
35015
36263
|
// src/protocol/gateway.ts
|
|
36264
|
+
import {
|
|
36265
|
+
DataPointDeletedError as DataPointDeletedError3,
|
|
36266
|
+
DataPointNotFoundError as DataPointNotFoundError2,
|
|
36267
|
+
DataPointVersionConflictError
|
|
36268
|
+
} from "./errors.js";
|
|
35016
36269
|
function withGrantPermissions(grant) {
|
|
35017
36270
|
const stripped = { ...grant };
|
|
35018
36271
|
delete stripped.permissions;
|
|
@@ -35058,7 +36311,7 @@ function createGatewayClient(baseUrl) {
|
|
|
35058
36311
|
}
|
|
35059
36312
|
async function deletedError(res, details) {
|
|
35060
36313
|
const body = await readBody(res);
|
|
35061
|
-
return new
|
|
36314
|
+
return new DataPointDeletedError3(
|
|
35062
36315
|
`Data point ${details.dataPointId ?? details.scope ?? ""} has been deleted`,
|
|
35063
36316
|
{ ...details, deletedAt: tombstoneDeletedAt(body) }
|
|
35064
36317
|
);
|
|
@@ -35131,7 +36384,7 @@ function createGatewayClient(baseUrl) {
|
|
|
35131
36384
|
}
|
|
35132
36385
|
const record = await unwrapEnvelope(res);
|
|
35133
36386
|
if (!options?.includeDeleted && isDataPointTombstone(record)) {
|
|
35134
|
-
throw new
|
|
36387
|
+
throw new DataPointDeletedError3(
|
|
35135
36388
|
`Data point ${dataPointId} has been deleted`,
|
|
35136
36389
|
{
|
|
35137
36390
|
dataPointId,
|
|
@@ -35293,7 +36546,7 @@ function createGatewayClient(baseUrl) {
|
|
|
35293
36546
|
})
|
|
35294
36547
|
});
|
|
35295
36548
|
if (res.status === 404) {
|
|
35296
|
-
throw new
|
|
36549
|
+
throw new DataPointNotFoundError2(
|
|
35297
36550
|
`Data point ${dataPointId} (scope '${params.scope}') is not registered`,
|
|
35298
36551
|
details
|
|
35299
36552
|
);
|
|
@@ -35783,18 +37036,9 @@ async function authorizeEscrowPayment(params) {
|
|
|
35783
37036
|
return toDirectPaymentReceipt(result);
|
|
35784
37037
|
}
|
|
35785
37038
|
|
|
35786
|
-
// src/direct/errors.ts
|
|
35787
|
-
var PersonalServerReadError = class extends VanaError {
|
|
35788
|
-
constructor(message, status, details) {
|
|
35789
|
-
super(message, "DIRECT_PERSONAL_SERVER_READ_ERROR");
|
|
35790
|
-
this.status = status;
|
|
35791
|
-
this.details = details;
|
|
35792
|
-
}
|
|
35793
|
-
status;
|
|
35794
|
-
details;
|
|
35795
|
-
};
|
|
35796
|
-
|
|
35797
37039
|
// src/direct/personal-server-read.ts
|
|
37040
|
+
import { PaymentRequiredError, PersonalServerReadError } from "./direct/errors.js";
|
|
37041
|
+
import { DataPointDeletedError as DataPointDeletedError4 } from "./errors.js";
|
|
35798
37042
|
function asRecord2(value) {
|
|
35799
37043
|
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
35800
37044
|
}
|
|
@@ -36041,7 +37285,7 @@ var KNOWN_CODES = /* @__PURE__ */ new Set([
|
|
|
36041
37285
|
"server_not_configured",
|
|
36042
37286
|
"content_too_large"
|
|
36043
37287
|
]);
|
|
36044
|
-
function
|
|
37288
|
+
function isRecord5(value) {
|
|
36045
37289
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
36046
37290
|
}
|
|
36047
37291
|
function normalizeCode(value) {
|
|
@@ -36052,10 +37296,10 @@ function normalizeCode(value) {
|
|
|
36052
37296
|
return KNOWN_CODES.has(code) ? code : null;
|
|
36053
37297
|
}
|
|
36054
37298
|
function extractPSErrorBody(body) {
|
|
36055
|
-
if (!
|
|
37299
|
+
if (!isRecord5(body)) {
|
|
36056
37300
|
return null;
|
|
36057
37301
|
}
|
|
36058
|
-
const nested =
|
|
37302
|
+
const nested = isRecord5(body.error) ? body.error : null;
|
|
36059
37303
|
const code = normalizeCode(
|
|
36060
37304
|
nested?.errorCode ?? nested?.code ?? body.errorCode ?? body.code
|
|
36061
37305
|
);
|
|
@@ -36084,42 +37328,34 @@ export {
|
|
|
36084
37328
|
AccountPersonalServerLiteOwnerBindingError,
|
|
36085
37329
|
AccountPersonalServerRegistrationError,
|
|
36086
37330
|
BUILDER_REGISTRATION_TYPES,
|
|
36087
|
-
BlockchainError,
|
|
36088
37331
|
BrowserPlatformAdapter,
|
|
37332
|
+
CLAIM_POLL_FLOOR_MS,
|
|
36089
37333
|
CONTRACTS,
|
|
36090
37334
|
CallbackStorage,
|
|
36091
37335
|
ContractFactory,
|
|
36092
|
-
ContractNotFoundError,
|
|
36093
37336
|
DATA_ACCESS_OP_TYPE,
|
|
36094
37337
|
DATA_REGISTRY_STATUS_ABI,
|
|
36095
37338
|
DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
|
|
36096
37339
|
DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
|
|
37340
|
+
DEFAULT_JOB_DEADLINE_SECONDS,
|
|
37341
|
+
DEFAULT_LEASE_SECONDS,
|
|
36097
37342
|
DEFAULT_QUESTION_POLL_INTERVAL_MS,
|
|
36098
37343
|
DEFAULT_QUESTION_TIMEOUT_MS,
|
|
36099
37344
|
DERIVATIVE_ERROR_CODES,
|
|
36100
37345
|
DERIVATIVE_QUESTIONS_PATH,
|
|
36101
37346
|
DERIVATIVE_STATUS_PATH,
|
|
36102
37347
|
DataFileEnvelopeSchema,
|
|
36103
|
-
DataPointDeletedError,
|
|
36104
|
-
DataPointNotFoundError,
|
|
36105
37348
|
DataPointStatus,
|
|
36106
|
-
DataPointVersionConflictError,
|
|
36107
|
-
DerivativeComputeUnavailableError,
|
|
36108
|
-
DerivativeCycleError,
|
|
36109
|
-
DerivativeDerivedScopeRequiredError,
|
|
36110
37349
|
DerivativeErrorCodeSchema,
|
|
36111
|
-
DerivativeQuestionFailedError,
|
|
36112
|
-
DerivativeQuestionInvalidError,
|
|
36113
|
-
DerivativeQuestionNotFoundError,
|
|
36114
|
-
DerivativeQuestionRejectedError,
|
|
36115
37350
|
DerivativeQuestionSchema,
|
|
36116
|
-
DerivativeQuestionTimeoutError,
|
|
36117
|
-
DerivativeSourceNotGrantedError,
|
|
36118
37351
|
DerivativeStatusSchema,
|
|
36119
37352
|
DropboxStorage,
|
|
36120
37353
|
ECIESError,
|
|
37354
|
+
ENCLAVE_IDENTITY_EVIDENCE_VERSION,
|
|
37355
|
+
ENCLAVE_TRUST_ANCHORS,
|
|
37356
|
+
ENCLAVE_WALLET_PURPOSE,
|
|
36121
37357
|
ESCROW_DEPOSIT_ABI2 as ESCROW_DEPOSIT_ABI,
|
|
36122
|
-
ExpiredTokenError,
|
|
37358
|
+
ExpiredTokenError2 as ExpiredTokenError,
|
|
36123
37359
|
FEE_REGISTRY_ABI,
|
|
36124
37360
|
GENERIC_PAYMENT_TYPES,
|
|
36125
37361
|
GRANT_OP_TYPE,
|
|
@@ -36128,28 +37364,36 @@ export {
|
|
|
36128
37364
|
GoogleDriveStorage,
|
|
36129
37365
|
InMemoryTokenStore,
|
|
36130
37366
|
IngestResponseSchema,
|
|
36131
|
-
InvalidConfigurationError,
|
|
36132
37367
|
InvalidScopeEntryError,
|
|
36133
|
-
InvalidSignatureError,
|
|
37368
|
+
InvalidSignatureError2 as InvalidSignatureError,
|
|
36134
37369
|
IpfsStorage,
|
|
37370
|
+
JOB_OPERATIONS,
|
|
37371
|
+
JOB_PROTOCOL_VERSION,
|
|
37372
|
+
JOB_RESULT_CHUNK_BYTES,
|
|
37373
|
+
JOB_RESULT_FORMAT_VERSION,
|
|
37374
|
+
JOB_STATES,
|
|
37375
|
+
JobEnvelopeError,
|
|
36135
37376
|
LINEAGE_FIELD,
|
|
36136
37377
|
LINEAGE_KEY,
|
|
36137
37378
|
LineageEntrySchema,
|
|
36138
37379
|
LineageGraphSchema,
|
|
36139
37380
|
LineageNodeSchema,
|
|
36140
|
-
LineageReadError,
|
|
36141
37381
|
MASTER_KEY_MESSAGE,
|
|
37382
|
+
MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
|
|
37383
|
+
MASTER_SIGNATURE_DELIVERY_VERSION,
|
|
37384
|
+
MAX_ATTEMPTS,
|
|
37385
|
+
MAX_JOB_DEADLINE_SECONDS,
|
|
37386
|
+
MAX_LEASE_SECONDS,
|
|
36142
37387
|
MAX_LINEAGE_SOURCES,
|
|
36143
37388
|
MAX_QUESTION_CHARS,
|
|
36144
37389
|
MAX_QUESTION_MODEL_CHARS,
|
|
36145
37390
|
MAX_QUESTION_SOURCE_SCOPES,
|
|
36146
|
-
|
|
37391
|
+
MAX_WAIT_SECONDS,
|
|
37392
|
+
MissingAuthError2 as MissingAuthError,
|
|
36147
37393
|
NATIVE_ASSET_ADDRESS,
|
|
36148
37394
|
NATIVE_VANA_ASSET,
|
|
36149
|
-
NetworkError,
|
|
36150
37395
|
NodeECIESUint8Provider as NodeECIESProvider,
|
|
36151
37396
|
NodePlatformAdapter,
|
|
36152
|
-
NonceError,
|
|
36153
37397
|
OAuthClient,
|
|
36154
37398
|
PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
|
|
36155
37399
|
PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
|
|
@@ -36159,9 +37403,6 @@ export {
|
|
|
36159
37403
|
PKCE_CHALLENGE_PATTERN,
|
|
36160
37404
|
PKCE_VERIFIER_PATTERN,
|
|
36161
37405
|
PSError,
|
|
36162
|
-
PermissionError,
|
|
36163
|
-
PersonalServerError,
|
|
36164
|
-
PersonalServerWriteError,
|
|
36165
37406
|
PinataStorage,
|
|
36166
37407
|
QUESTION_STATUSES,
|
|
36167
37408
|
QuestionDeleteResultSchema,
|
|
@@ -36172,24 +37413,18 @@ export {
|
|
|
36172
37413
|
RECORD_DATA_ACCESS_TYPES,
|
|
36173
37414
|
REGISTRATION_KIND_FOR_OP,
|
|
36174
37415
|
RESERVED_WRITE_KEYS,
|
|
36175
|
-
ReadOnlyError,
|
|
36176
37416
|
RedactedLineageNodeSchema,
|
|
36177
|
-
RelayerError,
|
|
36178
37417
|
SCOPE_ACTIONS,
|
|
37418
|
+
SEALED_ENVELOPE_VERSION,
|
|
36179
37419
|
SERVER_REGISTRATION_TYPES,
|
|
36180
37420
|
ScopeSchema,
|
|
36181
|
-
SerializationError,
|
|
36182
|
-
ServerUrlMismatchError,
|
|
36183
|
-
SignatureError,
|
|
36184
37421
|
StorageError,
|
|
36185
37422
|
StorageManager,
|
|
36186
37423
|
TOMBSTONE_DATA_HASH,
|
|
36187
37424
|
TOMBSTONE_DATA_HASH_PREIMAGE,
|
|
36188
37425
|
TOMBSTONE_METADATA_HASH,
|
|
36189
37426
|
TOMBSTONE_METADATA_HASH_PREIMAGE,
|
|
36190
|
-
|
|
36191
|
-
UserRejectedRequestError,
|
|
36192
|
-
VanaError,
|
|
37427
|
+
USER_PS_ID_DOMAIN,
|
|
36193
37428
|
VanaStorage,
|
|
36194
37429
|
WRITER_ATTRIBUTION_KEY,
|
|
36195
37430
|
WRITE_CONTENT_DISPOSITION_HEADER,
|
|
@@ -36197,15 +37432,7 @@ export {
|
|
|
36197
37432
|
WRITE_METADATA_HEADER,
|
|
36198
37433
|
WRITE_SESSION_PATH,
|
|
36199
37434
|
WRITE_SIGNATURE_HEADER,
|
|
36200
|
-
|
|
36201
|
-
WriteForbiddenError,
|
|
36202
|
-
WriteLineageError,
|
|
36203
|
-
WriteRejectedError,
|
|
36204
|
-
WriteRequestError,
|
|
36205
|
-
WriteSessionError,
|
|
36206
|
-
WriteSessionExpiredError,
|
|
36207
|
-
WriteTransportError,
|
|
36208
|
-
WriteUnauthorizedError,
|
|
37435
|
+
appRootPreimage,
|
|
36209
37436
|
askPersonalServer,
|
|
36210
37437
|
assertDerivedScopeNaming,
|
|
36211
37438
|
assertValidPkceVerifier,
|
|
@@ -36219,6 +37446,7 @@ export {
|
|
|
36219
37446
|
buildEscrowPaymentHeader,
|
|
36220
37447
|
buildGrantPaymentHeader,
|
|
36221
37448
|
buildMarkDataPointUnavailableRequest,
|
|
37449
|
+
buildMasterSignatureDelivery,
|
|
36222
37450
|
buildPersonalServerDataReadRequest,
|
|
36223
37451
|
buildPersonalServerLiteOwnerBindingMessage,
|
|
36224
37452
|
buildPersonalServerLiteOwnerBindingSignature,
|
|
@@ -36227,6 +37455,7 @@ export {
|
|
|
36227
37455
|
buildSetDataPointStatusRequest,
|
|
36228
37456
|
buildWeb3SignedHeader,
|
|
36229
37457
|
builderRegistrationDomain,
|
|
37458
|
+
canonicalJobRequestBytes,
|
|
36230
37459
|
chains,
|
|
36231
37460
|
clearContractCache,
|
|
36232
37461
|
computeBodyHash,
|
|
@@ -36238,6 +37467,7 @@ export {
|
|
|
36238
37467
|
createDefaultNonceSource,
|
|
36239
37468
|
createEscrowGatewayClient,
|
|
36240
37469
|
createGatewayClient,
|
|
37470
|
+
createJobsClient,
|
|
36241
37471
|
createNodePlatformAdapter,
|
|
36242
37472
|
createPlatformAdapter,
|
|
36243
37473
|
createPlatformAdapterFor,
|
|
@@ -36262,6 +37492,7 @@ export {
|
|
|
36262
37492
|
encodeDepositTokenData,
|
|
36263
37493
|
encodeSetDataPointStatusData,
|
|
36264
37494
|
encodeWriteMetadataHeader,
|
|
37495
|
+
encryptMasterSignatureDelivery,
|
|
36265
37496
|
encryptWithPassword,
|
|
36266
37497
|
escrowContractAddress,
|
|
36267
37498
|
escrowPaymentDomain,
|
|
@@ -36296,12 +37527,16 @@ export {
|
|
|
36296
37527
|
isPlatformSupported,
|
|
36297
37528
|
isRedactedLineageNode,
|
|
36298
37529
|
isTombstoneHashes,
|
|
37530
|
+
kmsIssuedPreimage,
|
|
36299
37531
|
listQuestions,
|
|
36300
37532
|
mainnetServices,
|
|
36301
37533
|
moksha,
|
|
36302
37534
|
mokshaServices,
|
|
36303
37535
|
mokshaTestnet2 as mokshaTestnet,
|
|
36304
37536
|
normalizeBinaryMimeType,
|
|
37537
|
+
openJobRequest,
|
|
37538
|
+
openJobResult,
|
|
37539
|
+
openJobResultStream,
|
|
36305
37540
|
openWriteSession,
|
|
36306
37541
|
parsePSError,
|
|
36307
37542
|
parsePersonalServerPaymentRequired,
|
|
@@ -36325,6 +37560,9 @@ export {
|
|
|
36325
37560
|
scopeMatchesPattern,
|
|
36326
37561
|
scopeNamespace,
|
|
36327
37562
|
scopeToPathSegments,
|
|
37563
|
+
sealJobRequest,
|
|
37564
|
+
sealJobResult,
|
|
37565
|
+
sealJobResultStream,
|
|
36328
37566
|
serializeECIES,
|
|
36329
37567
|
serverRegistrationDomain,
|
|
36330
37568
|
sessionCoversScope,
|
|
@@ -36335,7 +37573,9 @@ export {
|
|
|
36335
37573
|
toDirectPaymentReceipt,
|
|
36336
37574
|
tombstoneDeletedAt,
|
|
36337
37575
|
tryGrantPermissions,
|
|
37576
|
+
userPsId,
|
|
36338
37577
|
vanaMainnet2 as vanaMainnet,
|
|
37578
|
+
verifyEnclaveIdentityEvidence,
|
|
36339
37579
|
verifyGrantRegistration,
|
|
36340
37580
|
verifyPkceChallenge,
|
|
36341
37581
|
verifyWeb3Signed,
|