@opendatalabs/personal-server-ts-core 0.0.1-canary.00328bf

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 (573) hide show
  1. package/dist/api/index.d.ts +408 -0
  2. package/dist/api/index.d.ts.map +1 -0
  3. package/dist/api/index.js +1257 -0
  4. package/dist/api/index.js.map +1 -0
  5. package/dist/api/raw-envelope.d.ts +3 -0
  6. package/dist/api/raw-envelope.d.ts.map +1 -0
  7. package/dist/api/raw-envelope.js +215 -0
  8. package/dist/api/raw-envelope.js.map +1 -0
  9. package/dist/auth/index.d.ts +2 -0
  10. package/dist/auth/index.d.ts.map +1 -0
  11. package/dist/auth/index.js +2 -0
  12. package/dist/auth/index.js.map +1 -0
  13. package/dist/auth/request.d.ts +28 -0
  14. package/dist/auth/request.d.ts.map +1 -0
  15. package/dist/auth/request.js +106 -0
  16. package/dist/auth/request.js.map +1 -0
  17. package/dist/client.d.ts +233 -0
  18. package/dist/client.d.ts.map +1 -0
  19. package/dist/client.js +243 -0
  20. package/dist/client.js.map +1 -0
  21. package/dist/config/defaults.d.ts +12 -0
  22. package/dist/config/defaults.d.ts.map +1 -0
  23. package/dist/config/defaults.js +12 -0
  24. package/dist/config/defaults.js.map +1 -0
  25. package/dist/config/index.d.ts +3 -0
  26. package/dist/config/index.d.ts.map +1 -0
  27. package/dist/config/index.js +3 -0
  28. package/dist/config/index.js.map +1 -0
  29. package/dist/config/paths.d.ts +9 -0
  30. package/dist/config/paths.d.ts.map +1 -0
  31. package/dist/config/paths.js +14 -0
  32. package/dist/config/paths.js.map +1 -0
  33. package/dist/contracts/access-logs.d.ts +8 -0
  34. package/dist/contracts/access-logs.d.ts.map +1 -0
  35. package/dist/contracts/access-logs.js +7 -0
  36. package/dist/contracts/access-logs.js.map +1 -0
  37. package/dist/contracts/auth-device.d.ts +70 -0
  38. package/dist/contracts/auth-device.d.ts.map +1 -0
  39. package/dist/contracts/auth-device.js +163 -0
  40. package/dist/contracts/auth-device.js.map +1 -0
  41. package/dist/contracts/binary.d.ts +66 -0
  42. package/dist/contracts/binary.d.ts.map +1 -0
  43. package/dist/contracts/binary.js +123 -0
  44. package/dist/contracts/binary.js.map +1 -0
  45. package/dist/contracts/config.d.ts +5 -0
  46. package/dist/contracts/config.d.ts.map +1 -0
  47. package/dist/contracts/config.js +30 -0
  48. package/dist/contracts/config.js.map +1 -0
  49. package/dist/contracts/data.d.ts +165 -0
  50. package/dist/contracts/data.d.ts.map +1 -0
  51. package/dist/contracts/data.js +371 -0
  52. package/dist/contracts/data.js.map +1 -0
  53. package/dist/contracts/grants.d.ts +45 -0
  54. package/dist/contracts/grants.d.ts.map +1 -0
  55. package/dist/contracts/grants.js +177 -0
  56. package/dist/contracts/grants.js.map +1 -0
  57. package/dist/contracts/http.d.ts +21 -0
  58. package/dist/contracts/http.d.ts.map +1 -0
  59. package/dist/contracts/http.js +49 -0
  60. package/dist/contracts/http.js.map +1 -0
  61. package/dist/contracts/index.d.ts +16 -0
  62. package/dist/contracts/index.d.ts.map +1 -0
  63. package/dist/contracts/index.js +10 -0
  64. package/dist/contracts/index.js.map +1 -0
  65. package/dist/contracts/oauth.d.ts +38 -0
  66. package/dist/contracts/oauth.d.ts.map +1 -0
  67. package/dist/contracts/oauth.js +130 -0
  68. package/dist/contracts/oauth.js.map +1 -0
  69. package/dist/contracts/sync.d.ts +10 -0
  70. package/dist/contracts/sync.d.ts.map +1 -0
  71. package/dist/contracts/sync.js +35 -0
  72. package/dist/contracts/sync.js.map +1 -0
  73. package/dist/derivatives/answer-shape.d.ts +83 -0
  74. package/dist/derivatives/answer-shape.d.ts.map +1 -0
  75. package/dist/derivatives/answer-shape.js +320 -0
  76. package/dist/derivatives/answer-shape.js.map +1 -0
  77. package/dist/derivatives/api.d.ts +48 -0
  78. package/dist/derivatives/api.d.ts.map +1 -0
  79. package/dist/derivatives/api.js +374 -0
  80. package/dist/derivatives/api.js.map +1 -0
  81. package/dist/derivatives/compute.d.ts +112 -0
  82. package/dist/derivatives/compute.d.ts.map +1 -0
  83. package/dist/derivatives/compute.js +476 -0
  84. package/dist/derivatives/compute.js.map +1 -0
  85. package/dist/derivatives/e2ee/aad.d.ts +22 -0
  86. package/dist/derivatives/e2ee/aad.d.ts.map +1 -0
  87. package/dist/derivatives/e2ee/aad.js +32 -0
  88. package/dist/derivatives/e2ee/aad.js.map +1 -0
  89. package/dist/derivatives/e2ee/attestation.d.ts +134 -0
  90. package/dist/derivatives/e2ee/attestation.d.ts.map +1 -0
  91. package/dist/derivatives/e2ee/attestation.js +248 -0
  92. package/dist/derivatives/e2ee/attestation.js.map +1 -0
  93. package/dist/derivatives/e2ee/index.d.ts +6 -0
  94. package/dist/derivatives/e2ee/index.d.ts.map +1 -0
  95. package/dist/derivatives/e2ee/index.js +6 -0
  96. package/dist/derivatives/e2ee/index.js.map +1 -0
  97. package/dist/derivatives/e2ee/jcs.d.ts +17 -0
  98. package/dist/derivatives/e2ee/jcs.d.ts.map +1 -0
  99. package/dist/derivatives/e2ee/jcs.js +55 -0
  100. package/dist/derivatives/e2ee/jcs.js.map +1 -0
  101. package/dist/derivatives/e2ee/phala.d.ts +62 -0
  102. package/dist/derivatives/e2ee/phala.d.ts.map +1 -0
  103. package/dist/derivatives/e2ee/phala.js +168 -0
  104. package/dist/derivatives/e2ee/phala.js.map +1 -0
  105. package/dist/derivatives/e2ee/suite.d.ts +56 -0
  106. package/dist/derivatives/e2ee/suite.d.ts.map +1 -0
  107. package/dist/derivatives/e2ee/suite.js +164 -0
  108. package/dist/derivatives/e2ee/suite.js.map +1 -0
  109. package/dist/derivatives/index.d.ts +11 -0
  110. package/dist/derivatives/index.d.ts.map +1 -0
  111. package/dist/derivatives/index.js +11 -0
  112. package/dist/derivatives/index.js.map +1 -0
  113. package/dist/derivatives/inference.d.ts +151 -0
  114. package/dist/derivatives/inference.d.ts.map +1 -0
  115. package/dist/derivatives/inference.js +262 -0
  116. package/dist/derivatives/inference.js.map +1 -0
  117. package/dist/derivatives/prompt.d.ts +99 -0
  118. package/dist/derivatives/prompt.d.ts.map +1 -0
  119. package/dist/derivatives/prompt.js +281 -0
  120. package/dist/derivatives/prompt.js.map +1 -0
  121. package/dist/derivatives/registration.d.ts +56 -0
  122. package/dist/derivatives/registration.d.ts.map +1 -0
  123. package/dist/derivatives/registration.js +187 -0
  124. package/dist/derivatives/registration.js.map +1 -0
  125. package/dist/derivatives/scheduler.d.ts +114 -0
  126. package/dist/derivatives/scheduler.d.ts.map +1 -0
  127. package/dist/derivatives/scheduler.js +331 -0
  128. package/dist/derivatives/scheduler.js.map +1 -0
  129. package/dist/derivatives/store.d.ts +14 -0
  130. package/dist/derivatives/store.d.ts.map +1 -0
  131. package/dist/derivatives/store.js +79 -0
  132. package/dist/derivatives/store.js.map +1 -0
  133. package/dist/derivatives/types.d.ts +102 -0
  134. package/dist/derivatives/types.d.ts.map +1 -0
  135. package/dist/derivatives/types.js +29 -0
  136. package/dist/derivatives/types.js.map +1 -0
  137. package/dist/errors/catalog.d.ts +125 -0
  138. package/dist/errors/catalog.d.ts.map +1 -0
  139. package/dist/errors/catalog.js +198 -0
  140. package/dist/errors/catalog.js.map +1 -0
  141. package/dist/errors/pdpp-catalog.d.ts +36 -0
  142. package/dist/errors/pdpp-catalog.d.ts.map +1 -0
  143. package/dist/errors/pdpp-catalog.js +82 -0
  144. package/dist/errors/pdpp-catalog.js.map +1 -0
  145. package/dist/grants/index.d.ts +5 -0
  146. package/dist/grants/index.d.ts.map +1 -0
  147. package/dist/grants/index.js +6 -0
  148. package/dist/grants/index.js.map +1 -0
  149. package/dist/grants/pdpp-binding-store.d.ts +58 -0
  150. package/dist/grants/pdpp-binding-store.d.ts.map +1 -0
  151. package/dist/grants/pdpp-binding-store.js +97 -0
  152. package/dist/grants/pdpp-binding-store.js.map +1 -0
  153. package/dist/grants/pdpp-binding.d.ts +179 -0
  154. package/dist/grants/pdpp-binding.d.ts.map +1 -0
  155. package/dist/grants/pdpp-binding.js +214 -0
  156. package/dist/grants/pdpp-binding.js.map +1 -0
  157. package/dist/keys/index.d.ts +3 -0
  158. package/dist/keys/index.d.ts.map +1 -0
  159. package/dist/keys/index.js +2 -0
  160. package/dist/keys/index.js.map +1 -0
  161. package/dist/keys/public-only-account.d.ts +8 -0
  162. package/dist/keys/public-only-account.d.ts.map +1 -0
  163. package/dist/keys/public-only-account.js +21 -0
  164. package/dist/keys/public-only-account.js.map +1 -0
  165. package/dist/keys/server-account.d.ts +24 -0
  166. package/dist/keys/server-account.d.ts.map +1 -0
  167. package/dist/keys/server-account.js +2 -0
  168. package/dist/keys/server-account.js.map +1 -0
  169. package/dist/lineage/attestation.d.ts +42 -0
  170. package/dist/lineage/attestation.d.ts.map +1 -0
  171. package/dist/lineage/attestation.js +25 -0
  172. package/dist/lineage/attestation.js.map +1 -0
  173. package/dist/lineage/gateway.d.ts +105 -0
  174. package/dist/lineage/gateway.d.ts.map +1 -0
  175. package/dist/lineage/gateway.js +242 -0
  176. package/dist/lineage/gateway.js.map +1 -0
  177. package/dist/lineage/index.d.ts +5 -0
  178. package/dist/lineage/index.d.ts.map +1 -0
  179. package/dist/lineage/index.js +5 -0
  180. package/dist/lineage/index.js.map +1 -0
  181. package/dist/lineage/lineage.d.ts +141 -0
  182. package/dist/lineage/lineage.d.ts.map +1 -0
  183. package/dist/lineage/lineage.js +255 -0
  184. package/dist/lineage/lineage.js.map +1 -0
  185. package/dist/logger/index.d.ts +9 -0
  186. package/dist/logger/index.d.ts.map +1 -0
  187. package/dist/logger/index.js +5 -0
  188. package/dist/logger/index.js.map +1 -0
  189. package/dist/logging/access-log.d.ts +23 -0
  190. package/dist/logging/access-log.d.ts.map +1 -0
  191. package/dist/logging/access-log.js +2 -0
  192. package/dist/logging/access-log.js.map +1 -0
  193. package/dist/logging/access-reader.d.ts +14 -0
  194. package/dist/logging/access-reader.d.ts.map +1 -0
  195. package/dist/logging/access-reader.js +2 -0
  196. package/dist/logging/access-reader.js.map +1 -0
  197. package/dist/mcp/activity.d.ts +68 -0
  198. package/dist/mcp/activity.d.ts.map +1 -0
  199. package/dist/mcp/activity.js +111 -0
  200. package/dist/mcp/activity.js.map +1 -0
  201. package/dist/mcp/builder-registration.d.ts +24 -0
  202. package/dist/mcp/builder-registration.d.ts.map +1 -0
  203. package/dist/mcp/builder-registration.js +89 -0
  204. package/dist/mcp/builder-registration.js.map +1 -0
  205. package/dist/mcp/connection-api.d.ts +201 -0
  206. package/dist/mcp/connection-api.d.ts.map +1 -0
  207. package/dist/mcp/connection-api.js +506 -0
  208. package/dist/mcp/connection-api.js.map +1 -0
  209. package/dist/mcp/grantee.d.ts +52 -0
  210. package/dist/mcp/grantee.d.ts.map +1 -0
  211. package/dist/mcp/grantee.js +91 -0
  212. package/dist/mcp/grantee.js.map +1 -0
  213. package/dist/mcp/index.d.ts +12 -0
  214. package/dist/mcp/index.d.ts.map +1 -0
  215. package/dist/mcp/index.js +12 -0
  216. package/dist/mcp/index.js.map +1 -0
  217. package/dist/mcp/read-client.d.ts +176 -0
  218. package/dist/mcp/read-client.d.ts.map +1 -0
  219. package/dist/mcp/read-client.js +579 -0
  220. package/dist/mcp/read-client.js.map +1 -0
  221. package/dist/mcp/resources.d.ts +37 -0
  222. package/dist/mcp/resources.d.ts.map +1 -0
  223. package/dist/mcp/resources.js +114 -0
  224. package/dist/mcp/resources.js.map +1 -0
  225. package/dist/mcp/search/index.d.ts +34 -0
  226. package/dist/mcp/search/index.d.ts.map +1 -0
  227. package/dist/mcp/search/index.js +156 -0
  228. package/dist/mcp/search/index.js.map +1 -0
  229. package/dist/mcp/server.d.ts +72 -0
  230. package/dist/mcp/server.d.ts.map +1 -0
  231. package/dist/mcp/server.js +447 -0
  232. package/dist/mcp/server.js.map +1 -0
  233. package/dist/mcp/session.d.ts +160 -0
  234. package/dist/mcp/session.d.ts.map +1 -0
  235. package/dist/mcp/session.js +243 -0
  236. package/dist/mcp/session.js.map +1 -0
  237. package/dist/mcp/store.d.ts +13 -0
  238. package/dist/mcp/store.d.ts.map +1 -0
  239. package/dist/mcp/store.js +119 -0
  240. package/dist/mcp/store.js.map +1 -0
  241. package/dist/mcp/token-expiry.d.ts +38 -0
  242. package/dist/mcp/token-expiry.d.ts.map +1 -0
  243. package/dist/mcp/token-expiry.js +55 -0
  244. package/dist/mcp/token-expiry.js.map +1 -0
  245. package/dist/mcp/tools.d.ts +95 -0
  246. package/dist/mcp/tools.d.ts.map +1 -0
  247. package/dist/mcp/tools.js +1381 -0
  248. package/dist/mcp/tools.js.map +1 -0
  249. package/dist/mcp/types.d.ts +135 -0
  250. package/dist/mcp/types.d.ts.map +1 -0
  251. package/dist/mcp/types.js +24 -0
  252. package/dist/mcp/types.js.map +1 -0
  253. package/dist/payment/index.d.ts +2 -0
  254. package/dist/payment/index.d.ts.map +1 -0
  255. package/dist/payment/index.js +2 -0
  256. package/dist/payment/index.js.map +1 -0
  257. package/dist/payment/x402.d.ts +155 -0
  258. package/dist/payment/x402.d.ts.map +1 -0
  259. package/dist/payment/x402.js +402 -0
  260. package/dist/payment/x402.js.map +1 -0
  261. package/dist/pdpp/approval.d.ts +182 -0
  262. package/dist/pdpp/approval.d.ts.map +1 -0
  263. package/dist/pdpp/approval.js +337 -0
  264. package/dist/pdpp/approval.js.map +1 -0
  265. package/dist/pdpp/client-identity.d.ts +88 -0
  266. package/dist/pdpp/client-identity.d.ts.map +1 -0
  267. package/dist/pdpp/client-identity.js +183 -0
  268. package/dist/pdpp/client-identity.js.map +1 -0
  269. package/dist/pdpp/client-metadata.d.ts +95 -0
  270. package/dist/pdpp/client-metadata.d.ts.map +1 -0
  271. package/dist/pdpp/client-metadata.js +96 -0
  272. package/dist/pdpp/client-metadata.js.map +1 -0
  273. package/dist/pdpp/declaration.d.ts +118 -0
  274. package/dist/pdpp/declaration.d.ts.map +1 -0
  275. package/dist/pdpp/declaration.js +549 -0
  276. package/dist/pdpp/declaration.js.map +1 -0
  277. package/dist/pdpp/index.d.ts +35 -0
  278. package/dist/pdpp/index.d.ts.map +1 -0
  279. package/dist/pdpp/index.js +22 -0
  280. package/dist/pdpp/index.js.map +1 -0
  281. package/dist/pdpp/issuance.d.ts +91 -0
  282. package/dist/pdpp/issuance.d.ts.map +1 -0
  283. package/dist/pdpp/issuance.js +124 -0
  284. package/dist/pdpp/issuance.js.map +1 -0
  285. package/dist/pdpp/pkce.d.ts +53 -0
  286. package/dist/pdpp/pkce.d.ts.map +1 -0
  287. package/dist/pdpp/pkce.js +109 -0
  288. package/dist/pdpp/pkce.js.map +1 -0
  289. package/dist/pdpp/redirect.d.ts +60 -0
  290. package/dist/pdpp/redirect.d.ts.map +1 -0
  291. package/dist/pdpp/redirect.js +125 -0
  292. package/dist/pdpp/redirect.js.map +1 -0
  293. package/dist/pdpp/resolve.d.ts +53 -0
  294. package/dist/pdpp/resolve.d.ts.map +1 -0
  295. package/dist/pdpp/resolve.js +218 -0
  296. package/dist/pdpp/resolve.js.map +1 -0
  297. package/dist/pdpp/review.d.ts +155 -0
  298. package/dist/pdpp/review.d.ts.map +1 -0
  299. package/dist/pdpp/review.js +142 -0
  300. package/dist/pdpp/review.js.map +1 -0
  301. package/dist/pdpp/selection.d.ts +43 -0
  302. package/dist/pdpp/selection.d.ts.map +1 -0
  303. package/dist/pdpp/selection.js +211 -0
  304. package/dist/pdpp/selection.js.map +1 -0
  305. package/dist/pdpp/store.d.ts +204 -0
  306. package/dist/pdpp/store.d.ts.map +1 -0
  307. package/dist/pdpp/store.js +501 -0
  308. package/dist/pdpp/store.js.map +1 -0
  309. package/dist/pdpp/tokens.d.ts +149 -0
  310. package/dist/pdpp/tokens.d.ts.map +1 -0
  311. package/dist/pdpp/tokens.js +387 -0
  312. package/dist/pdpp/tokens.js.map +1 -0
  313. package/dist/pdpp/types.d.ts +258 -0
  314. package/dist/pdpp/types.d.ts.map +1 -0
  315. package/dist/pdpp/types.js +40 -0
  316. package/dist/pdpp/types.js.map +1 -0
  317. package/dist/pdpp-version.d.ts +28 -0
  318. package/dist/pdpp-version.d.ts.map +1 -0
  319. package/dist/pdpp-version.js +28 -0
  320. package/dist/pdpp-version.js.map +1 -0
  321. package/dist/policy/data-read.d.ts +56 -0
  322. package/dist/policy/data-read.d.ts.map +1 -0
  323. package/dist/policy/data-read.js +176 -0
  324. package/dist/policy/data-read.js.map +1 -0
  325. package/dist/policy/data-write.d.ts +69 -0
  326. package/dist/policy/data-write.d.ts.map +1 -0
  327. package/dist/policy/data-write.js +131 -0
  328. package/dist/policy/data-write.js.map +1 -0
  329. package/dist/policy/index.d.ts +4 -0
  330. package/dist/policy/index.d.ts.map +1 -0
  331. package/dist/policy/index.js +4 -0
  332. package/dist/policy/index.js.map +1 -0
  333. package/dist/policy/signed-artifacts.d.ts +17 -0
  334. package/dist/policy/signed-artifacts.d.ts.map +1 -0
  335. package/dist/policy/signed-artifacts.js +110 -0
  336. package/dist/policy/signed-artifacts.js.map +1 -0
  337. package/dist/ports/index.d.ts +243 -0
  338. package/dist/ports/index.d.ts.map +1 -0
  339. package/dist/ports/index.js +7 -0
  340. package/dist/ports/index.js.map +1 -0
  341. package/dist/ports/pdpp-auth.d.ts +103 -0
  342. package/dist/ports/pdpp-auth.d.ts.map +1 -0
  343. package/dist/ports/pdpp-auth.js +37 -0
  344. package/dist/ports/pdpp-auth.js.map +1 -0
  345. package/dist/ports/pdpp-auth.test-utils.d.ts +9 -0
  346. package/dist/ports/pdpp-auth.test-utils.d.ts.map +1 -0
  347. package/dist/ports/pdpp-auth.test-utils.js +18 -0
  348. package/dist/ports/pdpp-auth.test-utils.js.map +1 -0
  349. package/dist/schemas/server-config.d.ts +190 -0
  350. package/dist/schemas/server-config.d.ts.map +1 -0
  351. package/dist/schemas/server-config.js +282 -0
  352. package/dist/schemas/server-config.js.map +1 -0
  353. package/dist/signing/index.d.ts +3 -0
  354. package/dist/signing/index.d.ts.map +1 -0
  355. package/dist/signing/index.js +3 -0
  356. package/dist/signing/index.js.map +1 -0
  357. package/dist/signing/request-signer.d.ts +20 -0
  358. package/dist/signing/request-signer.d.ts.map +1 -0
  359. package/dist/signing/request-signer.js +23 -0
  360. package/dist/signing/request-signer.js.map +1 -0
  361. package/dist/signing/signer.d.ts +40 -0
  362. package/dist/signing/signer.d.ts.map +1 -0
  363. package/dist/signing/signer.js +56 -0
  364. package/dist/signing/signer.js.map +1 -0
  365. package/dist/storage/adapters/index.d.ts +4 -0
  366. package/dist/storage/adapters/index.d.ts.map +1 -0
  367. package/dist/storage/adapters/index.js +3 -0
  368. package/dist/storage/adapters/index.js.map +1 -0
  369. package/dist/storage/adapters/interface.d.ts +57 -0
  370. package/dist/storage/adapters/interface.d.ts.map +1 -0
  371. package/dist/storage/adapters/interface.js +2 -0
  372. package/dist/storage/adapters/interface.js.map +1 -0
  373. package/dist/storage/adapters/sdk.d.ts +23 -0
  374. package/dist/storage/adapters/sdk.d.ts.map +1 -0
  375. package/dist/storage/adapters/sdk.js +73 -0
  376. package/dist/storage/adapters/sdk.js.map +1 -0
  377. package/dist/storage/adapters/vana.d.ts +12 -0
  378. package/dist/storage/adapters/vana.d.ts.map +1 -0
  379. package/dist/storage/adapters/vana.js +111 -0
  380. package/dist/storage/adapters/vana.js.map +1 -0
  381. package/dist/storage/blocks/build.d.ts +20 -0
  382. package/dist/storage/blocks/build.d.ts.map +1 -0
  383. package/dist/storage/blocks/build.js +378 -0
  384. package/dist/storage/blocks/build.js.map +1 -0
  385. package/dist/storage/blocks/cursor.d.ts +33 -0
  386. package/dist/storage/blocks/cursor.d.ts.map +1 -0
  387. package/dist/storage/blocks/cursor.js +142 -0
  388. package/dist/storage/blocks/cursor.js.map +1 -0
  389. package/dist/storage/blocks/errors.d.ts +6 -0
  390. package/dist/storage/blocks/errors.d.ts.map +1 -0
  391. package/dist/storage/blocks/errors.js +9 -0
  392. package/dist/storage/blocks/errors.js.map +1 -0
  393. package/dist/storage/blocks/index.d.ts +6 -0
  394. package/dist/storage/blocks/index.d.ts.map +1 -0
  395. package/dist/storage/blocks/index.js +5 -0
  396. package/dist/storage/blocks/index.js.map +1 -0
  397. package/dist/storage/blocks/select.d.ts +29 -0
  398. package/dist/storage/blocks/select.d.ts.map +1 -0
  399. package/dist/storage/blocks/select.js +120 -0
  400. package/dist/storage/blocks/select.js.map +1 -0
  401. package/dist/storage/blocks/types.d.ts +56 -0
  402. package/dist/storage/blocks/types.d.ts.map +1 -0
  403. package/dist/storage/blocks/types.js +2 -0
  404. package/dist/storage/blocks/types.js.map +1 -0
  405. package/dist/storage/hierarchy/index.d.ts +3 -0
  406. package/dist/storage/hierarchy/index.d.ts.map +1 -0
  407. package/dist/storage/hierarchy/index.js +2 -0
  408. package/dist/storage/hierarchy/index.js.map +1 -0
  409. package/dist/storage/hierarchy/manager.d.ts +9 -0
  410. package/dist/storage/hierarchy/manager.d.ts.map +1 -0
  411. package/dist/storage/hierarchy/manager.js +2 -0
  412. package/dist/storage/hierarchy/manager.js.map +1 -0
  413. package/dist/storage/hierarchy/paths.d.ts +11 -0
  414. package/dist/storage/hierarchy/paths.d.ts.map +1 -0
  415. package/dist/storage/hierarchy/paths.js +43 -0
  416. package/dist/storage/hierarchy/paths.js.map +1 -0
  417. package/dist/storage/index/index.d.ts +3 -0
  418. package/dist/storage/index/index.d.ts.map +1 -0
  419. package/dist/storage/index/index.js +2 -0
  420. package/dist/storage/index/index.js.map +1 -0
  421. package/dist/storage/index/manager.d.ts +63 -0
  422. package/dist/storage/index/manager.d.ts.map +1 -0
  423. package/dist/storage/index/manager.js +2 -0
  424. package/dist/storage/index/manager.js.map +1 -0
  425. package/dist/storage/index/schema.d.ts +2 -0
  426. package/dist/storage/index/schema.d.ts.map +1 -0
  427. package/dist/storage/index/schema.js +2 -0
  428. package/dist/storage/index/schema.js.map +1 -0
  429. package/dist/storage/index/types.d.ts +37 -0
  430. package/dist/storage/index/types.d.ts.map +1 -0
  431. package/dist/storage/index/types.js +2 -0
  432. package/dist/storage/index/types.js.map +1 -0
  433. package/dist/storage/pdpp-records/cursor.d.ts +27 -0
  434. package/dist/storage/pdpp-records/cursor.d.ts.map +1 -0
  435. package/dist/storage/pdpp-records/cursor.js +49 -0
  436. package/dist/storage/pdpp-records/cursor.js.map +1 -0
  437. package/dist/storage/pdpp-records/enforcement.d.ts +37 -0
  438. package/dist/storage/pdpp-records/enforcement.d.ts.map +1 -0
  439. package/dist/storage/pdpp-records/enforcement.js +79 -0
  440. package/dist/storage/pdpp-records/enforcement.js.map +1 -0
  441. package/dist/storage/pdpp-records/index.d.ts +8 -0
  442. package/dist/storage/pdpp-records/index.d.ts.map +1 -0
  443. package/dist/storage/pdpp-records/index.js +8 -0
  444. package/dist/storage/pdpp-records/index.js.map +1 -0
  445. package/dist/storage/pdpp-records/interface.d.ts +49 -0
  446. package/dist/storage/pdpp-records/interface.d.ts.map +1 -0
  447. package/dist/storage/pdpp-records/interface.js +2 -0
  448. package/dist/storage/pdpp-records/interface.js.map +1 -0
  449. package/dist/storage/pdpp-records/memory-store.d.ts +9 -0
  450. package/dist/storage/pdpp-records/memory-store.d.ts.map +1 -0
  451. package/dist/storage/pdpp-records/memory-store.js +0 -0
  452. package/dist/storage/pdpp-records/memory-store.js.map +1 -0
  453. package/dist/storage/pdpp-records/record-key.d.ts +52 -0
  454. package/dist/storage/pdpp-records/record-key.d.ts.map +1 -0
  455. package/dist/storage/pdpp-records/record-key.js +97 -0
  456. package/dist/storage/pdpp-records/record-key.js.map +1 -0
  457. package/dist/storage/pdpp-records/stream-declaration.d.ts +43 -0
  458. package/dist/storage/pdpp-records/stream-declaration.d.ts.map +1 -0
  459. package/dist/storage/pdpp-records/stream-declaration.js +17 -0
  460. package/dist/storage/pdpp-records/stream-declaration.js.map +1 -0
  461. package/dist/storage/pdpp-records/types.d.ts +93 -0
  462. package/dist/storage/pdpp-records/types.d.ts.map +1 -0
  463. package/dist/storage/pdpp-records/types.js +17 -0
  464. package/dist/storage/pdpp-records/types.js.map +1 -0
  465. package/dist/storage/preview.d.ts +12 -0
  466. package/dist/storage/preview.d.ts.map +1 -0
  467. package/dist/storage/preview.js +239 -0
  468. package/dist/storage/preview.js.map +1 -0
  469. package/dist/sync/cursor.d.ts +10 -0
  470. package/dist/sync/cursor.d.ts.map +1 -0
  471. package/dist/sync/cursor.js +2 -0
  472. package/dist/sync/cursor.js.map +1 -0
  473. package/dist/sync/data-point-feed.d.ts +35 -0
  474. package/dist/sync/data-point-feed.d.ts.map +1 -0
  475. package/dist/sync/data-point-feed.js +122 -0
  476. package/dist/sync/data-point-feed.js.map +1 -0
  477. package/dist/sync/data-point-id.d.ts +7 -0
  478. package/dist/sync/data-point-id.d.ts.map +1 -0
  479. package/dist/sync/data-point-id.js +16 -0
  480. package/dist/sync/data-point-id.js.map +1 -0
  481. package/dist/sync/delete-data-port.d.ts +50 -0
  482. package/dist/sync/delete-data-port.d.ts.map +1 -0
  483. package/dist/sync/delete-data-port.js +244 -0
  484. package/dist/sync/delete-data-port.js.map +1 -0
  485. package/dist/sync/engine/sync-manager.d.ts +58 -0
  486. package/dist/sync/engine/sync-manager.d.ts.map +1 -0
  487. package/dist/sync/engine/sync-manager.js +285 -0
  488. package/dist/sync/engine/sync-manager.js.map +1 -0
  489. package/dist/sync/index.d.ts +15 -0
  490. package/dist/sync/index.d.ts.map +1 -0
  491. package/dist/sync/index.js +14 -0
  492. package/dist/sync/index.js.map +1 -0
  493. package/dist/sync/issues.d.ts +55 -0
  494. package/dist/sync/issues.d.ts.map +1 -0
  495. package/dist/sync/issues.js +168 -0
  496. package/dist/sync/issues.js.map +1 -0
  497. package/dist/sync/pdpp-import.d.ts +192 -0
  498. package/dist/sync/pdpp-import.d.ts.map +1 -0
  499. package/dist/sync/pdpp-import.js +422 -0
  500. package/dist/sync/pdpp-import.js.map +1 -0
  501. package/dist/sync/pending-blob-deletions.d.ts +29 -0
  502. package/dist/sync/pending-blob-deletions.d.ts.map +1 -0
  503. package/dist/sync/pending-blob-deletions.js +116 -0
  504. package/dist/sync/pending-blob-deletions.js.map +1 -0
  505. package/dist/sync/retry-memory.d.ts +33 -0
  506. package/dist/sync/retry-memory.d.ts.map +1 -0
  507. package/dist/sync/retry-memory.js +68 -0
  508. package/dist/sync/retry-memory.js.map +1 -0
  509. package/dist/sync/scope-deletions.d.ts +155 -0
  510. package/dist/sync/scope-deletions.d.ts.map +1 -0
  511. package/dist/sync/scope-deletions.js +225 -0
  512. package/dist/sync/scope-deletions.js.map +1 -0
  513. package/dist/sync/tombstone.d.ts +27 -0
  514. package/dist/sync/tombstone.d.ts.map +1 -0
  515. package/dist/sync/tombstone.js +28 -0
  516. package/dist/sync/tombstone.js.map +1 -0
  517. package/dist/sync/types.d.ts +27 -0
  518. package/dist/sync/types.d.ts.map +1 -0
  519. package/dist/sync/types.js +2 -0
  520. package/dist/sync/types.js.map +1 -0
  521. package/dist/sync/workers/delete.d.ts +163 -0
  522. package/dist/sync/workers/delete.d.ts.map +1 -0
  523. package/dist/sync/workers/delete.js +474 -0
  524. package/dist/sync/workers/delete.js.map +1 -0
  525. package/dist/sync/workers/download.d.ts +159 -0
  526. package/dist/sync/workers/download.d.ts.map +1 -0
  527. package/dist/sync/workers/download.js +731 -0
  528. package/dist/sync/workers/download.js.map +1 -0
  529. package/dist/sync/workers/upload.d.ts +98 -0
  530. package/dist/sync/workers/upload.d.ts.map +1 -0
  531. package/dist/sync/workers/upload.js +412 -0
  532. package/dist/sync/workers/upload.js.map +1 -0
  533. package/dist/test-utils/e2ee-fixtures.d.ts +94 -0
  534. package/dist/test-utils/e2ee-fixtures.d.ts.map +1 -0
  535. package/dist/test-utils/e2ee-fixtures.js +116 -0
  536. package/dist/test-utils/e2ee-fixtures.js.map +1 -0
  537. package/dist/test-utils/e2ee-gateway.d.ts +61 -0
  538. package/dist/test-utils/e2ee-gateway.d.ts.map +1 -0
  539. package/dist/test-utils/e2ee-gateway.js +248 -0
  540. package/dist/test-utils/e2ee-gateway.js.map +1 -0
  541. package/dist/test-utils/index.d.ts +5 -0
  542. package/dist/test-utils/index.d.ts.map +1 -0
  543. package/dist/test-utils/index.js +5 -0
  544. package/dist/test-utils/index.js.map +1 -0
  545. package/dist/test-utils/memory-storage.d.ts +12 -0
  546. package/dist/test-utils/memory-storage.d.ts.map +1 -0
  547. package/dist/test-utils/memory-storage.js +146 -0
  548. package/dist/test-utils/memory-storage.js.map +1 -0
  549. package/dist/test-utils/wallet.d.ts +47 -0
  550. package/dist/test-utils/wallet.d.ts.map +1 -0
  551. package/dist/test-utils/wallet.js +98 -0
  552. package/dist/test-utils/wallet.js.map +1 -0
  553. package/dist/write/attribution.d.ts +185 -0
  554. package/dist/write/attribution.d.ts.map +1 -0
  555. package/dist/write/attribution.js +450 -0
  556. package/dist/write/attribution.js.map +1 -0
  557. package/dist/write/authorize.d.ts +77 -0
  558. package/dist/write/authorize.d.ts.map +1 -0
  559. package/dist/write/authorize.js +109 -0
  560. package/dist/write/authorize.js.map +1 -0
  561. package/dist/write/index.d.ts +5 -0
  562. package/dist/write/index.d.ts.map +1 -0
  563. package/dist/write/index.js +5 -0
  564. package/dist/write/index.js.map +1 -0
  565. package/dist/write/route.d.ts +61 -0
  566. package/dist/write/route.d.ts.map +1 -0
  567. package/dist/write/route.js +132 -0
  568. package/dist/write/route.js.map +1 -0
  569. package/dist/write/session.d.ts +96 -0
  570. package/dist/write/session.d.ts.map +1 -0
  571. package/dist/write/session.js +136 -0
  572. package/dist/write/session.js.map +1 -0
  573. package/package.json +175 -0
