@opendatalabs/personal-server-ts-core 0.0.1-canary.01ca694 → 0.0.1-canary.052d47e

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 (322) hide show
  1. package/dist/api/index.d.ts +282 -9
  2. package/dist/api/index.d.ts.map +1 -1
  3. package/dist/api/index.js +867 -163
  4. package/dist/api/index.js.map +1 -1
  5. package/dist/auth/request.d.ts.map +1 -1
  6. package/dist/auth/request.js.map +1 -1
  7. package/dist/client.d.ts +8 -1
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +21 -3
  10. package/dist/client.js.map +1 -1
  11. package/dist/contracts/binary.d.ts +12 -0
  12. package/dist/contracts/binary.d.ts.map +1 -1
  13. package/dist/contracts/binary.js +31 -0
  14. package/dist/contracts/binary.js.map +1 -1
  15. package/dist/contracts/data.d.ts +51 -5
  16. package/dist/contracts/data.d.ts.map +1 -1
  17. package/dist/contracts/data.js +166 -30
  18. package/dist/contracts/data.js.map +1 -1
  19. package/dist/contracts/grants.d.ts +7 -5
  20. package/dist/contracts/grants.d.ts.map +1 -1
  21. package/dist/contracts/grants.js +60 -37
  22. package/dist/contracts/grants.js.map +1 -1
  23. package/dist/contracts/index.d.ts +1 -1
  24. package/dist/contracts/index.d.ts.map +1 -1
  25. package/dist/contracts/index.js +1 -1
  26. package/dist/contracts/index.js.map +1 -1
  27. package/dist/derivatives/api.d.ts +48 -0
  28. package/dist/derivatives/api.d.ts.map +1 -0
  29. package/dist/derivatives/api.js +366 -0
  30. package/dist/derivatives/api.js.map +1 -0
  31. package/dist/derivatives/compute.d.ts +106 -0
  32. package/dist/derivatives/compute.d.ts.map +1 -0
  33. package/dist/derivatives/compute.js +414 -0
  34. package/dist/derivatives/compute.js.map +1 -0
  35. package/dist/derivatives/e2ee/aad.d.ts +22 -0
  36. package/dist/derivatives/e2ee/aad.d.ts.map +1 -0
  37. package/dist/derivatives/e2ee/aad.js +32 -0
  38. package/dist/derivatives/e2ee/aad.js.map +1 -0
  39. package/dist/derivatives/e2ee/attestation.d.ts +134 -0
  40. package/dist/derivatives/e2ee/attestation.d.ts.map +1 -0
  41. package/dist/derivatives/e2ee/attestation.js +248 -0
  42. package/dist/derivatives/e2ee/attestation.js.map +1 -0
  43. package/dist/derivatives/e2ee/index.d.ts +6 -0
  44. package/dist/derivatives/e2ee/index.d.ts.map +1 -0
  45. package/dist/derivatives/e2ee/index.js +6 -0
  46. package/dist/derivatives/e2ee/index.js.map +1 -0
  47. package/dist/derivatives/e2ee/jcs.d.ts +17 -0
  48. package/dist/derivatives/e2ee/jcs.d.ts.map +1 -0
  49. package/dist/derivatives/e2ee/jcs.js +55 -0
  50. package/dist/derivatives/e2ee/jcs.js.map +1 -0
  51. package/dist/derivatives/e2ee/phala.d.ts +62 -0
  52. package/dist/derivatives/e2ee/phala.d.ts.map +1 -0
  53. package/dist/derivatives/e2ee/phala.js +168 -0
  54. package/dist/derivatives/e2ee/phala.js.map +1 -0
  55. package/dist/derivatives/e2ee/suite.d.ts +56 -0
  56. package/dist/derivatives/e2ee/suite.d.ts.map +1 -0
  57. package/dist/derivatives/e2ee/suite.js +164 -0
  58. package/dist/derivatives/e2ee/suite.js.map +1 -0
  59. package/dist/derivatives/index.d.ts +10 -0
  60. package/dist/derivatives/index.d.ts.map +1 -0
  61. package/dist/derivatives/index.js +10 -0
  62. package/dist/derivatives/index.js.map +1 -0
  63. package/dist/derivatives/inference.d.ts +151 -0
  64. package/dist/derivatives/inference.d.ts.map +1 -0
  65. package/dist/derivatives/inference.js +262 -0
  66. package/dist/derivatives/inference.js.map +1 -0
  67. package/dist/derivatives/prompt.d.ts +64 -0
  68. package/dist/derivatives/prompt.d.ts.map +1 -0
  69. package/dist/derivatives/prompt.js +193 -0
  70. package/dist/derivatives/prompt.js.map +1 -0
  71. package/dist/derivatives/registration.d.ts +54 -0
  72. package/dist/derivatives/registration.d.ts.map +1 -0
  73. package/dist/derivatives/registration.js +180 -0
  74. package/dist/derivatives/registration.js.map +1 -0
  75. package/dist/derivatives/scheduler.d.ts +84 -0
  76. package/dist/derivatives/scheduler.d.ts.map +1 -0
  77. package/dist/derivatives/scheduler.js +257 -0
  78. package/dist/derivatives/scheduler.js.map +1 -0
  79. package/dist/derivatives/store.d.ts +14 -0
  80. package/dist/derivatives/store.d.ts.map +1 -0
  81. package/dist/derivatives/store.js +77 -0
  82. package/dist/derivatives/store.js.map +1 -0
  83. package/dist/derivatives/types.d.ts +92 -0
  84. package/dist/derivatives/types.d.ts.map +1 -0
  85. package/dist/derivatives/types.js +27 -0
  86. package/dist/derivatives/types.js.map +1 -0
  87. package/dist/errors/catalog.d.ts +75 -0
  88. package/dist/errors/catalog.d.ts.map +1 -1
  89. package/dist/errors/catalog.js +104 -0
  90. package/dist/errors/catalog.js.map +1 -1
  91. package/dist/grants/index.d.ts +2 -1
  92. package/dist/grants/index.d.ts.map +1 -1
  93. package/dist/grants/index.js +1 -1
  94. package/dist/grants/index.js.map +1 -1
  95. package/dist/keys/index.d.ts +1 -0
  96. package/dist/keys/index.d.ts.map +1 -1
  97. package/dist/keys/index.js +1 -1
  98. package/dist/keys/index.js.map +1 -1
  99. package/dist/keys/public-only-account.d.ts +8 -0
  100. package/dist/keys/public-only-account.d.ts.map +1 -0
  101. package/dist/keys/public-only-account.js +21 -0
  102. package/dist/keys/public-only-account.js.map +1 -0
  103. package/dist/keys/server-account.d.ts +2 -2
  104. package/dist/keys/server-account.d.ts.map +1 -1
  105. package/dist/lineage/attestation.d.ts +42 -0
  106. package/dist/lineage/attestation.d.ts.map +1 -0
  107. package/dist/lineage/attestation.js +25 -0
  108. package/dist/lineage/attestation.js.map +1 -0
  109. package/dist/lineage/gateway.d.ts +105 -0
  110. package/dist/lineage/gateway.d.ts.map +1 -0
  111. package/dist/lineage/gateway.js +242 -0
  112. package/dist/lineage/gateway.js.map +1 -0
  113. package/dist/lineage/index.d.ts +5 -0
  114. package/dist/lineage/index.d.ts.map +1 -0
  115. package/dist/lineage/index.js +5 -0
  116. package/dist/lineage/index.js.map +1 -0
  117. package/dist/lineage/lineage.d.ts +141 -0
  118. package/dist/lineage/lineage.d.ts.map +1 -0
  119. package/dist/lineage/lineage.js +255 -0
  120. package/dist/lineage/lineage.js.map +1 -0
  121. package/dist/logging/access-log.d.ts +10 -1
  122. package/dist/logging/access-log.d.ts.map +1 -1
  123. package/dist/mcp/activity.d.ts.map +1 -1
  124. package/dist/mcp/activity.js.map +1 -1
  125. package/dist/mcp/connection-api.d.ts.map +1 -1
  126. package/dist/mcp/connection-api.js +0 -1
  127. package/dist/mcp/connection-api.js.map +1 -1
  128. package/dist/mcp/index.d.ts +1 -0
  129. package/dist/mcp/index.d.ts.map +1 -1
  130. package/dist/mcp/index.js +1 -0
  131. package/dist/mcp/index.js.map +1 -1
  132. package/dist/mcp/read-client.d.ts +61 -1
  133. package/dist/mcp/read-client.d.ts.map +1 -1
  134. package/dist/mcp/read-client.js +397 -42
  135. package/dist/mcp/read-client.js.map +1 -1
  136. package/dist/mcp/resources.d.ts +37 -0
  137. package/dist/mcp/resources.d.ts.map +1 -0
  138. package/dist/mcp/resources.js +114 -0
  139. package/dist/mcp/resources.js.map +1 -0
  140. package/dist/mcp/search/index.d.ts.map +1 -1
  141. package/dist/mcp/search/index.js +108 -21
  142. package/dist/mcp/search/index.js.map +1 -1
  143. package/dist/mcp/server.d.ts.map +1 -1
  144. package/dist/mcp/server.js +27 -9
  145. package/dist/mcp/server.js.map +1 -1
  146. package/dist/mcp/session.d.ts +160 -0
  147. package/dist/mcp/session.d.ts.map +1 -0
  148. package/dist/mcp/session.js +243 -0
  149. package/dist/mcp/session.js.map +1 -0
  150. package/dist/mcp/tools.d.ts +29 -3
  151. package/dist/mcp/tools.d.ts.map +1 -1
  152. package/dist/mcp/tools.js +515 -48
  153. package/dist/mcp/tools.js.map +1 -1
  154. package/dist/mcp/types.d.ts.map +1 -1
  155. package/dist/payment/index.d.ts +2 -0
  156. package/dist/payment/index.d.ts.map +1 -0
  157. package/dist/payment/index.js +2 -0
  158. package/dist/payment/index.js.map +1 -0
  159. package/dist/payment/x402.d.ts +155 -0
  160. package/dist/payment/x402.d.ts.map +1 -0
  161. package/dist/payment/x402.js +402 -0
  162. package/dist/payment/x402.js.map +1 -0
  163. package/dist/policy/data-read.d.ts +18 -2
  164. package/dist/policy/data-read.d.ts.map +1 -1
  165. package/dist/policy/data-read.js +80 -49
  166. package/dist/policy/data-read.js.map +1 -1
  167. package/dist/policy/data-write.d.ts +69 -0
  168. package/dist/policy/data-write.d.ts.map +1 -0
  169. package/dist/policy/data-write.js +131 -0
  170. package/dist/policy/data-write.js.map +1 -0
  171. package/dist/policy/index.d.ts +3 -1
  172. package/dist/policy/index.d.ts.map +1 -1
  173. package/dist/policy/index.js +3 -1
  174. package/dist/policy/index.js.map +1 -1
  175. package/dist/policy/signed-artifacts.d.ts +17 -0
  176. package/dist/policy/signed-artifacts.d.ts.map +1 -0
  177. package/dist/policy/signed-artifacts.js +110 -0
  178. package/dist/policy/signed-artifacts.js.map +1 -0
  179. package/dist/ports/index.d.ts +159 -32
  180. package/dist/ports/index.d.ts.map +1 -1
  181. package/dist/ports/index.js +6 -5
  182. package/dist/ports/index.js.map +1 -1
  183. package/dist/schemas/server-config.d.ts +49 -4
  184. package/dist/schemas/server-config.d.ts.map +1 -1
  185. package/dist/schemas/server-config.js +95 -13
  186. package/dist/schemas/server-config.js.map +1 -1
  187. package/dist/signing/index.d.ts +2 -2
  188. package/dist/signing/index.d.ts.map +1 -1
  189. package/dist/signing/index.js +1 -1
  190. package/dist/signing/index.js.map +1 -1
  191. package/dist/signing/request-signer.d.ts +2 -0
  192. package/dist/signing/request-signer.d.ts.map +1 -1
  193. package/dist/signing/request-signer.js +1 -0
  194. package/dist/signing/request-signer.js.map +1 -1
  195. package/dist/signing/signer.d.ts +27 -25
  196. package/dist/signing/signer.d.ts.map +1 -1
  197. package/dist/signing/signer.js +27 -51
  198. package/dist/signing/signer.js.map +1 -1
  199. package/dist/storage/adapters/index.d.ts +1 -1
  200. package/dist/storage/adapters/index.d.ts.map +1 -1
  201. package/dist/storage/adapters/index.js +1 -1
  202. package/dist/storage/adapters/index.js.map +1 -1
  203. package/dist/storage/adapters/interface.d.ts +10 -0
  204. package/dist/storage/adapters/interface.d.ts.map +1 -1
  205. package/dist/storage/adapters/sdk.d.ts +11 -1
  206. package/dist/storage/adapters/sdk.d.ts.map +1 -1
  207. package/dist/storage/adapters/sdk.js +38 -3
  208. package/dist/storage/adapters/sdk.js.map +1 -1
  209. package/dist/storage/adapters/vana.d.ts +3 -0
  210. package/dist/storage/adapters/vana.d.ts.map +1 -1
  211. package/dist/storage/adapters/vana.js +95 -2
  212. package/dist/storage/adapters/vana.js.map +1 -1
  213. package/dist/storage/blocks/errors.d.ts.map +1 -1
  214. package/dist/storage/blocks/errors.js.map +1 -1
  215. package/dist/storage/blocks/index.d.ts +2 -0
  216. package/dist/storage/blocks/index.d.ts.map +1 -1
  217. package/dist/storage/blocks/index.js +2 -0
  218. package/dist/storage/blocks/index.js.map +1 -1
  219. package/dist/storage/blocks/select.d.ts +29 -0
  220. package/dist/storage/blocks/select.d.ts.map +1 -0
  221. package/dist/storage/blocks/select.js +120 -0
  222. package/dist/storage/blocks/select.js.map +1 -0
  223. package/dist/storage/blocks/types.d.ts +7 -0
  224. package/dist/storage/blocks/types.d.ts.map +1 -1
  225. package/dist/storage/index/manager.d.ts +30 -2
  226. package/dist/storage/index/manager.d.ts.map +1 -1
  227. package/dist/storage/index/schema.d.ts +1 -1
  228. package/dist/storage/index/schema.js +1 -1
  229. package/dist/storage/index/types.d.ts +6 -1
  230. package/dist/storage/index/types.d.ts.map +1 -1
  231. package/dist/sync/data-point-feed.d.ts +35 -0
  232. package/dist/sync/data-point-feed.d.ts.map +1 -0
  233. package/dist/sync/data-point-feed.js +122 -0
  234. package/dist/sync/data-point-feed.js.map +1 -0
  235. package/dist/sync/data-point-id.d.ts +7 -0
  236. package/dist/sync/data-point-id.d.ts.map +1 -0
  237. package/dist/sync/data-point-id.js +16 -0
  238. package/dist/sync/data-point-id.js.map +1 -0
  239. package/dist/sync/delete-data-port.d.ts +50 -0
  240. package/dist/sync/delete-data-port.d.ts.map +1 -0
  241. package/dist/sync/delete-data-port.js +244 -0
  242. package/dist/sync/delete-data-port.js.map +1 -0
  243. package/dist/sync/engine/sync-manager.d.ts +16 -4
  244. package/dist/sync/engine/sync-manager.d.ts.map +1 -1
  245. package/dist/sync/engine/sync-manager.js +93 -32
  246. package/dist/sync/engine/sync-manager.js.map +1 -1
  247. package/dist/sync/index.d.ts +7 -0
  248. package/dist/sync/index.d.ts.map +1 -1
  249. package/dist/sync/index.js +7 -0
  250. package/dist/sync/index.js.map +1 -1
  251. package/dist/sync/issues.d.ts.map +1 -1
  252. package/dist/sync/issues.js +21 -3
  253. package/dist/sync/issues.js.map +1 -1
  254. package/dist/sync/pending-blob-deletions.d.ts +29 -0
  255. package/dist/sync/pending-blob-deletions.d.ts.map +1 -0
  256. package/dist/sync/pending-blob-deletions.js +116 -0
  257. package/dist/sync/pending-blob-deletions.js.map +1 -0
  258. package/dist/sync/retry-memory.d.ts +33 -0
  259. package/dist/sync/retry-memory.d.ts.map +1 -0
  260. package/dist/sync/retry-memory.js +68 -0
  261. package/dist/sync/retry-memory.js.map +1 -0
  262. package/dist/sync/scope-deletions.d.ts +155 -0
  263. package/dist/sync/scope-deletions.d.ts.map +1 -0
  264. package/dist/sync/scope-deletions.js +225 -0
  265. package/dist/sync/scope-deletions.js.map +1 -0
  266. package/dist/sync/tombstone.d.ts +27 -0
  267. package/dist/sync/tombstone.d.ts.map +1 -0
  268. package/dist/sync/tombstone.js +28 -0
  269. package/dist/sync/tombstone.js.map +1 -0
  270. package/dist/sync/workers/delete.d.ts +152 -31
  271. package/dist/sync/workers/delete.d.ts.map +1 -1
  272. package/dist/sync/workers/delete.js +457 -55
  273. package/dist/sync/workers/delete.js.map +1 -1
  274. package/dist/sync/workers/download.d.ts +108 -27
  275. package/dist/sync/workers/download.d.ts.map +1 -1
  276. package/dist/sync/workers/download.js +321 -126
  277. package/dist/sync/workers/download.js.map +1 -1
  278. package/dist/sync/workers/upload.d.ts +65 -10
  279. package/dist/sync/workers/upload.d.ts.map +1 -1
  280. package/dist/sync/workers/upload.js +371 -42
  281. package/dist/sync/workers/upload.js.map +1 -1
  282. package/dist/test-utils/e2ee-fixtures.d.ts +94 -0
  283. package/dist/test-utils/e2ee-fixtures.d.ts.map +1 -0
  284. package/dist/test-utils/e2ee-fixtures.js +116 -0
  285. package/dist/test-utils/e2ee-fixtures.js.map +1 -0
  286. package/dist/test-utils/e2ee-gateway.d.ts +61 -0
  287. package/dist/test-utils/e2ee-gateway.d.ts.map +1 -0
  288. package/dist/test-utils/e2ee-gateway.js +248 -0
  289. package/dist/test-utils/e2ee-gateway.js.map +1 -0
  290. package/dist/test-utils/index.d.ts +3 -0
  291. package/dist/test-utils/index.d.ts.map +1 -1
  292. package/dist/test-utils/index.js +3 -0
  293. package/dist/test-utils/index.js.map +1 -1
  294. package/dist/test-utils/memory-storage.d.ts +12 -0
  295. package/dist/test-utils/memory-storage.d.ts.map +1 -0
  296. package/dist/test-utils/memory-storage.js +146 -0
  297. package/dist/test-utils/memory-storage.js.map +1 -0
  298. package/dist/test-utils/wallet.d.ts +6 -0
  299. package/dist/test-utils/wallet.d.ts.map +1 -1
  300. package/dist/test-utils/wallet.js +46 -0
  301. package/dist/test-utils/wallet.js.map +1 -1
  302. package/dist/write/attribution.d.ts +185 -0
  303. package/dist/write/attribution.d.ts.map +1 -0
  304. package/dist/write/attribution.js +450 -0
  305. package/dist/write/attribution.js.map +1 -0
  306. package/dist/write/authorize.d.ts +77 -0
  307. package/dist/write/authorize.d.ts.map +1 -0
  308. package/dist/write/authorize.js +109 -0
  309. package/dist/write/authorize.js.map +1 -0
  310. package/dist/write/index.d.ts +5 -0
  311. package/dist/write/index.d.ts.map +1 -0
  312. package/dist/write/index.js +5 -0
  313. package/dist/write/index.js.map +1 -0
  314. package/dist/write/route.d.ts +61 -0
  315. package/dist/write/route.d.ts.map +1 -0
  316. package/dist/write/route.js +132 -0
  317. package/dist/write/route.js.map +1 -0
  318. package/dist/write/session.d.ts +96 -0
  319. package/dist/write/session.d.ts.map +1 -0
  320. package/dist/write/session.js +136 -0
  321. package/dist/write/session.js.map +1 -0
  322. package/package.json +19 -3
