@opendatalabs/vana-sdk 3.22.0-pr.208.dac9856 → 3.22.0-pr.208.e9c19e9

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result properties follow their interface order. The\n * wire ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified by\n * the ECIES provider interface. The Gateway hashes raw ciphertext bytes, not\n * plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport {\n deserializeECIES,\n serializeECIES,\n type ECIESProvider,\n} from \"../ecies/interface\";\nimport {\n JOB_OPERATIONS,\n JOB_PROTOCOL_VERSION,\n type JobOperation,\n type JobRequest,\n type JobRequestEnvelope,\n type JobResult,\n} from \"../../protocol/jobs\";\nimport { fromBase64, toBase64 } from \"../../utils/encoding\";\n\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\n\n/** A job envelope or result did not match the jobs protocol. */\nexport class JobEnvelopeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JobEnvelopeError\";\n }\n}\n\nfunction sortJsonKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJsonKeys);\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n sortJsonKeys((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n}\n\nfunction canonicalJsonBytes(value: unknown): Uint8Array {\n return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));\n}\n\n/**\n * Returns the canonical UTF-8 JSON bytes committed to by the auth body hash.\n *\n * @param request - Job request to validate and serialize canonically.\n * @returns Recursively key-sorted, whitespace-free UTF-8 JSON bytes.\n * @throws {JobEnvelopeError} If the request does not match the protocol schema.\n */\nexport function canonicalJobRequestBytes(request: JobRequest): Uint8Array {\n validateJobRequest(request);\n return canonicalJsonBytes(request);\n}\n\nfunction requestPlaintext(envelope: JobRequestEnvelope): Uint8Array {\n validateRequestEnvelope(envelope);\n return canonicalJsonBytes(envelope);\n}\n\nfunction resultPlaintext(result: JobResult): Uint8Array {\n return textEncoder.encode(\n JSON.stringify({\n v: result.v,\n jobId: result.jobId,\n scope: result.scope,\n version: result.version,\n contentType: result.contentType,\n body: result.body,\n }),\n );\n}\n\nfunction encryptedBytesToBase64(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): string {\n return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\"));\n}\n\nfunction base64ToEncrypted(ciphertext: string) {\n return deserializeECIES(toHex(fromBase64(ciphertext)));\n}\n\nfunction parseObject(\n plaintext: Uint8Array,\n kind: string,\n): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(textDecoder.decode(plaintext));\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);\n }\n return value as Record<string, unknown>;\n } catch (error) {\n if (error instanceof JobEnvelopeError) throw error;\n throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction requirePlainObject(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);\n }\n}\n\nfunction requireExactKeys(\n value: Record<string, unknown>,\n expectedKeys: readonly string[],\n kind: string,\n): void {\n for (const key of expectedKeys) {\n if (!Object.hasOwn(value, key) || value[key] === undefined) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);\n }\n }\n const expected = new Set<PropertyKey>(expectedKeys);\n for (const key of Reflect.ownKeys(value)) {\n if (!expected.has(key)) {\n throw new JobEnvelopeError(\n `Invalid ${kind}: unknown field ${String(key)}`,\n );\n }\n }\n}\n\nfunction requireString(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);\n }\n}\n\nfunction validateJobRequest(value: unknown): JobRequest {\n requirePlainObject(value, \"request\", \"job request\");\n requireExactKeys(\n value,\n [\n \"v\",\n \"jobId\",\n \"owner\",\n \"builder\",\n \"builderPublicKey\",\n \"grantId\",\n \"scope\",\n \"operation\",\n \"pinnedVersion\",\n \"deadline\",\n ],\n \"job request\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job request version: ${String(value.v)}`,\n );\n }\n requireString(value.jobId, \"jobId\", \"job request\");\n if (typeof value.owner !== \"string\" || !isAddress(value.owner)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid owner\");\n }\n if (typeof value.builder !== \"string\" || !isAddress(value.builder)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builder\");\n }\n if (\n typeof value.builderPublicKey !== \"string\" ||\n !isHex(value.builderPublicKey)\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builderPublicKey\");\n }\n if (typeof value.grantId !== \"string\" || !isHex(value.grantId)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid grantId\");\n }\n requireString(value.scope, \"scope\", \"job request\");\n if (!JOB_OPERATIONS.includes(value.operation as JobOperation)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid operation\");\n }\n if (value.pinnedVersion !== null && typeof value.pinnedVersion !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job request: missing pinnedVersion\");\n }\n if (\n typeof value.deadline !== \"string\" ||\n !Number.isFinite(Date.parse(value.deadline))\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid deadline\");\n }\n return value as unknown as JobRequest;\n}\n\nfunction validateRequestEnvelope(value: unknown): JobRequestEnvelope {\n requirePlainObject(value, \"envelope\", \"job request envelope\");\n requireExactKeys(value, [\"request\", \"auth\"], \"job request envelope\");\n validateJobRequest(value.request);\n requireString(value.auth, \"auth\", \"job request envelope\");\n return value as unknown as JobRequestEnvelope;\n}\n\nfunction validateResult(value: unknown): JobResult {\n requirePlainObject(value, \"result\", \"job result\");\n requireExactKeys(\n value,\n [\"v\", \"jobId\", \"scope\", \"version\", \"contentType\", \"body\"],\n \"job result\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job result version: ${String(value.v)}`,\n );\n }\n for (const field of [\"jobId\", \"scope\", \"contentType\"]) {\n requireString(value[field], field, \"job result\");\n }\n if (typeof value.body !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing body\");\n }\n if (value.version !== null && typeof value.version !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing version\");\n }\n return value as unknown as JobResult;\n}\n\n/**\n * Encrypts a validated job request envelope for a Personal Server enclave.\n *\n * The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext.\n *\n * @param envelope - Request and builder Web3Signed authorization to encrypt.\n * @param enclavePublicKey - Public key returned by `GET /v1/identity?owner=`.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext encoded as `iv || ephemPub || ct || mac`.\n * @throws {JobEnvelopeError} If the envelope or request is invalid.\n * @throws If ECIES encryption fails or the enclave public key is invalid.\n *\n * @example\n * ```ts\n * const identity = await fetch(`/v1/identity?owner=${owner}`).then((response) =>\n * response.json(),\n * );\n * const requestCiphertext = await sealJobRequest(\n * requestEnvelope,\n * identity.publicKey,\n * ecies,\n * );\n * await fetch(\"/v1/jobs\", {\n * method: \"POST\",\n * body: JSON.stringify({ ...submission, requestCiphertext }),\n * });\n * ```\n */\nexport async function sealJobRequest(\n envelope: JobRequestEnvelope,\n enclavePublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<string> {\n const encrypted = await ecies.encrypt(\n fromHex(enclavePublicKey, \"bytes\"),\n requestPlaintext(envelope),\n );\n return encryptedBytesToBase64(encrypted);\n}\n\n/**\n * Decrypts and validates a job request envelope inside the enclave.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param privateKey - Enclave key bytes, supplied as `Uint8Array` so the agent can zero them after use.\n * @param ecies - Injected ECIES implementation.\n * @returns The validated request envelope exactly as parsed from plaintext.\n * @throws {JobEnvelopeError} If plaintext is malformed or fails schema validation.\n * @throws If ciphertext decoding or ECIES decryption fails.\n */\nexport async function openJobRequest(\n ciphertext: string,\n privateKey: Uint8Array,\n ecies: ECIESProvider,\n): Promise<JobRequestEnvelope> {\n const plaintext = await ecies.decrypt(\n privateKey,\n base64ToEncrypted(ciphertext),\n );\n return validateRequestEnvelope(\n parseObject(plaintext, \"job request envelope\"),\n );\n}\n\n/**\n * Encrypts a validated job result for its builder and describes the ciphertext.\n *\n * `hash` is lowercase `0x` SHA-256 of decoded ciphertext bytes, not the\n * `sha256:` prefix used by Web3Signed `bodyHash`. `size` is that decoded byte\n * length. They equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext plus its Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ ciphertext: string; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const ciphertext = encryptedBytesToBase64(encrypted);\n const bytes = fromBase64(ciphertext);\n return { ciphertext, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const result = await openJobResult(\n * status.resultCiphertext,\n * key,\n * ecies,\n * { jobId, scope },\n * );\n * const body = fromBase64(result.body);\n * ```\n */\nexport async function openJobResult(\n ciphertext: string,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n base64ToEncrypted(ciphertext),\n );\n const result = validateResult(parseObject(plaintext, \"job result\"));\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":"AAiBA,SAAS,cAAc;AACvB,SAAS,YAAY,SAAS,W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B,QACA,kBACA,OAC0D;AAC1D,iBAAe,MAAM;AACrB,QAAM,YAAY,MAAM,MAAM;AAAA,IAC5B,QAAQ,kBAAkB,OAAO;AAAA,IACjC,gBAAgB,MAAM;AAAA,EACxB;AACA,QAAM,aAAa,uBAAuB,SAAS;AACnD,QAAM,QAAQ,WAAW,UAAU;AACnC,SAAO,EAAE,YAAY,MAAM,WAAW,OAAO,KAAK,CAAC,GAAG,MAAM,MAAM,OAAO;AAC3E;AA2BA,eAAsB,cACpB,YACA,mBACA,OACA,QACoB;AACpB,QAAM,YAAY,MAAM,MAAM;AAAA,IAC5B,QAAQ,mBAAmB,OAAO;AAAA,IAClC,kBAAkB,UAAU;AAAA,EAC9B;AACA,QAAM,SAAS,eAAe,YAAY,WAAW,YAAY,CAAC;AAClE,MAAI,OAAO,UAAU,OAAO,OAAO;AACjC,UAAM,IAAI;AAAA,MACR,iBAAiB,OAAO,KAAK,mCAAmC,OAAO,KAAK;AAAA,IAC9E;AAAA,EACF;AACA,MAAI,OAAO,UAAU,UAAa,OAAO,UAAU,OAAO,OAAO;AAC/D,UAAM,IAAI;AAAA,MACR,oBAAoB,OAAO,KAAK,kCAAkC,OAAO,KAAK;AAAA,IAChF;AAAA,EACF;AACA,MAAI,OAAO,YAAY,UAAa,OAAO,YAAY,OAAO,SAAS;AACrE,UAAM,IAAI;AAAA,MACR,sBAAsB,OAAO,OAAO,OAAO,CAAC,oCAAoC,OAAO,OAAO,OAAO,CAAC;AAAA,IACxG;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -38,6 +38,8 @@ export { buildWeb3SignedHeader, computeBodyHash, type Web3SignedSignFn, } from "
38
38
  export { MissingAuthError, InvalidSignatureError, ExpiredTokenError, } from "./auth/errors.js";
