@opendatalabs/vana-sdk 3.20.1 → 3.22.0-pr.207.5c11fe3

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.
Files changed (46) hide show
  1. package/README.md +64 -0
  2. package/dist/direct/access-request-client.cjs +100 -2
  3. package/dist/direct/access-request-client.cjs.map +1 -1
  4. package/dist/direct/access-request-client.d.ts +23 -1
  5. package/dist/direct/access-request-client.js +98 -1
  6. package/dist/direct/access-request-client.js.map +1 -1
  7. package/dist/direct/controller.cjs +4 -0
  8. package/dist/direct/controller.cjs.map +1 -1
  9. package/dist/direct/controller.d.ts +10 -1
  10. package/dist/direct/controller.js +6 -1
  11. package/dist/direct/controller.js.map +1 -1
  12. package/dist/direct/types.cjs.map +1 -1
  13. package/dist/direct/types.d.ts +45 -0
  14. package/dist/direct/types.js.map +1 -1
  15. package/dist/index.browser.d.ts +3 -1
  16. package/dist/index.browser.js +343 -4
  17. package/dist/index.browser.js.map +4 -4
  18. package/dist/index.node.cjs +386 -34
  19. package/dist/index.node.cjs.map +4 -4
  20. package/dist/index.node.d.ts +3 -1
  21. package/dist/index.node.js +346 -7
  22. package/dist/index.node.js.map +4 -4
  23. package/dist/protocol/derivative-questions.cjs +22 -0
  24. package/dist/protocol/derivative-questions.cjs.map +1 -1
  25. package/dist/protocol/derivative-questions.d.ts +53 -0
  26. package/dist/protocol/derivative-questions.js +19 -0
  27. package/dist/protocol/derivative-questions.js.map +1 -1
  28. package/dist/protocol/derivative-status.cjs +209 -0
  29. package/dist/protocol/derivative-status.cjs.map +1 -0
  30. package/dist/protocol/derivative-status.d.ts +196 -0
  31. package/dist/protocol/derivative-status.js +190 -0
  32. package/dist/protocol/derivative-status.js.map +1 -0
  33. package/dist/protocol/derivative-status.test.d.ts +1 -0
  34. package/dist/protocol/identity.cjs +191 -0
  35. package/dist/protocol/identity.cjs.map +1 -0
  36. package/dist/protocol/identity.d.ts +164 -0
  37. package/dist/protocol/identity.js +155 -0
  38. package/dist/protocol/identity.js.map +1 -0
  39. package/dist/protocol/identity.test.d.ts +1 -0
  40. package/dist/server.cjs +4 -2
  41. package/dist/server.cjs.map +1 -1
  42. package/dist/server.d.ts +2 -2
  43. package/dist/server.js +4 -2
  44. package/dist/server.js.map +1 -1
  45. package/dist/tests/mock-personal-server.d.ts +9 -0
  46. package/package.json +1 -1