@@ -0,0 +1,414 @@
1
+ /**
2
+ * The compute job: answer one registered question from local data and
3
+ * write the answer as a derivative record (owner path, `$lineage` = the
4
+ * source data points).
5
+ */
6
+ import { DerivativeCycleError, DerivativeSourceNotGrantedError, ProtocolError, } from "../errors/catalog.js";
7
+ import { resolveReadDeletion } from "../api/index.js";
8
+ import { LOCAL_SCOPE_SCAN_PAGE, readStoredLineage, } from "../lineage/lineage.js";
9
+ import { uncoveredSourceScopes } from "./registration.js";
10
+ import { ingestDataContract } from "../contracts/data.js";
11
+ import { isBinaryEnvelope } from "../contracts/binary.js";
12
+ import { assertDerivedScopeNaming } from "../lineage/lineage.js";
13
+ import { computeDataPointId } from "../sync/data-point-id.js";
14
+ import { verifyDataWritePolicy, } from "../policy/data-write.js";
15
+ import { InferenceRequestError } from "./inference.js";
16
+ import { buildQuestionMessages, parseAnswer, trimSourceData, } from "./prompt.js";
17
+ const DEFAULT_RETRY_DELAYS_MS = [1_000, 4_000];
18
+ /**
19
+ * Transient: no response, rate limited or a provider-side failure. An
20
+ * explicit `retryable` hint (E2EE key verification or decryption failures
21
+ * are permanent) wins over the status rule.
22
+ */
23
+ function isRetryableInferenceError(err) {
24
+ if (!(err instanceof InferenceRequestError))
25
+ return false;
26
+ if (err.retryable !== undefined)
27
+ return err.retryable;
28
+ return err.status === null || err.status === 429 || err.status >= 500;
29
+ }
30
+ /**
31
+ * Run `attempt` up to `delays.length + 1` times while `retryable(err)`;
32
+ * anything else (a ProtocolError, a permanent status) surfaces at once.
33
+ */
34
+ async function withRetries(deps, attempt, retryable) {
35
+ const delays = deps.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
36
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
37
+ for (let index = 0;; index += 1) {
38
+ try {
39
+ return await attempt();
40
+ }
41
+ catch (err) {
42
+ if (index >= delays.length || !retryable(err))
43
+ throw err;
44
+ await sleep(delays[index]);
45
+ }
46
+ }
47
+ }
48
+ /** A failure message safe to persist: never the prompt, never the data. */
49
+ class ComputeFailure extends Error {
50
+ code;
51
+ constructor(message, code) {
52
+ super(message);
53
+ this.name = "ComputeFailure";
54
+ this.code = code;
55
+ }
56
+ }
57
+ /**
58
+ * The machine-readable failure class stored next to the short reason. It is
59
+ * what the status route serves to readers of the derived scope, so it is a
60
+ * CLOSED vocabulary: never a scope name, never provider detail. It also
61
+ * drives the scheduler's automatic retry — `inference_unavailable` is the
62
+ * one transient class.
63
+ */
64
+ function classifyComputeError(err) {
65
+ if (err instanceof ComputeFailure)
66
+ return err.code ?? "internal";
67
+ if (err instanceof InferenceRequestError) {
68
+ return isRetryableInferenceError(err)
69
+ ? "inference_unavailable"
70
+ : "internal";
71
+ }
72
+ if (err instanceof ProtocolError) {
73
+ const grantShaped = err.errorCode === "DERIVATIVE_SOURCE_NOT_GRANTED" ||
74
+ err.errorCode === "SCOPE_MISMATCH" ||
75
+ err.errorCode === "UNREGISTERED_BUILDER" ||
76
+ err.errorCode.startsWith("GRANT_");
77
+ return grantShaped ? "grant_invalid" : "internal";
78
+ }
79
+ return "internal";
80
+ }
81
+ function shortError(err) {
82
+ if (err instanceof ComputeFailure)
83
+ return err.message;
84
+ if (err instanceof InferenceRequestError)
85
+ return err.message;
86
+ if (err instanceof ProtocolError)
87
+ return `${err.errorCode}: ${err.message}`;
88
+ // Unknown errors may quote data (a JSON parse error echoes its input);
89
+ // keep the class name only.
90
+ return `compute failed (${err instanceof Error ? err.name : "Error"})`;
91
+ }
92
+ /**
93
+ * Version stamp for the derived record, second precision like an HTTP
94
+ * ingest. A recompute inside the same second as the previous one would
95
+ * collide on the (scope, collectedAt) path, so the stamp advances past any
96
+ * version the scope already holds (bounded: at most one minute ahead).
97
+ */
98
+ export function collectedAtStamp(now, isTaken) {
99
+ const base = now();
100
+ base.setUTCMilliseconds(0);
101
+ for (let bump = 0; bump < 60; bump += 1) {
102
+ const candidate = new Date(base.getTime() + bump * 1000)
103
+ .toISOString()
104
+ .replace(/\.\d{3}Z$/, "Z");
105
+ if (!isTaken(candidate))
106
+ return candidate;
107
+ }
108
+ throw new ComputeFailure("could not allocate a version stamp");
109
+ }
110
+ async function tombstoneMarker(scopeDeletions, scope) {
111
+ if (!scopeDeletions)
112
+ return null;
113
+ const verdict = await scopeDeletions.resolve(scope);
114
+ if (!verdict.deleted || verdict.version === null)
115
+ return null;
116
+ const version = Number(verdict.version);
117
+ return Number.isSafeInteger(version) ? version : null;
118
+ }
119
+ /**
120
+ * `dataPointId -> scope` for every scope in the local index, used to walk
121
+ * stored lineage locally. Paged like the lineage resolver.
122
+ */
123
+ function localScopesById(storage, serverOwner) {
124
+ const byId = new Map();
125
+ for (let offset = 0;; offset += LOCAL_SCOPE_SCAN_PAGE) {
126
+ const { scopes, total } = storage.listScopes({
127
+ limit: LOCAL_SCOPE_SCAN_PAGE,
128
+ offset,
129
+ });
130
+ for (const summary of scopes) {
131
+ byId.set(computeDataPointId(serverOwner, summary.scope), summary.scope);
132
+ }
133
+ if (scopes.length === 0 || offset + scopes.length >= total)
134
+ break;
135
+ }
136
+ return byId;
137
+ }
138
+ /**
139
+ * Cycle guard on ACTUAL lineage, for cycles the per-store registration
140
+ * check cannot see (two replicas each holding one half: B <- A here, A <- B
141
+ * there, ping-ponging through sync). Walks `$lineage` from every source's
142
+ * latest local version through the local index; reaching the derived data
143
+ * point id means this question would consume its own output. Bounded by
144
+ * the visited set.
145
+ */
146
+ async function assertNoLineageCycle(deps, registration, serverOwner, sourceLineage) {
147
+ const derivedId = computeDataPointId(serverOwner, registration.derivedScope);
148
+ let byId = null;
149
+ const visited = new Set();
150
+ const stack = [];
151
+ for (const [scope, sources] of sourceLineage) {
152
+ for (const id of sources)
153
+ stack.push({ id, path: [scope] });
154
+ }
155
+ while (stack.length > 0) {
156
+ const { id, path } = stack.pop();
157
+ if (id === derivedId) {
158
+ throw new DerivativeCycleError({
159
+ derivedScope: registration.derivedScope,
160
+ path: [registration.derivedScope, ...path, registration.derivedScope],
161
+ });
162
+ }
163
+ if (visited.has(id))
164
+ continue;
165
+ visited.add(id);
166
+ byId ??= localScopesById(deps.storage, serverOwner);
167
+ const scope = byId.get(id);
168
+ if (!scope)
169
+ continue;
170
+ const entry = deps.storage.findEntry({ scope });
171
+ if (!entry)
172
+ continue;
173
+ let sources = [];
174
+ try {
175
+ const envelope = await deps.storage.readEnvelope(scope, entry.collectedAt);
176
+ sources = readStoredLineage(envelope.data)?.sources ?? [];
177
+ }
178
+ catch {
179
+ // Unreadable or malformed lineage: nothing further to walk here.
180
+ }
181
+ for (const next of sources)
182
+ stack.push({ id: next, path: [...path, scope] });
183
+ }
184
+ }
185
+ async function loadSource(deps, scope) {
186
+ const entry = deps.storage.findEntry({ scope });
187
+ // The same deletion gate a read applies: a tombstoned scope is refused
188
+ // (410 on the read path) whether or not a stale local copy remains.
189
+ const deletion = await resolveReadDeletion({ scopeDeletions: deps.scopeDeletions, serverOwner: deps.serverOwner }, scope, entry);
190
+ if (deletion) {
191
+ throw new ComputeFailure(`source scope ${scope} is deleted`, "source_missing");
192
+ }
193
+ if (!entry) {
194
+ throw new ComputeFailure(`source scope ${scope} has no local data`, "source_missing");
195
+ }
196
+ let envelope;
197
+ try {
198
+ envelope = await deps.storage.readEnvelope(scope, entry.collectedAt);
199
+ }
200
+ catch {
201
+ throw new ComputeFailure(`source scope ${scope} could not be read`);
202
+ }
203
+ let lineageSources = [];
204
+ try {
205
+ lineageSources = readStoredLineage(envelope.data)?.sources ?? [];
206
+ }
207
+ catch {
208
+ // Malformed stored lineage: treated as a root for the cycle walk.
209
+ }
210
+ const raw = isBinaryEnvelope(envelope)
211
+ ? {
212
+ binary: true,
213
+ note: "binary record; its content is not included in the prompt",
214
+ }
215
+ : envelope.data;
216
+ const trimmed = trimSourceData(raw, {
217
+ maxItems: deps.maxSourceItems,
218
+ maxChars: deps.maxSourceChars,
219
+ });
220
+ return {
221
+ source: {
222
+ scope,
223
+ collectedAt: entry.collectedAt,
224
+ version: entry.version,
225
+ data: trimmed.data,
226
+ kept: trimmed.kept,
227
+ total: trimmed.total,
228
+ truncated: trimmed.truncated,
229
+ },
230
+ lineageSources,
231
+ };
232
+ }
233
+ /**
234
+ * A builder question re-checks its grant before every compute: the write
235
+ * permission on the derived scope (revocation, expiry, coverage) AND read
236
+ * coverage of every source scope, since the answer exposes the sources to
237
+ * the builder. Gateway transport failures are retried; policy failures
238
+ * (ProtocolErrors) fail closed at once.
239
+ */
240
+ async function assertGrantStillValid(deps, registration) {
241
+ if (registration.registeredBy.kind !== "builder")
242
+ return;
243
+ if (!deps.writePolicyPorts) {
244
+ throw new ComputeFailure("builder grant verification is not configured");
245
+ }
246
+ if (!deps.serverOwner) {
247
+ throw new ComputeFailure("server owner is not configured");
248
+ }
249
+ const { builder, grantId } = registration.registeredBy;
250
+ const ports = deps.writePolicyPorts;
251
+ const serverOwner = deps.serverOwner;
252
+ const grant = await withRetries(deps, () => verifyDataWritePolicy({
253
+ signer: builder,
254
+ grantId,
255
+ requestedScope: registration.derivedScope,
256
+ serverOwner,
257
+ }, ports), (err) => !(err instanceof ProtocolError));
258
+ const uncovered = uncoveredSourceScopes(registration.sourceScopes, grant.scopes ?? []);
259
+ if (uncovered.length > 0) {
260
+ throw new DerivativeSourceNotGrantedError({ scopes: uncovered });
261
+ }
262
+ }
263
+ /**
264
+ * Compute one question end to end. Never throws for a compute failure: the
265
+ * registration is marked `failed` with a short reason and the outcome says
266
+ * so. Throws only when the store itself fails.
267
+ */
268
+ export async function computeQuestion(questionId, deps) {
269
+ const now = deps.now ?? (() => new Date());
270
+ if ((await deps.runtimeAvailability?.isAvailable()) === false) {
271
+ return { status: "skipped", reason: "runtime-unavailable" };
272
+ }
273
+ const registration = await deps.store.get(questionId);
274
+ if (!registration)
275
+ return { status: "skipped", reason: "unknown-question" };
276
+ try {
277
+ if (!deps.serverOwner) {
278
+ throw new ComputeFailure("server owner is not configured");
279
+ }
280
+ const serverOwner = deps.serverOwner;
281
+ await assertGrantStillValid(deps, registration);
282
+ // Defense in depth: the rule was checked at registration; a registration
283
+ // row edited by hand must still not produce a leaking derivative.
284
+ assertDerivedScopeNaming(registration.derivedScope, registration.sourceScopes);
285
+ const sources = [];
286
+ const sourceLineage = new Map();
287
+ for (const scope of registration.sourceScopes) {
288
+ const loaded = await loadSource(deps, scope);
289
+ sources.push(loaded.source);
290
+ sourceLineage.set(scope, loaded.lineageSources);
291
+ }
292
+ await assertNoLineageCycle(deps, registration, serverOwner, sourceLineage);
293
+ const messages = buildQuestionMessages({
294
+ question: registration.question,
295
+ sources,
296
+ });
297
+ const model = registration.model ?? deps.provider.defaultModel;
298
+ const reply = await withRetries(deps, () => deps.provider.chat({ model, messages, maxTokens: deps.maxTokens }), isRetryableInferenceError);
299
+ const parsed = parseAnswer(reply.content);
300
+ const computedAt = now().toISOString();
301
+ const lineageIds = registration.sourceScopes.map((scope) => computeDataPointId(serverOwner, scope));
302
+ const record = {
303
+ questionId: registration.questionId,
304
+ question: registration.question,
305
+ answer: parsed.answer,
306
+ evidence: parsed.evidence,
307
+ model,
308
+ computedAt,
309
+ sources: sources.map((source) => ({
310
+ scope: source.scope,
311
+ version: source.version,
312
+ collectedAt: source.collectedAt,
313
+ })),
314
+ lineage: lineageIds,
315
+ ...(reply.receiptId || reply.aciIdentity
316
+ ? {
317
+ inference: {
318
+ ...(reply.receiptId ? { receiptId: reply.receiptId } : {}),
319
+ ...(reply.aciIdentity ? { aciIdentity: reply.aciIdentity } : {}),
320
+ },
321
+ }
322
+ : {}),
323
+ };
324
+ const lineage = {
325
+ sources: lineageIds,
326
+ writtenAt: computedAt,
327
+ };
328
+ // `findEntry({ at })` may answer the closest version, so compare exactly.
329
+ const collectedAt = collectedAtStamp(now, (candidate) => deps.storage.findEntry({
330
+ scope: registration.derivedScope,
331
+ at: candidate,
332
+ })?.collectedAt === candidate);
333
+ const written = await ingestDataContract({
334
+ storage: deps.storage,
335
+ scopeParam: registration.derivedScope,
336
+ body: record,
337
+ collectedAt,
338
+ status: deps.syncManager ? "syncing" : "stored",
339
+ lineage,
340
+ afterTombstoneVersion: await tombstoneMarker(deps.scopeDeletions, registration.derivedScope),
341
+ });
342
+ if (!written.ok) {
343
+ throw new ComputeFailure(`derived record rejected: ${written.body.error}`);
344
+ }
345
+ const entry = deps.storage.findEntry({
346
+ scope: registration.derivedScope,
347
+ at: collectedAt,
348
+ });
349
+ const updated = await deps.store.update(questionId, {
350
+ status: "ready",
351
+ error: null,
352
+ errorCode: null,
353
+ updatedAt: computedAt,
354
+ lastComputedAt: computedAt,
355
+ derivedVersion: entry?.version ?? null,
356
+ derivedCollectedAt: collectedAt,
357
+ });
358
+ if (deps.syncManager?.notifyNewData) {
359
+ deps.syncManager.notifyNewData();
360
+ }
361
+ else if (deps.syncManager?.trigger) {
362
+ void deps.syncManager.trigger().catch(() => undefined);
363
+ }
364
+ try {
365
+ deps.onDerivedWritten?.({
366
+ scope: registration.derivedScope,
367
+ collectedAt,
368
+ lineageSources: lineageIds,
369
+ });
370
+ }
371
+ catch (err) {
372
+ deps.logger?.warn?.({
373
+ questionId,
374
+ derivedScope: registration.derivedScope,
375
+ error: err instanceof Error ? err.name : String(err),
376
+ }, "onDerivedWritten hook failed; derivative already written");
377
+ }
378
+ deps.logger?.info?.({
379
+ questionId,
380
+ derivedScope: registration.derivedScope,
381
+ sourceScopes: registration.sourceScopes,
382
+ model,
383
+ version: entry?.version ?? null,
384
+ receiptId: reply.receiptId ?? null,
385
+ }, "Derivative question computed");
386
+ return {
387
+ status: "ready",
388
+ registration: updated ?? { ...registration, status: "ready" },
389
+ };
390
+ }
391
+ catch (err) {
392
+ const error = shortError(err);
393
+ const errorCode = classifyComputeError(err);
394
+ const at = now().toISOString();
395
+ const updated = await deps.store.update(questionId, {
396
+ status: "failed",
397
+ error,
398
+ errorCode,
399
+ updatedAt: at,
400
+ });
401
+ deps.logger?.warn?.({ questionId, derivedScope: registration.derivedScope, error }, "Derivative question compute failed");
402
+ return {
403
+ status: "failed",
404
+ registration: updated ?? {
405
+ ...registration,
406
+ status: "failed",
407
+ error,
408
+ errorCode,
409
+ },
410
+ error,
411
+ };
412
+ }
413
+ }
414
+ //# sourceMappingURL=compute.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compute.js","sourceRoot":"","sources":["../../src/derivatives/compute.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,oBAAoB,EACpB,+BAA+B,EAC/B,aAAa,GACd,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAEjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAM9D,OAAO,EACL,qBAAqB,GAEtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,qBAAqB,EAA0B,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,cAAc,GAEf,MAAM,aAAa,CAAC;AAiErB,MAAM,uBAAuB,GAAsB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAElE;;;;GAIG;AACH,SAAS,yBAAyB,CAAC,GAAY;IAC7C,IAAI,CAAC,CAAC,GAAG,YAAY,qBAAqB,CAAC;QA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GAAG,EAAE,CAAC;QACb,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;QAC9B,MAAM,SAAS,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;QAC5C,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE;YAClD,MAAM,EAAE,QAAQ;YAChB,KAAK;YACL,SAAS;YACT,SAAS,EAAE,EAAE;SACd,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CACjB,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,CAAC,YAAY,EAAE,KAAK,EAAE,EAC9D,oCAAoC,CACrC,CAAC;QACF,OAAO;YACL,MAAM,EAAE,QAAQ;YAChB,YAAY,EAAE,OAAO,IAAI;gBACvB,GAAG,YAAY;gBACf,MAAM,EAAE,QAAQ;gBAChB,KAAK;gBACL,SAAS;aACV;YACD,KAAK;SACN,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * E2EE v2 associated data (spec section 6): RFC 8785 JCS bytes binding every
3
+ * ciphertext to its field path and request context. Byte-exact examples are
4
+ * pinned by the spec test vectors in aad.test.ts.
5
+ */
6
+ export declare const E2EE_REQUEST_AAD_PURPOSE = "aci.e2ee.request.v2";
7
+ export declare const E2EE_RESPONSE_AAD_PURPOSE = "aci.e2ee.response.v2";
8
+ export interface E2eeRequestContext {
9
+ /** The selected service key's `algo`. */
10
+ algo: string;
11
+ /** The request's top-level `model`, byte-exact. */
12
+ model: string;
13
+ /** `X-E2EE-Nonce`, 64 hex characters. */
14
+ nonce: string;
15
+ /** `X-E2EE-Timestamp`, Unix seconds. */
16
+ ts: number;
17
+ }
18
+ export declare function requestFieldAad(context: E2eeRequestContext, field: string): Uint8Array;
19
+ export declare function responseFieldAad(context: E2eeRequestContext, field: string,
20
+ /** The clear response `id`, or "" when the response has none. */
21
+ id: string): Uint8Array;
22
+ //# sourceMappingURL=aad.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aad.d.ts","sourceRoot":"","sources":["../../../src/derivatives/e2ee/aad.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,eAAO,MAAM,wBAAwB,wBAAwB,CAAC;AAC9D,eAAO,MAAM,yBAAyB,yBAAyB,CAAC;AAEhE,MAAM,WAAW,kBAAkB;IACjC,yCAAyC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAC;IACd,yCAAyC;IACzC,KAAK,EAAE,MAAM,CAAC;IACd,wCAAwC;IACxC,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,wBAAgB,eAAe,CAC7B,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,MAAM,GACZ,UAAU,CASZ;AAED,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,MAAM;AACb,iEAAiE;AACjE,EAAE,EAAE,MAAM,GACT,UAAU,CAUZ"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * E2EE v2 associated data (spec section 6): RFC 8785 JCS bytes binding every
3
+ * ciphertext to its field path and request context. Byte-exact examples are
4
+ * pinned by the spec test vectors in aad.test.ts.
5
+ */
6
+ import { canonicalJsonBytes } from "./jcs.js";
7
+ export const E2EE_REQUEST_AAD_PURPOSE = "aci.e2ee.request.v2";
8
+ export const E2EE_RESPONSE_AAD_PURPOSE = "aci.e2ee.response.v2";
9
+ export function requestFieldAad(context, field) {
10
+ return canonicalJsonBytes({
11
+ purpose: E2EE_REQUEST_AAD_PURPOSE,
12
+ algo: context.algo,
13
+ model: context.model,
14
+ field,
15
+ nonce: context.nonce,
16
+ ts: context.ts,
17
+ });
18
+ }
19
+ export function responseFieldAad(context, field,
20
+ /** The clear response `id`, or "" when the response has none. */
21
+ id) {
22
+ return canonicalJsonBytes({
23
+ purpose: E2EE_RESPONSE_AAD_PURPOSE,
24
+ algo: context.algo,
25
+ model: context.model,
26
+ id,
27
+ field,
28
+ nonce: context.nonce,
29
+ ts: context.ts,
30
+ });
31
+ }
32
+ //# sourceMappingURL=aad.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aad.js","sourceRoot":"","sources":["../../../src/derivatives/e2ee/aad.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE9C,MAAM,CAAC,MAAM,wBAAwB,GAAG,qBAAqB,CAAC;AAC9D,MAAM,CAAC,MAAM,yBAAyB,GAAG,sBAAsB,CAAC;AAahE,MAAM,UAAU,eAAe,CAC7B,OAA2B,EAC3B,KAAa;IAEb,OAAO,kBAAkB,CAAC;QACxB,OAAO,EAAE,wBAAwB;QACjC,IAAI,EAAE,OAAO,CAAC,IAAI;QAClB,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,KAAK;QACL,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,EAAE,EAAE,OAAO,CAAC,EAAE;KACf,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,gBAAgB,CAC9B,OAA2B,EAC3B,KAAa;AACb,iEAAiE;AACjE,EAAU;IAEV,OAAO,kBAAkB,CAAC;QACxB,OAAO,EAAE,yBAAyB;QAClC,IAAI,EAAE,OAAO,CAAC,IAAI;QAClB,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,EAAE;QACF,KAAK;QACL,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,EAAE,EAAE,OAAO,CAAC,EAAE;KACf,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Attested key fetch for E2EE v2: GET `/aci/attestation?nonce=<64 hex>` on
3
+ * the inference base URL (the Vana relay in production, which must pass the
4
+ * route through unchanged), verify the ACI binding chain structurally, and
5
+ * select the X25519 E2EE key from the quote-bound keyset.
6
+ *
7
+ * The fetch through the relay carries the same `Authorization: Web3Signed`
8
+ * header the chat completion does (GET, no body) when a `requestSigner` is
9
+ * configured, since the relay gates its passthrough routes on the caller
10
+ * being the owner or an active registered server. The direct Phala fallback
11
+ * is a different origin with no such gate and stays unsigned.
12
+ *
13
+ * What is verified here (ACI spec sections 3.1, 3.2, 4, 9.1):
14
+ * - api_version aci/1, tee_type tdx, service advertises E2EE version 2
15
+ * - sha256(JCS(workload_keyset)) equals workload_keyset_digest
16
+ * - sha256 of the section 3.2 statement built from that digest and OUR
17
+ * nonce equals attestation.report_data (freshness + keyset binding)
18
+ * - the TDX evidence's quote_report_data carries report_data zero-padded
19
+ * - now < not_after, and not_after is not implausibly far away
20
+ * - the selected key has the X25519 suite algo and a 32-byte public key
21
+ *
22
+ * What is NOT verified here: the hardware quote itself (DCAP/TDX signature
23
+ * chain to the Intel root, RTMR replay, compose-hash provenance). That is
24
+ * the `verifyEvidence` hook: the Node server can plug in a DCAP verifier
25
+ * (e.g. @phala/aci-verifier); without it the key is trusted on the TLS
26
+ * origin of the report plus the structural chain above.
27
+ * TODO(e2ee-quote-verification): wire a DCAP quote verifier in the server.
28
+ */
29
+ import type { RequestSigner } from "../../signing/request-signer.js";
30
+ export declare const ACI_API_VERSION = "aci/1";
31
+ export declare const ACI_REPORT_DATA_PURPOSE = "aci.report_data.v1";
32
+ export declare const E2EE_VERSION = "2";
33
+ /** The relay-independent origin of the Phala gateway, used as a fallback. */
34
+ export declare const PHALA_GATEWAY_BASE_URL = "https://inference.phala.com/v1";
35
+ export interface AciKeysetEntry {
36
+ key_id: string;
37
+ algo: string;
38
+ public_key: string;
39
+ }
40
+ export interface AciWorkloadKeyset {
41
+ subject: string | null;
42
+ not_after: number;
43
+ receipt_signing_keys: AciKeysetEntry[];
44
+ e2ee_public_keys: AciKeysetEntry[];
45
+ tls_public_keys: Array<{
46
+ spki_sha256: string;
47
+ domain?: string;
48
+ }>;
49
+ [key: string]: unknown;
50
+ }
51
+ export interface AciAttestationReport {
52
+ api_version: string;
53
+ workload_keyset_digest: string;
54
+ attestation: {
55
+ tee_type: string;
56
+ workload_keyset: AciWorkloadKeyset;
57
+ report_data: string;
58
+ source_provenance?: Record<string, unknown> | null;
59
+ evidence?: Record<string, unknown>;
60
+ [key: string]: unknown;
61
+ };
62
+ service_capabilities?: {
63
+ supported_e2ee_versions?: string[];
64
+ serving?: string;
65
+ [key: string]: unknown;
66
+ };
67
+ [key: string]: unknown;
68
+ }
69
+ export interface GatewayE2eeKey {
70
+ algo: string;
71
+ keyId: string;
72
+ /** Raw 32-byte X25519 key the request fields are encrypted to. */
73
+ publicKey: Uint8Array;
74
+ /** The keyset entry's `public_key` verbatim: the `X-Model-Pub-Key` value. */
75
+ publicKeyHex: string;
76
+ /** `workload_keyset_digest` of the verified report (the pin). */
77
+ keysetDigest: string;
78
+ notAfter: number;
79
+ /** Where the report was fetched from. */
80
+ source: string;
81
+ report: AciAttestationReport;
82
+ }
83
+ export type E2eeAttestationErrorCode = "fetch_failed" | "malformed_report" | "keyset_digest_mismatch" | "report_data_mismatch" | "keyset_expired" | "e2ee_unsupported" | "no_e2ee_key" | "evidence_rejected" | "request_signing_failed";
84
+ /** Carries no request data; safe to log and to surface as a compute error. */
85
+ export declare class E2eeAttestationError extends Error {
86
+ readonly code: E2eeAttestationErrorCode;
87
+ constructor(code: E2eeAttestationErrorCode, message: string);
88
+ }
89
+ export interface FetchGatewayE2eeKeyOptions {
90
+ /** Chat completions base, e.g. `https://relay.example/v1`. */
91
+ baseUrl: string;
92
+ /**
93
+ * Signs the report fetch from `baseUrl` as this personal server (the relay
94
+ * gates the passthrough route). Never used for the fallback origin.
95
+ */
96
+ requestSigner?: RequestSigner;
97
+ fetch?: typeof fetch;
98
+ /** Milliseconds since epoch (default Date.now). */
99
+ clock?: () => number;
100
+ /** Nonce source; tests pin it. */
101
+ random?: (length: number) => Uint8Array;
102
+ /** Require this `key_id` in addition to the algo (default: algo only). */
103
+ expectedKeyId?: string;
104
+ /** Hardware evidence verification hook (see the module comment). */
105
+ verifyEvidence?: (report: AciAttestationReport) => Promise<void>;
106
+ /**
107
+ * When the base URL answers 404/405 for the attestation route (a relay
108
+ * without the passthrough yet) the report is fetched from here instead;
109
+ * `null` disables the fallback. Default: the Phala gateway origin.
110
+ */
111
+ fallbackBaseUrl?: string | null;
112
+ timeoutMs?: number;
113
+ }
114
+ /** ACI section 3.1: `"sha256:" || hex(sha256(JCS(workload_keyset)))`. */
115
+ export declare function workloadKeysetDigest(keyset: AciWorkloadKeyset): Promise<string>;
116
+ /** ACI section 3.2: the statement bytes are fixed; no JSON escaping needed. */
117
+ export declare function reportDataFor(keysetDigest: string, nonce: string | null): Promise<string>;
118
+ /**
119
+ * Structural verification of a report against the nonce it was requested
120
+ * with (ACI section 9.1 steps 2 and 3, plus the E2EE v2 capability). Throws
121
+ * E2eeAttestationError; returns the verified keyset digest.
122
+ */
123
+ export declare function verifyAciReportBinding(report: AciAttestationReport, nonce: string, nowSeconds: number): Promise<string>;
124
+ /** The X25519 suite entry (spec section 7: clients select keys by algo). */
125
+ export declare function selectX25519Key(keyset: AciWorkloadKeyset, expectedKeyId?: string): {
126
+ entry: AciKeysetEntry;
127
+ publicKey: Uint8Array;
128
+ };
129
+ /**
130
+ * Fetch, verify and select the gateway's E2EE key. Fail closed: any
131
+ * verification failure throws and no key is returned.
132
+ */
133
+ export declare function fetchGatewayE2eeKey(options: FetchGatewayE2eeKeyOptions): Promise<GatewayE2eeKey>;
134
+ //# sourceMappingURL=attestation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attestation.d.ts","sourceRoot":"","sources":["../../../src/derivatives/e2ee/attestation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AASrE,eAAO,MAAM,eAAe,UAAU,CAAC;AACvC,eAAO,MAAM,uBAAuB,uBAAuB,CAAC;AA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