39
39
  export { NATIVE_VANA_ASSET, dataRegistryDomain, grantRegistrationDomain, grantRevocationDomain, serverRegistrationDomain, builderRegistrationDomain, escrowPaymentDomain, withdrawAuthorizationDomain, buildWithdrawAuthorizationTypedData, GRANT_REGISTRATION_TYPES, GRANT_REVOCATION_TYPES, SERVER_REGISTRATION_TYPES, BUILDER_REGISTRATION_TYPES, ADD_DATA_TYPES, RECORD_DATA_ACCESS_TYPES, WITHDRAW_AUTHORIZATION_TYPES, type DataPortabilityContracts, type DataPortabilityGatewayConfig, type GrantRegistrationMessage, type GrantRevocationMessage, type ServerRegistrationMessage, type BuilderRegistrationMessage, type AddDataMessage, type RecordDataAccessMessage, type WithdrawAuthorizationMessage, } from "./protocol/eip712.js";
40
40
  export { ENCLAVE_IDENTITY_EVIDENCE_VERSION, USER_PS_ID_DOMAIN, ENCLAVE_WALLET_PURPOSE, MASTER_SIGNATURE_DELIVERY_VERSION, MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS, 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";
41
+ export { JOB_PROTOCOL_VERSION, JOB_OPERATIONS, JOB_STATES, DEFAULT_LEASE_SECONDS, MAX_LEASE_SECONDS, MAX_ATTEMPTS, MAX_WAIT_SECONDS, CLAIM_POLL_FLOOR_MS, MAX_INLINE_RESULT_BYTES, DEFAULT_JOB_DEADLINE_SECONDS, MAX_JOB_DEADLINE_SECONDS, type JobOperation, type JobState, type PaymentState, type JobRequest, type JobRequestEnvelope, type JobSubmission, type JobStatus, type ClaimRequest, type ClaimResponse, type HeartbeatRequest, type CompleteRequest, type FailRequest, type FencedResponse, type JobResult, type TeeNodeState, type TeeNodeRegistration, type TeeNodeHeartbeat, type TeeNode, } from "./protocol/jobs.js";
42
+ export { JobEnvelopeError, canonicalJobRequestBytes, sealJobRequest, openJobRequest, sealJobResult, openJobResult, } from "./crypto/envelope/job.js";
41
43
  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";
42
44
  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";
43
45
  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";
@@ -31924,9 +31924,255 @@ async function encryptMasterSignatureDelivery(delivery, publicKey, ecies) {
31924
31924
  return `0x${serializeECIES(encrypted)}`;
31925
31925
  }
31926
31926
 
31927
+ // src/protocol/jobs.ts
31928
+ var JOB_PROTOCOL_VERSION = 1;
31929
+ var JOB_OPERATIONS = ["raw_read", "inference"];
31930
+ var JOB_STATES = [
31931
+ "queued",
31932
+ "claimed",
31933
+ "running",
31934
+ "completed",
31935
+ "failed",
31936
+ "expired",
31937
+ "cancelled"
31938
+ ];
31939
+ var DEFAULT_LEASE_SECONDS = 30;
31940
+ var MAX_LEASE_SECONDS = 300;
31941
+ var MAX_ATTEMPTS = 3;
31942
+ var MAX_WAIT_SECONDS = 25;
31943
+ var CLAIM_POLL_FLOOR_MS = 1e3;
31944
+ var MAX_INLINE_RESULT_BYTES = 1048576;
31945
+ var DEFAULT_JOB_DEADLINE_SECONDS = 600;
31946
+ var MAX_JOB_DEADLINE_SECONDS = 3600;
31947
+
31948
+ // src/crypto/envelope/job.ts
31949
+ init_interface();
31950
+ import { sha256 as sha2565 } from "@noble/hashes/sha2";
31951
+ import { bytesToHex as bytesToHex2, fromHex as fromHex6, isAddress, isHex, toHex as toHex7 } from "viem";
31952
+ var textDecoder = new TextDecoder();
31953
+ var textEncoder = new TextEncoder();
31954
+ var JobEnvelopeError = class extends Error {
31955
+ constructor(message) {
31956
+ super(message);
31957
+ this.name = "JobEnvelopeError";
31958
+ }
31959
+ };
31960
+ function sortJsonKeys(value) {
31961
+ if (Array.isArray(value)) {
31962
+ return value.map(sortJsonKeys);
31963
+ }
31964
+ if (value !== null && typeof value === "object") {
31965
+ return Object.fromEntries(
31966
+ Object.keys(value).sort().map((key) => [
31967
+ key,
31968
+ sortJsonKeys(value[key])
31969
+ ])
31970
+ );
31971
+ }
31972
+ return value;
31973
+ }
31974
+ function canonicalJsonBytes(value) {
31975
+ return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));
31976
+ }
31977
+ function canonicalJobRequestBytes(request) {
31978
+ validateJobRequest(request);
31979
+ return canonicalJsonBytes(request);
31980
+ }
31981
+ function requestPlaintext(envelope) {
31982
+ validateRequestEnvelope(envelope);
31983
+ return canonicalJsonBytes(envelope);
31984
+ }
31985
+ function resultPlaintext(result) {
31986
+ return textEncoder.encode(
31987
+ JSON.stringify({
31988
+ v: result.v,
31989
+ jobId: result.jobId,
31990
+ scope: result.scope,
31991
+ version: result.version,
31992
+ contentType: result.contentType,
31993
+ body: result.body
31994
+ })
31995
+ );
31996
+ }
31997
+ function encryptedBytesToBase64(encrypted) {
31998
+ return toBase64(fromHex6(`0x${serializeECIES(encrypted)}`, "bytes"));
31999
+ }
32000
+ function base64ToEncrypted(ciphertext) {
32001
+ return deserializeECIES(toHex7(fromBase64(ciphertext)));
32002
+ }
32003
+ function parseObject(plaintext, kind) {
32004
+ try {
32005
+ const value = JSON.parse(textDecoder.decode(plaintext));
32006
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
32007
+ throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);
32008
+ }
32009
+ return value;
32010
+ } catch (error) {
32011
+ if (error instanceof JobEnvelopeError) throw error;
32012
+ throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);
32013
+ }
32014
+ }
32015
+ function isPlainObject2(value) {
32016
+ if (value === null || typeof value !== "object") return false;
32017
+ const prototype = Object.getPrototypeOf(value);
32018
+ return prototype === Object.prototype || prototype === null;
32019
+ }
32020
+ function requirePlainObject(value, field, kind) {
32021
+ if (!isPlainObject2(value)) {
32022
+ throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);
32023
+ }
32024
+ }
32025
+ function requireExactKeys(value, expectedKeys, kind) {
32026
+ for (const key of expectedKeys) {
32027
+ if (!Object.hasOwn(value, key) || value[key] === void 0) {
32028
+ throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);
32029
+ }
32030
+ }
32031
+ const expected = new Set(expectedKeys);
32032
+ for (const key of Reflect.ownKeys(value)) {
32033
+ if (!expected.has(key)) {
32034
+ throw new JobEnvelopeError(
32035
+ `Invalid ${kind}: unknown field ${String(key)}`
32036
+ );
32037
+ }
32038
+ }
32039
+ }
32040
+ function requireString(value, field, kind) {
32041
+ if (typeof value !== "string" || value.length === 0) {
32042
+ throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);
32043
+ }
32044
+ }
32045
+ function validateJobRequest(value) {
32046
+ requirePlainObject(value, "request", "job request");
32047
+ requireExactKeys(
32048
+ value,
32049
+ [
32050
+ "v",
32051
+ "jobId",
32052
+ "owner",
32053
+ "builder",
32054
+ "builderPublicKey",
32055
+ "grantId",
32056
+ "scope",
32057
+ "operation",
32058
+ "pinnedVersion",
32059
+ "deadline"
32060
+ ],
32061
+ "job request"
32062
+ );
32063
+ if (value.v !== JOB_PROTOCOL_VERSION) {
32064
+ throw new JobEnvelopeError(
32065
+ `Unsupported job request version: ${String(value.v)}`
32066
+ );
32067
+ }
32068
+ requireString(value.jobId, "jobId", "job request");
32069
+ if (typeof value.owner !== "string" || !isAddress(value.owner)) {
32070
+ throw new JobEnvelopeError("Invalid job request: invalid owner");
32071
+ }
32072
+ if (typeof value.builder !== "string" || !isAddress(value.builder)) {
32073
+ throw new JobEnvelopeError("Invalid job request: invalid builder");
32074
+ }
32075
+ if (typeof value.builderPublicKey !== "string" || !isHex(value.builderPublicKey)) {
32076
+ throw new JobEnvelopeError("Invalid job request: invalid builderPublicKey");
32077
+ }
32078
+ if (typeof value.grantId !== "string" || !isHex(value.grantId)) {
32079
+ throw new JobEnvelopeError("Invalid job request: invalid grantId");
32080
+ }
32081
+ requireString(value.scope, "scope", "job request");
32082
+ if (!JOB_OPERATIONS.includes(value.operation)) {
32083
+ throw new JobEnvelopeError("Invalid job request: invalid operation");
32084
+ }
32085
+ if (value.pinnedVersion !== null && typeof value.pinnedVersion !== "string") {
32086
+ throw new JobEnvelopeError("Invalid job request: missing pinnedVersion");
32087
+ }
32088
+ if (typeof value.deadline !== "string" || !Number.isFinite(Date.parse(value.deadline))) {
32089
+ throw new JobEnvelopeError("Invalid job request: invalid deadline");
32090
+ }
32091
+ return value;
32092
+ }
32093
+ function validateRequestEnvelope(value) {
32094
+ requirePlainObject(value, "envelope", "job request envelope");
32095
+ requireExactKeys(value, ["request", "auth"], "job request envelope");
32096
+ validateJobRequest(value.request);
32097
+ requireString(value.auth, "auth", "job request envelope");
32098
+ return value;
32099
+ }
32100
+ function validateResult(value) {
32101
+ requirePlainObject(value, "result", "job result");
32102
+ requireExactKeys(
32103
+ value,
32104
+ ["v", "jobId", "scope", "version", "contentType", "body"],
32105
+ "job result"
32106
+ );
32107
+ if (value.v !== JOB_PROTOCOL_VERSION) {
32108
+ throw new JobEnvelopeError(
32109
+ `Unsupported job result version: ${String(value.v)}`
32110
+ );
32111
+ }
32112
+ for (const field of ["jobId", "scope", "contentType"]) {
32113
+ requireString(value[field], field, "job result");
32114
+ }
32115
+ if (typeof value.body !== "string") {
32116
+ throw new JobEnvelopeError("Invalid job result: missing body");
32117
+ }
32118
+ if (value.version !== null && typeof value.version !== "string") {
32119
+ throw new JobEnvelopeError("Invalid job result: missing version");
32120
+ }
32121
+ return value;
32122
+ }
32123
+ async function sealJobRequest(envelope, enclavePublicKey, ecies) {
32124
+ const encrypted = await ecies.encrypt(
32125
+ fromHex6(enclavePublicKey, "bytes"),
32126
+ requestPlaintext(envelope)
32127
+ );
32128
+ return encryptedBytesToBase64(encrypted);
32129
+ }
32130
+ async function openJobRequest(ciphertext, privateKey, ecies) {
32131
+ const plaintext = await ecies.decrypt(
32132
+ privateKey,
32133
+ base64ToEncrypted(ciphertext)
32134
+ );
32135
+ return validateRequestEnvelope(
32136
+ parseObject(plaintext, "job request envelope")
32137
+ );
32138
+ }
32139
+ async function sealJobResult(result, builderPublicKey, ecies) {
32140
+ validateResult(result);
32141
+ const encrypted = await ecies.encrypt(
32142
+ fromHex6(builderPublicKey, "bytes"),
32143
+ resultPlaintext(result)
32144
+ );
32145
+ const ciphertext = encryptedBytesToBase64(encrypted);
32146
+ const bytes = fromBase64(ciphertext);
32147
+ return { ciphertext, hash: bytesToHex2(sha2565(bytes)), size: bytes.length };
32148
+ }
32149
+ async function openJobResult(ciphertext, builderPrivateKey, ecies, expect) {
32150
+ const plaintext = await ecies.decrypt(
32151
+ fromHex6(builderPrivateKey, "bytes"),
32152
+ base64ToEncrypted(ciphertext)
32153
+ );
32154
+ const result = validateResult(parseObject(plaintext, "job result"));
32155
+ if (result.jobId !== expect.jobId) {
32156
+ throw new JobEnvelopeError(
32157
+ `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`
32158
+ );
32159
+ }
32160
+ if (expect.scope !== void 0 && result.scope !== expect.scope) {
32161
+ throw new JobEnvelopeError(
32162
+ `Job result scope ${result.scope} does not match expected scope ${expect.scope}`
32163
+ );
32164
+ }
32165
+ if (expect.version !== void 0 && result.version !== expect.version) {
32166
+ throw new JobEnvelopeError(
32167
+ `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`
32168
+ );
32169
+ }
32170
+ return result;
32171
+ }
32172
+
31927
32173
  // src/protocol/personal-server-registration.ts
