@codemem/core 0.49.1 → 0.50.0-beta.1

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 (371) hide show
  1. package/dist/api-types.d.ts +7 -0
  2. package/dist/api-types.d.ts.map +1 -1
  3. package/dist/better-sqlite-coordinator-runtime.d.ts.map +1 -1
  4. package/dist/better-sqlite-coordinator-store.d.ts +56 -3
  5. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  6. package/dist/boundary-readiness-inventory.d.ts +27 -0
  7. package/dist/boundary-readiness-inventory.d.ts.map +1 -0
  8. package/dist/coordinator-account-link-receiver.d.ts +15 -0
  9. package/dist/coordinator-account-link-receiver.d.ts.map +1 -1
  10. package/dist/coordinator-account-link-status-client.d.ts +1 -1
  11. package/dist/coordinator-account-link-status-client.d.ts.map +1 -1
  12. package/dist/coordinator-actions.d.ts +12 -0
  13. package/dist/coordinator-actions.d.ts.map +1 -1
  14. package/dist/coordinator-api.d.ts +7 -0
  15. package/dist/coordinator-api.d.ts.map +1 -1
  16. package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
  17. package/dist/coordinator-auth-link-revocation-test-harness.d.ts.map +1 -1
  18. package/dist/coordinator-auth-schema-stage.d.ts +14 -2
  19. package/dist/coordinator-auth-schema-stage.d.ts.map +1 -1
  20. package/dist/coordinator-block-tombstone-test-harness.d.ts +3 -0
  21. package/dist/coordinator-block-tombstone-test-harness.d.ts.map +1 -0
  22. package/dist/coordinator-bootstrap-authorization-api-test-harness.d.ts.map +1 -1
  23. package/dist/coordinator-bootstrap-authorization-test-harness.d.ts.map +1 -1
  24. package/dist/coordinator-bootstrap-revocation-test-harness.d.ts.map +1 -1
  25. package/dist/coordinator-boundary-readiness-client.d.ts +35 -0
  26. package/dist/coordinator-boundary-readiness-client.d.ts.map +1 -0
  27. package/dist/coordinator-boundary-readiness-route.d.ts +52 -0
  28. package/dist/coordinator-boundary-readiness-route.d.ts.map +1 -0
  29. package/dist/coordinator-boundary-readiness-test-harness.d.ts +15 -0
  30. package/dist/coordinator-boundary-readiness-test-harness.d.ts.map +1 -0
  31. package/dist/coordinator-boundary-readiness.d.ts +161 -0
  32. package/dist/coordinator-boundary-readiness.d.ts.map +1 -0
  33. package/dist/coordinator-browser-auth-app.d.ts +1 -1
  34. package/dist/coordinator-browser-auth-app.d.ts.map +1 -1
  35. package/dist/coordinator-browser-auth-callback.d.ts +2 -1
  36. package/dist/coordinator-browser-auth-callback.d.ts.map +1 -1
  37. package/dist/coordinator-controller-revocation-test-harness.d.ts.map +1 -1
  38. package/dist/coordinator-d1-schema-inventory.d.ts +2 -0
  39. package/dist/coordinator-d1-schema-inventory.d.ts.map +1 -1
  40. package/dist/coordinator-d1-scope-authorization-test-harness.d.ts.map +1 -1
  41. package/dist/coordinator-device-auth-link.d.ts +1 -0
  42. package/dist/coordinator-device-auth-link.d.ts.map +1 -1
  43. package/dist/coordinator-device-rejoin-browser-evidence.d.ts +28 -0
  44. package/dist/coordinator-device-rejoin-browser-evidence.d.ts.map +1 -0
  45. package/dist/coordinator-device-rejoin-browser-transaction-test-harness.d.ts +8 -0
  46. package/dist/coordinator-device-rejoin-browser-transaction-test-harness.d.ts.map +1 -0
  47. package/dist/coordinator-device-rejoin-browser-transaction.d.ts +43 -0
  48. package/dist/coordinator-device-rejoin-browser-transaction.d.ts.map +1 -0
  49. package/dist/coordinator-device-rejoin-browser-view.d.ts +30 -0
  50. package/dist/coordinator-device-rejoin-browser-view.d.ts.map +1 -0
  51. package/dist/coordinator-device-rejoin-browser.d.ts +26 -0
  52. package/dist/coordinator-device-rejoin-browser.d.ts.map +1 -0
  53. package/dist/coordinator-device-rejoin-client-requests.d.ts +70 -0
  54. package/dist/coordinator-device-rejoin-client-requests.d.ts.map +1 -0
  55. package/dist/coordinator-device-rejoin-client.d.ts +15 -0
  56. package/dist/coordinator-device-rejoin-client.d.ts.map +1 -0
  57. package/dist/coordinator-device-rejoin-confirmation-test-harness.d.ts +22 -0
  58. package/dist/coordinator-device-rejoin-confirmation-test-harness.d.ts.map +1 -0
  59. package/dist/coordinator-device-rejoin-confirmation.d.ts +18 -0
  60. package/dist/coordinator-device-rejoin-confirmation.d.ts.map +1 -0
  61. package/dist/coordinator-device-rejoin-destinations-test-harness.d.ts +7 -0
  62. package/dist/coordinator-device-rejoin-destinations-test-harness.d.ts.map +1 -0
  63. package/dist/coordinator-device-rejoin-destinations.d.ts +25 -0
  64. package/dist/coordinator-device-rejoin-destinations.d.ts.map +1 -0
  65. package/dist/coordinator-device-rejoin-display.d.ts +14 -0
  66. package/dist/coordinator-device-rejoin-display.d.ts.map +1 -0
  67. package/dist/coordinator-device-rejoin-event-client.d.ts +30 -0
  68. package/dist/coordinator-device-rejoin-event-client.d.ts.map +1 -0
  69. package/dist/coordinator-device-rejoin-events.d.ts +7 -0
  70. package/dist/coordinator-device-rejoin-events.d.ts.map +1 -0
  71. package/dist/coordinator-device-rejoin-finalize-test-harness.d.ts +14 -0
  72. package/dist/coordinator-device-rejoin-finalize-test-harness.d.ts.map +1 -0
  73. package/dist/coordinator-device-rejoin-finalize.d.ts +36 -0
  74. package/dist/coordinator-device-rejoin-finalize.d.ts.map +1 -0
  75. package/dist/coordinator-device-rejoin-http.d.ts +11 -0
  76. package/dist/coordinator-device-rejoin-http.d.ts.map +1 -0
  77. package/dist/coordinator-device-rejoin-link-evidence-test-harness.d.ts +17 -0
  78. package/dist/coordinator-device-rejoin-link-evidence-test-harness.d.ts.map +1 -0
  79. package/dist/coordinator-device-rejoin-link-evidence.d.ts +29 -0
  80. package/dist/coordinator-device-rejoin-link-evidence.d.ts.map +1 -0
  81. package/dist/coordinator-device-rejoin-link-lineage.d.ts +7 -0
  82. package/dist/coordinator-device-rejoin-link-lineage.d.ts.map +1 -0
  83. package/dist/coordinator-device-rejoin-oidc-pins.d.ts +14 -0
  84. package/dist/coordinator-device-rejoin-oidc-pins.d.ts.map +1 -0
  85. package/dist/coordinator-device-rejoin-proof.d.ts +41 -0
  86. package/dist/coordinator-device-rejoin-proof.d.ts.map +1 -0
  87. package/dist/coordinator-device-rejoin-schema-test-harness.d.ts +8 -0
  88. package/dist/coordinator-device-rejoin-schema-test-harness.d.ts.map +1 -0
  89. package/dist/coordinator-device-rejoin-schema.d.ts +9 -0
  90. package/dist/coordinator-device-rejoin-schema.d.ts.map +1 -0
  91. package/dist/coordinator-device-rejoin-start-evidence-test-harness.d.ts +40 -0
  92. package/dist/coordinator-device-rejoin-start-evidence-test-harness.d.ts.map +1 -0
  93. package/dist/coordinator-device-rejoin-start-evidence.d.ts +25 -0
  94. package/dist/coordinator-device-rejoin-start-evidence.d.ts.map +1 -0
  95. package/dist/coordinator-device-rejoin-start-http.d.ts +12 -0
  96. package/dist/coordinator-device-rejoin-start-http.d.ts.map +1 -0
  97. package/dist/coordinator-device-rejoin-start-input.d.ts +23 -0
  98. package/dist/coordinator-device-rejoin-start-input.d.ts.map +1 -0
  99. package/dist/coordinator-device-rejoin-start-write.d.ts +38 -0
  100. package/dist/coordinator-device-rejoin-start-write.d.ts.map +1 -0
  101. package/dist/coordinator-device-rejoin-status-http.d.ts +10 -0
  102. package/dist/coordinator-device-rejoin-status-http.d.ts.map +1 -0
  103. package/dist/coordinator-device-rejoin-status-live-test-harness.d.ts +33 -0
  104. package/dist/coordinator-device-rejoin-status-live-test-harness.d.ts.map +1 -0
  105. package/dist/coordinator-device-rejoin-status-projection.d.ts +28 -0
  106. package/dist/coordinator-device-rejoin-status-projection.d.ts.map +1 -0
  107. package/dist/coordinator-device-rejoin-status-test-harness.d.ts +8 -0
  108. package/dist/coordinator-device-rejoin-status-test-harness.d.ts.map +1 -0
  109. package/dist/coordinator-device-rejoin-status.d.ts +39 -0
  110. package/dist/coordinator-device-rejoin-status.d.ts.map +1 -0
  111. package/dist/coordinator-device-removal-commands.d.ts +13 -0
  112. package/dist/coordinator-device-removal-commands.d.ts.map +1 -0
  113. package/dist/coordinator-device-removal-commit-test-harness.d.ts +3 -0
  114. package/dist/coordinator-device-removal-commit-test-harness.d.ts.map +1 -0
  115. package/dist/coordinator-device-removal-commit.d.ts +44 -0
  116. package/dist/coordinator-device-removal-commit.d.ts.map +1 -0
  117. package/dist/coordinator-device-removal-dependents-test-harness.d.ts +9 -0
  118. package/dist/coordinator-device-removal-dependents-test-harness.d.ts.map +1 -0
  119. package/dist/coordinator-device-removal-dependents.d.ts +34 -0
  120. package/dist/coordinator-device-removal-dependents.d.ts.map +1 -0
  121. package/dist/coordinator-device-removal-list-test-harness.d.ts +4 -0
  122. package/dist/coordinator-device-removal-list-test-harness.d.ts.map +1 -0
  123. package/dist/coordinator-device-removal-list.d.ts +40 -0
  124. package/dist/coordinator-device-removal-list.d.ts.map +1 -0
  125. package/dist/coordinator-device-removal-preview-test-harness.d.ts +9 -0
  126. package/dist/coordinator-device-removal-preview-test-harness.d.ts.map +1 -0
  127. package/dist/coordinator-device-removal-routes.d.ts +13 -0
  128. package/dist/coordinator-device-removal-routes.d.ts.map +1 -0
  129. package/dist/coordinator-device-removal-target.d.ts +98 -0
  130. package/dist/coordinator-device-removal-target.d.ts.map +1 -0
  131. package/dist/coordinator-device-removal-test-harness.d.ts +70 -0
  132. package/dist/coordinator-device-removal-test-harness.d.ts.map +1 -0
  133. package/dist/coordinator-device-removal-writer-test-harness.d.ts +8 -0
  134. package/dist/coordinator-device-removal-writer-test-harness.d.ts.map +1 -0
  135. package/dist/coordinator-device-removal.d.ts +233 -0
  136. package/dist/coordinator-device-removal.d.ts.map +1 -0
  137. package/dist/coordinator-device-revocation-client.d.ts +2 -0
  138. package/dist/coordinator-device-revocation-client.d.ts.map +1 -1
  139. package/dist/coordinator-device-revocation-handler-test-harness.d.ts.map +1 -1
  140. package/dist/coordinator-device-revocation-handler.d.ts +1 -1
  141. package/dist/coordinator-device-revocation-handler.d.ts.map +1 -1
  142. package/dist/coordinator-device-revocation-route.d.ts.map +1 -1
  143. package/dist/coordinator-device-revocation-test-harness.d.ts.map +1 -1
  144. package/dist/coordinator-device-revocation.d.ts +20 -2
  145. package/dist/coordinator-device-revocation.d.ts.map +1 -1
  146. package/dist/coordinator-enrollment-reconciler.d.ts.map +1 -1
  147. package/dist/coordinator-enrollment-test-fixtures.d.ts +126 -0
  148. package/dist/coordinator-enrollment-test-fixtures.d.ts.map +1 -0
  149. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts +1 -1
  150. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts.map +1 -1
  151. package/dist/coordinator-identity-grant-revocation-test-harness.d.ts.map +1 -1
  152. package/dist/coordinator-identity-group-grant-test-harness.d.ts.map +1 -1
  153. package/dist/coordinator-invitation-lift-test-harness.d.ts +6 -0
  154. package/dist/coordinator-invitation-lift-test-harness.d.ts.map +1 -0
  155. package/dist/coordinator-invitation-removal.d.ts +71 -0
  156. package/dist/coordinator-invitation-removal.d.ts.map +1 -0
  157. package/dist/coordinator-join-review-guards.d.ts +2 -0
  158. package/dist/coordinator-join-review-guards.d.ts.map +1 -1
  159. package/dist/coordinator-join-revocation-test-harness.d.ts.map +1 -1
  160. package/dist/coordinator-key-id-fill-api-test-harness.d.ts +12 -0
  161. package/dist/coordinator-key-id-fill-api-test-harness.d.ts.map +1 -0
  162. package/dist/coordinator-key-id-fill-api.d.ts +19 -0
  163. package/dist/coordinator-key-id-fill-api.d.ts.map +1 -0
  164. package/dist/coordinator-legacy-device-ownership.d.ts +66 -5
  165. package/dist/coordinator-legacy-device-ownership.d.ts.map +1 -1
  166. package/dist/coordinator-legacy-owner-compatibility.d.ts +3 -0
  167. package/dist/coordinator-legacy-owner-compatibility.d.ts.map +1 -1
  168. package/dist/coordinator-membership-enrollment-test-harness.d.ts +4 -0
  169. package/dist/coordinator-membership-enrollment-test-harness.d.ts.map +1 -0
  170. package/dist/coordinator-membership-enrollment.d.ts +15 -0
  171. package/dist/coordinator-membership-enrollment.d.ts.map +1 -0
  172. package/dist/coordinator-owner-enrollment-commit.d.ts +1 -1
  173. package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -1
  174. package/dist/coordinator-owner-enrollment-qualification-test-harness.d.ts.map +1 -1
  175. package/dist/coordinator-owner-enrollment-qualification.d.ts +1 -0
  176. package/dist/coordinator-owner-enrollment-qualification.d.ts.map +1 -1
  177. package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts.map +1 -1
  178. package/dist/coordinator-peer-discovery-revocation-test-harness.d.ts.map +1 -1
  179. package/dist/coordinator-peer-removal-api-test-harness.d.ts +29 -0
  180. package/dist/coordinator-peer-removal-api-test-harness.d.ts.map +1 -0
  181. package/dist/coordinator-peer-removal-query-test-harness.d.ts +4 -0
  182. package/dist/coordinator-peer-removal-query-test-harness.d.ts.map +1 -0
  183. package/dist/coordinator-peer-removal-query.d.ts +32 -0
  184. package/dist/coordinator-peer-removal-query.d.ts.map +1 -0
  185. package/dist/coordinator-peer-revocation-route.d.ts +45 -0
  186. package/dist/coordinator-peer-revocation-route.d.ts.map +1 -0
  187. package/dist/coordinator-peer-revocation.d.ts +61 -0
  188. package/dist/coordinator-peer-revocation.d.ts.map +1 -0
  189. package/dist/coordinator-presence-capabilities.d.ts +10 -0
  190. package/dist/coordinator-presence-capabilities.d.ts.map +1 -0
  191. package/dist/coordinator-project-revocation-test-harness.d.ts +1 -1
  192. package/dist/coordinator-project-revocation-test-harness.d.ts.map +1 -1
  193. package/dist/coordinator-recipient-revocation-test-harness.d.ts.map +1 -1
  194. package/dist/coordinator-refresh-lifecycle.d.ts +11 -0
  195. package/dist/coordinator-refresh-lifecycle.d.ts.map +1 -0
  196. package/dist/coordinator-rejoin-discovery.d.ts +16 -0
  197. package/dist/coordinator-rejoin-discovery.d.ts.map +1 -0
  198. package/dist/coordinator-rejoin-timestamp.d.ts +3 -0
  199. package/dist/coordinator-rejoin-timestamp.d.ts.map +1 -0
  200. package/dist/coordinator-removal-notice.d.ts +21 -0
  201. package/dist/coordinator-removal-notice.d.ts.map +1 -0
  202. package/dist/coordinator-removal-progress-listing-test-harness.d.ts +3 -0
  203. package/dist/coordinator-removal-progress-listing-test-harness.d.ts.map +1 -0
  204. package/dist/coordinator-runtime-ynLTJI6d.js +1712 -0
  205. package/dist/coordinator-runtime-ynLTJI6d.js.map +1 -0
  206. package/dist/coordinator-runtime.d.ts +20 -1
  207. package/dist/coordinator-runtime.d.ts.map +1 -1
  208. package/dist/coordinator-scope-authorization-api-test-harness.d.ts.map +1 -1
  209. package/dist/coordinator-store-contract.d.ts +21 -3
  210. package/dist/coordinator-store-contract.d.ts.map +1 -1
  211. package/dist/coordinator-store-test-harness.d.ts.map +1 -1
  212. package/dist/coordinator-sync-config.d.ts +14 -0
  213. package/dist/coordinator-sync-config.d.ts.map +1 -1
  214. package/dist/d1-coordinator-runtime.d.ts +3 -1
  215. package/dist/d1-coordinator-runtime.d.ts.map +1 -1
  216. package/dist/d1-coordinator-store.d.ts +63 -3
  217. package/dist/d1-coordinator-store.d.ts.map +1 -1
  218. package/dist/database-runtime-primitives.d.ts +1 -1
  219. package/dist/db.d.ts.map +1 -1
  220. package/dist/device-identity-binding.d.ts +24 -0
  221. package/dist/device-identity-binding.d.ts.map +1 -1
  222. package/dist/device-identity-inventory.d.ts +19 -1
  223. package/dist/device-identity-inventory.d.ts.map +1 -1
  224. package/dist/device-retirement.d.ts +43 -0
  225. package/dist/device-retirement.d.ts.map +1 -0
  226. package/dist/identity-device-assignment.d.ts +8 -0
  227. package/dist/identity-device-assignment.d.ts.map +1 -1
  228. package/dist/index.d.ts +34 -8
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +11649 -10631
  231. package/dist/index.js.map +1 -1
  232. package/dist/internal/cloudflare-coordinator.js +2317 -1542
  233. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  234. package/dist/internal/relay-runtime.js +28 -28
  235. package/dist/legacy-pairing-assignment-conversion.d.ts +46 -0
  236. package/dist/legacy-pairing-assignment-conversion.d.ts.map +1 -0
  237. package/dist/legacy-pairing-assignment-state.d.ts +11 -0
  238. package/dist/legacy-pairing-assignment-state.d.ts.map +1 -0
  239. package/dist/legacy-team-setup-errors.d.ts +2 -1
  240. package/dist/legacy-team-setup-errors.d.ts.map +1 -1
  241. package/dist/local-origin-claim.d.ts +48 -0
  242. package/dist/local-origin-claim.d.ts.map +1 -0
  243. package/dist/maintenance/ai-structured.d.ts +2 -0
  244. package/dist/maintenance/ai-structured.d.ts.map +1 -1
  245. package/dist/observer-config.d.ts.map +1 -1
  246. package/dist/owned-recipient-d1-test-harness.d.ts.map +1 -1
  247. package/dist/owner-enrollment-link-authority.d.ts +1 -0
  248. package/dist/owner-enrollment-link-authority.d.ts.map +1 -1
  249. package/dist/{owner-enrollment-start-BsDwgxAh.js → owner-enrollment-start-D8QzF1Ar.js} +5548 -3637
  250. package/dist/owner-enrollment-start-D8QzF1Ar.js.map +1 -0
  251. package/dist/pairing-removal.d.ts +57 -0
  252. package/dist/pairing-removal.d.ts.map +1 -0
  253. package/dist/peer-project-filter-change.d.ts +33 -0
  254. package/dist/peer-project-filter-change.d.ts.map +1 -0
  255. package/dist/peer-project-filter-management.d.ts +7 -0
  256. package/dist/peer-project-filter-management.d.ts.map +1 -0
  257. package/dist/peer-project-filter-retention.d.ts +17 -0
  258. package/dist/peer-project-filter-retention.d.ts.map +1 -0
  259. package/dist/peer-removal-check-state.d.ts +24 -0
  260. package/dist/peer-removal-check-state.d.ts.map +1 -0
  261. package/dist/peer-removal.d.ts +34 -0
  262. package/dist/peer-removal.d.ts.map +1 -0
  263. package/dist/peer-traversal-coordinator-attempt-write-test-fixtures.d.ts.map +1 -1
  264. package/dist/peer-traversal-coordinator-decision-test-fixtures.d.ts.map +1 -1
  265. package/dist/policy-team-device-eligibility.d.ts +10 -0
  266. package/dist/policy-team-device-eligibility.d.ts.map +1 -1
  267. package/dist/project-boundary-migration-hold.d.ts +50 -0
  268. package/dist/project-boundary-migration-hold.d.ts.map +1 -0
  269. package/dist/project-boundary-migration-records.d.ts +46 -0
  270. package/dist/project-boundary-migration-records.d.ts.map +1 -0
  271. package/dist/project-filters-narrowing.d.ts +11 -0
  272. package/dist/project-filters-narrowing.d.ts.map +1 -0
  273. package/dist/project-scope-resume.d.ts +26 -0
  274. package/dist/project-scope-resume.d.ts.map +1 -0
  275. package/dist/project-scope-settings.d.ts +7 -0
  276. package/dist/project-scope-settings.d.ts.map +1 -1
  277. package/dist/project-scope-withdrawal.d.ts +48 -0
  278. package/dist/project-scope-withdrawal.d.ts.map +1 -0
  279. package/dist/project-withdrawal-state.d.ts +36 -0
  280. package/dist/project-withdrawal-state.d.ts.map +1 -0
  281. package/dist/{recipient-policy-contract-Ca40IBUh.js → recipient-policy-contract-BHxfaQZ2.js} +12 -5
  282. package/dist/recipient-policy-contract-BHxfaQZ2.js.map +1 -0
  283. package/dist/recipient-policy-contract.d.ts +7 -0
  284. package/dist/recipient-policy-contract.d.ts.map +1 -1
  285. package/dist/recipient-policy-contract.js +2 -2
  286. package/dist/recipient-policy-edges.d.ts.map +1 -1
  287. package/dist/recipient-policy-intent.d.ts +1 -0
  288. package/dist/recipient-policy-intent.d.ts.map +1 -1
  289. package/dist/recipient-policy-onboarding.d.ts.map +1 -1
  290. package/dist/recipient-policy-reconciler.d.ts.map +1 -1
  291. package/dist/recipient-policy-reconciliation.d.ts.map +1 -1
  292. package/dist/recipient-policy-team-create.d.ts +22 -0
  293. package/dist/recipient-policy-team-create.d.ts.map +1 -0
  294. package/dist/{relay-health-CeyhVeuq.js → relay-health-B8BpHFaE.js} +14 -14
  295. package/dist/{relay-health-CeyhVeuq.js.map → relay-health-B8BpHFaE.js.map} +1 -1
  296. package/dist/{relay-peer-client-DmZfZebO.js → relay-peer-client-w7WdS1AP.js} +3083 -2634
  297. package/dist/relay-peer-client-w7WdS1AP.js.map +1 -0
  298. package/dist/relay-server-test-fixtures.d.ts.map +1 -1
  299. package/dist/replication-cursor-orphan-cleanup.d.ts +14 -0
  300. package/dist/replication-cursor-orphan-cleanup.d.ts.map +1 -0
  301. package/dist/retired-device-aliases.d.ts +28 -0
  302. package/dist/retired-device-aliases.d.ts.map +1 -0
  303. package/dist/same-actor-peers.d.ts +5 -1
  304. package/dist/same-actor-peers.d.ts.map +1 -1
  305. package/dist/schema-bootstrap.d.ts +1 -0
  306. package/dist/schema-bootstrap.d.ts.map +1 -1
  307. package/dist/schema.d.ts +4456 -3623
  308. package/dist/schema.d.ts.map +1 -1
  309. package/dist/{scope-membership-cache-read-B6z47l2W.js → scope-resolution-B7FK15hx.js} +2242 -1608
  310. package/dist/scope-resolution-B7FK15hx.js.map +1 -0
  311. package/dist/semantic-worker-entry.js +1 -1
  312. package/dist/{semantic-worker-job-BLaC4xRY.js → semantic-worker-job-BjujlM4-.js} +3 -3
  313. package/dist/{semantic-worker-job-BLaC4xRY.js.map → semantic-worker-job-BjujlM4-.js.map} +1 -1
  314. package/dist/{semantic-worker-ranking-5-VSzEmx.js → semantic-worker-ranking-WaUCapnY.js} +66 -60
  315. package/dist/semantic-worker-ranking-WaUCapnY.js.map +1 -0
  316. package/dist/share-provisioning.d.ts +4 -0
  317. package/dist/share-provisioning.d.ts.map +1 -1
  318. package/dist/shared-owned-device-enrollment-test-harness.d.ts.map +1 -1
  319. package/dist/shared-owned-project-invites-test-harness.d.ts.map +1 -1
  320. package/dist/shared-owned-recipient-invites-test-harness.d.ts.map +1 -1
  321. package/dist/shared-ownership-writer-lifecycle-test-harness.d.ts.map +1 -1
  322. package/dist/snapshot-cross-scope-reconcile.d.ts +25 -0
  323. package/dist/snapshot-cross-scope-reconcile.d.ts.map +1 -0
  324. package/dist/{sync-auth-constants-BVzVfSmn.js → sync-auth-constants-DNUSV-Tn.js} +4482 -2842
  325. package/dist/sync-auth-constants-DNUSV-Tn.js.map +1 -0
  326. package/dist/sync-bootstrap.d.ts +2 -0
  327. package/dist/sync-bootstrap.d.ts.map +1 -1
  328. package/dist/sync-capability.d.ts +1 -1
  329. package/dist/sync-capability.d.ts.map +1 -1
  330. package/dist/sync-channel-progress.d.ts +7 -0
  331. package/dist/sync-channel-progress.d.ts.map +1 -1
  332. package/dist/sync-daemon.d.ts +4 -1
  333. package/dist/sync-daemon.d.ts.map +1 -1
  334. package/dist/sync-pass.d.ts.map +1 -1
  335. package/dist/sync-peer-addresses.d.ts +4 -2
  336. package/dist/sync-peer-addresses.d.ts.map +1 -1
  337. package/dist/sync-reachability-pass-BpTtRqcV.js +2 -0
  338. package/dist/{sync-reachability-pass-Dhn4N2hr.js → sync-reachability-pass-DKEORTbs.js} +2638 -2591
  339. package/dist/sync-reachability-pass-DKEORTbs.js.map +1 -0
  340. package/dist/sync-replication.d.ts +21 -3
  341. package/dist/sync-replication.d.ts.map +1 -1
  342. package/dist/sync-scope-protocol.d.ts.map +1 -1
  343. package/dist/test-environment-isolation.d.ts +2 -0
  344. package/dist/test-environment-isolation.d.ts.map +1 -0
  345. package/dist/test-schema.generated.d.ts +1 -1
  346. package/dist/test-schema.generated.d.ts.map +1 -1
  347. package/dist/test-utils.d.ts +4 -0
  348. package/dist/test-utils.d.ts.map +1 -1
  349. package/dist/{validated-vector-index-audit-B64yhEBF.js → validated-vector-index-audit-BtUovYuM.js} +269 -637
  350. package/dist/validated-vector-index-audit-BtUovYuM.js.map +1 -0
  351. package/dist/viewer-device-removal-commit.d.ts +56 -0
  352. package/dist/viewer-device-removal-commit.d.ts.map +1 -0
  353. package/dist/viewer-device-removal-evidence.d.ts +17 -0
  354. package/dist/viewer-device-removal-evidence.d.ts.map +1 -0
  355. package/dist/{scope-membership-semantics-B8qXaMqx.js → workspace-identity-C7EPmSZe.js} +121 -49
  356. package/dist/workspace-identity-C7EPmSZe.js.map +1 -0
  357. package/package.json +3 -3
  358. package/dist/coordinator-runtime-CEc6KhBE.js +0 -594
  359. package/dist/coordinator-runtime-CEc6KhBE.js.map +0 -1
  360. package/dist/owner-enrollment-start-BsDwgxAh.js.map +0 -1
  361. package/dist/recipient-policy-contract-Ca40IBUh.js.map +0 -1
  362. package/dist/relay-peer-client-DmZfZebO.js.map +0 -1
  363. package/dist/scope-membership-cache-read-B6z47l2W.js.map +0 -1
  364. package/dist/scope-membership-semantics-B8qXaMqx.js.map +0 -1
  365. package/dist/semantic-worker-ranking-5-VSzEmx.js.map +0 -1
  366. package/dist/sync-auth-constants-BVzVfSmn.js.map +0 -1
  367. package/dist/sync-reachability-pass-C_-w0t6b.js +0 -2
  368. package/dist/sync-reachability-pass-Dhn4N2hr.js.map +0 -1
  369. package/dist/validated-vector-index-audit-B64yhEBF.js.map +0 -1
  370. package/dist/workspace-identity-DI8bBR0Y.js +0 -76
  371. package/dist/workspace-identity-DI8bBR0Y.js.map +0 -1
