@opendatalabs/vana-sdk 3.23.0-pr.211.e98a9a2 → 3.23.0

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 (42) hide show
  1. package/dist/crypto/envelope/job.cjs +5 -7
  2. package/dist/crypto/envelope/job.cjs.map +1 -1
  3. package/dist/crypto/envelope/job.d.ts +16 -16
  4. package/dist/crypto/envelope/job.js +5 -7
  5. package/dist/crypto/envelope/job.js.map +1 -1
  6. package/dist/direct/connect-flow.cjs +1 -43
  7. package/dist/direct/connect-flow.cjs.map +1 -1
  8. package/dist/direct/connect-flow.d.ts +0 -12
  9. package/dist/direct/connect-flow.js +1 -43
  10. package/dist/direct/connect-flow.js.map +1 -1
  11. package/dist/direct/use-direct-vana-connect.cjs +1 -2
  12. package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
  13. package/dist/direct/use-direct-vana-connect.d.ts +1 -3
  14. package/dist/direct/use-direct-vana-connect.js +1 -2
  15. package/dist/direct/use-direct-vana-connect.js.map +1 -1
  16. package/dist/errors.cjs +0 -7
  17. package/dist/errors.cjs.map +1 -1
  18. package/dist/errors.d.ts +0 -10
  19. package/dist/errors.js +0 -6
  20. package/dist/errors.js.map +1 -1
  21. package/dist/index.browser.d.ts +1 -1
  22. package/dist/index.browser.js +7 -13
  23. package/dist/index.browser.js.map +2 -2
  24. package/dist/index.node.cjs +32 -79
  25. package/dist/index.node.cjs.map +3 -3
  26. package/dist/index.node.d.ts +1 -1
  27. package/dist/index.node.js +35 -83
  28. package/dist/index.node.js.map +3 -3
  29. package/dist/protocol/jobs-client.cjs +19 -60
  30. package/dist/protocol/jobs-client.cjs.map +1 -1
  31. package/dist/protocol/jobs-client.d.ts +5 -7
  32. package/dist/protocol/jobs-client.js +20 -62
  33. package/dist/protocol/jobs-client.js.map +1 -1
  34. package/dist/protocol/jobs.cjs +3 -0
  35. package/dist/protocol/jobs.cjs.map +1 -1
  36. package/dist/protocol/jobs.d.ts +12 -19
  37. package/dist/protocol/jobs.js +2 -0
  38. package/dist/protocol/jobs.js.map +1 -1
  39. package/dist/react.cjs.map +1 -1
  40. package/dist/react.d.ts +1 -1
  41. package/dist/react.js.map +1 -1
  42. package/package.json +1 -1
@@ -79,9 +79,6 @@ function resultPlaintext(result) {
79
79
  function encryptedBytesToBase64(encrypted) {
80
80
  return (0, import_encoding.toBase64)((0, import_viem.fromHex)(`0x${(0, import_interface.serializeECIES)(encrypted)}`, "bytes"));
81
81
  }
82
- function encryptedToBytes(encrypted) {
83
- return (0, import_viem.fromHex)(`0x${(0, import_interface.serializeECIES)(encrypted)}`, "bytes");
84
- }
85
82
  function base64ToEncrypted(ciphertext) {
86
83
  return (0, import_interface.deserializeECIES)((0, import_viem.toHex)((0, import_encoding.fromBase64)(ciphertext)));
87
84
  }
@@ -227,13 +224,14 @@ async function sealJobResult(result, builderPublicKey, ecies) {
227
224
  (0, import_viem.fromHex)(builderPublicKey, "bytes"),
228
225
  resultPlaintext(result)
229
226
  );
230
- const bytes = encryptedToBytes(encrypted);
231
- return { bytes, hash: (0, import_viem.bytesToHex)((0, import_sha2.sha256)(bytes)), size: bytes.length };
227
+ const ciphertext = encryptedBytesToBase64(encrypted);
228
+ const bytes = (0, import_encoding.fromBase64)(ciphertext);
229
+ return { ciphertext, hash: (0, import_viem.bytesToHex)((0, import_sha2.sha256)(bytes)), size: bytes.length };
232
230
  }