@@ -0,0 +1,1257 @@
1
+ import { DataDeletedError, DeleteTombstoneFailedError, GrantRequiredError, InvalidCascadeError, LineageCascadeUnavailableError, LineageGatewayError, LineageUnavailableError, ProtocolError, ServerNotConfiguredError, } from "../errors/catalog.js";
2
+ import { computeDataPointId } from "../sync/data-point-id.js";
3
+ import { isEntryCoveredByTombstone, } from "../sync/scope-deletions.js";
4
+ import { deleteScope as deleteScopeLocally, } from "../sync/workers/delete.js";
5
+ import { ingestDataContract, ingestBinaryDataContract, listAccessLogsContract, listDataScopesContract, listDataVersionsContract, parseDataScopeContract, parseJsonObjectBody, readDataContract, syncFileContract, triggerSyncContract, getSyncStatusContract, configReadErrorContract, configWriteErrorContract, createGrantContract, listGrantsContract, oauthTokenContract, revokeGrantContract, validateServerConfigContract, verifyGrantContract, decodeBinaryEnvelope, isBinaryEnvelope, parseMetadataHeader, stringifyMetadataHeader, IngestPersistedError, } from "../contracts/index.js";
6
+ import { WRITER_ATTRIBUTION_KEY, } from "../write/attribution.js";
7
+ import { extractLineageField, LINEAGE_KEY, prepareLineage, } from "../lineage/lineage.js";
8
+ import { binaryFilename, binaryMimeType, isJsonContentType, } from "../contracts/binary.js";
9
+ import { buildChallenge, parsePaymentHeader, verifyPayment, } from "../payment/index.js";
10
+ /**
11
+ * Stand-in for a grant/grantee that does not exist on a denial — a scope that
12
+ * no grant covers has no grant id and no builder to attribute the read to.
13
+ */
14
+ export const READ_FULFILLMENT_NONE = "none";
15
+ function jsonResponse(body, init) {
16
+ const headers = new Headers(init?.headers);
17
+ headers.set("Content-Type", "application/json");
18
+ return new Response(JSON.stringify(body), { ...init, headers });
19
+ }
20
+ // X402 spec convention: payment responses are JSON, base64-encoded into a
21
+ // single header value. Returns undefined on encode failure so callers can
22
+ // just omit the header rather than fail the read. Uses btoa + TextEncoder
23
+ // to stay portable across Node and web runtimes.
24
+ function encodePaymentResponseHeader(body) {
25
+ try {
26
+ const json = JSON.stringify(body ?? null);
27
+ const bytes = new TextEncoder().encode(json);
28
+ let binary = "";
29
+ for (const b of bytes)
30
+ binary += String.fromCharCode(b);
31
+ return btoa(binary);
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ function contractResponse(result) {
38
+ return jsonResponse(result.body, { status: result.status });
39
+ }
40
+ function contractErrorResponse(err) {
41
+ return jsonResponse(err.body, { status: err.status });
42
+ }
43
+ function protocolErrorResponse(err) {
44
+ return jsonResponse(err.toJSON(), { status: err.code });
45
+ }
46
+ function errorResponse(status, errorCode, message) {
47
+ return jsonResponse({
48
+ error: {
49
+ code: status,
50
+ errorCode,
51
+ message,
52
+ },
53
+ }, { status });
54
+ }
55
+ function methodNotAllowed() {
56
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
57
+ }
58
+ function notFound() {
59
+ return errorResponse(404, "NOT_FOUND", "Not found");
60
+ }
61
+ async function withApiErrors(handler) {
62
+ try {
63
+ return await handler();
64
+ }
65
+ catch (err) {
66
+ if (err instanceof ProtocolError) {
67
+ return protocolErrorResponse(err);
68
+ }
69
+ return errorResponse(500, "INTERNAL_ERROR", "Internal server error");
70
+ }
71
+ }
72
+ function normalizeLimit(value, fallback) {
73
+ if (value === null)
74
+ return fallback;
75
+ const parsed = Number(value);
76
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
77
+ }
78
+ function stripBasePath(pathname, basePath) {
79
+ if (!basePath || basePath === "/")
80
+ return pathname;
81
+ if (pathname === basePath)
82
+ return "/";
83
+ if (pathname.startsWith(`${basePath}/`)) {
84
+ return pathname.slice(basePath.length);
85
+ }
86
+ return pathname;
87
+ }
88
+ function decodePathPart(value) {
89
+ return decodeURIComponent(value ?? "");
90
+ }
91
+ /**
92
+ * The grant the caller nominates for a read: `?grantId=` or the
93
+ * `x-ps-grant-id` header, the SDK's shape on every read route. Exported so
94
+ * the derivatives status route authorizes with exactly the same inputs as
95
+ * a data read — a credential that reads /v1/data/<scope> must not be
96
+ * refused by /v1/derivatives/status.
97
+ */
98
+ export function selectedGrantId(request, url) {
99
+ return (url.searchParams.get("grantId") ??
100
+ request.headers.get("x-ps-grant-id") ??
101
+ undefined);
102
+ }
103
+ /**
104
+ * Run the X402 dispatch for one read:
105
+ *
106
+ * X-PAYMENT absent / malformed / fails local validation
107
+ * → challenge: fresh 402 with current fee + accessRecord
108
+ * X-PAYMENT valid, forward to gateway succeeds
109
+ * → ok: caller proceeds to read the data
110
+ * X-PAYMENT valid, gateway returns 4xx/5xx
111
+ * → gateway-error: relay the gateway's body verbatim so the builder
112
+ * can dispatch (insufficient balance vs. replay vs. race etc.)
113
+ *
114
+ * The gateway POST goes through `fetch` directly (not `gateway.payForOperation`)
115
+ * because the SDK client throws plain Errors and loses the body — which is
116
+ * exactly what we need to distinguish gateway 402 (insufficient balance) from
117
+ * 409 (replay) from 400 (amount mismatch).
118
+ */
119
+ export async function handleX402Cycle(input) {
120
+ const { deps, gateway, gatewayConfig, gatewayUrl, builder, scope } = input;
121
+ // The gateway lowercases opId before EIP-712 recovery — we must do the
122
+ // same in the challenge so the builder signs over the canonical form.
123
+ const opIdLower = input.grantId.toLowerCase();
124
+ // Live grant — re-fetched every cycle. The fee.totalDue is a snapshot
125
+ // (SDK comment: "clients shouldn't cache"); paymentStatus may have just
126
+ // flipped if a concurrent payer paid the registration fee.
127
+ const grant = await gateway.getGrant(opIdLower);
128
+ if (!grant) {
129
+ return {
130
+ kind: "challenge",
131
+ body: {
132
+ x402Version: 1,
133
+ error: "PAYMENT_REQUIRED",
134
+ accepts: [],
135
+ },
136
+ };
137
+ }
138
+ // Bind the accessRecord to the entry being served, if it exists and has
139
+ // been registered with DPv2 yet.
140
+ const entryRow = deps.storage.findEntry({
141
+ scope,
142
+ fileId: input.fileIdParam,
143
+ at: input.atParam,
144
+ });
145
+ const entryForChallenge = entryRow
146
+ ? {
147
+ dataPointId: entryRow.dataPointId,
148
+ scope,
149
+ version: entryRow.version,
150
+ }
151
+ : undefined;
152
+ // `grant` is narrowed to non-null above, but that narrowing is not carried
153
+ // into this closure (vana-sdk 3.14.0 made getGrant return `... | null`), so
154
+ // capture the guaranteed-present value via a typed alias for the closure.
155
+ const liveGrant = grant;
156
+ async function buildFreshChallenge() {
157
+ return buildChallenge({
158
+ builder,
159
+ grantId: opIdLower,
160
+ grant: liveGrant,
161
+ network: deps.network ?? `vana:${gatewayConfig.chainId}`,
162
+ gatewayConfig,
163
+ serverSigner: deps.serverSigner,
164
+ serverOwner: deps.serverOwner,
165
+ entry: entryForChallenge,
166
+ generateNonce: deps.generatePaymentNonce,
167
+ generateRecordIdFn: deps.generateRecordId,
168
+ now: deps.now,
169
+ });
170
+ }
171
+ const headerValue = input.request.headers.get("x-payment");
172
+ const parsed = parsePaymentHeader(headerValue);
173
+ if (!parsed) {
174
+ return { kind: "challenge", body: await buildFreshChallenge() };
175
+ }
176
+ if (!deps.serverAddress) {
177
+ // Can't validate accessRecord recovery without our own address; fail
178
+ // closed by reissuing a challenge.
179
+ deps.logger?.error?.({ scope, grantId: opIdLower }, "X402 enabled but serverAddress is not configured — cannot verify accessRecord");
180
+ return { kind: "challenge", body: await buildFreshChallenge() };
181
+ }
182
+ const verify = await verifyPayment({
183
+ builder,
184
+ grantId: opIdLower,
185
+ grant,
186
+ entry: entryForChallenge,
187
+ serverAddress: deps.serverAddress,
188
+ gatewayConfig,
189
+ serverOwner: deps.serverOwner,
190
+ payment: parsed,
191
+ });
192
+ if (!verify.ok) {
193
+ deps.logger?.info?.({ scope, grantId: opIdLower, reason: verify.reason }, "X402 payment verification failed; reissuing challenge");
194
+ return { kind: "challenge", body: await buildFreshChallenge() };
195
+ }
196
+ // Forward to gateway via direct fetch (preserves error body). The SDK
197
+ // client wraps the same endpoint but throws away the structured response
198
+ // on non-2xx, which is exactly the info we need to distinguish gateway
199
+ // 402 (insufficient balance) from 409 (replay / race) from 400 (mismatch).
200
+ const doFetch = deps.paymentFetch ?? fetch;
201
+ const body = {
202
+ payerAddress: verify.payment.payload.message.payerAddress,
203
+ opType: verify.payment.payload.message.opType,
204
+ opId: verify.payment.payload.message.opId,
205
+ asset: verify.payment.payload.message.asset,
206
+ amount: verify.payment.payload.message.amount,
207
+ paymentNonce: verify.payment.payload.message.paymentNonce,
208
+ };
209
+ if (verify.payment.payload.accessRecord) {
210
+ body["accessRecord"] = verify.payment.payload.accessRecord;
211
+ }
212
+ let gatewayRes;
213
+ try {
214
+ gatewayRes = await doFetch(`${gatewayUrl.replace(/\/+$/, "")}/v1/escrow/pay`, {
215
+ method: "POST",
216
+ headers: {
217
+ "Content-Type": "application/json",
218
+ Authorization: `Web3Signed ${verify.payment.payload.signature}`,
219
+ },
220
+ body: JSON.stringify(body),
221
+ });
222
+ }
223
+ catch (err) {
224
+ deps.logger?.error?.({
225
+ scope,
226
+ grantId: opIdLower,
227
+ error: err.message,
228
+ }, "X402 gateway forward threw; reissuing challenge");
229
+ return { kind: "challenge", body: await buildFreshChallenge() };
230
+ }
231
+ if (gatewayRes.ok) {
232
+ // Preserve the gateway's structured success body so the request
233
+ // handler can echo it back via the X-PAYMENT-RESPONSE header (canonical
234
+ // X402 convention). Empty/malformed body → propagate as null; the
235
+ // header still gets set so builders can tell payment succeeded.
236
+ let payResponseBody = null;
237
+ try {
238
+ payResponseBody = await gatewayRes.json();
239
+ }
240
+ catch {
241
+ // Body unreadable but status was 2xx — treat as success with no payload.
242
+ }
243
+ return { kind: "ok", payResponse: payResponseBody };
244
+ }
245
+ // Read the gateway's structured error body if there is one.
246
+ let errorBody;
247
+ try {
248
+ errorBody = await gatewayRes.json();
249
+ }
250
+ catch {
251
+ errorBody = { error: gatewayRes.statusText };
252
+ }
253
+ // 409 (replay or race) and 400 (amount mismatch / shape error) are
254
+ // recoverable with a fresh challenge — the builder re-signs with the
255
+ // new state and retries. 402 (insufficient balance) is relayed verbatim
256
+ // because the builder needs to fix their escrow, not their signature.
257
+ // 5xx is treated like 402-relayed since the personal server can't
258
+ // distinguish "transient" from "permanent" without more info.
259
+ if (gatewayRes.status === 409 || gatewayRes.status === 400) {
260
+ deps.logger?.info?.({ scope, grantId: opIdLower, status: gatewayRes.status, errorBody }, "Gateway rejected X-PAYMENT; reissuing X402 challenge");
261
+ return { kind: "challenge", body: await buildFreshChallenge() };
262
+ }
263
+ return { kind: "gateway-error", status: gatewayRes.status, body: errorBody };
264
+ }
265
+ function collectedAt(now) {
266
+ return now()
267
+ .toISOString()
268
+ .replace(/\.\d{3}Z$/, "Z");
269
+ }
270
+ /**
271
+ * The deletion that applies to a read of `scope`, or null when the read may
272
+ * be served. `entry` is the local version the read would serve (undefined
273
+ * on a local miss).
274
+ *
275
+ * - A local copy is refused when the gateway holds a tombstone that covers
276
+ * it (see `isEntryCoveredByTombstone`: registry versions and the ingest
277
+ * marker, never clocks). A local re-add on top of the tombstone is served.
278
+ * - A local miss asks the tracker to consult the gateway (bounded by its
279
+ * per-scope verdict cache and failure back-off): the local index cannot
280
+ * tell "deleted long ago" from "never had it".
281
+ * Gateway unreachability never fails the read: the tracker answers from its
282
+ * last known state, which is the documented offline behaviour.
283
+ */
284
+ export async function resolveReadDeletion(deps, scope, entry) {
285
+ if (!deps.scopeDeletions)
286
+ return null;
287
+ const verdict = await deps.scopeDeletions.resolve(scope, {
288
+ consultGateway: entry ? "if-stale" : "always",
289
+ });
290
+ if (!verdict.deleted)
291
+ return null;
292
+ if (entry && !isEntryCoveredByTombstone(entry, verdict)) {
293
+ return null;
294
+ }
295
+ return {
296
+ scope,
297
+ dataPointId: deps.serverOwner
298
+ ? computeDataPointId(deps.serverOwner, scope)
299
+ : null,
300
+ deletedAt: verdict.deletedAt,
301
+ };
302
+ }
303
+ /**
304
+ * Throw 410 DATA_DELETED when `resolveReadDeletion` says the read must not be
305
+ * served. Call it before any payment step: a builder must never be charged
306
+ * for a scope the owner deleted.
307
+ */
308
+ export async function assertScopeNotDeleted(deps, scope, entry) {
309
+ const deletion = await resolveReadDeletion(deps, scope, entry);
310
+ if (deletion)
311
+ throw new DataDeletedError(deletion);
312
+ }
313
+ /**
314
+ * Discovery filter for the scope and version listings: an entry a read would
315
+ * refuse with 410 is not listed either. Undefined (no filtering) when no
316
+ * deletion tracker is wired.
317
+ */
318
+ function discoveryVisibility(deps) {
319
+ if (!deps.scopeDeletions)
320
+ return undefined;
321
+ return async (scope, entry) => (await resolveReadDeletion(deps, scope, entry)) === null;
322
+ }
323
+ /**
324
+ * The causal marker a fresh ingest carries: the tombstone version this
325
+ * replica currently knows for the scope, if any, so the new entry is a
326
+ * deliberate re-add that survives that deletion (and only that one). Uses
327
+ * the same verdict path as reads, so it costs a gateway lookup only when the
328
+ * tracker's view is stale. An unknown or unsafe version leaves the marker
329
+ * null: the entry is then covered, never resurrected on a guess.
330
+ */
331
+ async function ingestTombstoneMarker(deps, scope) {
332
+ if (!deps.scopeDeletions)
333
+ return null;
334
+ const verdict = await deps.scopeDeletions.resolve(scope);
335
+ if (!verdict.deleted || verdict.version === null)
336
+ return null;
337
+ const version = Number(verdict.version);
338
+ return Number.isSafeInteger(version) ? version : null;
339
+ }
340
+ // The delete worker wants a full Logger; the API logger is all-optional.
341
+ function apiLoggerAsLogger(logger) {
342
+ const noop = () => undefined;
343
+ return {
344
+ debug: (payload, message) => (logger?.debug ?? noop)(payload, message ?? ""),
345
+ info: (payload, message) => (logger?.info ?? noop)(payload, message ?? ""),
346
+ warn: (payload, message) => (logger?.warn ?? noop)(payload, message ?? ""),
347
+ error: (payload, message) => (logger?.error ?? noop)(payload, message ?? ""),
348
+ };
349
+ }
350
+ function notifyDataWritten(deps, event) {
351
+ if (!deps.onDataWritten)
352
+ return;
353
+ try {
354
+ deps.onDataWritten(event);
355
+ }
356
+ catch (err) {
357
+ deps.logger?.warn?.({
358
+ scope: event.scope,
359
+ error: err instanceof Error ? err.message : String(err),
360
+ }, "onDataWritten hook failed; record already stored");
361
+ }
362
+ }
363
+ function notifyDataRead(deps, event) {
364
+ if (!deps.onDataRead)
365
+ return;
366
+ try {
367
+ deps.onDataRead(event);
368
+ }
369
+ catch (err) {
370
+ deps.logger?.warn?.({
371
+ scope: event.scope,
372
+ error: err instanceof Error ? err.message : String(err),
373
+ }, "onDataRead hook failed; the read is unaffected");
374
+ }
375
+ }
376
+ function notifyNewData(syncManager) {
377
+ if (!syncManager)
378
+ return;
379
+ if (syncManager.notifyNewData) {
380
+ syncManager.notifyNewData();
381
+ return;
382
+ }
383
+ void syncManager.trigger().catch(() => undefined);
384
+ }
385
+ function shouldReportReadFulfillment(grantId) {
386
+ return (grantId !== "unknown" && grantId !== "owner" && grantId !== "policy-bypass");
387
+ }
388
+ function warnReadFulfillmentReporterFailed(deps, event, err) {
389
+ deps.logger?.warn?.({
390
+ builder: event.builder,
391
+ error: err instanceof Error ? err.message : String(err),
392
+ grantId: event.grantId,
393
+ logId: event.logId,
394
+ scope: event.scope,
395
+ }, "Read fulfillment reporter failed");
396
+ }
397
+ export function reportPersonalServerReadFulfillment(deps, event) {
398
+ const reporter = deps.readFulfillmentReporter;
399
+ if (!reporter || !shouldReportReadFulfillment(event.grantId)) {
400
+ return;
401
+ }
402
+ fireReadReport(deps, event, reporter.report.bind(reporter));
403
+ }
404
+ /**
405
+ * Denials mirror fulfillments but skip the grant filter: a refused read has no
406
+ * grant to filter on, and the record is what proves the refusal happened.
407
+ */
408
+ export function reportPersonalServerReadDenial(deps, event) {
409
+ const reporter = deps.readFulfillmentReporter;
410
+ if (!reporter?.reportDenied)
411
+ return;
412
+ fireReadReport(deps, event, reporter.reportDenied.bind(reporter));
413
+ }
414
+ /** Fire-and-forget: reporting must never fail or delay the read it describes. */
415
+ function fireReadReport(deps, event, send) {
416
+ try {
417
+ void Promise.resolve(send(event)).catch((err) => warnReadFulfillmentReporterFailed(deps, event, err));
418
+ }
419
+ catch (err) {
420
+ warnReadFulfillmentReporterFailed(deps, event, err);
421
+ }
422
+ }
423
+ /**
424
+ * Validate a write's caller-supplied `lineage` (JSON body top level, or the
425
+ * binary metadata object) into the `$lineage` record to stamp. `undefined`
426
+ * (or null) means a root record. Throws ProtocolErrors; the write handler
427
+ * lets them propagate before anything is stored.
428
+ */
429
+ async function prepareWriteLineage(deps, scope, field) {
430
+ if (field === undefined || field === null)
431
+ return undefined;
432
+ return prepareLineage({
433
+ scope,
434
+ field,
435
+ serverOwner: deps.serverOwner,
436
+ storage: deps.storage,
437
+ gateway: deps.lineageGateway,
438
+ now: deps.now ?? (() => new Date()),
439
+ });
440
+ }
441
+ /**
442
+ * The lineage view a read auth result entitles the caller to. The auth port
443
+ * answers an owner read with no result or with the "owner" / "policy-bypass"
444
+ * sentinels (see api-auth): those get the full view. A builder read carries
445
+ * the grant the read policy resolved, and that grant names the view. A
446
+ * builder result with no resolved grant (or an "unknown" one) proves
447
+ * nothing and is refused: a missing grantId must never widen to the full
448
+ * view.
449
+ */
450
+ function resolveLineageGrantView(authResult) {
451
+ if (authResult === undefined ||
452
+ authResult.grantId === "owner" ||
453
+ authResult.grantId === "policy-bypass") {
454
+ return { grantId: undefined };
455
+ }
456
+ const grantId = authResult.grantId;
457
+ if (typeof grantId !== "string" || grantId === "" || grantId === "unknown") {
458
+ throw new GrantRequiredError({
459
+ reason: "a lineage read by a builder needs a resolved grant",
460
+ });
461
+ }
462
+ return { grantId };
463
+ }
464
+ /**
465
+ * True when a read auth result entitles the caller to the owner's view of a
466
+ * record — the same convention as resolveLineageGrantView: no result, or the
467
+ * "owner" / "policy-bypass" sentinels. Everything else is a grantee.
468
+ */
469
+ export function isOwnerView(authResult) {
470
+ return (authResult === undefined ||
471
+ authResult.grantId === "owner" ||
472
+ authResult.grantId === "policy-bypass");
473
+ }
474
+ /**
475
+ * The envelope view a grantee read is entitled to. The server-stamped
476
+ * `$writtenBy` (writing builder's address, grantId, signature) and
477
+ * `$lineage` (the owner's source data-point ids, dictionary-attackable back
478
+ * to scopes since dataPointId = keccak(owner, scope)) never leave the server
479
+ * on a grantee read: the owner reads them from storage, and grantees get the
480
+ * graph only through the grant-redacted lineage endpoint. When `$lineage` is
481
+ * present, the caller-supplied lineage field it mirrors (top-level `lineage`
482
+ * on a JSON record, `metadata.lineage` on a binary one) carries the same ids
483
+ * and is dropped with it; without the stamp such a field is ordinary user
484
+ * data and stays. Redaction is at serve time only — the stored envelope, its
485
+ * dataHash commitment, and the owner's view are unchanged.
486
+ */
487
+ export function redactEnvelopeForGrantee(envelope) {
488
+ const { [WRITER_ATTRIBUTION_KEY]: attribution, [LINEAGE_KEY]: storedLineage, ...rest } = envelope.data;
489
+ if (attribution === undefined && storedLineage === undefined) {
490
+ return envelope;
491
+ }
492
+ let data = rest;
493
+ if (storedLineage !== undefined) {
494
+ if (isBinaryEnvelope(envelope)) {
495
+ const metadata = data["metadata"];
496
+ if (metadata !== null &&
497
+ typeof metadata === "object" &&
498
+ !Array.isArray(metadata)) {
499
+ const { lineage: _consumed, ...metadataRest } = metadata;
500
+ if (Object.keys(metadataRest).length === 0) {
501
+ // The lineage was the whole metadata object; leaving `{}` behind
502
+ // would still disclose that a metadata object existed.
503
+ const { metadata: _emptied, ...dataRest } = data;
504
+ data = dataRest;
505
+ }
506
+ else {
507
+ data = { ...data, metadata: metadataRest };
508
+ }
509
+ }
510
+ }
511
+ else {
512
+ const { lineage: _consumed, ...dataRest } = data;
513
+ data = dataRest;
514
+ }
515
+ }
516
+ return { ...envelope, data };
517
+ }
518
+ export { redactJsonEnvelopeBytesForGrantee } from "./raw-envelope.js";
519
+ export async function handlePersonalServerDataRequest(request, deps, options = {}) {
520
+ return withApiErrors(async () => {
521
+ const url = new URL(request.url);
522
+ const pathname = stripBasePath(url.pathname, options.basePath);
523
+ if (pathname === "/" || pathname === "") {
524
+ if (request.method !== "GET")
525
+ return methodNotAllowed();
526
+ await deps.auth.authorizeBuilderList(request);
527
+ const result = await listDataScopesContract({
528
+ storage: deps.storage,
529
+ scopePrefix: url.searchParams.get("scopePrefix") ?? undefined,
530
+ limit: normalizeLimit(url.searchParams.get("limit"), 20),
531
+ offset: normalizeLimit(url.searchParams.get("offset"), 0),
532
+ isVisible: discoveryVisibility(deps),
533
+ });
534
+ return jsonResponse(result.response);
535
+ }
536
+ const parts = pathname.split("/").filter(Boolean);
537
+ if (parts.length === 2 && parts[1] === "versions") {
538
+ if (request.method !== "GET")
539
+ return methodNotAllowed();
540
+ await deps.auth.authorizeBuilderList(request);
541
+ const result = await listDataVersionsContract({
542
+ storage: deps.storage,
543
+ scopeParam: decodePathPart(parts[0]),
544
+ limit: normalizeLimit(url.searchParams.get("limit"), 20),
545
+ offset: normalizeLimit(url.searchParams.get("offset"), 0),
546
+ isVisible: discoveryVisibility(deps),
547
+ });
548
+ if (!result.ok)
549
+ return contractErrorResponse(result);
550
+ if (result.response.total === 0) {
551
+ // Nothing visible: answer 410 rather than an empty list when that is
552
+ // because the scope is tombstoned, exactly as a read would.
553
+ await assertScopeNotDeleted(deps, result.scope, undefined);
554
+ }
555
+ return jsonResponse(result.response);
556
+ }
557
+ if ((parts.length === 2 || parts.length === 3) && parts[1] === "lineage") {
558
+ if (request.method !== "GET")
559
+ return methodNotAllowed();
560
+ const scopeResult = parseDataScopeContract(decodePathPart(parts[0]));
561
+ if (!scopeResult.ok)
562
+ return contractErrorResponse(scopeResult);
563
+ // The version is a PATH segment (/v1/data/:scope/lineage/:version), so
564
+ // it is inside the signed request uri: a builder's signature for one
565
+ // version cannot be replayed to read another. The grant view is the
566
+ // signed grantId claim the read auth already honours. Query
567
+ // parameters would be unsigned inputs to the view and are refused.
568
+ if (url.searchParams.has("version")) {
569
+ return errorResponse(400, "INVALID_VERSION", "version is a path segment (/v1/data/:scope/lineage/:version), not a query parameter");
570
+ }
571
+ if (url.search.length > 0) {
572
+ return errorResponse(400, "INVALID_QUERY", "lineage reads take no query parameters; the version is a path segment and the grant view is the signed grantId claim");
573
+ }
574
+ const version = parts.length === 3 ? decodePathPart(parts[2]) : undefined;
575
+ if (version !== undefined && !/^[1-9]\d*$/.test(version)) {
576
+ return errorResponse(400, "INVALID_VERSION", "version must be a positive decimal integer");
577
+ }
578
+ // Same gate as a read of the scope: the owner, or a builder whose grant
579
+ // covers it. The gateway then attests the view that grant sees, so a
580
+ // builder only learns the scopes of nodes its grant covers.
581
+ const authResult = await deps.auth.authorizeBuilderRead({
582
+ request,
583
+ scope: scopeResult.scope,
584
+ grantId: selectedGrantId(request, url),
585
+ });
586
+ if (!deps.serverOwner) {
587
+ throw new ServerNotConfiguredError({
588
+ reason: "serverOwner is required to resolve the data point id",
589
+ });
590
+ }
591
+ if (!deps.lineageGateway)
592
+ throw new LineageUnavailableError();
593
+ const { grantId } = resolveLineageGrantView(authResult);
594
+ let result;
595
+ try {
596
+ result = await deps.lineageGateway.getLineage({
597
+ dataPointId: computeDataPointId(deps.serverOwner, scopeResult.scope),
598
+ version,
599
+ grantId,
600
+ });
601
+ }
602
+ catch (err) {
603
+ // Transport failures (DNS, refused, timeout) are gateway errors to
604
+ // the caller, not internal ones: same 502 as a gateway error body.
605
+ if (err instanceof ProtocolError)
606
+ throw err;
607
+ throw new LineageGatewayError({
608
+ status: 0,
609
+ body: { error: err instanceof Error ? err.message : String(err) },
610
+ });
611
+ }
612
+ if (!result.ok) {
613
+ if (result.status === 404) {
614
+ return errorResponse(404, "NOT_FOUND", version
615
+ ? `Scope "${scopeResult.scope}" has no registered version ${version}`
616
+ : `Scope "${scopeResult.scope}" is not registered at the gateway`);
617
+ }
618
+ if (result.status === 403) {
619
+ throw new ProtocolError(403, "LINEAGE_FORBIDDEN", "The gateway refused the lineage view for this grant", { gateway: result.body });
620
+ }
621
+ throw new LineageGatewayError({
622
+ status: result.status,
623
+ body: result.body,
624
+ });
625
+ }
626
+ // A lineage view discloses the derivation graph, so a served view is
627
+ // logged like a data read (refusals above return without an entry).
628
+ await deps.accessLogWriter.write({
629
+ logId: deps.createLogId?.() ?? crypto.randomUUID(),
630
+ grantId: authResult?.grantId ?? "owner",
631
+ builder: authResult?.builder ?? "unknown",
632
+ action: "lineage",
633
+ scope: scopeResult.scope,
634
+ timestamp: (deps.now ?? (() => new Date()))().toISOString(),
635
+ ipAddress: request.headers.get("x-forwarded-for") ??
636
+ request.headers.get("x-real-ip") ??
637
+ "unknown",
638
+ userAgent: request.headers.get("user-agent") ?? "unknown",
639
+ });
640
+ return jsonResponse({ data: result.data, proof: result.proof });
641
+ }
642
+ if (parts.length !== 1)
643
+ return notFound();
644
+ const scopeParam = decodePathPart(parts[0]);
645
+ if (request.method === "GET") {
646
+ const scopeResult = parseDataScopeContract(scopeParam);
647
+ if (!scopeResult.ok)
648
+ return contractErrorResponse(scopeResult);
649
+ const selectedEntry = deps.storage.findEntry({
650
+ scope: scopeResult.scope,
651
+ fileId: url.searchParams.get("fileId") ?? undefined,
652
+ at: url.searchParams.get("at") ?? undefined,
653
+ });
654
+ // Holds the base64-encoded gateway payForOperation response body when
655
+ // X402 succeeds — emitted on the final read response as X-PAYMENT-RESPONSE.
656
+ let paymentResponseHeader;
657
+ const grantId = selectedGrantId(request, url);
658
+ const authResult = await deps.auth.authorizeBuilderRead({
659
+ request,
660
+ scope: scopeResult.scope,
661
+ grantId,
662
+ fileId: url.searchParams.get("fileId") ?? selectedEntry?.fileId ?? undefined,
663
+ at: url.searchParams.get("at") ?? undefined,
664
+ });
665
+ // Deletion gate, after auth (so unauthenticated callers learn nothing)
666
+ // and before payment (so nobody is charged for deleted data). Covers
667
+ // both a stale local copy of a tombstoned scope and a local miss.
668
+ await assertScopeNotDeleted(deps, scopeResult.scope, selectedEntry);
669
+ // Demand: this authorized read is what pays for a recompute of a
670
+ // derivative whose sources have moved on. It runs after the gates
671
+ // above (an unauthenticated or refused read must never spend an
672
+ // inference call) and before the payment dance, because the status
673
+ // route grants the same caller the same trigger for free — gating it
674
+ // on payment would buy nothing and would leave a never-computed
675
+ // answer unreachable through this route. Nothing here blocks: a
676
+ // previous version is served now, the fresh one lands in a later read.
677
+ notifyDataRead(deps, { scope: scopeResult.scope });
678
+ // X402 payment dance for builder reads. Owner-exempt reads (the
679
+ // grantId sentinels "owner" / "policy-bypass") skip payment entirely
680
+ // since there's no payable op to attach the payment to.
681
+ //
682
+ // The grantId we pay against is the one verifyDataReadPolicy resolved
683
+ // from the Web3Signed payload (authoritative source) — not the URL /
684
+ // header hint, which may be absent when the payload carries it.
685
+ const isOwnerSignal = authResult?.grantId === "owner" ||
686
+ authResult?.grantId === "policy-bypass";
687
+ const builder = authResult?.builder;
688
+ const resolvedGrantId = !isOwnerSignal && authResult?.grantId ? authResult.grantId : undefined;
689
+ const willCharge = Boolean(deps.paymentEnabled &&
690
+ !isOwnerSignal &&
691
+ typeof builder === "string" &&
692
+ builder.startsWith("0x") &&
693
+ resolvedGrantId &&
694
+ deps.gateway &&
695
+ deps.gatewayConfig &&
696
+ deps.gatewayUrl);
697
+ // Diagnostic: makes it explicit why a read is/isn't charged. x402 has
698
+ // many "served free" branches (owner read, payment disabled, missing
699
+ // gateway deps); this surfaces the deciding inputs.
700
+ //
701
+ // Routing: when a logger is wired (the Node server always provides one),
702
+ // log the full detail through it at debug level so the operator's level
703
+ // controls + redaction apply and access metadata (scope/grantId/builder)
704
+ // doesn't unconditionally hit stdout. The browser PS-Lite runtime wires
705
+ // no logger; there we fall back to console but log ONLY the non-identifying
706
+ // decision booleans — never scope/grantId/builder.
707
+ if (deps.logger?.debug) {
708
+ deps.logger.debug({
709
+ scope: scopeResult.scope,
710
+ grantId: authResult?.grantId,
711
+ isOwnerSignal,
712
+ builder,
713
+ resolvedGrantId,
714
+ paymentEnabled: Boolean(deps.paymentEnabled),
715
+ hasGateway: Boolean(deps.gateway),
716
+ hasGatewayConfig: Boolean(deps.gatewayConfig),
717
+ hasGatewayUrl: Boolean(deps.gatewayUrl),
718
+ willCharge,
719
+ }, "[x402-gate] read");
720
+ }
721
+ else {
722
+ console.info("[x402-gate] read", {
723
+ isOwnerSignal,
724
+ paymentEnabled: Boolean(deps.paymentEnabled),
725
+ hasGateway: Boolean(deps.gateway),
726
+ hasGatewayConfig: Boolean(deps.gatewayConfig),
727
+ hasGatewayUrl: Boolean(deps.gatewayUrl),
728
+ willCharge,
729
+ });
730
+ }
731
+ // Keep the full condition inline (not `if (willCharge)`) so TS narrows
732
+ // deps.gateway/gatewayConfig/gatewayUrl to non-undefined in the block.
733
+ if (deps.paymentEnabled &&
734
+ !isOwnerSignal &&
735
+ typeof builder === "string" &&
736
+ builder.startsWith("0x") &&
737
+ resolvedGrantId &&
738
+ deps.gateway &&
739
+ deps.gatewayConfig &&
740
+ deps.gatewayUrl) {
741
+ const x402Result = await handleX402Cycle({
742
+ deps,
743
+ request,
744
+ scope: scopeResult.scope,
745
+ fileIdParam: url.searchParams.get("fileId") ?? undefined,
746
+ atParam: url.searchParams.get("at") ?? undefined,
747
+ grantId: resolvedGrantId,
748
+ builder: builder,
749
+ gateway: deps.gateway,
750
+ gatewayConfig: deps.gatewayConfig,
751
+ gatewayUrl: deps.gatewayUrl,
752
+ });
753
+ if (x402Result.kind === "challenge") {
754
+ return jsonResponse(x402Result.body, { status: 402 });
755
+ }
756
+ if (x402Result.kind === "gateway-error") {
757
+ // Relay the gateway's structured body verbatim so the builder can
758
+ // dispatch on it (insufficient balance vs. replay vs. race etc.).
759
+ return jsonResponse(x402Result.body, { status: x402Result.status });
760
+ }
761
+ // x402Result.kind === "ok" — payment accepted, proceed to read.
762
+ // The gateway's success body is forwarded back to the builder via
763
+ // X-PAYMENT-RESPONSE (canonical X402 convention) so callers can see
764
+ // breakdown / paidAt / paymentNonce without a second gateway round-trip.
765
+ paymentResponseHeader = encodePaymentResponseHeader(x402Result.payResponse);
766
+ }
767
+ const result = await readDataContract({
768
+ storage: deps.storage,
769
+ scopeParam: scopeResult.scope,
770
+ fileId: url.searchParams.get("fileId") ?? undefined,
771
+ at: url.searchParams.get("at") ?? undefined,
772
+ });
773
+ if (!result.ok) {
774
+ if (result.status === 404) {
775
+ // The entry selected above can vanish before the read (a sync
776
+ // reconcile applying a tombstone concurrently); answer 410, not
777
+ // 404, when that is why.
778
+ await assertScopeNotDeleted(deps, scopeResult.scope, undefined);
779
+ }
780
+ return contractErrorResponse(result);
781
+ }
782
+ const servedEnvelope = isOwnerView(authResult)
783
+ ? result.envelope
784
+ : redactEnvelopeForGrantee(result.envelope);
785
+ const logId = deps.createLogId?.() ?? crypto.randomUUID();
786
+ const timestamp = (deps.now ?? (() => new Date()))().toISOString();
787
+ const ipAddress = request.headers.get("x-forwarded-for") ??
788
+ request.headers.get("x-real-ip") ??
789
+ "unknown";
790
+ const userAgent = request.headers.get("user-agent") ?? "unknown";
791
+ const loggedGrantId = authResult?.grantId ?? grantId ?? "unknown";
792
+ const loggedBuilder = authResult?.builder ?? "unknown";
793
+ await deps.accessLogWriter.write({
794
+ logId,
795
+ grantId: loggedGrantId,
796
+ builder: loggedBuilder,
797
+ action: "read",
798
+ scope: scopeResult.scope,
799
+ timestamp,
800
+ ipAddress,
801
+ userAgent,
802
+ });
803
+ const reportReadFulfillment = () => {
804
+ if (!authResult?.grantId || !authResult.builder)
805
+ return;
806
+ reportPersonalServerReadFulfillment(deps, {
807
+ builder: authResult.builder,
808
+ fileId: url.searchParams.get("fileId") ??
809
+ selectedEntry?.fileId ??
810
+ undefined,
811
+ grantId: authResult.grantId,
812
+ ipAddress,
813
+ logId,
814
+ outcome: "served",
815
+ scope: scopeResult.scope,
816
+ servedAt: timestamp,
817
+ source: "api",
818
+ userAgent,
819
+ });
820
+ };
821
+ const headers = {};
822
+ if (paymentResponseHeader) {
823
+ headers["X-PAYMENT-RESPONSE"] = paymentResponseHeader;
824
+ }
825
+ const wantsRawContent = url.searchParams.get("content") === "raw";
826
+ // `?content=raw` streams the decoded bytes of a binary envelope with its
827
+ // original media type, so a builder can download the file directly. The
828
+ // X-PAYMENT-RESPONSE header (if any) rides along on the raw response too.
829
+ if (wantsRawContent) {
830
+ if (!isBinaryEnvelope(servedEnvelope)) {
831
+ return jsonResponse({
832
+ error: "NOT_BINARY_SCOPE",
833
+ message: `Scope "${scopeResult.scope}" does not expose raw binary content.`,
834
+ }, { status: 400, headers });
835
+ }
836
+ const decoded = decodeBinaryEnvelope(servedEnvelope);
837
+ headers["Content-Type"] = decoded.mimeType;
838
+ headers["Content-Length"] = String(decoded.bytes.length);
839
+ if (decoded.filename) {
840
+ headers["Content-Disposition"] =
841
+ `attachment; filename="${decoded.filename}"`;
842
+ }
843
+ if (decoded.metadata !== undefined) {
844
+ headers["X-Vana-Metadata"] = stringifyMetadataHeader(decoded.metadata);
845
+ }
846
+ const response = new Response(decoded.bytes, {
847
+ status: 200,
848
+ headers,
849
+ });
850
+ return response;
851
+ }
852
+ const response = jsonResponse(servedEnvelope, { headers });
853
+ reportReadFulfillment();
854
+ return response;
855
+ }
856
+ if (request.method === "POST") {
857
+ // Delegated writes: an auth port that supports write sessions handles
858
+ // both paths in authorizeWrite (builder session token -> write policy +
859
+ // attribution; anything else -> owner path). Ports without it keep
860
+ // today's owner-only gate.
861
+ let writeAuth;
862
+ if (deps.auth.authorizeWrite) {
863
+ writeAuth =
864
+ (await deps.auth.authorizeWrite({ request, scope: scopeParam })) ??
865
+ undefined;
866
+ }
867
+ else {
868
+ await deps.auth.authorizeOwner(request);
869
+ }
870
+ // A write that fails before commit hands the proof back (replay guard)
871
+ // so the builder's retry with the same still-valid proof is accepted;
872
+ // after commit the proof stays consumed (a retry would be a duplicate).
873
+ let committed = false;
874
+ const failWrite = async (response) => {
875
+ await writeAuth?.releaseProof?.();
876
+ return response;
877
+ };
878
+ try {
879
+ const scopeResult = parseDataScopeContract(scopeParam);
880
+ if (!scopeResult.ok)
881
+ return failWrite(contractErrorResponse(scopeResult));
882
+ const collectedAtValue = collectedAt(deps.now ?? (() => new Date()));
883
+ const status = deps.syncManager ? "syncing" : "stored";
884
+ const afterTombstoneVersion = await ingestTombstoneMarker(deps, scopeResult.scope);
885
+ // Builder writes land in the same access log as builder reads, so the
886
+ // owner sees who wrote what under which grant.
887
+ // Best-effort: it runs AFTER the record is committed, so a log failure
888
+ // must not turn a successful write into a 500 (the builder would retry
889
+ // and store a duplicate). The ingest log line above still names the
890
+ // builder; the failure itself is logged for the owner.
891
+ const logBuilderWrite = async () => {
892
+ if (!writeAuth)
893
+ return;
894
+ try {
895
+ await deps.accessLogWriter.write({
896
+ logId: deps.createLogId?.() ?? crypto.randomUUID(),
897
+ grantId: writeAuth.grantId,
898
+ builder: writeAuth.builder,
899
+ action: "write",
900
+ scope: scopeResult.scope,
901
+ timestamp: (deps.now ?? (() => new Date()))().toISOString(),
902
+ ipAddress: request.headers.get("x-forwarded-for") ??
903
+ request.headers.get("x-real-ip") ??
904
+ "unknown",
905
+ userAgent: request.headers.get("user-agent") ?? "unknown",
906
+ });
907
+ }
908
+ catch (err) {
909
+ deps.logger?.warn?.({
910
+ scope: scopeResult.scope,
911
+ builder: writeAuth.builder,
912
+ grantId: writeAuth.grantId,
913
+ error: err instanceof Error ? err.message : String(err),
914
+ }, "Builder write access-log entry failed; record already stored");
915
+ }
916
+ };
917
+ // Binary / unstructured data (e.g. a PDF): the body is raw bytes. DPv2
918
+ // data points are scope-addressed and carry no schemaId, so unstructured
919
+ // data needs no schema at all — we ingest it schemaless. (Structured JSON
920
+ // below still resolves a schema for validation/metadata.)
921
+ if (!isJsonContentType(request)) {
922
+ const bytes = new Uint8Array(await request.arrayBuffer());
923
+ const metadata = parseMetadataHeader(request.headers.get("x-vana-metadata"));
924
+ // A binary derivative names its sources inside the metadata
925
+ // object; the validated mirror lands at the top of the record.
926
+ const lineage = await prepareWriteLineage(deps, scopeResult.scope, extractLineageField(metadata));
927
+ const result = await ingestBinaryDataContract({
928
+ storage: deps.storage,
929
+ scopeParam: scopeResult.scope,
930
+ bytes,
931
+ mimeType: binaryMimeType(request),
932
+ filename: binaryFilename(request),
933
+ metadata,
934
+ collectedAt: collectedAtValue,
935
+ status,
936
+ attribution: writeAuth?.attribution,
937
+ lineage,
938
+ afterTombstoneVersion,
939
+ });
940
+ if (!result.ok)
941
+ return failWrite(contractErrorResponse(result));
942
+ committed = true;
943
+ deps.logger?.info?.({
944
+ scope: scopeResult.scope,
945
+ collectedAt: collectedAtValue,
946
+ path: result.writeResult.relativePath,
947
+ mimeType: binaryMimeType(request),
948
+ sizeBytes: bytes.length,
949
+ ...(writeAuth ? { builder: writeAuth.builder } : {}),
950
+ }, "Binary data file ingested");
951
+ await logBuilderWrite();
952
+ notifyNewData(deps.syncManager);
953
+ notifyDataWritten(deps, {
954
+ scope: scopeResult.scope,
955
+ collectedAt: collectedAtValue,
956
+ lineageSources: lineage?.sources,
957
+ });
958
+ return jsonResponse(result.response, { status: 201 });
959
+ }
960
+ const parsed = await parseJsonObjectBody(request, "Request body must be valid JSON");
961
+ if (!parsed.ok)
962
+ return failWrite(contractResponse(parsed.result));
963
+ // Derivative writes: validate the caller's `lineage` before anything
964
+ // is stored (a failure here throws, releasing the builder's proof).
965
+ const lineage = await prepareWriteLineage(deps, scopeResult.scope, extractLineageField(parsed.body));
966
+ // DPv2 is scope-addressed and the gateway records no schemas, so JSON
967
+ // ingest is schemaless too — no lookup, no schemaId/$schema stamped.
968
+ const result = await ingestDataContract({
969
+ storage: deps.storage,
970
+ scopeParam: scopeResult.scope,
971
+ body: parsed.body,
972
+ collectedAt: collectedAtValue,
973
+ status,
974
+ attribution: writeAuth?.attribution,
975
+ lineage,
976
+ afterTombstoneVersion,
977
+ });
978
+ if (!result.ok)
979
+ return failWrite(contractErrorResponse(result));
980
+ committed = true;
981
+ deps.logger?.info?.({
982
+ scope: scopeResult.scope,
983
+ collectedAt: collectedAtValue,
984
+ path: result.writeResult.relativePath,
985
+ ...(writeAuth ? { builder: writeAuth.builder } : {}),
986
+ }, "Data file ingested");
987
+ await logBuilderWrite();
988
+ notifyNewData(deps.syncManager);
989
+ notifyDataWritten(deps, {
990
+ scope: scopeResult.scope,
991
+ collectedAt: collectedAtValue,
992
+ lineageSources: lineage?.sources,
993
+ });
994
+ return jsonResponse(result.response, { status: 201 });
995
+ }
996
+ catch (err) {
997
+ // An envelope that reached storage before indexing failed is
998
+ // persisted (a re-index surfaces it): keep the proof consumed so a
999
+ // retry cannot store it twice; the builder needs a fresh proof.
1000
+ if (err instanceof IngestPersistedError) {
1001
+ deps.logger?.error?.({
1002
+ scope: scopeParam,
1003
+ path: err.relativePath,
1004
+ error: err.cause instanceof Error
1005
+ ? err.cause.message
1006
+ : String(err.cause),
1007
+ }, "Envelope written but indexing failed; record persisted unindexed");
1008
+ }
1009
+ else if (!committed) {
1010
+ await writeAuth?.releaseProof?.();
1011
+ }
1012
+ throw err;
1013
+ }
1014
+ }
1015
+ if (request.method === "DELETE") {
1016
+ await deps.auth.authorizeOwner(request);
1017
+ const cascade = url.searchParams.get("cascade");
1018
+ if (cascade !== null && cascade !== "lineage") {
1019
+ throw new InvalidCascadeError({ cascade });
1020
+ }
1021
+ // Parse the scope first so an invalid scope still 400s without a
1022
+ // wasted remote call.
1023
+ const parsed = parseDataScopeContract(scopeParam);
1024
+ if (!parsed.ok)
1025
+ return contractErrorResponse(parsed);
1026
+ if (cascade === "lineage") {
1027
+ // Specified (docs/derivative-data-api.md, "Delete") but not
1028
+ // implemented here. The durable per-scope delete below is what a
1029
+ // cascade node needs; the missing part is the lineage walk itself
1030
+ // (owner view of the gateway graph, deepest derivatives first,
1031
+ // truncation and cross-owner handling, all-or-nothing before the
1032
+ // first tombstone). Until that lands the only honest answer is 501.
1033
+ throw new LineageCascadeUnavailableError({ scope: parsed.scope });
1034
+ }
1035
+ // Durable order: gateway tombstone -> storage blobs -> local copy. The
1036
+ // sync manager owns the remote ports; without one (sync disabled or
1037
+ // no owner key material) only the local copy goes and the result says
1038
+ // so (`durable: false`) rather than pretending.
1039
+ const result = deps.syncManager?.deleteScope
1040
+ ? await deps.syncManager.deleteScope(parsed.scope)
1041
+ : await deleteScopeLocally({
1042
+ storage: deps.storage,
1043
+ serverOwner: deps.serverOwner,
1044
+ deleteData: null,
1045
+ logger: apiLoggerAsLogger(deps.logger),
1046
+ }, parsed.scope);
1047
+ if (result.steps.gateway.status === "failed") {
1048
+ // Nothing was deleted: the local copy is kept on purpose so sync
1049
+ // cannot resurrect a half-deleted scope. Surface it as an upstream
1050
+ // failure with the per-step result attached.
1051
+ throw new DeleteTombstoneFailedError({
1052
+ scope: parsed.scope,
1053
+ result,
1054
+ });
1055
+ }
1056
+ // Audit entry, best-effort: the deletion above is irreversible and
1057
+ // already done, so a failed log write must not turn it into an error
1058
+ // response that invites a misleading retry. The failure is logged.
1059
+ try {
1060
+ await deps.accessLogWriter.write({
1061
+ logId: deps.createLogId?.() ?? crypto.randomUUID(),
1062
+ grantId: "owner",
1063
+ builder: deps.serverOwner ?? "owner",
1064
+ action: "delete",
1065
+ scope: parsed.scope,
1066
+ timestamp: (deps.now ?? (() => new Date()))().toISOString(),
1067
+ ipAddress: request.headers.get("x-forwarded-for") ??
1068
+ request.headers.get("x-real-ip") ??
1069
+ "unknown",
1070
+ userAgent: request.headers.get("user-agent") ?? "unknown",
1071
+ });
1072
+ }
1073
+ catch (err) {
1074
+ deps.logger?.warn?.({
1075
+ scope: parsed.scope,
1076
+ error: err instanceof Error ? err.message : String(err),
1077
+ }, "Delete access-log entry failed; scope already deleted");
1078
+ }
1079
+ deps.logger?.info?.({
1080
+ scope: parsed.scope,
1081
+ durable: result.durable,
1082
+ gateway: result.steps.gateway.status,
1083
+ storage: result.steps.storage.status,
1084
+ local: result.steps.local.status,
1085
+ deletedCount: result.steps.local.deletedCount,
1086
+ }, "Scope deleted");
1087
+ return jsonResponse(result, { status: 200 });
1088
+ }
1089
+ return methodNotAllowed();
1090
+ });
1091
+ }
1092
+ export async function handlePersonalServerAccessLogsRequest(request, deps, options = {}) {
1093
+ return withApiErrors(async () => {
1094
+ const url = new URL(request.url);
1095
+ const pathname = stripBasePath(url.pathname, options.basePath);
1096
+ if (pathname !== "/" && pathname !== "")
1097
+ return notFound();
1098
+ if (request.method !== "GET")
1099
+ return methodNotAllowed();
1100
+ await deps.auth.authorizeOwner(request);
1101
+ return contractResponse(await listAccessLogsContract({
1102
+ accessLogReader: deps.accessLogReader,
1103
+ limit: url.searchParams.get("limit"),
1104
+ offset: url.searchParams.get("offset"),
1105
+ }));
1106
+ });
1107
+ }
1108
+ export async function handlePersonalServerSyncRequest(request, deps, options = {}) {
1109
+ return withApiErrors(async () => {
1110
+ const url = new URL(request.url);
1111
+ const pathname = stripBasePath(url.pathname, options.basePath);
1112
+ if (pathname === "/trigger") {
1113
+ if (request.method !== "POST")
1114
+ return methodNotAllowed();
1115
+ await deps.auth.authorizeOwner(request);
1116
+ return contractResponse(await triggerSyncContract(deps.syncManager));
1117
+ }
1118
+ if (pathname === "/status") {
1119
+ if (request.method !== "GET")
1120
+ return methodNotAllowed();
1121
+ await deps.auth.authorizeOwner(request);
1122
+ return contractResponse(getSyncStatusContract(deps.syncManager));
1123
+ }
1124
+ if (pathname.startsWith("/file/")) {
1125
+ if (request.method !== "POST")
1126
+ return methodNotAllowed();
1127
+ await deps.auth.authorizeOwner(request);
1128
+ const fileId = decodeURIComponent(pathname.slice("/file/".length));
1129
+ deps.logger?.info?.({ fileId }, "File sync requested, triggering full sync");
1130
+ return contractResponse(await syncFileContract({
1131
+ fileId,
1132
+ syncManager: deps.syncManager,
1133
+ }));
1134
+ }
1135
+ return notFound();
1136
+ });
1137
+ }
1138
+ export async function handlePersonalServerGrantsRequest(request, deps, options = {}) {
1139
+ return withApiErrors(async () => {
1140
+ const url = new URL(request.url);
1141
+ const pathname = stripBasePath(url.pathname, options.basePath);
1142
+ if (pathname === "/" || pathname === "") {
1143
+ await deps.auth.authorizeOwner(request);
1144
+ if (!deps.gateway) {
1145
+ return errorResponse(500, "SERVER_NOT_CONFIGURED", "Gateway is not configured");
1146
+ }
1147
+ if (request.method === "GET") {
1148
+ return contractResponse(await listGrantsContract({
1149
+ gateway: deps.gateway,
1150
+ serverOwner: deps.serverOwner,
1151
+ }));
1152
+ }
1153
+ if (request.method === "POST") {
1154
+ const parsed = await parseJsonObjectBody(request);
1155
+ if (!parsed.ok)
1156
+ return contractResponse(parsed.result);
1157
+ // Canary createGrant doesn't need a clock — grantVersion defaults
1158
+ // to "1" and callers re-registering pass a strictly higher value.
1159
+ return contractResponse(await createGrantContract({
1160
+ gateway: deps.gateway,
1161
+ serverOwner: deps.serverOwner,
1162
+ serverSigner: deps.serverSigner,
1163
+ body: parsed.body,
1164
+ }));
1165
+ }
1166
+ return methodNotAllowed();
1167
+ }
1168
+ if (pathname === "/verify") {
1169
+ if (request.method !== "POST")
1170
+ return methodNotAllowed();
1171
+ const parsed = await parseJsonObjectBody(request);
1172
+ if (!parsed.ok)
1173
+ return contractResponse(parsed.result);
1174
+ return contractResponse(await verifyGrantContract({
1175
+ body: parsed.body,
1176
+ gatewayConfig: deps.gatewayConfig,
1177
+ }));
1178
+ }
1179
+ if (pathname.startsWith("/")) {
1180
+ if (request.method !== "DELETE")
1181
+ return methodNotAllowed();
1182
+ await deps.auth.authorizeOwner(request);
1183
+ if (!deps.gateway) {
1184
+ return errorResponse(500, "SERVER_NOT_CONFIGURED", "Gateway is not configured");
1185
+ }
1186
+ return contractResponse(await revokeGrantContract({
1187
+ gateway: deps.gateway,
1188
+ serverOwner: deps.serverOwner,
1189
+ serverSigner: deps.serverSigner,
1190
+ grantId: decodeURIComponent(pathname.slice(1)),
1191
+ }));
1192
+ }
1193
+ return notFound();
1194
+ });
1195
+ }
1196
+ export async function handlePersonalServerConfigRequest(request, deps) {
1197
+ return withApiErrors(async () => {
1198
+ await deps.auth.authorizeOwner(request);
1199
+ if (request.method === "GET") {
1200
+ try {
1201
+ return jsonResponse(await deps.readConfig());
1202
+ }
1203
+ catch (err) {
1204
+ const kind = err instanceof Error &&
1205
+ "code" in err &&
1206
+ err.code === "ENOENT"
1207
+ ? "not-found"
1208
+ : "read";
1209
+ return contractResponse(configReadErrorContract(kind));
1210
+ }
1211
+ }
1212
+ if (request.method === "PUT") {
1213
+ const parsed = await parseJsonObjectBody(request);
1214
+ if (!parsed.ok)
1215
+ return contractResponse(parsed.result);
1216
+ const result = validateServerConfigContract(parsed.body);
1217
+ if (!result.ok)
1218
+ return contractResponse(result);
1219
+ try {
1220
+ await deps.writeConfig(result.body.config);
1221
+ }
1222
+ catch {
1223
+ return contractResponse(configWriteErrorContract());
1224
+ }
1225
+ return contractResponse(result);
1226
+ }
1227
+ return methodNotAllowed();
1228
+ });
1229
+ }
1230
+ export async function handlePersonalServerOauthTokenRequest(request, deps) {
1231
+ return withApiErrors(async () => {
1232
+ if (request.method !== "POST")
1233
+ return methodNotAllowed();
1234
+ const contentType = request.headers.get("content-type") ?? "";
1235
+ if (!contentType.includes("application/x-www-form-urlencoded")) {
1236
+ return jsonResponse({
1237
+ error: "invalid_request",
1238
+ error_description: "Content-Type must be application/x-www-form-urlencoded",
1239
+ }, { status: 400 });
1240
+ }
1241
+ const result = await oauthTokenContract({
1242
+ body: new URLSearchParams(await request.text()),
1243
+ authorizationHeader: request.headers.get("authorization"),
1244
+ tokenStore: deps.tokenStore,
1245
+ controlPlaneSecret: deps.controlPlaneSecret,
1246
+ deviceSessions: deps.deviceSessions,
1247
+ randomToken: deps.randomToken,
1248
+ now: deps.now,
1249
+ safeCompare: deps.safeCompare,
1250
+ });
1251
+ return jsonResponse(result.body, {
1252
+ status: result.status,
1253
+ headers: result.headers,
1254
+ });
1255
+ });
1256
+ }
1257
+ //# sourceMappingURL=index.js.map