@@ -0,0 +1,1712 @@
1
+ import { Qt as e, Vt as t, Xt as n, Zt as r, l as i } from "./scope-resolution-B7FK15hx.js";
2
+ import { _ as a, h as o } from "./workspace-identity-C7EPmSZe.js";
3
+ import { Na as s, V as c, i as l, io as u, lo as d, r as f } from "./sync-auth-constants-DNUSV-Tn.js";
4
+ import { A as p, J as m, M as h, O as g, T as _, V as ee, _ as v, ct as y, ft as te, g as ne, j as b, m as re, v as ie, y as ae } from "./relay-peer-client-w7WdS1AP.js";
5
+ import { createHash as oe } from "node:crypto";
6
+ import { networkInterfaces as se } from "node:os";
7
+ //#region src/identity-device-assignment.ts
8
+ var x = class extends Error {
9
+ code;
10
+ constructor(e) {
11
+ super(e), this.name = "IdentityDeviceAssignmentError", this.code = e;
12
+ }
13
+ };
14
+ function S() {
15
+ throw new x("team_setup_assignment_changed");
16
+ }
17
+ function ce(e) {
18
+ return typeof e == "object" && !!e && "code" in e && e.code === "SQLITE_CONSTRAINT_PRIMARYKEY";
19
+ }
20
+ function le(e, t) {
21
+ return e.prepare("SELECT identity_id, assignment_version, status\n FROM identity_devices\n WHERE device_id = ?").get(t) ?? null;
22
+ }
23
+ function ue(e, t) {
24
+ if (t.kind === "absent") {
25
+ e && S();
26
+ return;
27
+ }
28
+ (e?.status !== "active" || e.identity_id !== t.identityId || e.assignment_version !== t.assignmentVersion) && S();
29
+ }
30
+ function de(e, t, n) {
31
+ let r = e.prepare("SELECT d.team_id\n FROM policy_team_device_decisions d\n JOIN policy_teams t ON t.team_id = d.team_id\n WHERE d.device_id = ?\n AND d.decision = 'included'\n AND t.device_eligibility_mode = 'reviewed_allowlist'").all(t), i = e.prepare("UPDATE policy_team_device_decisions\n SET decision = 'unresolved', updated_at = ?\n WHERE device_id = ?\n AND decision = 'included'\n AND team_id IN (\n SELECT team_id FROM policy_teams\n WHERE device_eligibility_mode = 'reviewed_allowlist'\n )").run(n, t);
32
+ for (let t of r) e.prepare("UPDATE policy_teams\n SET source_fingerprint = NULL, updated_at = ?\n WHERE team_id = ?").run(n, t.team_id);
33
+ return {
34
+ invalidatedDecisionCount: i.changes,
35
+ invalidatedTeamCount: r.length
36
+ };
37
+ }
38
+ function fe(e, t) {
39
+ if (!e.inTransaction) throw new x("identity_device_assignment_transaction_required");
40
+ let n = le(e, t.deviceId);
41
+ if (ue(n, t.expectation), n?.status === "active" && n?.identity_id === t.targetIdentityId) return {
42
+ assignmentVersion: n.assignment_version,
43
+ changed: !1,
44
+ invalidatedDecisionCount: 0,
45
+ invalidatedTeamCount: 0
46
+ };
47
+ let r = t.now ?? (/* @__PURE__ */ new Date()).toISOString();
48
+ if (n) {
49
+ let n = t.expectation;
50
+ n.kind !== "existing" && S();
51
+ let i = n.identityId !== t.targetIdentityId;
52
+ e.prepare(`UPDATE identity_devices
53
+ SET identity_id = ?, ${i ? "source_fingerprint = NULL," : ""} updated_at = ?
54
+ WHERE device_id = ?
55
+ AND identity_id = ?
56
+ AND assignment_version = ?
57
+ AND status = 'active'`).run(t.targetIdentityId, r, t.deviceId, n.identityId, n.assignmentVersion).changes !== 1 && S();
58
+ } else {
59
+ let n = t.insert;
60
+ if (!n) throw new x("identity_device_assignment_insert_values_required");
61
+ try {
62
+ e.prepare("INSERT INTO identity_devices(\n device_id, identity_id, display_name, status, provenance, revision,\n migration_state, source_fingerprint, idempotency_key, created_at, updated_at\n ) VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?)").run(t.deviceId, t.targetIdentityId, n.displayName, n.provenance, n.revision, n.migrationState, n.sourceFingerprint ?? null, n.idempotencyKey, r, r);
63
+ } catch (e) {
64
+ throw ce(e) && S(), e;
65
+ }
66
+ }
67
+ let i = le(e, t.deviceId);
68
+ return (i?.status !== "active" || i.identity_id !== t.targetIdentityId) && S(), n ? {
69
+ assignmentVersion: i.assignment_version,
70
+ changed: !0,
71
+ ...de(e, t.deviceId, r)
72
+ } : {
73
+ assignmentVersion: i.assignment_version,
74
+ changed: !0,
75
+ invalidatedDecisionCount: 0,
76
+ invalidatedTeamCount: 0
77
+ };
78
+ }
79
+ //#endregion
80
+ //#region src/coordinator-rejoin-timestamp.ts
81
+ function pe(e) {
82
+ return typeof e == "number" && Number.isSafeInteger(e) && e >= 0 && e <= 864e13;
83
+ }
84
+ //#endregion
85
+ //#region src/retired-device-aliases.ts
86
+ function C(e) {
87
+ if (!e) return null;
88
+ let t = a(e);
89
+ return t.kind === "ed25519" ? oe("sha256").update(t.blob).digest("hex") : null;
90
+ }
91
+ function me(e) {
92
+ e.exec("CREATE TABLE IF NOT EXISTS retired_device_aliases (\n device_id TEXT PRIMARY KEY,\n kind TEXT NOT NULL CHECK(kind IN ('device_id', 'key')),\n fingerprint TEXT NOT NULL,\n key_id TEXT,\n retired_at TEXT NOT NULL\n )");
93
+ }
94
+ function he(e) {
95
+ if (!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'retired_device_aliases'").get()) return /* @__PURE__ */ new Map();
96
+ let t = e.prepare("SELECT device_id, kind, fingerprint, key_id FROM retired_device_aliases").all();
97
+ return new Map(t.map((e) => [e.device_id, {
98
+ kind: e.kind,
99
+ fingerprint: e.fingerprint,
100
+ keyId: e.key_id
101
+ }]));
102
+ }
103
+ function w(e, t) {
104
+ if (!e) return !1;
105
+ if (e.kind === "device_id" || !t || !t.publicKey && !t.fingerprint) return !0;
106
+ let n = C(t.publicKey);
107
+ return e.keyId && n ? n === e.keyId : t.fingerprint === e.fingerprint;
108
+ }
109
+ function ge(e, t) {
110
+ me(e);
111
+ let n = e.prepare("INSERT INTO retired_device_aliases(device_id, kind, fingerprint, key_id, retired_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(device_id) DO UPDATE SET\n kind = CASE WHEN retired_device_aliases.kind = 'device_id' THEN 'device_id' ELSE excluded.kind END,\n fingerprint = excluded.fingerprint,\n key_id = excluded.key_id,\n retired_at = excluded.retired_at"), r = (/* @__PURE__ */ new Date()).toISOString();
112
+ for (let e of t) n.run(e.deviceId, e.kind, e.fingerprint, e.keyId, r);
113
+ }
114
+ //#endregion
115
+ //#region src/device-identity-inventory.ts
116
+ var _e = 1, ve = 500, T = 2e3;
117
+ function E(e) {
118
+ return typeof e == "string" && e.trim() ? e.trim() : null;
119
+ }
120
+ function D(e, t) {
121
+ if (!e) return {
122
+ value: t,
123
+ conflict: !1
124
+ };
125
+ let n = o(e);
126
+ return t && t !== n ? {
127
+ value: null,
128
+ conflict: !0
129
+ } : {
130
+ value: t ?? n,
131
+ conflict: !1
132
+ };
133
+ }
134
+ function ye(e) {
135
+ let t = D(E(e.publicKey), E(e.fingerprint));
136
+ return {
137
+ deviceId: e.deviceId,
138
+ displayName: e.displayName,
139
+ source: "local_device",
140
+ fingerprint: t.value,
141
+ fingerprintConflict: t.conflict,
142
+ isLocal: !0,
143
+ suggestedIdentityId: null,
144
+ bindingIdentityId: null,
145
+ bindingStatus: null,
146
+ bindingIdentityStatus: null,
147
+ bindingAuthoritative: !1,
148
+ enrollmentEnabled: null,
149
+ pairingProof: !0,
150
+ serviceDevice: !1,
151
+ revoked: !1,
152
+ rejoinedAtMs: null
153
+ };
154
+ }
155
+ function be(e) {
156
+ let t = D(E(e.publicKey), E(e.pinnedFingerprint));
157
+ return {
158
+ deviceId: e.deviceId,
159
+ displayName: e.displayName,
160
+ source: "sync_peer",
161
+ fingerprint: t.value,
162
+ fingerprintConflict: t.conflict,
163
+ isLocal: !1,
164
+ suggestedIdentityId: E(e.suggestedIdentityId),
165
+ bindingIdentityId: null,
166
+ bindingStatus: null,
167
+ bindingIdentityStatus: null,
168
+ bindingAuthoritative: !1,
169
+ enrollmentEnabled: null,
170
+ pairingProof: E(e.trustProvenance) !== "coordinator_policy" || e.claimedLocalActor,
171
+ serviceDevice: !1,
172
+ revoked: e.retired === !0,
173
+ rejoinedAtMs: null
174
+ };
175
+ }
176
+ function xe(e) {
177
+ return {
178
+ deviceId: e.deviceId,
179
+ displayName: e.displayName,
180
+ source: "identity_binding",
181
+ fingerprint: null,
182
+ fingerprintConflict: !1,
183
+ isLocal: !1,
184
+ suggestedIdentityId: null,
185
+ bindingIdentityId: e.identityId,
186
+ bindingStatus: e.status,
187
+ bindingIdentityStatus: e.identityStatus,
188
+ bindingAuthoritative: !0,
189
+ enrollmentEnabled: null,
190
+ pairingProof: !1,
191
+ serviceDevice: !1,
192
+ revoked: e.retired === !0,
193
+ rejoinedAtMs: null
194
+ };
195
+ }
196
+ function Se(e) {
197
+ let t = D(E(e.public_key), E(e.fingerprint));
198
+ return {
199
+ deviceId: e.device_id,
200
+ displayName: E(e.display_name) ?? "",
201
+ source: "coordinator_enrollment",
202
+ fingerprint: t.value,
203
+ fingerprintConflict: t.conflict,
204
+ isLocal: !1,
205
+ suggestedIdentityId: E(e.identity_id),
206
+ bindingIdentityId: null,
207
+ bindingStatus: null,
208
+ bindingIdentityStatus: null,
209
+ bindingAuthoritative: !1,
210
+ enrollmentEnabled: e.enabled === 1,
211
+ pairingProof: !1,
212
+ serviceDevice: e.service_role === "relay_health_probe",
213
+ revoked: e.revoked === !0,
214
+ rejoinedAtMs: e.enabled === 1 && pe(e.rejoined_at_ms) ? e.rejoined_at_ms : null
215
+ };
216
+ }
217
+ function Ce(e) {
218
+ return [
219
+ ...e.localDevice ? [ye(e.localDevice)] : [],
220
+ ...e.peers.map(be),
221
+ ...e.bindings.map(xe),
222
+ ...e.coordinator.availability === "available" ? e.coordinator.enrollments.map(Se) : []
223
+ ].filter((e) => E(e.deviceId) != null);
224
+ }
225
+ function we(e) {
226
+ let t = e.map((e, t) => t), n = (e) => {
227
+ let r = t[e] ?? e;
228
+ return r === e ? e : (t[e] = n(r), t[e] ?? e);
229
+ }, r = (e, r) => {
230
+ let i = n(e), a = n(r);
231
+ i !== a && (t[a] = i);
232
+ }, i = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map();
233
+ e.forEach((e, t) => {
234
+ let n = i.get(e.deviceId);
235
+ if (n == null ? i.set(e.deviceId, t) : r(t, n), !e.fingerprint || e.fingerprintConflict) return;
236
+ let o = a.get(e.fingerprint);
237
+ o == null ? a.set(e.fingerprint, t) : r(t, o);
238
+ });
239
+ let o = /* @__PURE__ */ new Map();
240
+ return e.forEach((e, t) => {
241
+ let r = n(t);
242
+ o.set(r, [...o.get(r) ?? [], e]);
243
+ }), [...o.values()];
244
+ }
245
+ var O = [
246
+ "local_device",
247
+ "identity_binding",
248
+ "sync_peer",
249
+ "coordinator_enrollment"
250
+ ];
251
+ function Te(e, t) {
252
+ return e.find((e) => e.source === t) ?? null;
253
+ }
254
+ function Ee(e) {
255
+ for (let t of O) {
256
+ let n = e.filter((e) => e.source === t && e.displayName.length > 0 && !["Canonical device", "Unnamed device"].includes(e.displayName)).toSorted((e, t) => e.deviceId.localeCompare(t.deviceId) || e.displayName.localeCompare(t.displayName))[0];
257
+ if (n) return n.displayName;
258
+ }
259
+ return "Unnamed device";
260
+ }
261
+ function De(e, t) {
262
+ if (e.some((e) => e.revoked)) return "retired";
263
+ if (t.conflicted) return "conflicted";
264
+ if (e.every((e) => e.source === "coordinator_enrollment" && e.serviceDevice)) return "service";
265
+ if (t.activeBindings.length > 0) return "configured";
266
+ let n = e.some((e) => e.pairingProof);
267
+ return e.some((e) => e.source === "coordinator_enrollment" || e.source === "sync_peer" && !e.pairingProof) && !n ? "pairing_required" : "setup_required";
268
+ }
269
+ function Oe(e, t, n) {
270
+ return e === "service" || e === "retired" || t.length > 0 ? null : n.size === 1 ? [...n][0] ?? null : null;
271
+ }
272
+ function ke(e) {
273
+ return e.source === "identity_binding" && e.bindingAuthoritative && e.bindingStatus !== "active" && e.bindingStatus !== "removed";
274
+ }
275
+ function Ae(e) {
276
+ return e.flatMap((e) => e.rejoinedAtMs === null ? [] : [{
277
+ deviceId: e.deviceId,
278
+ rejoinedAtMs: e.rejoinedAtMs
279
+ }]).toSorted((e, t) => t.rejoinedAtMs - e.rejoinedAtMs || e.deviceId.localeCompare(t.deviceId))[0] ?? null;
280
+ }
281
+ function je(e, t) {
282
+ if (e.isLocal || [
283
+ "retired",
284
+ "service",
285
+ "conflicted"
286
+ ].includes(e.state)) return e;
287
+ let n = Ae(t);
288
+ return n ? {
289
+ ...e,
290
+ rejoin: n
291
+ } : e;
292
+ }
293
+ function Me(e) {
294
+ return new Set(e.flatMap((e) => e.fingerprint && !e.fingerprintConflict ? [e.fingerprint] : []));
295
+ }
296
+ function Ne(e) {
297
+ let t = [...new Set(e.map((e) => e.deviceId))].toSorted(), n = Me(e), r = e.filter((e) => e.source === "identity_binding" && e.bindingAuthoritative && e.bindingStatus === "active"), i = new Set(r.flatMap((e) => e.bindingIdentityId ? [e.bindingIdentityId] : [])), a = new Set(e.flatMap((e) => e.suggestedIdentityId ? [e.suggestedIdentityId] : [])), o = [
298
+ e.some((e) => e.fingerprintConflict) ? "fingerprint_invalid" : null,
299
+ n.size > 1 ? "fingerprint_conflict" : null,
300
+ i.size > 1 ? "identity_binding_conflict" : null,
301
+ e.some((e) => e.source === "identity_binding" && e.bindingAuthoritative && e.bindingStatus === "active" && e.bindingIdentityStatus !== "active") ? "identity_inactive" : null,
302
+ e.some(ke) ? "identity_binding_revoked" : null,
303
+ e.some((e) => e.source === "coordinator_enrollment" && e.enrollmentEnabled === !1) ? "coordinator_enrollment_disabled" : null
304
+ ].filter((e) => e != null), s = De(e, {
305
+ conflicted: o.length > 0,
306
+ activeBindings: r
307
+ }), c = O.map((t) => Te(e, t)).find((e) => e != null), l = O.filter((t) => e.some((e) => e.source === t));
308
+ return je({
309
+ version: 1,
310
+ deviceId: c?.deviceId ?? t[0] ?? "",
311
+ evidenceDeviceIds: t,
312
+ displayName: Ee(e),
313
+ state: s,
314
+ identityId: s === "configured" && i.size === 1 ? [...i][0] ?? null : null,
315
+ suggestedIdentityId: Oe(s, r, a),
316
+ validatedFingerprint: n.size === 1 ? [...n][0] ?? null : null,
317
+ isLocal: e.some((e) => e.isLocal),
318
+ sources: l,
319
+ conflictCodes: [...new Set(o)].toSorted()
320
+ }, e);
321
+ }
322
+ function Pe(e, t = {}) {
323
+ let n = Math.max(1, Math.min(t.limit ?? 500, 2e3)), r = we(Ce(e)).map(Ne).toSorted((e, t) => Number(t.isLocal) - Number(e.isLocal) || e.displayName.localeCompare(t.displayName) || e.deviceId.localeCompare(t.deviceId));
324
+ return {
325
+ version: 1,
326
+ items: r.slice(0, n),
327
+ coordinatorEvidence: {
328
+ availability: e.coordinator.availability,
329
+ safeErrorCode: e.coordinator.safeErrorCode
330
+ },
331
+ truncated: e.localEvidenceTruncated === !0 || r.length > n
332
+ };
333
+ }
334
+ function Fe(e) {
335
+ let t = E(e.display_name) ?? "";
336
+ return e.provenance === "coordinator_enrollment" && t === "Enrolled device" || ["managed_exact_project", "review_resolution"].includes(String(e.provenance)) && t === "Peer device" ? "" : t;
337
+ }
338
+ function Ie(e, t) {
339
+ let n = String(e.device_id ?? "");
340
+ return {
341
+ deviceId: n,
342
+ displayName: Fe(e),
343
+ identityId: String(e.identity_id ?? ""),
344
+ status: String(e.status ?? ""),
345
+ identityStatus: E(e.identity_status),
346
+ retired: t(n)
347
+ };
348
+ }
349
+ function Le(e, t) {
350
+ return e.slice(0, 2001).map((e) => Ie(e, t)).filter((e) => e.status !== "removed" || e.retired);
351
+ }
352
+ function Re(e, t) {
353
+ let n = he(e), r = new Map(t.map((e) => [e.deviceId, {
354
+ publicKey: e.publicKey,
355
+ fingerprint: e.pinnedFingerprint
356
+ }]));
357
+ return (e) => w(n.get(e), r.get(e) ?? null);
358
+ }
359
+ function ze(e, t) {
360
+ let n = e.prepare("SELECT device_id, public_key, fingerprint FROM sync_device\n WHERE device_id = ? LIMIT 1").get(t.localDeviceId), r = e.prepare("SELECT peer_device_id, name, public_key, pinned_fingerprint, actor_id,\n trust_provenance, claimed_local_actor\n FROM sync_peers ORDER BY peer_device_id LIMIT ?").all(2001), i = r.slice(0, T).map((e) => {
361
+ let t = e;
362
+ return {
363
+ deviceId: String(t.peer_device_id ?? ""),
364
+ displayName: E(t.name) ?? "",
365
+ publicKey: E(t.public_key),
366
+ pinnedFingerprint: E(t.pinned_fingerprint),
367
+ suggestedIdentityId: E(t.actor_id),
368
+ trustProvenance: E(t.trust_provenance),
369
+ claimedLocalActor: t.claimed_local_actor === 1
370
+ };
371
+ }), a = e.prepare("SELECT device.device_id, device.display_name, device.identity_id, device.status, device.provenance,\n actor.status AS identity_status\n FROM identity_devices device\n LEFT JOIN actors actor ON actor.actor_id = device.identity_id\n ORDER BY CASE\n WHEN device.device_id = ? THEN 0\n WHEN device.device_id IN (\n SELECT peer_device_id FROM sync_peers ORDER BY peer_device_id LIMIT ?\n ) THEN 1\n ELSE 2\n END, device.device_id LIMIT ?").all(t.localDeviceId, T, 2002), o = Re(e, i), s = Le(a, o);
372
+ return {
373
+ localDevice: n ? {
374
+ deviceId: n.device_id,
375
+ displayName: E(t.localDisplayName) ?? "",
376
+ publicKey: n.public_key,
377
+ fingerprint: n.fingerprint
378
+ } : null,
379
+ peers: i.map((e) => ({
380
+ ...e,
381
+ retired: o(e.deviceId)
382
+ })),
383
+ bindings: s,
384
+ coordinator: t.coordinator,
385
+ localEvidenceTruncated: r.length > T || a.length > 2001
386
+ };
387
+ }
388
+ function k(e, t, n = {}) {
389
+ return Pe(ze(e, t), n);
390
+ }
391
+ //#endregion
392
+ //#region src/recipient-policy-actor-eligibility.ts
393
+ function A(e) {
394
+ return e?.status === "active" && e.mergedIntoActorId === null;
395
+ }
396
+ function Be(e, t) {
397
+ let n = e.prepare("SELECT is_local, status, merged_into_actor_id FROM actors WHERE actor_id = ? LIMIT 1").get(t);
398
+ return n ? {
399
+ isLocal: n.is_local === 1,
400
+ status: n.status,
401
+ mergedIntoActorId: n.merged_into_actor_id
402
+ } : null;
403
+ }
404
+ function j(e, t) {
405
+ return A(Be(e, t));
406
+ }
407
+ function M(e, t) {
408
+ let n = Be(e, t);
409
+ return n?.isLocal === !0 && A(n);
410
+ }
411
+ function Ve(e) {
412
+ return e.prepare("SELECT actor_id FROM actors WHERE status = 'active' AND merged_into_actor_id IS NULL ORDER BY actor_id").pluck().all();
413
+ }
414
+ function He(e, t) {
415
+ let n = [...new Set(t)];
416
+ return n.length === 0 ? [] : e.prepare(`SELECT actor_id FROM actors
417
+ WHERE actor_id IN (${n.map(() => "?").join(", ")})
418
+ AND status = 'active' AND merged_into_actor_id IS NULL
419
+ ORDER BY actor_id`).pluck().all(...n);
420
+ }
421
+ function Ue(e, t, n) {
422
+ return M(e, t) ? t : n !== t && M(e, n) ? n : e.prepare("SELECT actor_id FROM actors\n WHERE is_local = 1 AND status = 'active' AND merged_into_actor_id IS NULL\n ORDER BY actor_id LIMIT 1").pluck().get() ?? null;
423
+ }
424
+ //#endregion
425
+ //#region src/device-identity-binding.ts
426
+ var We = 1, Ge = 100, N = class extends Error {
427
+ status;
428
+ errorCode;
429
+ constructor(e, t) {
430
+ super(t), this.status = e, this.errorCode = t;
431
+ }
432
+ }, Ke = u, P = d;
433
+ function qe(e) {
434
+ return Ke({ bindings: e.bindings.map((e) => ({
435
+ deviceId: e.deviceId,
436
+ targetIdentityId: e.targetIdentityId,
437
+ confirmed: e.confirmed,
438
+ allowRebind: e.allowRebind === !0
439
+ })) });
440
+ }
441
+ function F(e, t) {
442
+ return {
443
+ version: 1,
444
+ status: e,
445
+ reviewedInventoryDigest: "",
446
+ errorCode: t,
447
+ outcomes: [],
448
+ writeCount: 0
449
+ };
450
+ }
451
+ function Je(e) {
452
+ return typeof e?.deviceId == "string" && e.deviceId.trim() === e.deviceId && e.deviceId.length > 0 && typeof e.targetIdentityId == "string" && e.targetIdentityId.trim() === e.targetIdentityId && e.targetIdentityId.length > 0 && e.confirmed === !0 && (e.allowRebind === void 0 || typeof e.allowRebind == "boolean");
453
+ }
454
+ function Ye(e, t, n) {
455
+ return e.state === "service" ? F("conflict", "device_service_role") : e.state === "retired" ? F("conflict", "device_retired") : e.state === "pairing_required" ? F("conflict", "device_pairing_required") : e.state === "conflicted" ? F("conflict", "device_evidence_conflict") : e.state === "configured" && e.identityId !== t.targetIdentityId ? t.allowRebind === !0 ? {
456
+ deviceId: n,
457
+ displayName: e.displayName,
458
+ targetIdentityId: t.targetIdentityId,
459
+ previousIdentityId: e.identityId,
460
+ action: "rebind",
461
+ isLocal: e.isLocal
462
+ } : F("conflict", "device_rebind_confirmation_required") : {
463
+ deviceId: n,
464
+ displayName: e.displayName,
465
+ targetIdentityId: t.targetIdentityId,
466
+ previousIdentityId: e.identityId,
467
+ action: e.state === "configured" ? "unchanged" : "bind",
468
+ isLocal: e.isLocal
469
+ };
470
+ }
471
+ function Xe(e) {
472
+ return {
473
+ deviceId: e.deviceId,
474
+ evidenceDeviceIds: e.evidenceDeviceIds,
475
+ state: e.state,
476
+ identityId: e.identityId,
477
+ validatedFingerprint: e.validatedFingerprint,
478
+ isLocal: e.isLocal,
479
+ sources: e.sources,
480
+ conflictCodes: e.conflictCodes
481
+ };
482
+ }
483
+ function Ze(e, t) {
484
+ let n = e.prepare("SELECT status, updated_at FROM identity_devices WHERE device_id = ? AND status = 'removed'");
485
+ return [...new Set(t.flatMap((e) => e.evidenceDeviceIds))].toSorted().flatMap((e) => {
486
+ let t = n.get(e);
487
+ return t ? [{
488
+ deviceId: e,
489
+ status: t.status,
490
+ endedAt: t.updated_at
491
+ }] : [];
492
+ });
493
+ }
494
+ function Qe(e, t) {
495
+ let n = Ze(e, t.selectedItems);
496
+ return P("device-identity-binding-preview-v1", {
497
+ selectedItems: t.selectedItems.map(Xe),
498
+ coordinatorAvailability: t.inventory.coordinatorEvidence.availability,
499
+ inventoryTruncated: t.inventory.truncated,
500
+ request: JSON.parse(qe(t.request)),
501
+ ...n.length > 0 ? { endedBindings: n } : {}
502
+ });
503
+ }
504
+ function I(e, t, n) {
505
+ if (!n || !Array.isArray(n.bindings) || n.bindings.length === 0 || n.bindings.length > Ge || n.bindings.some((e) => !Je(e))) return F("invalid", "binding_request_invalid");
506
+ let r = n.bindings.map((e) => e.deviceId);
507
+ if (new Set(r).size !== r.length) return F("invalid", "duplicate_device_id");
508
+ let i = k(e, t);
509
+ if (i.truncated) return F("conflict", "device_inventory_truncated");
510
+ let a = new Map(i.items.map((e) => [e.deviceId, e])), o = [];
511
+ for (let e of n.bindings) {
512
+ let t = a.get(e.deviceId);
513
+ if (!t) return F("not_found", "device_not_found");
514
+ o.push(t);
515
+ }
516
+ if (i.coordinatorEvidence.availability !== "available" && !(i.coordinatorEvidence.safeErrorCode === "coordinator_not_configured" && o.every((e) => e.isLocal))) return F("conflict", "device_inventory_incomplete");
517
+ let s = [];
518
+ for (let [t, r] of n.bindings.entries()) {
519
+ if (!j(e, r.targetIdentityId)) return F("not_found", "target_identity_unavailable");
520
+ let n = o[t];
521
+ if (!n) return F("not_found", "device_not_found");
522
+ let i = n.deviceId;
523
+ if (n.state === "configured") {
524
+ let t = n.evidenceDeviceIds.filter((t) => L(e, t)?.status === "active");
525
+ if (t.length !== 1) return F("conflict", "device_evidence_conflict");
526
+ i = t[0] ?? n.deviceId;
527
+ }
528
+ let a = Ye(n, r, i);
529
+ if ("status" in a) return a;
530
+ s.push(a);
531
+ }
532
+ return {
533
+ version: 1,
534
+ status: "ready",
535
+ reviewedInventoryDigest: Qe(e, {
536
+ selectedItems: o,
537
+ inventory: i,
538
+ request: n
539
+ }),
540
+ errorCode: null,
541
+ outcomes: s,
542
+ writeCount: s.filter((e) => e.action !== "unchanged").length
543
+ };
544
+ }
545
+ function L(e, t) {
546
+ return e.prepare("SELECT identity_id, status, assignment_version FROM identity_devices\n WHERE device_id = ?").get(t);
547
+ }
548
+ function $e(e, t, n, r, i) {
549
+ let a = e.prepare("SELECT request_json, outcomes_json, write_count\n FROM device_identity_binding_commits WHERE commit_digest = ?").get(n);
550
+ if (!a) return null;
551
+ if (a.request_json !== r) return {
552
+ ...F("conflict", "binding_commit_conflict"),
553
+ status: "conflict",
554
+ reviewedInventoryDigest: i.reviewedInventoryDigest,
555
+ idempotent: !1
556
+ };
557
+ let o = JSON.parse(a.outcomes_json);
558
+ if (!o.every((t) => {
559
+ let n = L(e, t.deviceId);
560
+ return n?.status === "active" && n.identity_id === t.targetIdentityId && j(e, t.targetIdentityId);
561
+ })) return {
562
+ version: 1,
563
+ status: "stale",
564
+ reviewedInventoryDigest: i.reviewedInventoryDigest,
565
+ errorCode: "binding_retry_stale",
566
+ outcomes: [],
567
+ writeCount: 0,
568
+ idempotent: !1
569
+ };
570
+ let s = I(e, t, i);
571
+ return s.status === "invalid" || s.status === "not_found" || s.status === "conflict" ? {
572
+ ...s,
573
+ status: s.status,
574
+ reviewedInventoryDigest: i.reviewedInventoryDigest,
575
+ idempotent: !1
576
+ } : s.outcomes.some((e) => e.action !== "unchanged") ? {
577
+ version: 1,
578
+ status: "stale",
579
+ reviewedInventoryDigest: i.reviewedInventoryDigest,
580
+ errorCode: "binding_retry_stale",
581
+ outcomes: [],
582
+ writeCount: 0,
583
+ idempotent: !1
584
+ } : {
585
+ version: 1,
586
+ status: "applied",
587
+ reviewedInventoryDigest: i.reviewedInventoryDigest,
588
+ errorCode: null,
589
+ outcomes: o,
590
+ writeCount: 0,
591
+ idempotent: !0
592
+ };
593
+ }
594
+ function et(e, t) {
595
+ if (!e.inTransaction) throw Error("binding_reactivation_transaction_required");
596
+ let n = L(e, t.deviceId);
597
+ if (n?.status !== "removed") return null;
598
+ e.prepare("UPDATE identity_devices SET identity_id = ?, display_name = ?, status = 'active',\n provenance = ?, revision = ?, migration_state = ?, source_fingerprint = ?,\n idempotency_key = ?, updated_at = ?\n WHERE device_id = ? AND status = 'removed'").run(t.targetIdentityId, t.displayName, t.provenance, t.revision, t.migrationState, t.sourceFingerprint, t.idempotencyKey, t.now, t.deviceId), n.identity_id !== t.targetIdentityId && de(e, t.deviceId, t.now);
599
+ let r = L(e, t.deviceId)?.assignment_version ?? 0;
600
+ return R(e, [n.identity_id, t.targetIdentityId], t.now), {
601
+ assignmentVersion: r,
602
+ previousIdentityId: n.identity_id
603
+ };
604
+ }
605
+ function tt(e, t, n, r) {
606
+ if (n && n.status !== "removed") throw new N("conflict", "binding_write_conflict");
607
+ if (n) {
608
+ if (!et(e, {
609
+ deviceId: t.deviceId,
610
+ targetIdentityId: t.targetIdentityId,
611
+ displayName: t.displayName,
612
+ provenance: "user_confirmed_identity_setup",
613
+ revision: r.revision,
614
+ migrationState: "user_managed",
615
+ sourceFingerprint: r.commitDigest,
616
+ idempotencyKey: r.idempotencyKey,
617
+ now: r.now
618
+ })) throw new N("stale", "binding_write_stale");
619
+ return;
620
+ }
621
+ e.prepare("INSERT INTO identity_devices(\n device_id, identity_id, display_name, status, provenance, revision, migration_state,\n source_fingerprint, idempotency_key, created_at, updated_at\n ) VALUES (?, ?, ?, 'active', 'user_confirmed_identity_setup', ?, 'user_managed', ?, ?, ?, ?)").run(t.deviceId, t.targetIdentityId, t.displayName, r.revision, r.commitDigest, r.idempotencyKey, r.now, r.now);
622
+ }
623
+ function nt(e, t, n, r, i) {
624
+ let a = L(e, r.deviceId);
625
+ if (r.action === "rebind" && (a?.status !== "active" || a.identity_id !== r.previousIdentityId)) throw new N("stale", "binding_rebind_stale");
626
+ if (r.action === "unchanged" && (a?.status !== "active" || a.identity_id !== r.targetIdentityId)) throw new N("stale", "binding_unchanged_stale");
627
+ let o = P("device-identity-binding-revision-v1", [n, r.deviceId]), s = P("device-identity-binding-row-v1", [n, r.deviceId]);
628
+ if (r.action === "rebind") {
629
+ if (e.prepare("UPDATE identity_devices SET identity_id = ?, status = 'active',\n provenance = 'user_confirmed_identity_setup', revision = ?, migration_state = 'user_managed',\n source_fingerprint = ?, idempotency_key = ?, updated_at = ?\n WHERE device_id = ? AND identity_id = ? AND status = 'active'").run(r.targetIdentityId, o, n, s, i, r.deviceId, r.previousIdentityId).changes !== 1) throw new N("stale", "binding_rebind_stale");
630
+ } else r.action === "bind" && tt(e, r, a, {
631
+ revision: o,
632
+ commitDigest: n,
633
+ idempotencyKey: s,
634
+ now: i
635
+ });
636
+ let c = L(e, r.deviceId);
637
+ if (c?.status !== "active" || c.identity_id !== r.targetIdentityId) throw new N("stale", "binding_write_stale");
638
+ e.prepare("INSERT INTO device_identity_binding_audit(\n event_id, commit_digest, device_id, previous_identity_id, target_identity_id,\n action, previous_assignment_version, resulting_assignment_version,\n decided_by_identity_id, decided_by_device_id, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(P("device-identity-binding-event-v1", [n, r.deviceId]), n, r.deviceId, a?.identity_id ?? null, r.targetIdentityId, r.action, a?.assignment_version ?? null, c.assignment_version, t.localActorId, t.localDeviceId, i);
639
+ }
640
+ function R(e, t, n) {
641
+ let r = e.prepare("SELECT DISTINCT recipient.canonical_project_identity\n FROM project_recipients recipient\n WHERE recipient.status = 'active'\n AND (\n (recipient.recipient_kind = 'identity' AND recipient.recipient_id = ?)\n OR (recipient.recipient_kind = 'team' AND recipient.recipient_id IN (\n SELECT membership.team_id\n FROM policy_team_memberships membership\n JOIN policy_teams team ON team.team_id = membership.team_id\n WHERE membership.identity_id = ? AND team.status = 'active'\n AND (\n (team.device_eligibility_mode = 'person_all_devices' AND membership.status = 'active')\n OR (team.device_eligibility_mode = 'reviewed_allowlist'\n AND membership.status = 'reviewed_active')\n )\n ))\n )"), i = /* @__PURE__ */ new Set();
642
+ for (let e of new Set(t)) for (let t of r.pluck().all(e, e)) i.add(t);
643
+ rt(e, i, n);
644
+ }
645
+ function rt(e, t, n) {
646
+ let r = [...t];
647
+ if (r.length === 0) return;
648
+ let i = ee(e), a = new Set(r.map((e) => h(i, e))), o = e.prepare("SELECT canonical_project_identity FROM recipient_policy_authority_states").pluck().all(), s = e.prepare("UPDATE recipient_policy_authority_states\n SET last_attempt_at = NULL, wake_epoch = wake_epoch + 1\n WHERE canonical_project_identity = ?");
649
+ for (let e of o) {
650
+ let t = h(i, e);
651
+ a.has(t) && s.run(e);
652
+ }
653
+ }
654
+ function it(e, t, n) {
655
+ let r = /* @__PURE__ */ new Set();
656
+ for (let e of t) e.action !== "unchanged" && (e.previousIdentityId && r.add(e.previousIdentityId), r.add(e.targetIdentityId));
657
+ R(e, r, n);
658
+ }
659
+ function at(e, t, n, r) {
660
+ if (typeof r.reviewedInventoryDigest != "string" || !r.reviewedInventoryDigest) return {
661
+ ...F("invalid", "reviewed_inventory_digest_required"),
662
+ status: "invalid",
663
+ idempotent: !1
664
+ };
665
+ let i = qe(r), a = P("device-identity-binding-commit-v1", {
666
+ request: JSON.parse(i),
667
+ reviewedInventoryDigest: r.reviewedInventoryDigest
668
+ }), o = $e(e, n, a, i, r);
669
+ if (o) return o;
670
+ let s = I(e, n, r);
671
+ if (s.status !== "ready") return {
672
+ ...s,
673
+ status: s.status,
674
+ idempotent: !1
675
+ };
676
+ if (s.reviewedInventoryDigest !== r.reviewedInventoryDigest) return {
677
+ ...s,
678
+ status: "stale",
679
+ errorCode: "binding_evidence_stale",
680
+ writeCount: 0,
681
+ idempotent: !1
682
+ };
683
+ if (!M(e, t.localActorId)) return {
684
+ ...s,
685
+ status: "invalid",
686
+ errorCode: "deciding_identity_unavailable",
687
+ writeCount: 0,
688
+ idempotent: !1
689
+ };
690
+ let c = (t.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))();
691
+ e.prepare("INSERT INTO device_identity_binding_commits(\n commit_digest, reviewed_inventory_digest, request_json, outcomes_json, write_count,\n decided_by_identity_id, decided_by_device_id, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(a, r.reviewedInventoryDigest, i, Ke(s.outcomes), s.writeCount, t.localActorId, t.localDeviceId, c);
692
+ for (let n of s.outcomes) nt(e, t, a, n, c);
693
+ return it(e, s.outcomes, c), {
694
+ ...s,
695
+ status: "applied",
696
+ idempotent: !1
697
+ };
698
+ }
699
+ function ot(e, t, n, r) {
700
+ try {
701
+ return e.transaction(() => at(e, t, n, r)).immediate();
702
+ } catch (e) {
703
+ if (e instanceof N) return {
704
+ version: 1,
705
+ status: e.status,
706
+ reviewedInventoryDigest: r.reviewedInventoryDigest ?? "",
707
+ errorCode: e.errorCode,
708
+ outcomes: [],
709
+ writeCount: 0,
710
+ idempotent: !1
711
+ };
712
+ if ((e && typeof e == "object" && "code" in e ? String(e.code ?? "") : "").startsWith("SQLITE_CONSTRAINT")) return {
713
+ ...F("conflict", "binding_commit_conflict"),
714
+ status: "conflict",
715
+ reviewedInventoryDigest: r.reviewedInventoryDigest ?? "",
716
+ idempotent: !1
717
+ };
718
+ throw e;
719
+ }
720
+ }
721
+ //#endregion
722
+ //#region src/coordinator-peer-revocation.ts
723
+ var st = 25, ct = class extends Error {
724
+ status;
725
+ constructor(e) {
726
+ super(`peer revocation check failed (${e})`), this.status = e;
727
+ }
728
+ };
729
+ function lt(e) {
730
+ if (typeof e == "string" && e.trim() !== "") return e.length <= 4096 && !e.includes("\0") ? e : void 0;
731
+ }
732
+ function ut(e, t) {
733
+ let n = lt(t);
734
+ return n === void 0 ? { device_id: e } : {
735
+ device_id: e,
736
+ public_key: n
737
+ };
738
+ }
739
+ function dt(e, t) {
740
+ let n = e.prepare("SELECT peer_device_id, public_key FROM sync_peers\n WHERE peer_device_id IS NOT ? ORDER BY peer_device_id").all(t), r = new Map(n.map((e) => [e.peer_device_id, e.public_key])), i = e.prepare("SELECT device_id FROM identity_devices\n WHERE status = 'active' AND device_id IS NOT ? ORDER BY device_id").pluck().all(t), a = [...r.keys(), ...i.filter((e) => !r.has(e))], o = a.filter((e) => s(e)).map((e) => ut(e, r.get(e)));
741
+ return {
742
+ entries: o,
743
+ omitted: o.length !== a.length
744
+ };
745
+ }
746
+ function z(e, t) {
747
+ return e.filter((e) => typeof e == "string" && t.has(e));
748
+ }
749
+ function ft(e, t) {
750
+ let { version: n, revoked: r, removed: i, enrolled: a, removal_seq: o } = e ?? {};
751
+ if (n !== 1 || !Array.isArray(r) || !Array.isArray(i) || !Array.isArray(a) || !Number.isSafeInteger(o) || o < 0) throw Error("peer_revocation_response_invalid");
752
+ let s = new Set(t.map((e) => e.device_id)), c = z(r, s);
753
+ return {
754
+ revoked: c,
755
+ removed: z(i, s).filter((e) => !c.includes(e)),
756
+ enrolled: z(a, s),
757
+ removalSeq: o
758
+ };
759
+ }
760
+ async function pt(e, t, n, r) {
761
+ let i = { peers: r }, a = Buffer.from(JSON.stringify(i), "utf8"), o = `${p(t.syncCoordinatorUrl)}/v1/peers/revocations?group_id=${encodeURIComponent(n.groupId)}`, s = m({
762
+ deviceId: n.localDeviceId,
763
+ dbPath: e.dbPath,
764
+ method: "POST",
765
+ url: o,
766
+ bodyBytes: a,
767
+ keysDir: n.keysDir
768
+ }), [c, l] = await b("POST", o, {
769
+ headers: s,
770
+ body: i,
771
+ bodyBytes: a,
772
+ timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
773
+ });
774
+ if (c === 403 && l?.error === "device_removed" && n.removedFromGroups?.push(n.groupId), c !== 200) throw new ct(c);
775
+ return ft(l, r);
776
+ }
777
+ function mt(e) {
778
+ return e instanceof ct ? e.status === 404 ? "unsupported" : e.status !== 401 && e.status !== 403 && e.status !== 409 ? "failed" : "refused" : "failed";
779
+ }
780
+ async function ht(e, t, n, r, i) {
781
+ for (let a of t.syncCoordinatorGroups) try {
782
+ return {
783
+ kind: "answered",
784
+ groupId: a,
785
+ reply: await pt(e, t, {
786
+ ...n,
787
+ groupId: a,
788
+ removedFromGroups: i
789
+ }, r)
790
+ };
791
+ } catch (e) {
792
+ let t = mt(e);
793
+ if (t === "failed") throw e;
794
+ if (t === "unsupported") return { kind: "unsupported" };
795
+ }
796
+ return { kind: "refused" };
797
+ }
798
+ function gt(e) {
799
+ if (e.length === 0) return [[]];
800
+ let t = [];
801
+ for (let n = 0; n < e.length; n += st) t.push(e.slice(n, n + st));
802
+ return t;
803
+ }
804
+ function B(e, t, n = []) {
805
+ return {
806
+ status: e,
807
+ revoked: [],
808
+ removed: [],
809
+ enrolled: [],
810
+ removalSeq: null,
811
+ generation: t,
812
+ removedFromGroups: n
813
+ };
814
+ }
815
+ async function _t(e, t, n) {
816
+ let { entries: i, omitted: a, generation: o } = e.db.transaction(() => ({
817
+ ...dt(e.db, n.localDeviceId),
818
+ generation: r(e.db)?.generation ?? null
819
+ }))(), s = [];
820
+ try {
821
+ let [r = [], ...c] = gt(i), l = await ht(e, t, n, r, s);
822
+ if (l.kind === "unsupported") return B("unsupported", o, s);
823
+ if (l.kind === "refused") return B("failed", o, s);
824
+ let u = [l.reply], d = {
825
+ ...n,
826
+ groupId: l.groupId,
827
+ removedFromGroups: s
828
+ };
829
+ for (let n of c) u.push(await pt(e, t, d, n));
830
+ return {
831
+ status: "checked",
832
+ revoked: u.flatMap((e) => e.revoked),
833
+ removed: u.flatMap((e) => e.removed),
834
+ enrolled: u.flatMap((e) => e.enrolled),
835
+ removalSeq: a ? null : Math.min(...u.map((e) => e.removalSeq)),
836
+ generation: o,
837
+ removedFromGroups: []
838
+ };
839
+ } catch {
840
+ return B("failed", o, s);
841
+ }
842
+ }
843
+ async function vt(e, t, n) {
844
+ let r = n.publicKey !== void 0 && lt(n.publicKey) === void 0;
845
+ if (!s(n.deviceId) || r) return { answered: !1 };
846
+ let i = ut(n.deviceId, n.publicKey);
847
+ try {
848
+ let r = await ht(e, t, n, [i]);
849
+ return r.kind === "answered" ? {
850
+ answered: !0,
851
+ enrolled: r.reply.enrolled.includes(n.deviceId),
852
+ removed: r.reply.removed.includes(n.deviceId),
853
+ revoked: r.reply.revoked.includes(n.deviceId)
854
+ } : { answered: !1 };
855
+ } catch {
856
+ return { answered: !1 };
857
+ }
858
+ }
859
+ //#endregion
860
+ //#region src/coordinator-removal-notice.ts
861
+ var V = "sync_coordinator_device_removed";
862
+ function yt(e) {
863
+ return e.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(V) !== void 0;
864
+ }
865
+ function bt(e, t) {
866
+ t.groupIds.length !== 0 && e.transaction(() => {
867
+ e.exec(`CREATE TABLE IF NOT EXISTS ${V} (
868
+ coordinator_id TEXT NOT NULL,
869
+ group_id TEXT NOT NULL,
870
+ noticed_at TEXT NOT NULL,
871
+ PRIMARY KEY (coordinator_id, group_id)
872
+ )`);
873
+ let n = e.prepare(`INSERT OR IGNORE INTO ${V}(coordinator_id, group_id, noticed_at) VALUES (?, ?, ?)`), r = t.now ?? (/* @__PURE__ */ new Date()).toISOString();
874
+ for (let e of t.groupIds) n.run(t.coordinatorId, e, r);
875
+ }).immediate();
876
+ }
877
+ function xt(e, t) {
878
+ yt(e) && e.prepare(`DELETE FROM ${V} WHERE coordinator_id = ?`).run(t);
879
+ }
880
+ function St(e, t) {
881
+ if (!yt(e)) return {
882
+ removed: !1,
883
+ removedFromGroups: []
884
+ };
885
+ let n = new Set(e.prepare(`SELECT group_id FROM ${V} WHERE coordinator_id = ?`).pluck().all(t.coordinatorId)), r = t.groupIds.filter((e) => n.has(e));
886
+ return {
887
+ removed: t.groupIds.length > 0 && r.length === t.groupIds.length,
888
+ removedFromGroups: r
889
+ };
890
+ }
891
+ //#endregion
892
+ //#region src/memory-retirement-trust.ts
893
+ function Ct(e) {
894
+ return !!(e?.public_key && e.pinned_fingerprint && o(e.public_key) === e.pinned_fingerprint);
895
+ }
896
+ function H(e, t) {
897
+ if (!e.inTransaction) throw Error("retirement_trust_transaction_required");
898
+ let n = e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(t.peerDeviceId);
899
+ Ct(n) && e.prepare("INSERT OR IGNORE INTO memory_retirement_peer_trust\n (local_device_id, peer_device_id, public_key, pinned_fingerprint) VALUES (?, ?, ?, ?)").run(t.localDeviceId, t.peerDeviceId, n.public_key, n.pinned_fingerprint);
900
+ }
901
+ //#endregion
902
+ //#region src/pairing-removal.ts
903
+ function wt(e, t) {
904
+ let n = e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(t);
905
+ return !n?.public_key || !n.pinned_fingerprint || o(n.public_key) !== n.pinned_fingerprint ? [] : [{
906
+ deviceId: t,
907
+ kind: "key",
908
+ fingerprint: n.pinned_fingerprint,
909
+ keyId: C(n.public_key)
910
+ }];
911
+ }
912
+ function Tt(e, t) {
913
+ return e.prepare("DELETE FROM sync_peers WHERE peer_device_id = ?").run(t).changes;
914
+ }
915
+ function Et(e, t) {
916
+ return e.prepare("DELETE FROM sync_peers\n WHERE peer_device_id = ? AND claimed_local_actor = 0\n AND actor_id IS NULL AND pending_bootstrap_grant_id IS NULL\n AND trust_provenance = 'coordinator_policy'\n AND discovered_via_coordinator_id = ? AND discovered_via_group_id = ?").run(t.deviceId, t.coordinatorId, t.groupId).changes;
917
+ }
918
+ function Dt(e, n) {
919
+ return {
920
+ replicationCursors: e.prepare("DELETE FROM replication_cursors WHERE peer_device_id = ?").run(n).changes,
921
+ replicationCursorsV2: e.prepare("DELETE FROM replication_cursors_v2 WHERE peer_device_id = ?").run(n).changes,
922
+ syncChannelProgress: t(e, n)
923
+ };
924
+ }
925
+ function Ot(e, t, n) {
926
+ return e.prepare("UPDATE identity_devices SET status = 'removed', updated_at = ?\n WHERE device_id = ? AND status = 'active' RETURNING identity_id").get(n, t)?.identity_id ?? null;
927
+ }
928
+ function kt(e, t) {
929
+ e.syncPeers += t.syncPeers, e.replicationCursors += t.replicationCursors, e.replicationCursorsV2 += t.replicationCursorsV2, e.syncChannelProgress += t.syncChannelProgress;
930
+ }
931
+ function At(e, t, n) {
932
+ let r = Mt();
933
+ for (let i of n) {
934
+ H(e, {
935
+ localDeviceId: t,
936
+ peerDeviceId: i.deviceId
937
+ });
938
+ let n = Et(e, i);
939
+ n !== 0 && kt(r, {
940
+ syncPeers: n,
941
+ ...Dt(e, i.deviceId)
942
+ });
943
+ }
944
+ return r;
945
+ }
946
+ function jt(e, t) {
947
+ let n = Mt(), r = [...new Set(t.deviceIds)];
948
+ t.reason === "revoked" && ge(e, t.retiredAliases ?? r.flatMap((t) => wt(e, t)));
949
+ let i = (/* @__PURE__ */ new Date()).toISOString(), a = /* @__PURE__ */ new Set();
950
+ for (let o of r) {
951
+ if (H(e, {
952
+ localDeviceId: t.localDeviceId,
953
+ peerDeviceId: o
954
+ }), kt(n, {
955
+ syncPeers: Tt(e, o),
956
+ ...Dt(e, o)
957
+ }), t.reason === "disconnect" || o === t.localDeviceId) continue;
958
+ let r = Ot(e, o, i);
959
+ r && (n.identityDevices += 1, a.add(r));
960
+ }
961
+ return a.size === 0 || R(e, a, i), n;
962
+ }
963
+ function Mt() {
964
+ return {
965
+ syncPeers: 0,
966
+ replicationCursors: 0,
967
+ replicationCursorsV2: 0,
968
+ syncChannelProgress: 0,
969
+ identityDevices: 0
970
+ };
971
+ }
972
+ function U(e, t) {
973
+ return e.transaction(() => t.reason === "policy" ? At(e, t.localDeviceId, t.pairings) : jt(e, t)).immediate();
974
+ }
975
+ //#endregion
976
+ //#region src/device-retirement.ts
977
+ var Nt = /* @__PURE__ */ new Set(["fingerprint_conflict", "fingerprint_invalid"]);
978
+ function Pt(e, t) {
979
+ let n = e.prepare("SELECT device_id, public_key, fingerprint FROM sync_device").all(), [r] = n;
980
+ return n.length !== 1 || !r || r.device_id !== t || !r.public_key || r.fingerprint !== o(r.public_key) ? null : C(r.public_key);
981
+ }
982
+ function Ft(e, t) {
983
+ let n = k(e, {
984
+ localDeviceId: t.localDeviceId,
985
+ coordinator: {
986
+ availability: "available",
987
+ safeErrorCode: null,
988
+ enrollments: t.enrollments
989
+ }
990
+ }, { limit: 2e3 });
991
+ return n.truncated ? "device_evidence_incomplete" : n.items.find((e) => e.evidenceDeviceIds.includes(t.deviceId)) ?? "device_not_enrolled";
992
+ }
993
+ function It(e) {
994
+ return e.isLocal ? "cannot_retire_this_device" : e.state === "retired" ? "device_already_retired" : e.conflictCodes.some((e) => Nt.has(e)) || !e.validatedFingerprint ? "device_enrollment_conflict" : null;
995
+ }
996
+ function Lt(e) {
997
+ return e.prepare("SELECT peer_device_id, public_key, pinned_fingerprint FROM sync_peers WHERE public_key IS NOT NULL").all().map((e) => ({
998
+ deviceId: e.peer_device_id,
999
+ publicKey: e.public_key,
1000
+ fingerprint: e.pinned_fingerprint?.trim() || null
1001
+ }));
1002
+ }
1003
+ function Rt(e, t, n, r) {
1004
+ return [...t.enrollments.map((e) => ({
1005
+ deviceId: e.device_id,
1006
+ publicKey: e.public_key
1007
+ })), ...Lt(e)].filter((e) => !n.has(e.deviceId)).some((e) => C(e.publicKey) === r);
1008
+ }
1009
+ function zt(e, t) {
1010
+ let n = he(e), r = new Map(Lt(e).map((e) => [e.deviceId, e]));
1011
+ return t.some((e) => w(n.get(e), r.get(e) ?? null));
1012
+ }
1013
+ function Bt(e, t, n) {
1014
+ return e.enrollments.filter((e) => t.evidenceDeviceIds.includes(e.device_id) && e.fingerprint === n).toSorted((e, t) => e.group_id.localeCompare(t.group_id) || e.device_id.localeCompare(t.device_id))[0];
1015
+ }
1016
+ function Vt(e, t) {
1017
+ let n = Pt(e, t.localDeviceId);
1018
+ if (!n) return "local_identity_unverified";
1019
+ if (t.deviceId === t.localDeviceId) return "cannot_retire_this_device";
1020
+ let r = Ft(e, t);
1021
+ if (typeof r == "string") return r;
1022
+ let i = It(r);
1023
+ if (i) return i;
1024
+ if (zt(e, r.evidenceDeviceIds)) return "device_already_retired";
1025
+ let a = r.validatedFingerprint, o = Bt(t, r, a);
1026
+ if (!o) return "device_not_enrolled";
1027
+ let s = C(o.public_key);
1028
+ return s ? s === n ? "cannot_retire_this_device" : Rt(e, t, new Set(r.evidenceDeviceIds), s) ? "device_enrollment_conflict" : {
1029
+ aliasDeviceIds: r.evidenceDeviceIds.filter((e) => e !== t.localDeviceId),
1030
+ displayName: r.displayName,
1031
+ fingerprint: a,
1032
+ keyId: s,
1033
+ groupId: o.group_id,
1034
+ enrollmentDeviceId: o.device_id
1035
+ } : "device_key_unrecognized";
1036
+ }
1037
+ function Ht(e, t, n) {
1038
+ let r = n.filter((e) => e !== t);
1039
+ return r.length === 0 ? 0 : U(e, {
1040
+ localDeviceId: t,
1041
+ reason: "revoked",
1042
+ deviceIds: r
1043
+ }).syncPeers;
1044
+ }
1045
+ function Ut(e, t, n) {
1046
+ let r = e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(t);
1047
+ return !r || w({
1048
+ kind: "key",
1049
+ fingerprint: n.fingerprint,
1050
+ keyId: n.keyId
1051
+ }, {
1052
+ publicKey: r.public_key,
1053
+ fingerprint: r.pinned_fingerprint
1054
+ });
1055
+ }
1056
+ function Wt(e, t, n) {
1057
+ return e.transaction(() => {
1058
+ let r = n.aliasDeviceIds.filter((r) => r !== t && (r === n.enrollmentDeviceId || Ut(e, r, n)));
1059
+ return U(e, {
1060
+ localDeviceId: t,
1061
+ reason: "revoked",
1062
+ deviceIds: r,
1063
+ retiredAliases: r.map((e) => ({
1064
+ deviceId: e,
1065
+ kind: e === n.enrollmentDeviceId ? "device_id" : "key",
1066
+ fingerprint: n.fingerprint,
1067
+ keyId: n.keyId
1068
+ }))
1069
+ }).syncPeers;
1070
+ }).immediate();
1071
+ }
1072
+ //#endregion
1073
+ //#region src/coordinator-runtime.ts
1074
+ function W(e) {
1075
+ return typeof e == "string" ? e.trim() : "";
1076
+ }
1077
+ function Gt(e, t) {
1078
+ let n = [], r = /* @__PURE__ */ new Set();
1079
+ for (let i of [...e, ...t]) {
1080
+ let e = i.trim();
1081
+ !e || r.has(e) || (r.add(e), n.push(e));
1082
+ }
1083
+ return n;
1084
+ }
1085
+ function Kt(e, t) {
1086
+ let n = Date.parse(W(e)), r = Date.parse(W(t));
1087
+ return Number.isFinite(n) ? Number.isFinite(r) && r < n ? t : e : Number.isFinite(r) ? t : e;
1088
+ }
1089
+ var G = /* @__PURE__ */ new Map(), K = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Map(), qt = 3e4;
1090
+ function Jt(e, t) {
1091
+ let n = e + qt;
1092
+ for (let r of t) {
1093
+ if (r.stale) continue;
1094
+ let t = Date.parse(W(r.expires_at));
1095
+ if (Number.isFinite(t)) {
1096
+ if (t <= e) return e;
1097
+ n = Math.min(n, t);
1098
+ }
1099
+ }
1100
+ return n;
1101
+ }
1102
+ function J(e) {
1103
+ K.delete(e), q.set(e, (q.get(e) ?? 0) + 1);
1104
+ }
1105
+ function Yt(e, t) {
1106
+ let n = [...t.syncCoordinatorGroups].sort().join(",");
1107
+ return [
1108
+ e.dbPath,
1109
+ t.syncCoordinatorUrl,
1110
+ n,
1111
+ Xt(e),
1112
+ t.syncHost,
1113
+ t.syncPort,
1114
+ t.syncAdvertise,
1115
+ t.syncCoordinatorPresenceTtlS
1116
+ ].join("|");
1117
+ }
1118
+ function Xt(e) {
1119
+ let t = process.env.CODEMEM_KEYS_DIR?.trim() || "";
1120
+ try {
1121
+ let n = e.db.prepare("SELECT device_id, fingerprint FROM sync_device LIMIT 1").get();
1122
+ return `${t}|${n?.device_id ?? ""}|${n?.fingerprint ?? ""}`;
1123
+ } catch {
1124
+ return t;
1125
+ }
1126
+ }
1127
+ function Y(e, t) {
1128
+ return [
1129
+ Yt(e, t),
1130
+ t.syncEnabled ? "sync-enabled" : "sync-disabled",
1131
+ t.syncHost,
1132
+ t.syncPort,
1133
+ t.syncAdvertise,
1134
+ t.syncCoordinatorPresenceTtlS
1135
+ ].join("|");
1136
+ }
1137
+ function Zt(e) {
1138
+ return Number(e.db.prepare("SELECT COUNT(1) AS total FROM sync_peers").get()?.total ?? 0);
1139
+ }
1140
+ function Qt(e) {
1141
+ let t = Math.max(1, e.syncCoordinatorPresenceTtlS), n = Math.floor(t / 2);
1142
+ return Math.max(5, Math.min(60, n > 0 ? n : 1)) * 1e3;
1143
+ }
1144
+ function $t() {
1145
+ return 3e4;
1146
+ }
1147
+ async function en(e, t, n, r) {
1148
+ let i = Yt(e, t), a = G.get(i);
1149
+ if (a && r < a.nextRefreshAtMs) {
1150
+ n.presence_status = a.status, n.presence_error = a.error, n.advertised_addresses = a.advertisedAddresses;
1151
+ return;
1152
+ }
1153
+ try {
1154
+ let a = (await nn(e, t))?.responses?.[0], o = a && typeof a == "object" ? a.addresses ?? [] : [];
1155
+ n.presence_status = "posted", n.presence_error = null, n.advertised_addresses = o, G.set(i, {
1156
+ status: "posted",
1157
+ error: null,
1158
+ advertisedAddresses: o,
1159
+ nextRefreshAtMs: r + Qt(t)
1160
+ });
1161
+ } catch (e) {
1162
+ let t = e instanceof Error ? e.message : String(e), a = t.includes("unknown_device") ? "not_enrolled" : "error", o = a === "not_enrolled" ? r : r + $t();
1163
+ n.presence_status = a, n.presence_error = t, n.advertised_addresses = [], G.set(i, {
1164
+ status: a,
1165
+ error: t,
1166
+ advertisedAddresses: [],
1167
+ nextRefreshAtMs: o
1168
+ });
1169
+ }
1170
+ }
1171
+ function tn(e) {
1172
+ let t = e.syncAdvertise.toLowerCase();
1173
+ if (t && t !== "auto" && t !== "default") return v([], t.split(",").map((e) => e.trim()).filter(Boolean), { defaultHttpPort: e.syncPort });
1174
+ if (e.syncHost && e.syncHost !== "0.0.0.0") return [ae(ne(e.syncHost, e.syncPort))].filter(Boolean);
1175
+ let n = Object.values(se()).flatMap((e) => e ?? []).filter((e) => !e.internal).map((e) => e.address).filter((e) => e && e !== "127.0.0.1" && e !== "::1").map((t) => ae(ne(t, e.syncPort))).filter(Boolean);
1176
+ return [...new Set(n)];
1177
+ }
1178
+ async function nn(e, t, r) {
1179
+ if (!_(t)) return null;
1180
+ let i = r?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [a, o] = y(e.db, { keysDir: i }), s = te(i);
1181
+ if (!s) throw Error("public key missing");
1182
+ let c = p(t.syncCoordinatorUrl), u = {
1183
+ fingerprint: o,
1184
+ public_key: s,
1185
+ addresses: tn(t),
1186
+ ttl_s: Math.max(1, t.syncCoordinatorPresenceTtlS),
1187
+ capabilities: {
1188
+ sync_capability: f,
1189
+ sync_features: l,
1190
+ applied_removal_seq: n(e.db)
1191
+ }
1192
+ }, d = [];
1193
+ for (let n of t.syncCoordinatorGroups) {
1194
+ let r = {
1195
+ ...u,
1196
+ group_id: n
1197
+ }, o = Buffer.from(JSON.stringify(r), "utf8"), s = `${c}/v1/presence`, l = m({
1198
+ deviceId: a,
1199
+ dbPath: e.dbPath,
1200
+ method: "POST",
1201
+ url: s,
1202
+ bodyBytes: o,
1203
+ keysDir: i
1204
+ }), [f, p] = await b("POST", s, {
1205
+ headers: l,
1206
+ body: r,
1207
+ bodyBytes: o,
1208
+ timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
1209
+ });
1210
+ if (f !== 200 || !p) {
1211
+ let e = typeof p?.error == "string" ? p.error : "unknown";
1212
+ throw Error(`coordinator presence failed (${f}: ${e})`);
1213
+ }
1214
+ d.push(p);
1215
+ }
1216
+ return {
1217
+ groups: t.syncCoordinatorGroups,
1218
+ responses: d
1219
+ };
1220
+ }
1221
+ async function X(e, t, n) {
1222
+ if (!_(t)) return [];
1223
+ let r = n?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [i] = y(e.db, { keysDir: r }), a = p(t.syncCoordinatorUrl), o = /* @__PURE__ */ new Map();
1224
+ for (let n of t.syncCoordinatorGroups) {
1225
+ let s = `${a}/v1/peers?group_id=${encodeURIComponent(n)}`, c = m({
1226
+ deviceId: i,
1227
+ dbPath: e.dbPath,
1228
+ method: "GET",
1229
+ url: s,
1230
+ bodyBytes: Buffer.alloc(0),
1231
+ keysDir: r
1232
+ }), [l, u] = await b("GET", s, {
1233
+ headers: c,
1234
+ timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
1235
+ });
1236
+ if (l !== 200 || !u) {
1237
+ let e = typeof u?.error == "string" ? u.error : "unknown";
1238
+ throw Error(`coordinator lookup failed (${l}: ${e})`);
1239
+ }
1240
+ let d = Array.isArray(u.items) ? u.items : [];
1241
+ for (let e of d) {
1242
+ if (!e || typeof e != "object") continue;
1243
+ let t = e, r = W(t.device_id), i = W(t.fingerprint);
1244
+ if (!r) continue;
1245
+ let s = t.stale ? [] : Array.isArray(t.addresses) ? t.addresses.filter((e) => typeof e == "string") : [], c = `${r}:${i}`, l = o.get(c);
1246
+ if (!l) {
1247
+ o.set(c, {
1248
+ ...t,
1249
+ addresses: v([], s),
1250
+ coordinator_id: a,
1251
+ groups: [n],
1252
+ fresh_groups: t.stale ? [] : [n]
1253
+ });
1254
+ continue;
1255
+ }
1256
+ rn(l, t, n, s);
1257
+ }
1258
+ }
1259
+ return [...o.values()];
1260
+ }
1261
+ function rn(e, t, n, r) {
1262
+ e.addresses = v(Z(e.addresses), r), e.groups = Gt(Z(e.groups), [n]);
1263
+ let i = !!e.stale, a = !!t.stale;
1264
+ e.fresh_groups = Gt(Z(e.fresh_groups), a ? [] : [n]), e.stale = i && a;
1265
+ let o = W(t.last_seen_at) > W(e.last_seen_at) || i && !a;
1266
+ o && (!a || i) && (e.last_seen_at = t.last_seen_at), a ? i && o && (e.expires_at = t.expires_at) : e.expires_at = i ? t.expires_at : Kt(e.expires_at, t.expires_at);
1267
+ }
1268
+ function Z(e) {
1269
+ return Array.isArray(e) ? e.filter((e) => typeof e == "string" && e.trim().length > 0) : [];
1270
+ }
1271
+ function an(e) {
1272
+ if (!Array.isArray(e) || e.length === 0) return null;
1273
+ let t = [];
1274
+ for (let n of e) {
1275
+ if (typeof n != "string" || !n.trim()) return null;
1276
+ t.push(n.trim());
1277
+ }
1278
+ return t;
1279
+ }
1280
+ function on(e) {
1281
+ if (typeof e != "string" || e.trim().length === 0) return [];
1282
+ try {
1283
+ return Z(JSON.parse(e));
1284
+ } catch {
1285
+ return [];
1286
+ }
1287
+ }
1288
+ function sn(e, t, n) {
1289
+ let r = W(e.peer_device_id), i = W(e.pinned_fingerprint);
1290
+ if (!r || !i) return !1;
1291
+ let a = t.get(`${r}:${i}`);
1292
+ if (!a?.length) return !1;
1293
+ let o = v(on(e.addresses_json), []), s = e.manual_addresses_json == null ? o : on(e.manual_addresses_json), c = ie(o, a, s, { successfulAddress: e.last_success_address ?? void 0 });
1294
+ return JSON.stringify(c) === JSON.stringify(o) && e.manual_addresses_json != null ? !1 : (n(JSON.stringify(c), JSON.stringify(s), r, i), !0);
1295
+ }
1296
+ function cn(e, t) {
1297
+ let n = /* @__PURE__ */ new Map();
1298
+ for (let e of t) {
1299
+ if (e.stale) continue;
1300
+ let t = W(e.device_id), r = W(e.fingerprint);
1301
+ if (!t || !r) continue;
1302
+ let i = Z(e.addresses);
1303
+ if (i.length === 0) continue;
1304
+ let a = `${t}:${r}`;
1305
+ n.set(a, v(n.get(a) ?? [], i));
1306
+ }
1307
+ if (n.size === 0) return 0;
1308
+ let r = e.prepare("SELECT peer_device_id, pinned_fingerprint, addresses_json, manual_addresses_json, last_success_address FROM sync_peers").all(), i = e.prepare("UPDATE sync_peers SET addresses_json = ?, manual_addresses_json = ? WHERE peer_device_id = ? AND pinned_fingerprint = ?"), a = (e, t, n, r) => {
1309
+ i.run(e, t, n, r);
1310
+ }, o = 0;
1311
+ return e.transaction(() => {
1312
+ for (let e of r) sn(e, n, a) && (o += 1);
1313
+ }).immediate(), o;
1314
+ }
1315
+ function ln(e, t) {
1316
+ let { localDeviceId: n, peerDeviceId: r, coordinatorId: a, peerGroupIds: o, peerPublicKey: s } = t, c = t.kinds?.length ? t.kinds : ["managed_project"], l = e.prepare("SELECT public_key FROM sync_device WHERE device_id = ?").pluck().get(n), u = e.prepare(`SELECT scope.scope_id, scope.coordinator_id, scope.group_id
1317
+ FROM scope_memberships local_member
1318
+ JOIN scope_memberships peer_member
1319
+ ON peer_member.scope_id = local_member.scope_id
1320
+ JOIN replication_scopes scope
1321
+ ON scope.scope_id = local_member.scope_id
1322
+ WHERE local_member.device_id = ?
1323
+ AND peer_member.device_id = ?
1324
+ AND scope.status = 'active'
1325
+ AND scope.kind IN (${c.map(() => "?").join(", ")})
1326
+ AND scope.authority_type = 'coordinator'
1327
+ ORDER BY scope.scope_id`).all(n, r, ...c), d = [], f = !1;
1328
+ for (let t of u) {
1329
+ let c = W(t.scope_id), u = W(t.group_id);
1330
+ if (!c || W(t.coordinator_id) !== a || !u || o !== null && !o.includes(u)) continue;
1331
+ let p = {
1332
+ coordinatorId: a,
1333
+ groupId: u
1334
+ }, m = i(e, {
1335
+ deviceId: n,
1336
+ scopeId: c,
1337
+ authority: p,
1338
+ expectedPublicKey: l ?? ""
1339
+ }), h = i(e, {
1340
+ deviceId: r,
1341
+ scopeId: c,
1342
+ authority: p,
1343
+ expectedPublicKey: s
1344
+ });
1345
+ if (!(!m.authorized || !h.authorized)) {
1346
+ if (m.freshness !== "fresh" || h.freshness !== "fresh") {
1347
+ f = !0;
1348
+ continue;
1349
+ }
1350
+ d.push({
1351
+ scopeId: c,
1352
+ groupId: u
1353
+ });
1354
+ }
1355
+ }
1356
+ return {
1357
+ scopes: d,
1358
+ indeterminate: f
1359
+ };
1360
+ }
1361
+ function Q(e, t, n, r, i, a) {
1362
+ let { scopes: o, indeterminate: s } = ln(e, {
1363
+ localDeviceId: t,
1364
+ peerDeviceId: n,
1365
+ coordinatorId: r,
1366
+ peerGroupIds: i,
1367
+ peerPublicKey: a
1368
+ }), [c] = o;
1369
+ return c ? {
1370
+ state: "authorized",
1371
+ groupId: c.groupId
1372
+ } : { state: s ? "indeterminate" : "not_authorized" };
1373
+ }
1374
+ function un(e, t, n, r, i) {
1375
+ let a = n.stale ? [] : Z(n.addresses);
1376
+ re(e, t, a, {
1377
+ name: W(n.display_name) || void 0,
1378
+ pinnedFingerprint: r,
1379
+ publicKey: i,
1380
+ coordinatorCandidates: !0
1381
+ });
1382
+ }
1383
+ function dn(e, t, n) {
1384
+ let r = 0;
1385
+ for (let i of n) {
1386
+ let n = W(i.device_id), a = W(i.public_key), o = W(i.fingerprint), s = W(i.coordinator_id), c = an(i.groups);
1387
+ if (!n || n === t || !a || !o || !s || !c || !fn(a, o)) continue;
1388
+ let l = Q(e, t, n, s, c, a);
1389
+ if (l.state !== "authorized") continue;
1390
+ let u = e.prepare("SELECT pinned_fingerprint, public_key, claimed_local_actor, actor_id,\n pending_bootstrap_grant_id, trust_provenance\n FROM sync_peers WHERE peer_device_id = ? LIMIT 1").get(n);
1391
+ if (u && (u.claimed_local_actor === 1 || W(u.pinned_fingerprint) && W(u.pinned_fingerprint) !== o || W(u.public_key) && W(u.public_key) !== a)) continue;
1392
+ let d = !!(W(u?.pinned_fingerprint) || W(u?.public_key)), f = !u || u.claimed_local_actor === 0 && u.actor_id == null && u.pending_bootstrap_grant_id == null && (!d || u.trust_provenance === "coordinator_policy");
1393
+ un(e, n, i, o, a), f && e.prepare("UPDATE sync_peers SET discovered_via_coordinator_id = ?,\n discovered_via_group_id = ?, trust_provenance = 'coordinator_policy'\n WHERE peer_device_id = ?\n AND claimed_local_actor = 0 AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL").run(s, l.groupId, n), r += 1;
1394
+ }
1395
+ return r;
1396
+ }
1397
+ function fn(e, t) {
1398
+ try {
1399
+ return o(e) === t;
1400
+ } catch {
1401
+ return !1;
1402
+ }
1403
+ }
1404
+ function pn(e, t) {
1405
+ let n = e.prepare("SELECT peer_device_id, public_key, discovered_via_coordinator_id, discovered_via_group_id\n FROM sync_peers\n WHERE claimed_local_actor = 0\n AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL\n AND trust_provenance = 'coordinator_policy'\n AND discovered_via_coordinator_id IS NOT NULL\n AND discovered_via_group_id IS NOT NULL\n AND (pinned_fingerprint IS NOT NULL OR public_key IS NOT NULL)").all(), r = 0;
1406
+ for (let i of n) {
1407
+ let n = W(i.peer_device_id), a = W(i.discovered_via_coordinator_id), o = W(i.discovered_via_group_id);
1408
+ !n || !a || !o || Q(e, t, n, a, null, W(i.public_key)).state === "not_authorized" && (r += U(e, {
1409
+ localDeviceId: t,
1410
+ reason: "policy",
1411
+ pairings: [{
1412
+ deviceId: n,
1413
+ coordinatorId: a,
1414
+ groupId: o
1415
+ }]
1416
+ }).syncPeers);
1417
+ }
1418
+ return r;
1419
+ }
1420
+ function mn(e, t, n) {
1421
+ return e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers\n WHERE peer_device_id = ? AND discovered_via_coordinator_id = ?\n AND trust_provenance = 'coordinator_policy'\n AND claimed_local_actor = 0 AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL").get(t, n);
1422
+ }
1423
+ function hn(e, t, n) {
1424
+ let r = W(n.device_id), i = W(n.coordinator_id), a = W(n.public_key), o = W(n.fingerprint), s = an(n.groups);
1425
+ if (!r || r === t || !i || !s || !fn(a, o)) return null;
1426
+ let c = mn(e, r, i);
1427
+ if (!c?.public_key || !c.pinned_fingerprint || !fn(c.public_key, c.pinned_fingerprint)) return null;
1428
+ let l = Q(e, t, r, i, s, a);
1429
+ return l.state !== "authorized" || Q(e, t, r, i, null, c.public_key).state !== "not_authorized" ? null : {
1430
+ peerDeviceId: r,
1431
+ coordinatorId: i,
1432
+ groupId: l.groupId,
1433
+ publicKey: a,
1434
+ fingerprint: o,
1435
+ previousPublicKey: c.public_key,
1436
+ previousFingerprint: c.pinned_fingerprint
1437
+ };
1438
+ }
1439
+ function gn(e, t, n) {
1440
+ H(e, {
1441
+ localDeviceId: t,
1442
+ peerDeviceId: n.peerDeviceId
1443
+ }), e.prepare("UPDATE sync_peers SET public_key = ?, pinned_fingerprint = ?, discovered_via_group_id = ?\n WHERE peer_device_id = ? AND discovered_via_coordinator_id = ?\n AND public_key = ? AND pinned_fingerprint = ?\n AND trust_provenance = 'coordinator_policy'\n AND claimed_local_actor = 0 AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL").run(n.publicKey, n.fingerprint, n.groupId, n.peerDeviceId, n.coordinatorId, n.previousPublicKey, n.previousFingerprint);
1444
+ }
1445
+ function _n(e, t, n) {
1446
+ return e.transaction(() => {
1447
+ let r = /* @__PURE__ */ new Set();
1448
+ for (let i of n) {
1449
+ let n = hn(e, t, i);
1450
+ n && (gn(e, t, n), vn(e, n, i), r.add(n.peerDeviceId));
1451
+ }
1452
+ pn(e, t);
1453
+ let i = n.filter((e) => !r.has(W(e.device_id)));
1454
+ return r.size + dn(e, t, i);
1455
+ }).immediate();
1456
+ }
1457
+ function vn(e, t, n) {
1458
+ n.stale || sn(e.prepare("SELECT peer_device_id, pinned_fingerprint, addresses_json, manual_addresses_json,\n last_success_address FROM sync_peers WHERE peer_device_id = ?").get(t.peerDeviceId), /* @__PURE__ */ new Map([[`${t.peerDeviceId}:${t.fingerprint}`, Z(n.addresses)]]), (t, n, r, i) => {
1459
+ e.prepare("UPDATE sync_peers SET addresses_json = ?,\n manual_addresses_json = COALESCE(manual_addresses_json, ?)\n WHERE peer_device_id = ? AND pinned_fingerprint = ?").run(t, n, r, i);
1460
+ });
1461
+ }
1462
+ async function yn(e, t, n) {
1463
+ if (!_(t)) return {
1464
+ peers: [],
1465
+ trusted: 0
1466
+ };
1467
+ let r = n?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [i] = y(e.db, { keysDir: r }), a = await X(e, t, { keysDir: r });
1468
+ return cn(e.db, a), {
1469
+ peers: a,
1470
+ trusted: _n(e.db, i, a)
1471
+ };
1472
+ }
1473
+ function bn(e, t, n) {
1474
+ if (n.status === "checked") {
1475
+ xt(e, t);
1476
+ return;
1477
+ }
1478
+ bt(e, {
1479
+ coordinatorId: t,
1480
+ groupIds: n.removedFromGroups
1481
+ });
1482
+ }
1483
+ async function xn(t, n, i) {
1484
+ if (!_(n)) return {
1485
+ revoked: 0,
1486
+ removed: 0,
1487
+ enrolled: [],
1488
+ status: "unsupported"
1489
+ };
1490
+ let a = i?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [o] = y(t.db, { keysDir: a }), s = await _t(t, n, {
1491
+ localDeviceId: o,
1492
+ keysDir: a
1493
+ }), c = t.db, l = p(n.syncCoordinatorUrl);
1494
+ return s.status === "checked" ? c.transaction(() => {
1495
+ let t = s.generation;
1496
+ if (t === null || r(c)?.generation !== t) return {
1497
+ revoked: 0,
1498
+ removed: 0,
1499
+ enrolled: [],
1500
+ status: "failed"
1501
+ };
1502
+ bn(c, l, s);
1503
+ let n = Ht(c, o, s.revoked), i = U(c, {
1504
+ localDeviceId: o,
1505
+ reason: "removed",
1506
+ deviceIds: s.removed.filter((e) => e !== o)
1507
+ }).syncPeers;
1508
+ return s.removalSeq !== null && e(c, {
1509
+ generation: t,
1510
+ removalSeq: s.removalSeq
1511
+ }), {
1512
+ revoked: n,
1513
+ removed: i,
1514
+ enrolled: s.enrolled,
1515
+ status: s.status
1516
+ };
1517
+ }).immediate() : (bn(c, l, s), {
1518
+ revoked: 0,
1519
+ removed: 0,
1520
+ enrolled: [],
1521
+ status: s.status
1522
+ });
1523
+ }
1524
+ async function Sn(e, t, n, r) {
1525
+ if (r?.peers) return Cn(r.peers);
1526
+ let i = g();
1527
+ if (!_(i)) return /* @__PURE__ */ new Set();
1528
+ try {
1529
+ let r = await X({
1530
+ db: e,
1531
+ dbPath: t
1532
+ }, i, { keysDir: n });
1533
+ return cn(e, r), Cn(r);
1534
+ } catch {
1535
+ return /* @__PURE__ */ new Set();
1536
+ }
1537
+ }
1538
+ function Cn(e) {
1539
+ let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Set();
1540
+ for (let a of e) {
1541
+ let e = W(a.device_id);
1542
+ if (!e) continue;
1543
+ let o = W(a.fingerprint), s = o ? `${e}:${o}` : "";
1544
+ a.stale ? (n.add(e), s && i.add(s)) : (t.add(e), s && r.add(s));
1545
+ }
1546
+ for (let e of t) n.delete(e);
1547
+ for (let e of r) i.delete(e);
1548
+ return /* @__PURE__ */ new Set([...n, ...i]);
1549
+ }
1550
+ async function $(e, t, n) {
1551
+ if (!_(t)) return [];
1552
+ let r = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [i] = y(e.db, { keysDir: r }), a = p(t.syncCoordinatorUrl), o = /* @__PURE__ */ new Map();
1553
+ for (let s of t.syncCoordinatorGroups) {
1554
+ let c = `${a}/v1/reciprocal-approvals?${new URLSearchParams({
1555
+ group_id: s,
1556
+ direction: n.direction,
1557
+ status: n.status?.trim() || "pending"
1558
+ }).toString()}`, l = m({
1559
+ deviceId: i,
1560
+ dbPath: e.dbPath,
1561
+ method: "GET",
1562
+ url: c,
1563
+ bodyBytes: Buffer.alloc(0),
1564
+ keysDir: r
1565
+ }), [u, d] = await b("GET", c, {
1566
+ headers: l,
1567
+ timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
1568
+ });
1569
+ if (u !== 200 || !d) {
1570
+ let e = typeof d?.error == "string" ? d.error : "unknown";
1571
+ throw Error(`coordinator reciprocal approval lookup failed (${u}: ${e})`);
1572
+ }
1573
+ let f = Array.isArray(d.items) ? d.items : [];
1574
+ for (let e of f) {
1575
+ if (!e || typeof e != "object") continue;
1576
+ let t = e, n = W(t.request_id);
1577
+ n && o.set(n, t);
1578
+ }
1579
+ }
1580
+ return [...o.values()];
1581
+ }
1582
+ async function wn(e, t, n) {
1583
+ if (!_(t)) throw Error("Coordinator not configured.");
1584
+ let r = n.groupId.trim(), i = n.requestedDeviceId.trim(), a = n.expectedIncomingRequestId?.trim();
1585
+ if (!r || !i) throw Error("groupId and requestedDeviceId are required.");
1586
+ if (n.expectedIncomingRequestId !== void 0 && !a) throw Error("expectedIncomingRequestId must not be empty when provided.");
1587
+ let o = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [s] = y(e.db, { keysDir: o }), l = `${p(t.syncCoordinatorUrl)}/v1/reciprocal-approvals`, u = {
1588
+ group_id: r,
1589
+ requested_device_id: i,
1590
+ ...a === void 0 ? {} : { expected_incoming_request_id: a }
1591
+ }, d = Buffer.from(JSON.stringify(u), "utf8"), f = m({
1592
+ deviceId: s,
1593
+ dbPath: e.dbPath,
1594
+ method: "POST",
1595
+ url: l,
1596
+ bodyBytes: d,
1597
+ keysDir: o
1598
+ }), [h, g] = await b("POST", l, {
1599
+ headers: f,
1600
+ body: u,
1601
+ bodyBytes: d,
1602
+ timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
1603
+ });
1604
+ if (h !== 200 || !g || !g.request || typeof g.request != "object") {
1605
+ let n = typeof g?.error == "string" ? g.error : "unknown";
1606
+ throw h === 409 && n === "reciprocal_approval_request_changed" ? (J(Y(e, t)), new c()) : Error(`coordinator reciprocal approval create failed (${h}: ${n})`);
1607
+ }
1608
+ return J(Y(e, t)), g.request;
1609
+ }
1610
+ function Tn(e, t) {
1611
+ let n = /* @__PURE__ */ new Map();
1612
+ for (let r of e) {
1613
+ let e = W(r[t]);
1614
+ e && n.set(e, r);
1615
+ }
1616
+ return n;
1617
+ }
1618
+ async function En(e, t) {
1619
+ let n = Zt(e);
1620
+ if (!_(t)) return {
1621
+ enabled: !1,
1622
+ configured: !1,
1623
+ sync_enabled: t.syncEnabled,
1624
+ coordinator_url: t.syncCoordinatorUrl || null,
1625
+ groups: t.syncCoordinatorGroups,
1626
+ paired_peer_count: n
1627
+ };
1628
+ let r = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [i] = y(e.db, { keysDir: r }), a = Y(e, t), o = q.get(a) ?? 0, s = Date.now(), c = K.get(a);
1629
+ if (c && s < c.nextRefreshAtMs) {
1630
+ let n = structuredClone(c.snapshot);
1631
+ if (await en(e, t, n, s), s = Date.now(), n.presence_status === "not_enrolled") return J(a), n.fresh_peer_count = 0, n.stale_peer_count = 0, n.discovered_peer_count = 0, n.discovered_devices = [], n.reciprocal_approvals = {
1632
+ incoming: [],
1633
+ outgoing: []
1634
+ }, {
1635
+ ...n,
1636
+ paired_peer_count: Zt(e)
1637
+ };
1638
+ if (s < c.nextRefreshAtMs) return _n(e.db, i, c.discoveredPeers), {
1639
+ ...n,
1640
+ paired_peer_count: Zt(e)
1641
+ };
1642
+ }
1643
+ let l = {
1644
+ enabled: !0,
1645
+ configured: !0,
1646
+ sync_enabled: t.syncEnabled,
1647
+ coordinator_url: t.syncCoordinatorUrl,
1648
+ groups: t.syncCoordinatorGroups,
1649
+ paired_peer_count: n,
1650
+ presence_status: "unknown",
1651
+ presence_error: null,
1652
+ advertised_addresses: [],
1653
+ fresh_peer_count: 0,
1654
+ stale_peer_count: 0,
1655
+ discovered_peer_count: 0,
1656
+ discovered_devices: []
1657
+ };
1658
+ await en(e, t, l, s);
1659
+ let u = [];
1660
+ try {
1661
+ let { peers: n } = await yn(e, t, { keysDir: r });
1662
+ u = structuredClone(n);
1663
+ let i = [], a = [];
1664
+ try {
1665
+ i = await $(e, t, { direction: "incoming" }), a = await $(e, t, { direction: "outgoing" });
1666
+ } catch (e) {
1667
+ l.reciprocal_approval_error = e instanceof Error ? e.message : String(e);
1668
+ }
1669
+ let o = Tn(i, "requesting_device_id"), s = Tn(a, "requested_device_id");
1670
+ l.discovered_peer_count = n.length, l.fresh_peer_count = n.filter((e) => !e.stale).length, l.stale_peer_count = n.filter((e) => !!e.stale).length, l.reciprocal_approvals = {
1671
+ incoming: i,
1672
+ outgoing: a
1673
+ }, l.discovered_devices = n.map((e) => Dn(e, o, s));
1674
+ } catch (e) {
1675
+ l.lookup_error = e instanceof Error ? e.message : String(e);
1676
+ }
1677
+ return l.presence_status !== "not_enrolled" && !l.lookup_error && !l.reciprocal_approval_error && (q.get(a) ?? 0) === o && K.set(a, {
1678
+ snapshot: structuredClone(l),
1679
+ discoveredPeers: u,
1680
+ nextRefreshAtMs: Jt(Date.now(), u)
1681
+ }), l;
1682
+ }
1683
+ function Dn(e, t, n) {
1684
+ let r = t.get(W(e.device_id)), i = n.get(W(e.device_id));
1685
+ return {
1686
+ device_id: e.device_id,
1687
+ display_name: e.display_name ?? null,
1688
+ fingerprint: e.fingerprint ?? null,
1689
+ addresses: Array.isArray(e.addresses) ? e.addresses : [],
1690
+ groups: Array.isArray(e.groups) ? e.groups : [],
1691
+ last_seen_at: e.last_seen_at ?? null,
1692
+ expires_at: e.expires_at ?? null,
1693
+ stale: !!e.stale,
1694
+ needs_local_approval: !!r,
1695
+ waiting_for_peer_approval: !!i,
1696
+ incoming_reciprocal_request_id: r?.request_id ?? null,
1697
+ outgoing_reciprocal_request_id: i?.request_id ?? null
1698
+ };
1699
+ }
1700
+ async function On(e) {
1701
+ let t = e.syncCoordinatorGroup || e.syncCoordinatorGroups[0] || "";
1702
+ if (!t || !e.syncCoordinatorUrl || !e.syncCoordinatorAdminSecret) return [];
1703
+ let n = `${p(e.syncCoordinatorUrl)}/v1/admin/join-requests?group_id=${encodeURIComponent(t)}`, [r, i] = await b("GET", n, {
1704
+ headers: { "X-Codemem-Coordinator-Admin": e.syncCoordinatorAdminSecret },
1705
+ timeoutS: Math.max(1, e.syncCoordinatorTimeoutS)
1706
+ });
1707
+ return r !== 200 || !i ? [] : Array.isArray(i.items) ? i.items.filter((e) => !!e && typeof e == "object") : [];
1708
+ }
1709
+ //#endregion
1710
+ export { M as A, pe as B, et as C, He as D, Ve as E, ze as F, fe as H, Pe as I, C as L, ve as M, _e as N, j as O, k as P, he as R, I as S, rt as T, x as V, U as _, $ as a, We as b, cn as c, ln as d, dn as f, Pt as g, Wt as h, On as i, Ue as j, A as k, nn as l, Vt as m, wn as n, X as o, Ht as p, Sn as r, yn as s, En as t, xn as u, St as v, R as w, ot as x, vt as y, w as z };
1711
+
1712
+ //# sourceMappingURL=coordinator-runtime-ynLTJI6d.js.map