233
- async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
231
+ async function openJobResult(ciphertext, builderPrivateKey, ecies, expect) {
234
232
  const plaintext = await ecies.decrypt(
235
233
  (0, import_viem.fromHex)(builderPrivateKey, "bytes"),
236
- (0, import_interface.deserializeECIES)((0, import_viem.toHex)(sealedBytes))
234
+ base64ToEncrypted(ciphertext)
237
235
  );
238
236
  const result = validateResult(parseObject(plaintext, "job result"));
239
237
  if (result.jobId !== expect.jobId) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result properties follow their interface order. The\n * Request ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified\n * by the ECIES provider interface. Result ciphertext is the raw concatenated\n * byte sequence stored in object storage. The Gateway hashes raw ciphertext\n * bytes, not plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport {\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 encryptedToBytes(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): Uint8Array {\n return 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 the raw sealed bytes, not the `sha256:`\n * prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They\n * equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Raw sealed bytes plus their Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ bytes: Uint8Array; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const bytes = encryptedToBytes(encrypted);\n return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const sealedBytes = new Uint8Array(await response.arrayBuffer());\n * const result = await openJobResult(sealedBytes, key, ecies, {\n * jobId,\n * scope,\n * });\n * const body = fromBase64(result.body);\n * ```\n */\nexport async function openJobResult(\n sealedBytes: Uint8Array,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n deserializeECIES(toHex(sealedBytes)),\n );\n const result = validateResult(parseObject(plaintext, \"job result\"));\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,k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sB;AAAA,EAC/C;AACF;AAgBA,eAAsB,cACpB,QACA,kBACA,OACyD;AACzD,iBAAe,MAAM;AACrB,QAAM,YAAY,MAAM,MAAM;AAAA,QAC5B,qBAAQ,kBAAkB,OAAO;AAAA,IACjC,gBAAgB,MAAM;AAAA,EACxB;AACA,QAAM,QAAQ,iBAAiB,SAAS;AACxC,SAAO,EAAE,OAAO,UAAM,4BAAW,oBAAO,KAAK,CAAC,GAAG,MAAM,MAAM,OAAO;AACtE;AA0BA,eAAsB,cACpB,aACA,mBACA,OACA,QACoB;AACpB,QAAM,YAAY,MAAM,MAAM;AAAA,QAC5B,qBAAQ,mBAAmB,OAAO;AAAA,QAClC,uCAAiB,mBAAM,WAAW,CAAC;AAAA,EACrC;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":[]}
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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,kBAAuB;AACvB,kBAAuE;AACvE,uBAIO;AACP,kBAOO;AACP,sBAAqC;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAG7B,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,aAAa,OAAyB;AAC7C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,YAAY;AAAA,EAC/B;AACA,MAAI,UAAU,QAAQ,OAAO,UAAU,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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":[]}
@@ -3,10 +3,9 @@
3
3
  *
4
4
  * Request plaintext is UTF-8 JSON with object keys sorted recursively and
5
5
  * array order preserved. Result properties follow their interface order. The
6
- * Request ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified
7
- * by the ECIES provider interface. Result ciphertext is the raw concatenated
8
- * byte sequence stored in object storage. The Gateway hashes raw ciphertext
9
- * bytes, not plaintext.
6
+ * wire ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified by
7
+ * the ECIES provider interface. The Gateway hashes raw ciphertext bytes, not
8
+ * plaintext.
10
9
  * The builder verifies the decrypted result's job ID, scope, and version
11
10
  * bindings. The PS worker verifies
12
11
  * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway
@@ -75,19 +74,19 @@ export declare function openJobRequest(ciphertext: string, privateKey: Uint8Arra
75
74
  /**
76
75
  * Encrypts a validated job result for its builder and describes the ciphertext.
77
76
  *
78
- * `hash` is lowercase `0x` SHA-256 of the raw sealed bytes, not the `sha256:`
79
- * prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They
80
- * equal the Gateway's `resultHash` and `resultSize`.
77
+ * `hash` is lowercase `0x` SHA-256 of decoded ciphertext bytes, not the
78
+ * `sha256:` prefix used by Web3Signed `bodyHash`. `size` is that decoded byte
79
+ * length. They equal the Gateway's `resultHash` and `resultSize`.
81
80
  *
82
81
  * @param result - Job result to validate and encrypt.
83
82
  * @param builderPublicKey - Builder wallet public key recorded in the request.
84
83
  * @param ecies - Injected ECIES implementation.
85
- * @returns Raw sealed bytes plus their Gateway-compatible hash and size.
84
+ * @returns Base64 ciphertext plus its Gateway-compatible hash and size.
86
85
  * @throws {JobEnvelopeError} If the result does not match the protocol schema.
87
86
  * @throws If ECIES encryption fails or the builder public key is invalid.
88
87
  */
89
88
  export declare function sealJobResult(result: JobResult, builderPublicKey: Hex, ecies: ECIESProvider): Promise<{
90
- bytes: Uint8Array;
89
+ ciphertext: string;
91
90
  hash: Hex;
92
91
  size: number;
93
92
  }>;
@@ -97,7 +96,7 @@ export declare function sealJobResult(result: JobResult, builderPublicKey: Hex,
97
96
  * The builder private key is a `Hex` wallet key. For `expect.version`,
98
97
  * `undefined` skips the check while `null` requires a null result version.
99
98
  *
100
- * @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.
99
+ * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.
101
100
  * @param builderPrivateKey - Builder's wallet private key as hex.
102
101
  * @param ecies - Injected ECIES implementation.
103
102
  * @param expect - Required job ID and optional scope and version bindings.
@@ -107,15 +106,16 @@ export declare function sealJobResult(result: JobResult, builderPublicKey: Hex,
107
106
  *
108
107
  * @example
109
108
  * ```ts
110
- * const sealedBytes = new Uint8Array(await response.arrayBuffer());
111
- * const result = await openJobResult(sealedBytes, key, ecies, {
112
- * jobId,
113
- * scope,
114
- * });
109
+ * const result = await openJobResult(
110
+ * status.resultCiphertext,
111
+ * key,
112
+ * ecies,
113
+ * { jobId, scope },
114
+ * );
115
115
  * const body = fromBase64(result.body);
116
116
  * ```
117
117
  */
118
- export declare function openJobResult(sealedBytes: Uint8Array, builderPrivateKey: Hex, ecies: ECIESProvider, expect: {
118
+ export declare function openJobResult(ciphertext: string, builderPrivateKey: Hex, ecies: ECIESProvider, expect: {
119
119
  jobId: string;
120
120
  scope?: string;
121
121
  version?: string | null;
@@ -57,9 +57,6 @@ function resultPlaintext(result) {
57
57
  function encryptedBytesToBase64(encrypted) {
58
58
  return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, "bytes"));
59
59
  }
60
- function encryptedToBytes(encrypted) {
61
- return fromHex(`0x${serializeECIES(encrypted)}`, "bytes");
62
- }
63
60
  function base64ToEncrypted(ciphertext) {
64
61
  return deserializeECIES(toHex(fromBase64(ciphertext)));
65
62
  }
@@ -205,13 +202,14 @@ async function sealJobResult(result, builderPublicKey, ecies) {
205
202
  fromHex(builderPublicKey, "bytes"),
206
203
  resultPlaintext(result)
207
204
  );
208
- const bytes = encryptedToBytes(encrypted);
209
- return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };
205
+ const ciphertext = encryptedBytesToBase64(encrypted);
206
+ const bytes = fromBase64(ciphertext);
207
+ return { ciphertext, hash: bytesToHex(sha256(bytes)), size: bytes.length };
210
208
  }
211
- async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
209
+ async function openJobResult(ciphertext, builderPrivateKey, ecies, expect) {
212
210
  const plaintext = await ecies.decrypt(
213
211
  fromHex(builderPrivateKey, "bytes"),
214
- deserializeECIES(toHex(sealedBytes))
212
+ base64ToEncrypted(ciphertext)
215
213
  );
216
214
  const result = validateResult(parseObject(plaintext, "job result"));
217
215
  if (result.jobId !== expect.jobId) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result properties follow their interface order. The\n * Request ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified\n * by the ECIES provider interface. Result ciphertext is the raw concatenated\n * byte sequence stored in object storage. The Gateway hashes raw ciphertext\n * bytes, not plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport {\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 encryptedToBytes(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): Uint8Array {\n return 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 the raw sealed bytes, not the `sha256:`\n * prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They\n * equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Raw sealed bytes plus their Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ bytes: Uint8Array; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const bytes = encryptedToBytes(encrypted);\n return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const sealedBytes = new Uint8Array(await response.arrayBuffer());\n * const result = await openJobResult(sealedBytes, key, ecies, {\n * jobId,\n * scope,\n * });\n * const body = fromBase64(result.body);\n * ```\n */\nexport async function openJobResult(\n sealedBytes: Uint8Array,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n deserializeECIES(toHex(sealedBytes)),\n );\n const result = validateResult(parseObject(plaintext, \"job result\"));\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":"AAkBA,SAAS,cAAc;AACvB,SAAS,YAAY,SAAS,WAAW,OAAO,aAAuB;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,SAAS,YAAY,gBAAgB;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAG7B,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,U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,iBAAiB,SAAS;AACxC,SAAO,EAAE,OAAO,MAAM,WAAW,OAAO,KAAK,CAAC,GAAG,MAAM,MAAM,OAAO;AACtE;AA0BA,eAAsB,cACpB,aACA,mBACA,OACA,QACoB;AACpB,QAAM,YAAY,MAAM,MAAM;AAAA,IAC5B,QAAQ,mBAAmB,OAAO;AAAA,IAClC,iBAAiB,MAAM,WAAW,CAAC;AAAA,EACrC;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":[]}
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,WAAW,OAAO,aAAuB;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,SAAS,YAAY,gBAAgB;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAG7B,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,aAAa,OAAyB;AAC7C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,YAAY;AAAA,EAC/B;AACA,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO;AAAA,MACZ,OAAO,KAAK,KAAK,EACd,KAAK,EACL,IAAI,CAAC,QAAQ;AAAA,QACZ;AAAA,QACA,aAAc,MAAkC,GAAG,CAAC;AAAA,MACtD,CAAC;AAAA,IACL;AAAA,EACF;AACA,SAAO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A,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":[]}
@@ -78,7 +78,6 @@ function createDirectConnectFlow(transports, options = {}) {
78
78
  const listeners = /* @__PURE__ */ new Set();
79
79
  let pollHandle = null;
80
80
  let running = false;
81
- let approvedRequest = null;
82
81
  let activeRunId = 0;
83
82
  let openedWindow = null;
84
83
  function emit() {
@@ -176,7 +175,6 @@ function createDirectConnectFlow(transports, options = {}) {
176
175
  }
177
176
  if (isReadReadyStatus(status.status)) {
178
177
  clearPoll();
179
- approvedRequest = request;
180
178
  await readAndFinish(request);
181
179
  return;
182
180
  }
@@ -190,7 +188,7 @@ function createDirectConnectFlow(transports, options = {}) {
190
188
  }
191
189
  scheduleNextPoll(request, deadline);
192
190
  }
193
- const flow = {
191
+ return {
194
192
  getState() {
195
193
  return state;
196
194
  },
@@ -201,7 +199,6 @@ function createDirectConnectFlow(transports, options = {}) {
201
199
  async start() {
202
200
  if (running || isRunningPhase()) return;
203
201
  running = true;
204
- approvedRequest = null;
205
202
  const runId = ++activeRunId;
206
203
  const browserPlatform = (options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()).current();
207
204
  const approvalWindow = browserPlatform === "desktop" ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)() : null;
@@ -249,53 +246,14 @@ function createDirectConnectFlow(transports, options = {}) {
249
246
  popupBlocked: approvalWindow === null
250
247
  });
251
248
  },
252
- async retryRead() {
253
- if (running || isRunningPhase()) {
254
- throw new Error(
255
- "Cannot retry a read while the connect flow is running"
256
- );
257
- }
258
- const request = approvedRequest;
259
- const parsedExpiry = request?.expiresAt ? Date.parse(request.expiresAt) : Number.NaN;
260
- const requestExpired = Number.isFinite(parsedExpiry) && now() >= parsedExpiry;
261
- if (request && !requestExpired) {
262
- running = true;
263
- const runId = ++activeRunId;
264
- let status;
265
- try {
266
- status = await transports.getStatus(request.requestId);
267
- } catch (err) {
268
- if (runId !== activeRunId) {
269
- throw new Error("Read retry was superseded");
270
- }
271
- running = false;
272
- const error = toError(err);
273
- setState({ type: "error", error });
274
- throw error;
275
- }
276
- if (runId !== activeRunId) {
277
- throw new Error("Read retry was superseded");
278
- }
279
- if (isReadReadyStatus(status.status)) {
280
- await readAndFinish(request);
281
- return "retried_existing_grant";
282
- }
283
- running = false;
284
- }
285
- approvedRequest = null;
286
- await flow.start();
287
- return "fresh_approval_required";
288
- },
289
249
  reset() {
290
250
  running = false;
291
- approvedRequest = null;
292
251
  activeRunId++;
293
252
  clearPoll();
294
253
  closeUnnavigatedWindow();
295
254
  setState({ type: "idle" });
296
255
  }
297
256
  };
298
- return flow;
299
257
  }
300
258
  // Annotate the CommonJS export names for ESM import in node:
301
259
  0 && (module.exports = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Browser class used only to choose the destination returned by Vana. */\nexport type DirectBrowserPlatform = \"desktop\" | \"mobile\";\n\n/** Injectable browser-platform policy; it never asserts whether an app exists. */\nexport interface DirectBrowserPlatformPolicy {\n current(): DirectBrowserPlatform;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /**\n * Overall timeout in ms before giving up. Defaults to 300000 (5 min).\n * Used only when the access request does not carry an authoritative\n * `expiresAt` value.\n */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** SDK-owned mobile/desktop policy. Injectable for deterministic tests. */\n browserPlatformPolicy?: DirectBrowserPlatformPolicy;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n *\n * Desktop and light-data requests move through `\"awaiting_approval\"` (Vana Web\n * opens in a popup). A deep Direct request on a mobile browser moves through\n * `\"ready_to_open\"` instead: the SDK exposes a plain HTTPS\n * `mobileContinuationUrl` for the UI to render as a primary \"Open Vana\" link,\n * never launching it automatically, and keeps polling in memory.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the popup was blocked. The UI should render the universal\n * HTTPS `request.approvalUrl` as a manual \"Open approval\" link.\n */\n popupBlocked: boolean;\n }\n | {\n type: \"ready_to_open\";\n request: AccessRequest;\n /**\n * Validated HTTPS continuation URL the mobile UI renders as the primary\n * \"Open Vana\" tap. Polling continues while it is shown; its embedded\n * ticket may rotate to a fresh URL between polls.\n */\n mobileContinuationUrl: string;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** Whether an explicit read retry reused consent or started fresh approval. */\nexport type DirectConnectRetryOutcome =\n | \"retried_existing_grant\"\n | \"fresh_approval_required\";\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /**\n * Retry a failed read, reusing a still-live approved request when possible.\n *\n * @remarks\n * This explicit path avoids the observed double-approval symptom where\n * \"Try that again\" minted a new request after a transient read failure.\n * The return value tells callers whether existing consent was reused or a\n * fresh approval was required.\n */\n retryRead(): Promise<DirectConnectRetryOutcome>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\nconst MOBILE_USER_AGENT =\n /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;\n\nfunction defaultBrowserPlatformPolicy(): DirectBrowserPlatformPolicy {\n return {\n current() {\n if (typeof navigator === \"undefined\") return \"desktop\";\n const isTouchCapableIpad =\n navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1;\n return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad\n ? \"mobile\"\n : \"desktop\";\n },\n };\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // `openApprovalWindow` and `browserPlatformPolicy` are resolved lazily at\n // start() (see below) so options swapped in after construction are still\n // honoured — matching the latest-callback pattern the React hook uses for its\n // transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Retained only after status proved this request had a read-ready grant.\n // A retry rechecks that status before trusting the prior consent.\n let approvedRequest: AccessRequest | null = null;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"ready_to_open\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n function requestDeadline(request: AccessRequest): number {\n if (request.expiresAt !== undefined) {\n const expiresAt = Date.parse(request.expiresAt);\n if (Number.isFinite(expiresAt)) return expiresAt;\n }\n return now() + timeoutMs;\n }\n\n /**\n * Enter the polling loop from the given initial state (either\n * `awaiting_approval` for desktop/light or `ready_to_open` for mobile-deep).\n * Errors out immediately if the request has already expired.\n */\n function startPolling(\n request: AccessRequest,\n initialState: DirectConnectState<T>,\n ): void {\n setState(initialState);\n const deadline = requestDeadline(request);\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Access request expired\"),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n // A pending deep-mobile status may rotate the continuation ticket. Adopt a\n // fresh, still-valid URL so the rendered \"Open Vana\" link always points at a\n // live ticket; ignore it on the desktop/light path.\n if (status.status === \"pending\" && state.type === \"ready_to_open\") {\n const refreshed = normalizeMobileContinuationUrl(\n status.mobileContinuationUrl,\n );\n if (refreshed && refreshed !== state.mobileContinuationUrl) {\n request = { ...request, mobileContinuationUrl: refreshed };\n setState({\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl: refreshed,\n });\n }\n }\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n approvedRequest = request;\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n const flow: DirectConnectFlow<T> = {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n // start() deliberately keeps its established first-run semantics: every\n // explicit start creates a request. Only retryRead() may reuse consent.\n approvedRequest = null;\n const runId = ++activeRunId;\n // Read the platform policy at start time, like openApprovalWindow below,\n // so a policy swapped in after construction (a React rerender forwards\n // options through a ref) still decides this run's destination.\n const browserPlatform = (\n options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()\n ).current();\n\n // Desktop preserves the pre-mobile synchronous popup contract: open a\n // blank tab while the click's transient activation is live, then navigate\n // it once createRequest returns the approval URL (BUI-622). Mobile never\n // creates that transient tab; deep requests expose one explicit HTTPS\n // link, while light requests retain the manual approvalUrl fallback.\n // Read the opener option at start time so a swapped-in custom opener is\n // still honored for desktop flows.\n const approvalWindow =\n browserPlatform === \"desktop\"\n ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)()\n : null;\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n // Re-validate the continuation URL at the SDK boundary (defense in depth\n // for custom transports that bypass the default client).\n request = {\n ...request,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n request.mobileContinuationUrl,\n ),\n };\n\n // The SDK owns only the small mobile-versus-desktop destination choice.\n // A deep Direct request on mobile carries a validated continuation URL;\n // desktop keeps its popup contract, while mobile light exposes the HTTPS\n // approval URL as the existing manual fallback without opening a tab.\n const mobileContinuationUrl =\n browserPlatform === \"mobile\"\n ? request.mobileContinuationUrl\n : undefined;\n\n if (mobileContinuationUrl) {\n // Do not auto-launch: DCR creation is async, so the original Connect\n // gesture can no longer be trusted to retain iOS user activation. Let\n // the UI render an explicit primary \"Open Vana\" link; polling continues\n // in this tab.\n startPolling(request, {\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl,\n });\n return;\n }\n\n // Desktop/light: navigate the synchronously-opened tab to the HTTPS\n // approval URL. `approvalWindow === null` means the popup was blocked;\n // surface it so the UI renders request.approvalUrl as a visible manual\n // \"Open approval\" link instead of hanging. We poll either way, so a manual\n // open still resolves the flow, and the timeout still bounds the wait.\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n startPolling(request, {\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n },\n\n async retryRead(): Promise<DirectConnectRetryOutcome> {\n if (running || isRunningPhase()) {\n throw new Error(\n \"Cannot retry a read while the connect flow is running\",\n );\n }\n\n const request = approvedRequest;\n const parsedExpiry = request?.expiresAt\n ? Date.parse(request.expiresAt)\n : Number.NaN;\n const requestExpired =\n Number.isFinite(parsedExpiry) && now() >= parsedExpiry;\n\n if (request && !requestExpired) {\n running = true;\n const runId = ++activeRunId;\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n running = false;\n const error = toError(err);\n setState({ type: \"error\", error });\n throw error;\n }\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n if (isReadReadyStatus(status.status)) {\n await readAndFinish(request);\n return \"retried_existing_grant\";\n }\n running = false;\n }\n\n approvedRequest = null;\n await flow.start();\n return \"fresh_approval_required\";\n },\n\n reset(): void {\n running = false;\n approvedRequest = null;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a subsequent run.\n activeRunId++;\n clearPoll();\n closeUnnavigatedWindow();\n setState({ type: \"idle\" });\n },\n };\n\n return flow;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAA+C;AA0I/C,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAE3B,SAAS,QAAQ,OAAuB;AACtC,SAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;AAEA,SAAS,kBAAkB,QAA2C;AACpE,SAAO,WAAW,cAAc,WAAW;AAC7C;AAEA,MAAM,oBACJ;AAEF,SAAS,+BAA4D;AACnE,SAAO;AAAA,IACL,UAAU;AACR,UAAI,OAAO,cAAc,YAAa,QAAO;AAC7C,YAAM,qBACJ,UAAU,aAAa,cAAc,UAAU,iBAAiB;AAClE,aAAO,kBAAkB,KAAK,UAAU,SAAS,KAAK,qBAClD,WACA;AAAA,IACN;AAAA,EACF;AACF;AAOA,SAAS,4BAAkD;AACzD,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAM,QAAO;AAI1D,QAAM,SAAS,OAAO,KAAK,IAAI,QAAQ;AACvC,MAAI,CAAC,OAAQ,QAAO;AAGpB,MAAI;AACF,WAAO,SAAS;AAAA,EAClB,QAA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AQ,GAAG;AACzB,mBAAS,EAAE,MAAM,SAAS,MAAM,CAAC;AACjC,gBAAM;AAAA,QACR;AACA,YAAI,UAAU,aAAa;AACzB,gBAAM,IAAI,MAAM,2BAA2B;AAAA,QAC7C;AACA,YAAI,kBAAkB,OAAO,MAAM,GAAG;AACpC,gBAAM,cAAc,OAAO;AAC3B,iBAAO;AAAA,QACT;AACA,kBAAU;AAAA,MACZ;AAEA,wBAAkB;AAClB,YAAM,KAAK,MAAM;AACjB,aAAO;AAAA,IACT;AAAA,IAEA,QAAc;AACZ,gBAAU;AACV,wBAAkB;AAGlB;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Browser class used only to choose the destination returned by Vana. */\nexport type DirectBrowserPlatform = \"desktop\" | \"mobile\";\n\n/** Injectable browser-platform policy; it never asserts whether an app exists. */\nexport interface DirectBrowserPlatformPolicy {\n current(): DirectBrowserPlatform;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /**\n * Overall timeout in ms before giving up. Defaults to 300000 (5 min).\n * Used only when the access request does not carry an authoritative\n * `expiresAt` value.\n */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** SDK-owned mobile/desktop policy. Injectable for deterministic tests. */\n browserPlatformPolicy?: DirectBrowserPlatformPolicy;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n *\n * Desktop and light-data requests move through `\"awaiting_approval\"` (Vana Web\n * opens in a popup). A deep Direct request on a mobile browser moves through\n * `\"ready_to_open\"` instead: the SDK exposes a plain HTTPS\n * `mobileContinuationUrl` for the UI to render as a primary \"Open Vana\" link,\n * never launching it automatically, and keeps polling in memory.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the popup was blocked. The UI should render the universal\n * HTTPS `request.approvalUrl` as a manual \"Open approval\" link.\n */\n popupBlocked: boolean;\n }\n | {\n type: \"ready_to_open\";\n request: AccessRequest;\n /**\n * Validated HTTPS continuation URL the mobile UI renders as the primary\n * \"Open Vana\" tap. Polling continues while it is shown; its embedded\n * ticket may rotate to a fresh URL between polls.\n */\n mobileContinuationUrl: string;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\nconst MOBILE_USER_AGENT =\n /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;\n\nfunction defaultBrowserPlatformPolicy(): DirectBrowserPlatformPolicy {\n return {\n current() {\n if (typeof navigator === \"undefined\") return \"desktop\";\n const isTouchCapableIpad =\n navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1;\n return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad\n ? \"mobile\"\n : \"desktop\";\n },\n };\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // `openApprovalWindow` and `browserPlatformPolicy` are resolved lazily at\n // start() (see below) so options swapped in after construction are still\n // honoured — matching the latest-callback pattern the React hook uses for its\n // transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"ready_to_open\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n function requestDeadline(request: AccessRequest): number {\n if (request.expiresAt !== undefined) {\n const expiresAt = Date.parse(request.expiresAt);\n if (Number.isFinite(expiresAt)) return expiresAt;\n }\n return now() + timeoutMs;\n }\n\n /**\n * Enter the polling loop from the given initial state (either\n * `awaiting_approval` for desktop/light or `ready_to_open` for mobile-deep).\n * Errors out immediately if the request has already expired.\n */\n function startPolling(\n request: AccessRequest,\n initialState: DirectConnectState<T>,\n ): void {\n setState(initialState);\n const deadline = requestDeadline(request);\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Access request expired\"),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n // A pending deep-mobile status may rotate the continuation ticket. Adopt a\n // fresh, still-valid URL so the rendered \"Open Vana\" link always points at a\n // live ticket; ignore it on the desktop/light path.\n if (status.status === \"pending\" && state.type === \"ready_to_open\") {\n const refreshed = normalizeMobileContinuationUrl(\n status.mobileContinuationUrl,\n );\n if (refreshed && refreshed !== state.mobileContinuationUrl) {\n request = { ...request, mobileContinuationUrl: refreshed };\n setState({\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl: refreshed,\n });\n }\n }\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n const runId = ++activeRunId;\n // Read the platform policy at start time, like openApprovalWindow below,\n // so a policy swapped in after construction (a React rerender forwards\n // options through a ref) still decides this run's destination.\n const browserPlatform = (\n options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()\n ).current();\n\n // Desktop preserves the pre-mobile synchronous popup contract: open a\n // blank tab while the click's transient activation is live, then navigate\n // it once createRequest returns the approval URL (BUI-622). Mobile never\n // creates that transient tab; deep requests expose one explicit HTTPS\n // link, while light requests retain the manual approvalUrl fallback.\n // Read the opener option at start time so a swapped-in custom opener is\n // still honored for desktop flows.\n const approvalWindow =\n browserPlatform === \"desktop\"\n ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)()\n : null;\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n // Re-validate the continuation URL at the SDK boundary (defense in depth\n // for custom transports that bypass the default client).\n request = {\n ...request,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n request.mobileContinuationUrl,\n ),\n };\n\n // The SDK owns only the small mobile-versus-desktop destination choice.\n // A deep Direct request on mobile carries a validated continuation URL;\n // desktop keeps its popup contract, while mobile light exposes the HTTPS\n // approval URL as the existing manual fallback without opening a tab.\n const mobileContinuationUrl =\n browserPlatform === \"mobile\"\n ? request.mobileContinuationUrl\n : undefined;\n\n if (mobileContinuationUrl) {\n // Do not auto-launch: DCR creation is async, so the original Connect\n // gesture can no longer be trusted to retain iOS user activation. Let\n // the UI render an explicit primary \"Open Vana\" link; polling continues\n // in this tab.\n startPolling(request, {\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl,\n });\n return;\n }\n\n // Desktop/light: navigate the synchronously-opened tab to the HTTPS\n // approval URL. `approvalWindow === null` means the popup was blocked;\n // surface it so the UI renders request.approvalUrl as a visible manual\n // \"Open approval\" link instead of hanging. We poll either way, so a manual\n // open still resolves the flow, and the timeout still bounds the wait.\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n startPolling(request, {\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n },\n\n reset(): void {\n running = false;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a subsequent run.\n activeRunId++;\n clearPoll();\n closeUnnavigatedWindow();\n setState({ type: \"idle\" });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAA+C;AA2H/C,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAE3B,SAAS,QAAQ,OAAuB;AACtC,SAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;AAEA,SAAS,kBAAkB,QAA2C;AACpE,SAAO,WAAW,cAAc,WAAW;AAC7C;AAEA,MAAM,oBACJ;AAEF,SAAS,+BAA4D;AACnE,SAAO;AAAA,IACL,UAAU;AACR,UAAI,OAAO,cAAc,YAAa,QAAO;AAC7C,YAAM,qBACJ,UAAU,aAAa,cAAc,UAAU,iBAAiB;AAClE,aAAO,kBAAkB,KAAK,UAAU,SAAS,KAAK,qBAClD,WACA;AAAA,IACN;AAAA,EACF;AACF;AAOA,SAAS,4BAAkD;AACzD,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAM,QAAO;AAI1D,QAAM,SAAS,OAAO,KAAK,IAAI,QAAQ;AACvC,MAAI,CAAC,OAAQ,QAAO;AAGpB,MAAI;AACF,WAAO,SAAS;AAAA,EAClB,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,SAAS,KAAa;AAIpB,UAAI;AACF,cAAM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ACV,+BAAuB;AACvB,iBAAS,EAAE,MAAM,SAAS,OAAO,QAAQ,GAAG,EAAE,CAAC;AAC/C;AAAA,MACF;AACA,UAAI,UAAU,aAAa;AACzB,wBAAgB,MAAM;AACtB;AAAA,MACF;AAGA,gBAAU;AAAA,QACR,GAAG;AAAA,QACH,2BAAuB;AAAA,UACrB,QAAQ;AAAA,QACV;AAAA,MACF;AAMA,YAAM,wBACJ,oBAAoB,WAChB,QAAQ,wBACR;AAEN,UAAI,uBAAuB;AAKzB,qBAAa,SAAS;AAAA,UACpB,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACF,CAAC;AACD;AAAA,MACF;AAOA,UAAI,gBAAgB;AAClB,uBAAe,SAAS,QAAQ,WAAW;AAE3C,uBAAe;AAAA,MACjB;AACA,mBAAa,SAAS;AAAA,QACpB,MAAM;AAAA,QACN;AAAA,QACA,cAAc,mBAAmB;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,IAEA,QAAc;AACZ,gBAAU;AAGV;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
@@ -122,8 +122,6 @@ export type DirectConnectState<T = unknown> = {
122
122
  type: "error";
123
123
  error: Error;
124
124
  };
125
- /** Whether an explicit read retry reused consent or started fresh approval. */
126
- export type DirectConnectRetryOutcome = "retried_existing_grant" | "fresh_approval_required";
127
125
  /** The store returned by {@link createDirectConnectFlow}. */
128
126
  export interface DirectConnectFlow<T = unknown> {
129
127
  /** Current state. */
@@ -132,16 +130,6 @@ export interface DirectConnectFlow<T = unknown> {
132
130
  subscribe(listener: () => void): () => void;
133
131
  /** Begin the flow. No-op if already running. */
134
132
  start(): Promise<void>;
135
- /**
136
- * Retry a failed read, reusing a still-live approved request when possible.
137
- *
138
- * @remarks
139
- * This explicit path avoids the observed double-approval symptom where
140
- * "Try that again" minted a new request after a transient read failure.
141
- * The return value tells callers whether existing consent was reused or a
142
- * fresh approval was required.
143
- */
144
- retryRead(): Promise<DirectConnectRetryOutcome>;
145
133
  /** Reset to `idle` and stop any in-flight polling. */
146
134
  reset(): void;
147
135
  }