31928
32174
  import {
31929
- isAddress
32175
+ isAddress as isAddress2
31930
32176
  } from "viem";
31931
32177
  var PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID = vanaMainnet2.id;
31932
32178
  var PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT = getContractAddress(
@@ -31934,7 +32180,7 @@ var PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT = getContractAddress
31934
32180
  "DataPortabilityServers"
31935
32181
  );
31936
32182
  function assertAddress(value, name) {
31937
- if (!isAddress(value)) {
32183
+ if (!isAddress2(value)) {
31938
32184
  throw new Error(`${name} must be a valid EVM address`);
31939
32185
  }
31940
32186
  }
@@ -32021,13 +32267,13 @@ var registerPersonalServerSignature = buildPersonalServerRegistrationSignature;
32021
32267
 
32022
32268
  // src/personal-server-lite/owner-binding.ts
32023
32269
  import {
32024
- isAddress as isAddress2
32270
+ isAddress as isAddress3
32025
32271
  } from "viem";
32026
32272
  var PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION = "vana.ps-lite.owner-binding.v1";
32027
32273
  var PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE = "ps-lite-owner";
32028
32274
  var PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX = `${PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION}:${PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE}:`;
32029
32275
  function assertAddress2(value, name) {
32030
- if (!isAddress2(value)) {
32276
+ if (!isAddress3(value)) {
32031
32277
  throw new Error(`${name} must be a valid EVM address`);
32032
32278
  }
32033
32279
  }
@@ -32077,7 +32323,7 @@ async function buildPersonalServerLiteOwnerBindingSignature(input) {
32077
32323
  var signPersonalServerLiteOwnerBinding = buildPersonalServerLiteOwnerBindingSignature;
32078
32324
 
32079
32325
  // src/account/personal-server-registration.ts
32080
- import { isAddress as isAddress3 } from "viem";
32326
+ import { isAddress as isAddress4 } from "viem";
32081
32327
  var ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT = "personal_server.server_registration.v1";
32082
32328
  var AccountPersonalServerRegistrationError = class extends Error {
32083
32329
  status;
@@ -32096,7 +32342,7 @@ function trimTrailingSlash(value) {
32096
32342
  return value.replace(/\/+$/, "");
32097
32343
  }
32098
32344
  function assertAddress3(value, name) {
32099
- if (!isAddress3(value)) {
32345
+ if (!isAddress4(value)) {
32100
32346
  throw new Error(`${name} must be a valid EVM address`);
32101
32347
  }
32102
32348
  }
@@ -32622,7 +32868,7 @@ function buildMarkDataPointUnavailableRequest(config, input) {
32622
32868
 
32623
32869
  // src/protocol/data-point-deletion.ts
32624
32870
  import {
32625
- isAddress as isAddress5,
32871
+ isAddress as isAddress6,
32626
32872
  keccak256 as keccak2563,
32627
32873
  maxUint256,
32628
32874
  stringToBytes as stringToBytes3
@@ -32631,7 +32877,7 @@ import {
32631
32877
  // src/protocol/lineage.ts
32632
32878
  import {
32633
32879
  encodeAbiParameters,
32634
- isAddress as isAddress4,
32880
+ isAddress as isAddress5,
32635
32881
  keccak256 as keccak2562
32636
32882
  } from "viem";
32637
32883
  import { z } from "zod";
@@ -32711,7 +32957,7 @@ function isDataPointId(value) {
32711
32957
  return typeof value === "string" && DATA_POINT_ID_PATTERN.test(value);
32712
32958
  }
32713
32959
  function deriveDataPointId(ownerAddress, scope) {
32714
- if (!isAddress4(ownerAddress, { strict: false })) {
32960
+ if (!isAddress5(ownerAddress, { strict: false })) {
32715
32961
  throw new Error(
32716
32962
  `ownerAddress is not an EVM address: ${String(ownerAddress)}`
32717
32963
  );
@@ -32962,7 +33208,7 @@ function tombstoneDeletedAt(value) {
32962
33208
  return typeof deletedAt === "string" ? deletedAt : null;
32963
33209
  }
32964
33210
  function assertAddress4(value, name) {
32965
- if (!isAddress5(value)) {
33211
+ if (!isAddress6(value)) {
32966
33212
  throw new Error(`${name} must be a valid EVM address`);
32967
33213
  }
32968
33214
  }
@@ -33377,13 +33623,13 @@ function tryGrantPermissions(scopes) {
33377
33623
  }
33378
33624
 
33379
33625
  // src/protocol/personal-server-write.ts
33380
- import { sha256 as sha2566 } from "@noble/hashes/sha2";
33381
- import { bytesToHex as bytesToHex3, isAddress as isAddress6 } from "viem";
33626
+ import { sha256 as sha2567 } from "@noble/hashes/sha2";
33627
+ import { bytesToHex as bytesToHex4, isAddress as isAddress7 } from "viem";
33382
33628
  import { z as z4 } from "zod";
33383
33629
 
33384
33630
  // src/protocol/write-request.ts
33385
- import { sha256 as sha2565 } from "@noble/hashes/sha2";
33386
- import { bytesToHex as bytesToHex2 } from "viem";
33631
+ import { sha256 as sha2566 } from "@noble/hashes/sha2";
33632
+ import { bytesToHex as bytesToHex3 } from "viem";
33387
33633
  function normalizeBaseUrl2(url) {
33388
33634
  return url.replace(/\/+$/, "");
33389
33635
  }
@@ -33450,22 +33696,22 @@ function freshProofNonce() {
33450
33696
  return webCrypto.randomUUID();
33451
33697
  }
33452
33698
  if (typeof webCrypto?.getRandomValues === "function") {
33453
- return bytesToHex2(webCrypto.getRandomValues(new Uint8Array(16)));
33699
+ return bytesToHex3(webCrypto.getRandomValues(new Uint8Array(16)));
33454
33700
  }
33455
33701
  throw new WriteRequestError(
33456
33702
  "No secure random source available to build a proof nonce; provide a crypto global"
33457
33703
  );
33458
33704
  }
33459
33705
  function proofKeyFor(parts) {
33460
- return bytesToHex2(
33461
- sha2565(
33706
+ return bytesToHex3(
33707
+ sha2566(
33462
33708
  new TextEncoder().encode(
33463
33709
  JSON.stringify([
33464
33710
  parts.aud,
33465
33711
  parts.method,
33466
33712
  parts.uri,
33467
33713
  parts.grantId,
33468
- parts.signedBytes ? bytesToHex2(sha2565(parts.signedBytes)) : ""
33714
+ parts.signedBytes ? bytesToHex3(sha2566(parts.signedBytes)) : ""
33469
33715
  ])
33470
33716
  )
33471
33717
  )
@@ -33652,7 +33898,7 @@ function binaryWriteSignedBytes(input) {
33652
33898
  mimeType: normalizeBinaryMimeType(input.contentType),
33653
33899
  ...input.filename ? { filename: input.filename } : {},
33654
33900
  sizeBytes: input.bytes.length,
33655
- contentHash: bytesToHex3(sha2566(input.bytes)),
33901
+ contentHash: bytesToHex4(sha2567(input.bytes)),
33656
33902
  encoding: "base64",
33657
33903
  content: toBase64(input.bytes),
33658
33904
  ...metadata !== void 0 ? { metadata } : {}
@@ -33700,7 +33946,7 @@ function normalizeLineage(lineage, derivedScope) {
33700
33946
  for (const entry of lineage) {
33701
33947
  let id;
33702
33948
  if (isLineagePair(entry)) {
33703
- if (!isAddress6(entry.ownerAddress, { strict: false })) {
33949
+ if (!isAddress7(entry.ownerAddress, { strict: false })) {
33704
33950
  throw new WriteRequestError(
33705
33951
  "lineage source ownerAddress must be an EVM address",
33706
33952
  { ownerAddress: entry.ownerAddress }
@@ -34996,7 +35242,7 @@ function createGatewayClient(baseUrl) {
34996
35242
  }
34997
35243
 
34998
35244
  // src/protocol/escrow.ts
34999
- import { isHex } from "viem";
35245
+ import { isHex as isHex2 } from "viem";
35000
35246
  var GENERIC_PAYMENT_TYPES = {
35001
35247
  GenericPayment: [
35002
35248
  { name: "payerAddress", type: "address" },
@@ -35212,10 +35458,10 @@ function optionalUint256Decimal(value) {
35212
35458
  return value === void 0 || isUint256Decimal(value);
35213
35459
  }
35214
35460
  function isAddressHex(value) {
35215
- return typeof value === "string" && isHex(value, { strict: true }) && value.length === 42;
35461
+ return typeof value === "string" && isHex2(value, { strict: true }) && value.length === 42;
35216
35462
  }
35217
35463
  function isHash(value) {
35218
- return typeof value === "string" && isHex(value, { strict: true }) && value.length === 66;
35464
+ return typeof value === "string" && isHex2(value, { strict: true }) && value.length === 66;
35219
35465
  }
35220
35466
  function isUint256Decimal(value) {
35221
35467
  if (typeof value !== "string" || value.length === 0 || value.length > 78) {
@@ -35321,6 +35567,7 @@ export {
35321
35567
  BlockchainError,
35322
35568
  BrowserECIESUint8Provider as BrowserECIESProvider,
35323
35569
  BrowserPlatformAdapter,
35570
+ CLAIM_POLL_FLOOR_MS,
35324
35571
  CONTRACTS,
35325
35572
  CallbackStorage,
35326
35573
  ContractFactory,
@@ -35328,6 +35575,8 @@ export {
35328
35575
  DATA_REGISTRY_STATUS_ABI,
35329
35576
  DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
35330
35577
  DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
35578
+ DEFAULT_JOB_DEADLINE_SECONDS,
35579
+ DEFAULT_LEASE_SECONDS,
35331
35580
  DEFAULT_QUESTION_POLL_INTERVAL_MS,
35332
35581
  DEFAULT_QUESTION_TIMEOUT_MS,
35333
35582
  DERIVATIVE_ERROR_CODES,
@@ -35370,6 +35619,10 @@ export {
35370
35619
  InvalidScopeEntryError,
35371
35620
  InvalidSignatureError,
35372
35621
  IpfsStorage,
35622
+ JOB_OPERATIONS,
35623
+ JOB_PROTOCOL_VERSION,
35624
+ JOB_STATES,
35625
+ JobEnvelopeError,
35373
35626
  LINEAGE_FIELD,
35374
35627
  LINEAGE_KEY,
35375
35628
  LineageEntrySchema,
@@ -35379,10 +35632,15 @@ export {
35379
35632
  MASTER_KEY_MESSAGE,
35380
35633
  MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
35381
35634
  MASTER_SIGNATURE_DELIVERY_VERSION,
35635
+ MAX_ATTEMPTS,
35636
+ MAX_INLINE_RESULT_BYTES,
35637
+ MAX_JOB_DEADLINE_SECONDS,
35638
+ MAX_LEASE_SECONDS,
35382
35639
  MAX_LINEAGE_SOURCES,
35383
35640
  MAX_QUESTION_CHARS,
35384
35641
  MAX_QUESTION_MODEL_CHARS,
35385
35642
  MAX_QUESTION_SOURCE_SCOPES,
35643
+ MAX_WAIT_SECONDS,
35386
35644
  MissingAuthError,
35387
35645
  NATIVE_ASSET_ADDRESS,
35388
35646
  NATIVE_VANA_ASSET,
@@ -35467,6 +35725,7 @@ export {
35467
35725
  buildWeb3SignedHeader,
35468
35726
  buildWithdrawAuthorizationTypedData,
35469
35727
  builderRegistrationDomain,
35728
+ canonicalJobRequestBytes,
35470
35729
  chains,
35471
35730
  clearContractCache,
35472
35731
  computeBodyHash,
@@ -35540,6 +35799,8 @@ export {
35540
35799
  mokshaServices,
35541
35800
  mokshaTestnet2 as mokshaTestnet,
35542
35801
  normalizeBinaryMimeType,
35802
+ openJobRequest,
35803
+ openJobResult,
35543
35804
  openWriteSession,
35544
35805
  parsePSError,
35545
35806
  parseScope,
@@ -35560,6 +35821,8 @@ export {
35560
35821
  scopeMatchesPattern,
35561
35822
  scopeNamespace,
35562
35823
  scopeToPathSegments,
35824
+ sealJobRequest,
35825
+ sealJobResult,
35563
35826
  serializeECIES,
35564
35827
  serverRegistrationDomain,
35565
35828
  sessionCoversScope,