@@ -37,6 +37,7 @@ export { generatePkceVerifier, computePkceChallenge, verifyPkceChallenge, assert
37
37
  export { InMemoryTokenStore, type TokenStore, type TokenRecord, } from "./auth/token-store.js";
38
38
  export { OAuthClient, type OAuthClientConfig, type AuthorizationUrlResult, } from "./auth/oauth-client.js";
39
39
  export { NATIVE_VANA_ASSET, dataRegistryDomain, grantRegistrationDomain, grantRevocationDomain, serverRegistrationDomain, builderRegistrationDomain, escrowPaymentDomain, GRANT_REGISTRATION_TYPES, GRANT_REVOCATION_TYPES, SERVER_REGISTRATION_TYPES, BUILDER_REGISTRATION_TYPES, ADD_DATA_TYPES, RECORD_DATA_ACCESS_TYPES, type DataPortabilityContracts, type DataPortabilityGatewayConfig, type GrantRegistrationMessage, type GrantRevocationMessage, type ServerRegistrationMessage, type BuilderRegistrationMessage, type AddDataMessage, type RecordDataAccessMessage, } from "./protocol/eip712.js";
40
+ export { ENCLAVE_IDENTITY_EVIDENCE_VERSION, USER_PS_ID_DOMAIN, ENCLAVE_WALLET_PURPOSE, MASTER_SIGNATURE_DELIVERY_VERSION, SEALED_ENVELOPE_VERSION, ENCLAVE_TRUST_ANCHORS, userPsId, appRootPreimage, kmsIssuedPreimage, verifyEnclaveIdentityEvidence, buildMasterSignatureDelivery, encryptMasterSignatureDelivery, type UserPsId, type EnclaveIdentityEvidence, type ExpectedIdentity, type IdentityRequest, type IdentityState, type IdentityResponse, type IdentityRegistrationRequest, type IdentityRegistrationResponse, type MasterSignatureDelivery, type SealedSecretSubmission, type SealedSecretResponse, type AesGcmBox, type SealedEnvelope, type EnclaveTrustAnchors, } from "./protocol/identity.js";
40
41
  export { PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID, PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT, personalServerRegistrationDomain, createViemPersonalServerRegistrationSigner, buildPersonalServerRegistrationTypedData, buildPersonalServerRegistrationSignature, registerPersonalServerSignature, type PersonalServerRegistrationTypedData, type PersonalServerRegistrationSigner, type PersonalServerRegistrationDomainInput, type ViemPersonalServerRegistrationWalletClient, type ViemPersonalServerRegistrationSignerSource, type BuildPersonalServerRegistrationTypedDataInput, type BuildPersonalServerRegistrationSignatureInput, type PersonalServerRegistrationSignature, } from "./protocol/personal-server-registration.js";
41
42
  export { PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION, PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE, PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX, buildPersonalServerLiteOwnerBindingMessage, createViemPersonalServerLiteOwnerBindingSigner, buildPersonalServerLiteOwnerBindingSignature, signPersonalServerLiteOwnerBinding, type PersonalServerLiteOwnerBindingPurpose, type PersonalServerLiteOwnerBindingMessage, type PersonalServerLiteOwnerBindingSigner, type ViemPersonalServerLiteOwnerBindingWalletClient, type ViemPersonalServerLiteOwnerBindingSignerSource, type BuildPersonalServerLiteOwnerBindingSignatureInput, type PersonalServerLiteOwnerBindingSignature, } from "./personal-server-lite/owner-binding.js";
42
43
  export { ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT, AccountPersonalServerRegistrationError, signPersonalServerRegistrationWithAccount, type AccountPersonalServerRegistrationIntent, type AccountPersonalServerRegistrationSignature, type AccountPersonalServerRegistrationStatus, type AccountPersonalServerRegistrationRequest, type AccountPersonalServerRegistrationConfig, type AccountSignedPersonalServerRegistration, type AccountConfirmationRequiredPersonalServerRegistration, type AccountFallbackSignedPersonalServerRegistration, type AccountPersonalServerRegistrationResult, } from "./account/personal-server-registration.js";
@@ -51,7 +52,8 @@ export { ScopeSchema, parseScope, scopeToPathSegments, scopeMatchesPattern, scop
51
52
  export { SCOPE_ACTIONS, InvalidScopeEntryError, parseScopeEntry, formatScopeEntry, grantPermissions, permissionsToScopes, tryGrantPermissions, hasAction, type ScopeAction, type ParsedScopeEntry, type GrantPermission, } from "./protocol/scope-actions.js";
52
53
  export { WRITE_SESSION_PATH, WRITE_SIGNATURE_HEADER, WRITE_METADATA_HEADER, WRITE_FILENAME_HEADER, WRITE_CONTENT_DISPOSITION_HEADER, WRITER_ATTRIBUTION_KEY, LINEAGE_KEY, LINEAGE_FIELD, MAX_LINEAGE_SOURCES, RESERVED_WRITE_KEYS, openWriteSession, writeData, writePersonalServerData, sessionCoversScope, binaryWriteSignedBytes, normalizeBinaryMimeType, parseWriteMetadataHeader, encodeWriteMetadataHeader, type WriteTransportRetryOptions, type WriteSession, type OpenWriteSessionParams, type WriteBinaryPayload, type LineageSource, type WriteJsonDataParams, type WriteBinaryDataParams, type WriteDataParams, type WriteDataResult, type WritePersonalServerDataParams, type WritePersonalServerDataResult, type BinaryWriteSignedBytesInput, } from "./protocol/personal-server-write.js";
53
54
  export { resolveWriteSigner, type WriteSigner, type WriteSignerSource, type ViemWriteAccount, type ViemWriteWalletClient, type ResolveWriteSignerOptions, } from "./protocol/write-signer.js";
54
- export { DERIVATIVE_QUESTIONS_PATH, MAX_QUESTION_SOURCE_SCOPES, MAX_QUESTION_CHARS, MAX_QUESTION_MODEL_CHARS, DEFAULT_QUESTION_TIMEOUT_MS, DEFAULT_QUESTION_POLL_INTERVAL_MS, QUESTION_STATUSES, registerQuestion, getQuestion, listQuestions, recomputeQuestion, deleteQuestion, waitForQuestion, askPersonalServer, QuestionStatusSchema, QuestionRegisteredBySchema, DerivativeQuestionSchema, QuestionRecomputeResultSchema, QuestionDeleteResultSchema, type QuestionStatus, type QuestionRegisteredBy, type DerivativeQuestion, type QuestionRecomputeResult, type QuestionDeleteResult, type DerivativeQuestionAuthParams, type RegisterQuestionParams, type GetQuestionParams, type ListQuestionsParams, type RecomputeQuestionParams, type DeleteQuestionParams, type WaitForQuestionParams, type AskPersonalServerParams, type AskPersonalServerResult, } from "./protocol/derivative-questions.js";
55
+ export { DERIVATIVE_QUESTIONS_PATH, MAX_QUESTION_SOURCE_SCOPES, MAX_QUESTION_CHARS, MAX_QUESTION_MODEL_CHARS, DEFAULT_QUESTION_TIMEOUT_MS, DEFAULT_QUESTION_POLL_INTERVAL_MS, QUESTION_STATUSES, DERIVATIVE_ERROR_CODES, DerivativeErrorCodeSchema, type DerivativeErrorCode, registerQuestion, getQuestion, listQuestions, recomputeQuestion, deleteQuestion, waitForQuestion, askPersonalServer, QuestionStatusSchema, QuestionRegisteredBySchema, DerivativeQuestionSchema, QuestionRecomputeResultSchema, QuestionDeleteResultSchema, type QuestionStatus, type QuestionRegisteredBy, type DerivativeQuestion, type QuestionRecomputeResult, type QuestionDeleteResult, type DerivativeQuestionAuthParams, type RegisterQuestionParams, type GetQuestionParams, type ListQuestionsParams, type RecomputeQuestionParams, type DeleteQuestionParams, type WaitForQuestionParams, type AskPersonalServerParams, type AskPersonalServerResult, } from "./protocol/derivative-questions.js";
56
+ export { DERIVATIVE_STATUS_PATH, DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS, DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS, derivativeStatusTarget, getDerivativeStatus, waitForDerivativeStatus, isDerivativeStatusSettled, DerivativeStatusSchema, type DerivativeStatus, type GetDerivativeStatusParams, type WaitForDerivativeStatusParams, } from "./protocol/derivative-status.js";
55
57
  export { deriveDataPointId, isDataPointId, scopeNamespace, derivedScopeViolatesNaming, assertDerivedScopeNaming, isRedactedLineageNode, personalServerLineagePath, gatewayLineagePath, getLineage, getPersonalServerLineage, getGatewayLineage, LineageNodeSchema, RedactedLineageNodeSchema, LineageEntrySchema, LineageGraphSchema, type LineageNode, type RedactedLineageNode, type LineageEntry, type LineageGraph, type LineageReadResult, type PersonalServerLineageParams, type GatewayLineageParams, type GetLineageParams, } from "./protocol/lineage.js";
56
58
  export { DataFileEnvelopeSchema, createDataFileEnvelope, IngestResponseSchema, type DataFileEnvelope, type IngestResponse, } from "./protocol/data-file.js";
57
59
  export { createGatewayClient, type GatewayEnvelope, type GatewayProof, type Builder, type Schema, type ServerInfo, type OwnerServerRecord, type OwnerServersResult, type GatewayGrantFee, type GatewayGrantStatus, type GatewayGrantResponse, type GrantListItem, type DataPointRecord, type DataPointListResult, type ListDataPointsOptions, type RegisterServerParams, type RegisterServerResult, type RegisterBuilderParams, type RegisterBuilderResult, type RegisterDataPointParams, type RegisterDataPointResult, type GetDataPointOptions, type DeleteDataPointParams, type DeleteDataPointResult, type CreateGrantParams, type RevokeGrantParams, type AccessRecord, type PayForOperationParams, type PayForOperationResult, type SettleOpType, type SettleItem, type SettlePromoteResult, type SettleReconcileItem, type SettleParams, type SettleResult, type GatewayClient, } from "./protocol/gateway.js";
@@ -31347,13 +31347,13 @@ var NodeCryptoAdapter = class {
31347
31347
  */
31348
31348
  async generateKeyPair() {
31349
31349
  try {
31350
- const secp256k14 = secp256k1Import2;
31350
+ const secp256k15 = secp256k1Import2;
31351
31351
  let privateKey;
31352
31352
  do {
31353
31353
  privateKey = randomBytes2(32);
31354
- } while (!secp256k14.privateKeyVerify(privateKey));
31354
+ } while (!secp256k15.privateKeyVerify(privateKey));
31355
31355
  const publicKey = Buffer.from(
31356
- secp256k14.publicKeyCreate(privateKey, true)
31356
+ secp256k15.publicKeyCreate(privateKey, true)
31357
31357
  );
31358
31358
  return {
31359
31359
  privateKey: privateKey.toString("hex"),
@@ -32363,6 +32363,147 @@ var RECORD_DATA_ACCESS_TYPES = {
32363
32363
  ]
32364
32364
  };
32365
32365
 
32366
+ // src/protocol/identity.ts
32367
+ init_interface();
32368
+ import * as secp256k14 from "@noble/secp256k1";
32369
+ import {
32370
+ concat as concat4,
32371
+ encodePacked,
32372
+ fromHex as fromHex5,
32373
+ getAddress,
32374
+ isAddressEqual,
32375
+ keccak256,
32376
+ recoverPublicKey,
32377
+ toBytes
32378
+ } from "viem";
32379
+ import { publicKeyToAddress } from "viem/accounts";
32380
+ var ENCLAVE_IDENTITY_EVIDENCE_VERSION = 1;
32381
+ var USER_PS_ID_DOMAIN = "vana.ps-enclave.v1";
32382
+ var ENCLAVE_WALLET_PURPOSE = "vana.ps-enclave.wallet.v1";
32383
+ var MASTER_SIGNATURE_DELIVERY_VERSION = "vana.ps-enclave.delivery.v1";
32384
+ var SEALED_ENVELOPE_VERSION = 1;
32385
+ var VANA_MAINNET_CHAIN_ID = 1480;
32386
+ var MOKSHA_CHAIN_ID = 14800;
32387
+ var KMS_ISSUED_PREFIX = "dstack-kms-issued";
32388
+ var PREIMAGE_SEPARATOR = ":";
32389
+ var UNCOMPRESSED_PUBLIC_KEY_BYTES = 65;
32390
+ var UNCOMPRESSED_PUBLIC_KEY_PREFIX = "04";
32391
+ var ENCLAVE_TRUST_ANCHORS = {
32392
+ // filled at fleet provisioning; verify fails closed while empty
32393
+ [VANA_MAINNET_CHAIN_ID]: { kmsRootPubkey: "0x", appIds: [] },
32394
+ // filled at fleet provisioning; verify fails closed while empty
32395
+ [MOKSHA_CHAIN_ID]: { kmsRootPubkey: "0x", appIds: [] }
32396
+ };
32397
+ function userPsId(chainId, ownerAddress) {
32398
+ const packed = encodePacked(
32399
+ ["string", "uint256", "address"],
32400
+ [USER_PS_ID_DOMAIN, BigInt(chainId), getAddress(ownerAddress)]
32401
+ );
32402
+ return keccak256(packed);
32403
+ }
32404
+ function appRootPreimage(purpose, publicKey) {
32405
+ const keyHex = publicKey.slice(2).toLowerCase();
32406
+ return keccak256(toBytes(`${purpose}${PREIMAGE_SEPARATOR}${keyHex}`));
32407
+ }
32408
+ function kmsIssuedPreimage(appId, appRootPublicKey) {
32409
+ const appIdHex = appId.slice(2).toLowerCase();
32410
+ const prefix = toBytes(
32411
+ `${KMS_ISSUED_PREFIX}${PREIMAGE_SEPARATOR}${appIdHex}`
32412
+ );
32413
+ const compressed = secp256k14.ProjectivePoint.fromHex(
32414
+ fromHex5(appRootPublicKey, "bytes")
32415
+ ).toRawBytes(true);
32416
+ return keccak256(concat4([prefix, compressed]));
32417
+ }
32418
+ async function recoverChainKey(hash, signature, link) {
32419
+ try {
32420
+ return (await recoverPublicKey({ hash, signature })).toLowerCase();
32421
+ } catch {
32422
+ throw new Error(`Invalid enclave signature chain link ${link}`);
32423
+ }
32424
+ }
32425
+ async function verifyEnclaveIdentityEvidence(evidence, anchors, expected) {
32426
+ if (evidence.v !== ENCLAVE_IDENTITY_EVIDENCE_VERSION) {
32427
+ throw new Error("Unsupported enclave identity evidence version");
32428
+ }
32429
+ if (!Number.isInteger(evidence.epoch) || evidence.epoch < 1) {
32430
+ throw new Error("Invalid enclave identity epoch");
32431
+ }
32432
+ if (evidence.chainId !== expected.chainId) {
32433
+ throw new Error(
32434
+ "Enclave identity chain ID does not match expected chain ID"
32435
+ );
32436
+ }
32437
+ if (!isAddressEqual(evidence.ownerAddress, expected.ownerAddress)) {
32438
+ throw new Error("Enclave identity owner does not match expected owner");
32439
+ }
32440
+ if (evidence.epoch !== expected.epoch) {
32441
+ throw new Error("Enclave identity epoch does not match expected epoch");
32442
+ }
32443
+ const expectedUserPsId = userPsId(expected.chainId, expected.ownerAddress);
32444
+ if (evidence.userPsId.toLowerCase() !== expectedUserPsId.toLowerCase()) {
32445
+ throw new Error("Enclave userPsId does not match expected identity");
32446
+ }
32447
+ if (evidence.purpose !== ENCLAVE_WALLET_PURPOSE) {
32448
+ throw new Error("Unexpected enclave wallet purpose");
32449
+ }
32450
+ const derivedAddress = publicKeyToAddress(evidence.publicKey);
32451
+ if (getAddress(derivedAddress) !== getAddress(evidence.address)) {
32452
+ throw new Error("Enclave public key does not match its address");
32453
+ }
32454
+ const appRootPublicKey = await recoverChainKey(
32455
+ appRootPreimage(evidence.purpose, evidence.publicKey),
32456
+ evidence.signatureChain[0],
32457
+ 0
32458
+ );
32459
+ const kmsRootPublicKey = await recoverChainKey(
32460
+ kmsIssuedPreimage(evidence.appId, appRootPublicKey),
32461
+ evidence.signatureChain[1],
32462
+ 1
32463
+ );
32464
+ if (anchors.kmsRootPubkey === "0x") {
32465
+ throw new Error("KMS root trust anchor is not provisioned");
32466
+ }
32467
+ if (kmsRootPublicKey !== anchors.kmsRootPubkey.toLowerCase()) {
32468
+ throw new Error("KMS root public key does not match the trust anchor");
32469
+ }
32470
+ if (keccak256(kmsRootPublicKey) !== evidence.kmsRootFingerprint.toLowerCase()) {
32471
+ throw new Error("KMS root fingerprint does not match the evidence");
32472
+ }
32473
+ const appId = evidence.appId.toLowerCase();
32474
+ if (!anchors.appIds.some((allowedAppId) => allowedAppId.toLowerCase() === appId)) {
32475
+ throw new Error("Enclave app ID is not trusted");
32476
+ }
32477
+ }
32478
+ async function buildMasterSignatureDelivery(evidence, masterSignature, now = Math.floor(Date.now() / 1e3)) {
32479
+ deriveMasterKey(masterSignature);
32480
+ const signerAddress = await recoverServerOwner(masterSignature);
32481
+ if (!isAddressEqual(signerAddress, evidence.ownerAddress)) {
32482
+ throw new Error("Master signature signer does not match evidence owner");
32483
+ }
32484
+ return {
32485
+ v: MASTER_SIGNATURE_DELIVERY_VERSION,
32486
+ userPsId: evidence.userPsId,
32487
+ epoch: evidence.epoch,
32488
+ enclaveAddress: evidence.address,
32489
+ ownerAddress: evidence.ownerAddress,
32490
+ masterSignature,
32491
+ issuedAt: now
32492
+ };
32493
+ }
32494
+ function assertUncompressedKey(publicKey) {
32495
+ const hex = publicKey.slice(2);
32496
+ if (hex.length !== UNCOMPRESSED_PUBLIC_KEY_BYTES * 2 || !hex.startsWith(UNCOMPRESSED_PUBLIC_KEY_PREFIX) || !/^[0-9a-fA-F]+$/.test(hex)) {
32497
+ throw new Error("Public key must be a 65-byte uncompressed secp256k1 key");
32498
+ }
32499
+ }
32500
+ async function encryptMasterSignatureDelivery(delivery, publicKey, ecies) {
32501
+ assertUncompressedKey(publicKey);
32502
+ const plaintext = toBytes(JSON.stringify(delivery));
32503
+ const encrypted = await ecies.encrypt(fromHex5(publicKey, "bytes"), plaintext);
32504
+ return `0x${serializeECIES(encrypted)}`;
32505
+ }
32506
+
32366
32507
  // src/protocol/personal-server-registration.ts
32367
32508
  import {
32368
32509
  isAddress
@@ -33062,7 +33203,7 @@ function buildMarkDataPointUnavailableRequest(config, input) {
33062
33203
  // src/protocol/data-point-deletion.ts
33063
33204
  import {
33064
33205
  isAddress as isAddress5,
33065
- keccak256 as keccak2562,
33206
+ keccak256 as keccak2563,
33066
33207
  maxUint256,
33067
33208
  stringToBytes as stringToBytes3
33068
33209
  } from "viem";
@@ -33071,7 +33212,7 @@ import {
33071
33212
  import {
33072
33213
  encodeAbiParameters,
33073
33214
  isAddress as isAddress4,
33074
- keccak256
33215
+ keccak256 as keccak2562
33075
33216
  } from "viem";
33076
33217
  import { z } from "zod";
33077
33218
 
@@ -33155,7 +33296,7 @@ function deriveDataPointId(ownerAddress, scope) {
33155
33296
  `ownerAddress is not an EVM address: ${String(ownerAddress)}`
33156
33297
  );
33157
33298
  }
33158
- return keccak256(
33299
+ return keccak2562(
33159
33300
  encodeAbiParameters(
33160
33301
  [
33161
33302
  { name: "ownerAddress", type: "address" },
@@ -33382,7 +33523,7 @@ var TOMBSTONE_METADATA_HASH_PREIMAGE = "vana.data-point.tombstone.metadata.v1";
33382
33523
  var TOMBSTONE_DATA_HASH = "0x30c45ee72fe56d1927701316925ab7ceacd3b6f9267061735d59396f075c6222";
33383
33524
  var TOMBSTONE_METADATA_HASH = "0xc5255a141acd6a2ae55971b62c0a85977c2511989dc114ad2abc2b7644f57d90";
33384
33525
  function computeTombstoneHash(preimage) {
33385
- return keccak2562(stringToBytes3(preimage));
33526
+ return keccak2563(stringToBytes3(preimage));
33386
33527
  }
33387
33528
  function isTombstoneHashes(dataHash, metadataHash) {
33388
33529
  return typeof dataHash === "string" && typeof metadataHash === "string" && dataHash.toLowerCase() === TOMBSTONE_DATA_HASH && metadataHash.toLowerCase() === TOMBSTONE_METADATA_HASH;
@@ -34404,6 +34545,13 @@ var QUESTION_STATUSES = [
34404
34545
  "failed",
34405
34546
  "stale"
34406
34547
  ];
34548
+ var DERIVATIVE_ERROR_CODES = [
34549
+ "inference_unavailable",
34550
+ "source_missing",
34551
+ "grant_invalid",
34552
+ "internal"
34553
+ ];
34554
+ var DerivativeErrorCodeSchema = z5.enum(DERIVATIVE_ERROR_CODES);
34407
34555
  var QuestionStatusSchema = z5.enum(QUESTION_STATUSES);
34408
34556
  var QuestionRegisteredBySchema = z5.union([
34409
34557
  z5.object({ kind: z5.literal("owner") }),
@@ -34425,6 +34573,14 @@ var DerivativeQuestionSchema = z5.object({
34425
34573
  status: QuestionStatusSchema,
34426
34574
  /** A short reason, set only while `status` is `failed`. */
34427
34575
  error: nullableString,
34576
+ /**
34577
+ * The coarse failure class behind `error`, set only while `status` is
34578
+ * `failed`. `null` from a Personal Server that predates the class
34579
+ * (`personal-server-ts` before the status route).
34580
+ */
34581
+ errorCode: DerivativeErrorCodeSchema.nullish().transform(
34582
+ (value) => value ?? null
34583
+ ),
34428
34584
  createdAt: z5.string(),
34429
34585
  updatedAt: nullableString,
34430
34586
  /** When the last compute finished, or `null` while `pending`. */
@@ -34557,6 +34713,7 @@ async function questionErrorFromResponse(response, body) {
34557
34713
  );
34558
34714
  }
34559
34715
  }
34716
+ var personalServerErrorFromQuestionResponse = questionErrorFromResponse;
34560
34717
  async function sendOnce(params, resolved, session, spec, bodyBytes) {
34561
34718
  return sendWithFreshProof(
34562
34719
  spec.label,
@@ -34836,6 +34993,166 @@ async function askPersonalServer(params) {
34836
34993
  return { registration, record };
34837
34994
  }
34838
34995
 
34996
+ // src/protocol/derivative-status.ts
34997
+ import { z as z6 } from "zod";
34998
+ var DERIVATIVE_STATUS_PATH = "/v1/derivatives/status";
34999
+ var DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS = 12e4;
35000
+ var DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS = 2e3;
35001
+ var nullable = (schema) => schema.nullish().transform((value) => value ?? null);
35002
+ var DerivativeStatusSchema = z6.object({
35003
+ derivedScope: z6.string().min(1),
35004
+ status: QuestionStatusSchema,
35005
+ /** When the last compute finished, or `null` if none ever has. */
35006
+ lastComputedAt: nullable(z6.string()),
35007
+ /** Local version of the derived record the last compute wrote. */
35008
+ derivedVersion: nullable(z6.number()),
35009
+ derivedCollectedAt: nullable(z6.string()),
35010
+ /** The failure class; `null` unless `status` is `failed`. */
35011
+ errorCode: nullable(DerivativeErrorCodeSchema),
35012
+ /**
35013
+ * Seconds until the Personal Server's next automatic retry, or `null` when
35014
+ * none is pending or running — the terminal signature. Poll on this cadence
35015
+ * rather than guessing one.
35016
+ */
35017
+ retryAfterSeconds: nullable(z6.number())
35018
+ });
35019
+ function derivativeStatusTarget(derivedScope) {
35020
+ return `${DERIVATIVE_STATUS_PATH}?derivedScope=${encodeURIComponent(derivedScope)}`;
35021
+ }
35022
+ function normalizeBaseUrl3(url) {
35023
+ return url.replace(/\/+$/, "");
35024
+ }
35025
+ function resolveFetch3(fetchFn) {
35026
+ const resolved = fetchFn ?? globalThis.fetch;
35027
+ if (resolved === void 0) {
35028
+ throw new WriteRequestError("No fetch implementation available");
35029
+ }
35030
+ return resolved;
35031
+ }
35032
+ function requireDerivedScope(derivedScope) {
35033
+ if (typeof derivedScope !== "string" || derivedScope.length === 0) {
35034
+ throw new WriteRequestError("derivedScope is required");
35035
+ }
35036
+ return derivedScope;
35037
+ }
35038
+ function sleep3(ms, signal) {
35039
+ if (ms <= 0) return Promise.resolve();
35040
+ return new Promise((resolve, reject) => {
35041
+ const timer = setTimeout(() => {
35042
+ signal?.removeEventListener("abort", onAbort);
35043
+ resolve();
35044
+ }, ms);
35045
+ const onAbort = () => {
35046
+ clearTimeout(timer);
35047
+ reject(abortError2(signal));
35048
+ };
35049
+ signal?.addEventListener("abort", onAbort, { once: true });
35050
+ });
35051
+ }
35052
+ function timeoutError(latest, timeoutMs) {
35053
+ return new DerivativeQuestionTimeoutError(
35054
+ `Derived scope ${latest.derivedScope} was still ${latest.status} after ${timeoutMs}ms`,
35055
+ {
35056
+ derivedScope: latest.derivedScope,
35057
+ status: latest.status,
35058
+ errorCode: latest.errorCode,
35059
+ retryAfterSeconds: latest.retryAfterSeconds,
35060
+ timeoutMs
35061
+ }
35062
+ );
35063
+ }
35064
+ function abortError2(signal) {
35065
+ const reason = signal?.reason;
35066
+ return reason instanceof Error ? reason : new WriteRequestError("Derivative status wait was aborted");
35067
+ }
35068
+ function isDerivativeStatusSettled(status) {
35069
+ if (status.status === "ready") return true;
35070
+ return status.status === "failed" && status.retryAfterSeconds === null;
35071
+ }
35072
+ async function getDerivativeStatus(params) {
35073
+ const derivedScope = requireDerivedScope(params.derivedScope);
35074
+ const fetchFn = resolveFetch3(params.fetch);
35075
+ const baseUrl = normalizeBaseUrl3(params.personalServerUrl);
35076
+ const signer = resolveWriteSigner(params.signer, { account: params.account });
35077
+ const headers = new Headers(params.headers);
35078
+ headers.set(
35079
+ "Authorization",
35080
+ await buildWeb3SignedHeader({
35081
+ signMessage: signer.signMessage,
35082
+ aud: params.audience ?? baseUrl,
35083
+ method: "GET",
35084
+ uri: DERIVATIVE_STATUS_PATH,
35085
+ grantId: params.grantId
35086
+ })
35087
+ );
35088
+ let response;
35089
+ try {
35090
+ response = await fetchFn(
35091
+ `${baseUrl}${derivativeStatusTarget(derivedScope)}`,
35092
+ {
35093
+ method: "GET",
35094
+ headers,
35095
+ ...params.signal ? { signal: params.signal } : {}
35096
+ }
35097
+ );
35098
+ } catch (err) {
35099
+ throw new WriteTransportError(
35100
+ `Derivative status read failed: ${err instanceof Error ? err.message : String(err)}`,
35101
+ 1,
35102
+ err
35103
+ );
35104
+ }
35105
+ if (!response.ok) {
35106
+ throw await personalServerErrorFromQuestionResponse(
35107
+ response
35108
+ );
35109
+ }
35110
+ let body;
35111
+ try {
35112
+ body = await response.json();
35113
+ } catch (err) {
35114
+ throw new DerivativeQuestionRejectedError(
35115
+ "Derivative status response is not JSON",
35116
+ response.status,
35117
+ null,
35118
+ { cause: err instanceof Error ? err.message : String(err) }
35119
+ );
35120
+ }
35121
+ const parsed = DerivativeStatusSchema.safeParse(body);
35122
+ if (!parsed.success) {
35123
+ throw new DerivativeQuestionRejectedError(
35124
+ "Derivative status response is not a status view",
35125
+ response.status,
35126
+ null,
35127
+ { issues: parsed.error.issues }
35128
+ );
35129
+ }
35130
+ return parsed.data;
35131
+ }
35132
+ async function waitForDerivativeStatus(params) {
35133
+ const timeoutMs = Math.max(
35134
+ 0,
35135
+ params.timeoutMs ?? DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS
35136
+ );
35137
+ const pollIntervalMs = Math.max(
35138
+ 0,
35139
+ params.pollIntervalMs ?? DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS
35140
+ );
35141
+ const deadline = Date.now() + timeoutMs;
35142
+ for (; ; ) {
35143
+ if (params.signal?.aborted) throw abortError2(params.signal);
35144
+ const latest = await getDerivativeStatus(params);
35145
+ if (isDerivativeStatusSettled(latest)) return latest;
35146
+ const remaining = deadline - Date.now();
35147
+ if (remaining <= 0) throw timeoutError(latest, timeoutMs);
35148
+ const waitMs = latest.retryAfterSeconds === null ? pollIntervalMs : latest.retryAfterSeconds * 1e3;
35149
+ if (waitMs > remaining) {
35150
+ throw timeoutError(latest, timeoutMs);
35151
+ }
35152
+ await sleep3(waitMs, params.signal);
35153
+ }
35154
+ }
35155
+
34839
35156
  // src/protocol/gateway.ts
34840
35157
  function withGrantPermissions(grant) {
34841
35158
  const stripped = { ...grant };
@@ -35916,9 +36233,13 @@ export {
35916
36233
  ContractNotFoundError,
35917
36234
  DATA_ACCESS_OP_TYPE,
35918
36235
  DATA_REGISTRY_STATUS_ABI,
36236
+ DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
36237
+ DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
35919
36238
  DEFAULT_QUESTION_POLL_INTERVAL_MS,
35920
36239
  DEFAULT_QUESTION_TIMEOUT_MS,
36240
+ DERIVATIVE_ERROR_CODES,
35921
36241
  DERIVATIVE_QUESTIONS_PATH,
36242
+ DERIVATIVE_STATUS_PATH,
35922
36243
  DataFileEnvelopeSchema,
35923
36244
  DataPointDeletedError,
35924
36245
  DataPointNotFoundError,
@@ -35927,6 +36248,7 @@ export {
35927
36248
  DerivativeComputeUnavailableError,
35928
36249
  DerivativeCycleError,
35929
36250
  DerivativeDerivedScopeRequiredError,
36251
+ DerivativeErrorCodeSchema,
35930
36252
  DerivativeQuestionFailedError,
35931
36253
  DerivativeQuestionInvalidError,
35932
36254
  DerivativeQuestionNotFoundError,
@@ -35934,8 +36256,12 @@ export {
35934
36256
  DerivativeQuestionSchema,
35935
36257
  DerivativeQuestionTimeoutError,
35936
36258
  DerivativeSourceNotGrantedError,
36259
+ DerivativeStatusSchema,
35937
36260
  DropboxStorage,
35938
36261
  ECIESError,
36262
+ ENCLAVE_IDENTITY_EVIDENCE_VERSION,
36263
+ ENCLAVE_TRUST_ANCHORS,
36264
+ ENCLAVE_WALLET_PURPOSE,
35939
36265
  ESCROW_DEPOSIT_ABI2 as ESCROW_DEPOSIT_ABI,
35940
36266
  ExpiredTokenError,
35941
36267
  FEE_REGISTRY_ABI,
@@ -35957,6 +36283,7 @@ export {
35957
36283
  LineageNodeSchema,
35958
36284
  LineageReadError,
35959
36285
  MASTER_KEY_MESSAGE,
36286
+ MASTER_SIGNATURE_DELIVERY_VERSION,
35960
36287
  MAX_LINEAGE_SOURCES,
35961
36288
  MAX_QUESTION_CHARS,
35962
36289
  MAX_QUESTION_MODEL_CHARS,
@@ -35994,6 +36321,7 @@ export {
35994
36321
  RedactedLineageNodeSchema,
35995
36322
  RelayerError,
35996
36323
  SCOPE_ACTIONS,
36324
+ SEALED_ENVELOPE_VERSION,
35997
36325
  SERVER_REGISTRATION_TYPES,
35998
36326
  ScopeSchema,
35999
36327
  SerializationError,
@@ -36006,6 +36334,7 @@ export {
36006
36334
  TOMBSTONE_METADATA_HASH,
36007
36335
  TOMBSTONE_METADATA_HASH_PREIMAGE,
36008
36336
  TransactionPendingError,
36337
+ USER_PS_ID_DOMAIN,
36009
36338
  UserRejectedRequestError,
36010
36339
  VanaError,
36011
36340
  VanaStorage,
@@ -36024,6 +36353,7 @@ export {
36024
36353
  WriteSessionExpiredError,
36025
36354
  WriteTransportError,
36026
36355
  WriteUnauthorizedError,
36356
+ appRootPreimage,
36027
36357
  askPersonalServer,
36028
36358
  assertDerivedScopeNaming,
36029
36359
  assertValidPkceVerifier,
@@ -36037,6 +36367,7 @@ export {
36037
36367
  buildEscrowPaymentHeader,
36038
36368
  buildGrantPaymentHeader,
36039
36369
  buildMarkDataPointUnavailableRequest,
36370
+ buildMasterSignatureDelivery,
36040
36371
  buildPersonalServerDataReadRequest,
36041
36372
  buildPersonalServerLiteOwnerBindingMessage,
36042
36373
  buildPersonalServerLiteOwnerBindingSignature,
@@ -36069,6 +36400,7 @@ export {
36069
36400
  decryptWithPassword,
36070
36401
  deleteDataPoint,
36071
36402
  deleteQuestion,
36403
+ derivativeStatusTarget,
36072
36404
  deriveDataPointId,
36073
36405
  deriveMasterKey,
36074
36406
  deriveScopeKey,
@@ -36079,6 +36411,7 @@ export {
36079
36411
  encodeDepositTokenData,
36080
36412
  encodeSetDataPointStatusData,
36081
36413
  encodeWriteMetadataHeader,
36414
+ encryptMasterSignatureDelivery,
36082
36415
  encryptWithPassword,
36083
36416
  escrowContractAddress,
36084
36417
  escrowPaymentDomain,
@@ -36092,6 +36425,7 @@ export {
36092
36425
  getContractAddress,
36093
36426
  getContractController,
36094
36427
  getContractInfo,
36428
+ getDerivativeStatus,
36095
36429
  getFee,
36096
36430
  getGatewayLineage,
36097
36431
  getLineage,
@@ -36107,10 +36441,12 @@ export {
36107
36441
  isDataPointId,
36108
36442
  isDataPointTombstone,
36109
36443
  isDataPortabilityGatewayConfig,
36444
+ isDerivativeStatusSettled,
36110
36445
  isECIESEncrypted,
36111
36446
  isPlatformSupported,
36112
36447
  isRedactedLineageNode,
36113
36448
  isTombstoneHashes,
36449
+ kmsIssuedPreimage,
36114
36450
  listQuestions,
36115
36451
  mainnetServices,
36116
36452
  moksha,
@@ -36150,10 +36486,13 @@ export {
36150
36486
  toDirectPaymentReceipt,
36151
36487
  tombstoneDeletedAt,
36152
36488
  tryGrantPermissions,
36489
+ userPsId,
36153
36490
  vanaMainnet2 as vanaMainnet,
36491
+ verifyEnclaveIdentityEvidence,
36154
36492
  verifyGrantRegistration,
36155
36493
  verifyPkceChallenge,
36156
36494
  verifyWeb3Signed,
36495
+ waitForDerivativeStatus,
36157
36496
  waitForQuestion,
36158
36497
  writeData,
36159
36498
  writePersonalServerData