@zortexhq/indra-v2.5 0.4.1 → 0.4.2

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 (155) hide show
  1. package/README.md +5 -5
  2. package/bin/codex-postinstall.mjs +1 -1
  3. package/dist/action-effect.js +1 -0
  4. package/dist/action-read-progress.js +1 -1
  5. package/dist/actions-catalog.js +1 -0
  6. package/dist/auto-sync.js +1 -1
  7. package/dist/auto-update.js +1 -1
  8. package/dist/automatic-updates.js +1 -0
  9. package/dist/bundled-handbook.js +1 -1
  10. package/dist/cli-run.js +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/codex-install.js +1 -1
  13. package/dist/codex-setup.js +1 -1
  14. package/dist/computer-use-setup.js +1 -0
  15. package/dist/default-root.js +1 -1
  16. package/dist/documentation-action.js +1 -0
  17. package/dist/gateway.js +1 -1
  18. package/dist/imessage-sync.js +1 -1
  19. package/dist/local-cloud-policy.js +1 -1
  20. package/dist/local-cloud.js +1 -1
  21. package/dist/mcp.js +1 -3
  22. package/dist/native-connect.js +1 -1
  23. package/dist/native-level1-setup.js +1 -1
  24. package/dist/native-ollama-discovery.js +1 -0
  25. package/dist/native-vault-discovery.js +1 -1
  26. package/dist/onboard-cli.js +1 -1
  27. package/dist/onboard.js +1 -1
  28. package/dist/onboarding.js +1 -1
  29. package/dist/profile.js +1 -1
  30. package/dist/public-tool.js +4 -1
  31. package/dist/recovery-authorization-url.js +1 -1
  32. package/dist/recovery-progress.js +1 -1
  33. package/dist/recovery.js +1 -1
  34. package/dist/resident-autopilot.js +1 -0
  35. package/dist/resident-ensure-ready.js +1 -1
  36. package/dist/resident-host.js +2 -2
  37. package/dist/resident-jobs.js +1 -1
  38. package/dist/resident-platform.js +2 -2
  39. package/dist/resident-runtime-identity.js +1 -1
  40. package/dist/resident-startup-state.js +1 -0
  41. package/dist/resident-telemetry.js +1 -1
  42. package/dist/shared-action-schemas.js +1 -0
  43. package/dist/source-data.js +1 -1
  44. package/dist/storage-compatibility.js +1 -0
  45. package/dist/supervised-sync.js +1 -1
  46. package/dist/tools.js +1 -1
  47. package/dist/update-check.js +1 -1
  48. package/dist/update-cli.js +1 -1
  49. package/dist/update-command.js +1 -1
  50. package/dist/update-recovery.js +1 -1
  51. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
  52. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
  53. package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
  54. package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
  55. package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
  56. package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
  57. package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
  58. package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
  59. package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
  60. package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
  61. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
  62. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
  63. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
  64. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
  65. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
  66. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
  67. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
  68. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
  69. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
  70. package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
  71. package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
  72. package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
  73. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
  74. package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
  75. package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -1
  76. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  77. package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
  78. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  79. package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
  80. package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
  81. package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
  82. package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
  83. package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
  84. package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
  85. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
  86. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
  87. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
  88. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
  89. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
  90. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
  91. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
  92. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
  93. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
  94. package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
  95. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  96. package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
  97. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
  98. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
  99. package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
  100. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  101. package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
  102. package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
  103. package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
  104. package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
  105. package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
  106. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
  107. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
  108. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  109. package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
  110. package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
  111. package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
  112. package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
  113. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
  114. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
  115. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
  116. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
  117. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
  118. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  119. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
  120. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  121. package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
  122. package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
  123. package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
  124. package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
  125. package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
  126. package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
  127. package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
  128. package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
  129. package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
  130. package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
  131. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
  132. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  133. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
  134. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -1
  135. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
  136. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  137. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
  138. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
  139. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
  140. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
  141. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
  142. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
  143. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
  144. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
  145. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
  146. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
  147. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
  148. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
  149. package/package.json +13 -7
  150. package/profiles/core.yml +2 -0
  151. package/release-provenance.json +43 -36
  152. package/update-manifest.json +516 -275
  153. package/dist/content-find.js +0 -2
  154. package/dist/find-snapshots.js +0 -1
  155. package/dist/match-excerpt.js +0 -1
@@ -1 +1 @@
1
- export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";export*from"./storage-metadata.js";export*from"./source-sync.js";export*from"./search-text.js";export*from"./content-acquisition.js";
1
+ export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";export*from"./storage-metadata.js";export*from"./source-sync.js";export*from"./search-text.js";export*from"./content-acquisition.js";export*from"./public-result-visibility.js";export{assertVaultRuntime,UnsupportedVaultRuntimeError}from"../runtime.js";
@@ -0,0 +1 @@
1
+ import{businessError}from"@zortexhq/plugin-connector-framework/api";const visibility=Symbol("public-result-visibility");const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);export function withPublicReadValidation(result,validate){if(!object(result)||!("ok"in result))return result;return{...result,[visibility]:[...result[visibility]??[],validate]}}export function inheritPublicReadValidation(source,result){if(!object(source)||!object(result)||!("ok"in result)||!source[visibility])return result;return{...result,[visibility]:[...result[visibility]??[],...source[visibility]]}}export function validatePublicReadResult(result){if(!object(result)||!("ok"in result))return result;try{if((result[visibility]??[]).every(validate=>validate()))return result}catch{}return{...businessError("aborted","Public record visibility changed before delivery; retry the read.","storage"),...typeof result.operationId==="string"?{operationId:result.operationId}:{}}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Original,canonicalJson,businessError,ok}from"@zortexhq/plugin-connector-framework/api";const hash=value=>createHash("sha256").update(value).digest("hex");const fail=message=>businessError("failed_precondition",message,"auth");const nextId=Original.makeUlidFactory();function scope(db,source){try{const selection=db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const bindings=selection?db.query("SELECT id,metadata FROM account_bindings WHERE source=? AND id=?").all(source,selection.binding_id):db.query("SELECT id,metadata FROM account_bindings WHERE source=?").all(source);if(bindings.length!==1)return fail("Select one verified account before acquiring content.");const row=bindings[0],binding=JSON.parse(row.metadata);if(binding.state!=="connected"||binding.identity?.source!==source||!Number.isFinite(Date.parse(binding.verifiedAt))||!binding.identity.subject&&!binding.authority)return fail("Content acquisition requires a verified account or explicit session authority.");const pin=db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==binding.identity.subject)return fail("Content belongs to a different isolated account.");const grants=db.query("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' ORDER BY id").all(row.id);if(!grants.some(row2=>{const g=JSON.parse(row2.metadata);return g.purpose==="L1"&&g.state==="active"}))return fail("Content acquisition requires active L1 authorization.");const resources=db.query("SELECT id,revision FROM credential_resources WHERE binding_id=? ORDER BY id").all(row.id);return ok({fingerprint:hash(canonicalJson({selection:selection??null,binding,grants,resources})),identity:hash(canonicalJson(binding.identity.subject?{...binding.identity}:{source,authority:binding.authority}))})}catch{return fail("Content acquisition custody is unavailable; reconnect through the product.")}}export function beginContentAcquisition(deps,source,resource){if(!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof resource!=="string"||!resource.trim()||resource.length>256)return businessError("invalid_argument","A bounded source and resource are required.","storage");if(deps.closed())return fail("Vault is closed.");const captured=scope(deps.db,source);if(!("ok"in captured))return captured;const declared=deps.declare(source);if(!("ok"in declared))return declared;const expires=Date.now()+3e5;let used=false;return ok({append(records,signal){const check=()=>{if(deps.closed()||used||Date.now()>expires)return fail("Acquisition expired or was already committed.");if(signal?.aborted)return businessError("aborted","Content acquisition cancelled.","storage");const current=scope(deps.db,source);return"ok"in current&&current.ok.fingerprint===captured.ok.fingerprint?ok(true):businessError("permission_denied","Account or authorization changed before content commit.","auth")};const admitted=check();if(!("ok"in admitted))return admitted;if(!Array.isArray(records)||records.length>100)return businessError("invalid_argument","Acquire at most 100 reviewed records per page.","storage");const observedAt=new Date().toISOString(),id=nextId(),origin={kind:"connector",source,grant:id};let drafts;try{const ids=new Set;drafts=records.map(row=>{if(!row||typeof row.id!=="string"||!row.id||row.id.length>4096||ids.has(row.id)||typeof row.body!=="string"||!row.fields||typeof row.fields!=="object"||Array.isArray(row.fields)||Object.hasOwn(row.fields,"acquisition")||row.ts!==void 0&&(!Number.isFinite(Date.parse(row.ts))||new Date(row.ts).toISOString()!==row.ts))throw Error();ids.add(row.id);const payload=JSON.parse(canonicalJson({...row.fields,acquisition:{resource,nativeId:row.id,scope:"acquired",identity:captured.ok.identity}}));return{nk:{source,stream:"acquired-content",sourceId:hash(canonicalJson({identity:captured.ok.identity,resource,id:row.id})),rev:""},ts:row.ts??observedAt,tier:"api",kind:"content.acquired",schemaVersion:1,mentions:[],body:row.body,payload}});if(Buffer.byteLength(canonicalJson(drafts))>4*1024*1024)return businessError("resource_exhausted","Acquisition page exceeds the complete-content budget.","storage")}catch{return businessError("invalid_argument","Acquisition requires unique IDs and complete JSON content.","storage")}let receipt;const save=results=>{if(results.some(row=>!["appended","duplicate","head-noop"].includes(row.outcome)))return businessError("data_loss","Content was not durably accepted.","storage");receipt={id,source,resource,scope:"acquired",returned:records.length,persisted:results.length,observedAt};deps.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,1,?)").run("content-acquisition",id,canonicalJson(receipt));return ok(true)};if(drafts.length){const result=deps.append(drafts,origin,check,save);if(!("ok"in result))return result}else{try{deps.db.exec("BEGIN IMMEDIATE");const checked=check();if(!("ok"in checked)){deps.db.exec("ROLLBACK");return checked}save([]);deps.db.exec("COMMIT")}catch{try{deps.db.exec("ROLLBACK")}catch{}return businessError("unavailable","Empty acquisition receipt could not commit.","storage")}}used=true;return ok(receipt)}})}export function contentAcquisitionScopes(db){const sources=db.query("SELECT DISTINCT source FROM events WHERE stream='acquired-content'").all();return sources.flatMap(({source})=>{const current=scope(db,source);return"ok"in current?[{source,identity:current.ok.identity}]:[]})}
1
+ import{createHash}from"node:crypto";import{Original,canonicalJson,businessError,ok}from"@zortexhq/plugin-connector-framework/api";const hash=value=>createHash("sha256").update(value).digest("hex");const fail=message=>businessError("failed_precondition",message,"auth");const nextId=Original.makeUlidFactory();export function contentAcquisitionScope(db,source){try{const selection=db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const bindings=selection?db.query("SELECT id,metadata FROM account_bindings WHERE source=? AND id=?").all(source,selection.binding_id):db.query("SELECT id,metadata FROM account_bindings WHERE source=?").all(source);if(bindings.length!==1)return fail("Select one verified account before acquiring content.");const row=bindings[0],binding=JSON.parse(row.metadata);if(binding.state!=="connected"||binding.identity?.source!==source||!Number.isFinite(Date.parse(binding.verifiedAt))||!binding.identity.subject&&!binding.authority)return fail("Content acquisition requires a verified account or explicit session authority.");const pin=db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==binding.identity.subject)return fail("Content belongs to a different isolated account.");const grants=db.query("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' ORDER BY id").all(row.id);if(!grants.some(row2=>{const g=JSON.parse(row2.metadata);return g.purpose==="L1"&&g.state==="active"}))return fail("Content acquisition requires active L1 authorization.");const resources=db.query("SELECT id,revision FROM credential_resources WHERE binding_id=? ORDER BY id").all(row.id);return ok({fingerprint:hash(canonicalJson({selection:selection??null,binding,grants,resources})),identity:hash(canonicalJson(binding.identity.subject?{...binding.identity}:{source,authority:binding.authority}))})}catch{return fail("Content acquisition custody is unavailable; reconnect through the product.")}}export function beginContentAcquisition(deps,source,resource){if(!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof resource!=="string"||!resource.trim()||resource.length>256)return businessError("invalid_argument","A bounded source and resource are required.","storage");if(deps.closed())return fail("Vault is closed.");const captured=contentAcquisitionScope(deps.db,source);if(!("ok"in captured))return captured;const declared=deps.declare(source);if(!("ok"in declared))return declared;const expires=Date.now()+3e5;let used=false;return ok({append(records,signal){const check=()=>{if(deps.closed()||used||Date.now()>expires)return fail("Acquisition expired or was already committed.");if(signal?.aborted)return businessError("aborted","Content acquisition cancelled.","storage");const current=contentAcquisitionScope(deps.db,source);return"ok"in current&&current.ok.fingerprint===captured.ok.fingerprint?ok(true):businessError("permission_denied","Account or authorization changed before content commit.","auth")};const admitted=check();if(!("ok"in admitted))return admitted;if(!Array.isArray(records)||records.length>100)return businessError("invalid_argument","Acquire at most 100 reviewed records per page.","storage");const observedAt=new Date().toISOString(),id=nextId(),origin={kind:"connector",source,grant:id};let drafts;try{const ids=new Set;drafts=records.map(row=>{if(!row||typeof row.id!=="string"||!row.id||row.id.length>4096||ids.has(row.id)||typeof row.body!=="string"||!row.fields||typeof row.fields!=="object"||Array.isArray(row.fields)||Object.hasOwn(row.fields,"acquisition")||row.ts!==void 0&&(!Number.isFinite(Date.parse(row.ts))||new Date(row.ts).toISOString()!==row.ts))throw Error();ids.add(row.id);const payload=JSON.parse(canonicalJson({...row.fields,acquisition:{resource,nativeId:row.id,scope:"acquired",identity:captured.ok.identity}}));return{nk:{source,stream:"acquired-content",sourceId:hash(canonicalJson({identity:captured.ok.identity,resource,id:row.id})),rev:""},ts:row.ts??observedAt,tier:"api",kind:"content.acquired",schemaVersion:1,mentions:[],body:row.body,payload}});if(Buffer.byteLength(canonicalJson(drafts))>4*1024*1024)return businessError("resource_exhausted","Acquisition page exceeds the complete-content budget.","storage")}catch{return businessError("invalid_argument","Acquisition requires unique IDs and complete JSON content.","storage")}let receipt;const save=results=>{if(results.some(row=>!["appended","duplicate","head-noop"].includes(row.outcome)))return businessError("data_loss","Content was not durably accepted.","storage");receipt={id,source,resource,scope:"acquired",returned:records.length,persisted:results.length,observedAt};deps.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,1,?)").run("content-acquisition",id,canonicalJson(receipt));return ok(true)};if(drafts.length){const result=deps.append(drafts,origin,check,save);if(!("ok"in result))return result}else{try{deps.db.exec("BEGIN IMMEDIATE");const checked=check();if(!("ok"in checked)){deps.db.exec("ROLLBACK");return checked}save([]);deps.db.exec("COMMIT")}catch{try{deps.db.exec("ROLLBACK")}catch{}return businessError("unavailable","Empty acquisition receipt could not commit.","storage")}}used=true;return ok(receipt)}})}export function contentAcquisitionScopes(db){const sources=db.query("SELECT DISTINCT source FROM events WHERE stream='acquired-content'").all();return sources.flatMap(({source})=>{const current=contentAcquisitionScope(db,source);return"ok"in current?[{source,identity:current.ok.identity}]:[]})}
@@ -1,4 +1,4 @@
1
- import{createHash,randomUUID}from"node:crypto";import{DatabaseSync}from"node:sqlite";import{lstat,mkdir,realpath}from"node:fs/promises";import{isAbsolute,join}from"node:path";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{BINDING_CUSTODY_CONTRACT,oauthCredentialResourceId,isMcpSessionAuthority,isServerSessionAuthority,isConnectionAuthority}from"./api/index.js";import{createSystemCodec}from"./codec.js";import{assertNotRecovery}from"./recovery-guard.js";import{beginJoplinPairing,commitJoplinPairing,initializeJoplinPairingCommits,joplinPairingAuthority,reconcileJoplinPairing}from"./joplin-pairing-commit.js";import{createMetadataSnapshotReader}from"./metadata.js";export const name="zortex-vault-store";const sourceKey=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);const opaqueId=(prefix,value)=>`${prefix}_${createHash("sha256").update(JSON.stringify(value)).digest("base64url").slice(0,32)}`;const tenantKey=value=>value??"";const encryptedRef=id=>`vault:credential-resources:${id}`;const validId=value=>typeof value==="string"&&value.length>0&&value.length<=256;const NO_SECRET_MATERIAL='{"kind":"local-no-secret"}';const isNoSecretMaterial=value=>!!value&&typeof value==="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(value))&&Reflect.ownKeys(value).length===1&&Object.getOwnPropertyDescriptor(value,"kind")?.value==="local-no-secret";const invalid=()=>businessError("invalid_argument","Invalid binding, credential, record or limit.","storage");const conflict=()=>businessError("failed_precondition","Credential custody revision changed; reload before retrying.","storage");const unknownRefresh=()=>businessError("failed_precondition","Credential refresh has an active or unknown outcome; verified reauthorization is required if its owner cannot finish.","storage");const unknownLegacyRefresh=()=>businessError("failed_precondition","Legacy credential refresh has an active or unknown outcome. Preserve this Vault and open zortex help for account recovery; do not retry refresh or ordinary reconnect to clear mixed history.","storage");const storedSubject=binding=>binding.identity.subject??`mcp-session:${binding.authority.id}`;const scopesMatch=(left,right)=>Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&new Set(left).size===left.length&&left.every(scope=>typeof scope==="string"&&!!scope&&!/\s/u.test(scope)&&right.includes(scope));const sessionMaterialMatches=(binding,grant,material)=>!binding.authority||material.kind==="local-no-secret"&&isServerSessionAuthority(binding.authority)&&grant.audience===binding.authority.resource||material.kind==="oauth"&&isMcpSessionAuthority(binding.authority)&&material.credential.clientId===binding.authority.clientId&&grant.audience===binding.authority.resource&&scopesMatch(grant.scopes,material.credential.scopes);const resourceOwnerKey=owner=>owner.kind==="resident"?"resident":`managed-sidecar-profile:${owner.profileId}:${owner.bindingId}`;const authorityFence=({binding,grant,resource})=>JSON.stringify([binding.id,binding.revision,binding.state,grant.id,grant.revision,grant.scopeEpoch,grant.state,resource.id,resource.bindingId,resource.revision,resourceOwnerKey(resource.owner)]);const refreshFlights=new Map;export{systemCodec,createSystemCodec}from"./codec.js";export async function createVaultStore({root,codec:providedCodec,existingVault}){if(!isAbsolute(root))throw Error("Vault root must be an absolute directory.");assertNotRecovery(join(root,"vault.sqlite"));await mkdir(root,{recursive:true,mode:448});if((await lstat(root)).isSymbolicLink())throw Error("Vault root cannot be a link.");const file=join(await realpath(root),"vault.sqlite");const fileInfo=await lstat(file).catch(()=>null);if(fileInfo?.isSymbolicLink())throw Error("Vault database cannot be a link.");const db=new DatabaseSync(file);let closed=false;let closing;const pending=new Set;let codec;try{db.exec("PRAGMA busy_timeout=3000;");if(existingVault){try{if(db.prepare("SELECT value FROM meta WHERE key='vault-identity'").get()?.value!==existingVault.identity||db.prepare("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error()}catch{throw Error("Shared SQLite Vault identity mismatch.")}db.exec(`CREATE TABLE IF NOT EXISTS connector_records(source TEXT NOT NULL,source_id TEXT NOT NULL,ts TEXT NOT NULL,body TEXT NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(source,source_id));
1
+ import{createHash,randomUUID}from"node:crypto";import{DatabaseSync}from"node:sqlite";import{lstat,mkdir,realpath}from"node:fs/promises";import{isAbsolute,join}from"node:path";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{BINDING_CUSTODY_CONTRACT,oauthCredentialResourceId,isMcpSessionAuthority,isServerSessionAuthority,isConnectionAuthority}from"./api/index.js";import{createSystemCodec}from"./codec.js";import{assertNotRecovery}from"./recovery-guard.js";import{beginJoplinPairing,commitJoplinPairing,initializeJoplinPairingCommits,joplinPairingAuthority,reconcileJoplinPairing}from"./joplin-pairing-commit.js";import{createMetadataSnapshotReader}from"./metadata.js";import{initializePublicVisibility}from"./public-visibility.js";export const name="zortex-vault-store";const sourceKey=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);const opaqueId=(prefix,value)=>`${prefix}_${createHash("sha256").update(JSON.stringify(value)).digest("base64url").slice(0,32)}`;const tenantKey=value=>value??"";const encryptedRef=id=>`vault:credential-resources:${id}`;const validId=value=>typeof value==="string"&&value.length>0&&value.length<=256;const NO_SECRET_MATERIAL='{"kind":"local-no-secret"}';const isNoSecretMaterial=value=>!!value&&typeof value==="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(value))&&Reflect.ownKeys(value).length===1&&Object.getOwnPropertyDescriptor(value,"kind")?.value==="local-no-secret";const invalid=()=>businessError("invalid_argument","Invalid binding, credential, record or limit.","storage");const conflict=()=>businessError("failed_precondition","Credential custody revision changed; reload before retrying.","storage");const unknownRefresh=()=>businessError("failed_precondition","Credential refresh has an active or unknown outcome; verified reauthorization is required if its owner cannot finish.","storage");const unknownLegacyRefresh=()=>businessError("failed_precondition","Legacy credential refresh has an active or unknown outcome. Preserve this Vault and open zortex help for account recovery; do not retry refresh or ordinary reconnect to clear mixed history.","storage");const storedSubject=binding=>binding.identity.subject??`mcp-session:${binding.authority.id}`;const scopesMatch=(left,right)=>Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&new Set(left).size===left.length&&left.every(scope=>typeof scope==="string"&&!!scope&&!/\s/u.test(scope)&&right.includes(scope));const sessionMaterialMatches=(binding,grant,material)=>!binding.authority||material.kind==="local-no-secret"&&isServerSessionAuthority(binding.authority)&&grant.audience===binding.authority.resource||material.kind==="oauth"&&isMcpSessionAuthority(binding.authority)&&material.credential.clientId===binding.authority.clientId&&grant.audience===binding.authority.resource&&scopesMatch(grant.scopes,material.credential.scopes);const resourceOwnerKey=owner=>owner.kind==="resident"?"resident":`managed-sidecar-profile:${owner.profileId}:${owner.bindingId}`;const authorityFence=({binding,grant,resource})=>JSON.stringify([binding.id,binding.revision,binding.state,grant.id,grant.revision,grant.scopeEpoch,grant.state,resource.id,resource.bindingId,resource.revision,resourceOwnerKey(resource.owner)]);const refreshFlights=new Map;export{systemCodec,createSystemCodec}from"./codec.js";export async function createVaultStore({root,codec:providedCodec,existingVault}){if(!isAbsolute(root))throw Error("Vault root must be an absolute directory.");assertNotRecovery(join(root,"vault.sqlite"));await mkdir(root,{recursive:true,mode:448});if((await lstat(root)).isSymbolicLink())throw Error("Vault root cannot be a link.");const file=join(await realpath(root),"vault.sqlite");const fileInfo=await lstat(file).catch(()=>null);if(fileInfo?.isSymbolicLink())throw Error("Vault database cannot be a link.");const db=new DatabaseSync(file);let closed=false;let closing;const pending=new Set;let codec;try{db.exec("PRAGMA busy_timeout=3000;");if(existingVault){try{if(db.prepare("SELECT value FROM meta WHERE key='vault-identity'").get()?.value!==existingVault.identity||db.prepare("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error()}catch{throw Error("Shared SQLite Vault identity mismatch.")}db.exec(`CREATE TABLE IF NOT EXISTS connector_records(source TEXT NOT NULL,source_id TEXT NOT NULL,ts TEXT NOT NULL,body TEXT NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(source,source_id));
2
2
  CREATE VIEW IF NOT EXISTS z_records AS SELECT id,source,stream,source_id,title,body,ts,payload FROM z_events UNION ALL SELECT source || ':' || source_id AS id,source,'provider-read' AS stream,source_id,COALESCE(json_extract(payload,'$.fields.subject'),json_extract(payload,'$.fields.title'),json_extract(payload,'$.fields.name'),source_id) AS title,body,ts,payload FROM connector_records;`)}db.exec(`PRAGMA journal_mode=WAL;
3
3
  CREATE TABLE IF NOT EXISTS connections(source TEXT PRIMARY KEY,metadata TEXT NOT NULL,credential TEXT NOT NULL);
4
4
  CREATE TABLE IF NOT EXISTS legacy_connections(source TEXT PRIMARY KEY,metadata TEXT NOT NULL,credential TEXT NOT NULL);
@@ -14,6 +14,6 @@ import{createHash,randomUUID}from"node:crypto";import{DatabaseSync}from"node:sql
14
14
  CREATE TABLE IF NOT EXISTS credential_resources(id TEXT PRIMARY KEY,binding_id TEXT NOT NULL,kind TEXT NOT NULL,owner_key TEXT NOT NULL,revision INTEGER NOT NULL,metadata TEXT NOT NULL,credential TEXT NOT NULL);
15
15
  CREATE INDEX IF NOT EXISTS credential_resources_binding ON credential_resources(binding_id,id);
16
16
  CREATE TABLE IF NOT EXISTS credential_refresh_claims(resource_id TEXT PRIMARY KEY,claim_id TEXT NOT NULL,expected_revision INTEGER NOT NULL,owner_key TEXT NOT NULL);
17
- CREATE TABLE IF NOT EXISTS binding_records(binding_id TEXT NOT NULL,stream TEXT NOT NULL,native_id TEXT NOT NULL,ts INTEGER NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(binding_id,stream,native_id));`);db.exec(`CREATE TABLE IF NOT EXISTS joplin_pairing_generation(id INTEGER PRIMARY KEY CHECK(id=1),revision INTEGER NOT NULL);
17
+ CREATE TABLE IF NOT EXISTS binding_records(binding_id TEXT NOT NULL,stream TEXT NOT NULL,native_id TEXT NOT NULL,ts INTEGER NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(binding_id,stream,native_id));`);initializePublicVisibility(db);db.exec(`CREATE TABLE IF NOT EXISTS joplin_pairing_generation(id INTEGER PRIMARY KEY CHECK(id=1),revision INTEGER NOT NULL);
18
18
  INSERT OR IGNORE INTO joplin_pairing_generation(id,revision) VALUES(1,0);
19
- ${["legacy_connections","account_bindings","source_selections","legacy_refresh_claims"].flatMap(table=>["INSERT","UPDATE","DELETE"].map(op=>{const condition=op==="UPDATE"?"OLD.source='joplin' OR NEW.source='joplin'":`${op==="DELETE"?"OLD":"NEW"}.source='joplin'`;return`CREATE TRIGGER IF NOT EXISTS joplin_generation_${table}_${op.toLowerCase()} AFTER ${op} ON ${table} WHEN ${condition} BEGIN UPDATE joplin_pairing_generation SET revision=revision+1 WHERE id=1; END;`})).join("\n")}`);initializeJoplinPairingCommits(db);if(!db.prepare("SELECT 1 FROM custody_migrations WHERE id='binding-custody-v1'").get()){db.exec("BEGIN IMMEDIATE");try{db.exec("INSERT OR IGNORE INTO legacy_connections(source,metadata,credential) SELECT source,metadata,credential FROM connections; DELETE FROM connections;");db.prepare("INSERT INTO custody_migrations(id,applied_at) VALUES(?,?)").run("binding-custody-v1",new Date().toISOString());db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Binding custody migration failed.")}}let account=existingVault?.identity;if(!providedCodec&&process.platform==="darwin"&&!account){db.exec("CREATE TABLE IF NOT EXISTS custody_identity(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);");db.prepare("INSERT OR IGNORE INTO custody_identity(id,value) VALUES(1,?)").run(randomUUID());account=String(db.prepare("SELECT value FROM custody_identity WHERE id=1").get().value)}codec=providedCodec??createSystemCodec(account?{account}:{})}catch(error){try{db.close()}catch{}throw error}async function perform(operation){if(closed)return businessError("unavailable","Vault is inactive.","storage");let settle;const task=new Promise(done=>settle=done);pending.add(task);void(async()=>{try{const result=await operation();settle(closed?businessError("unavailable","Vault is inactive.","storage"):result)}catch{settle(businessError("data_loss","Vault operation or system credential protection failed.","storage"))}})();try{return await task}finally{pending.delete(task)}}const bindingRows=source=>db.prepare("SELECT metadata FROM account_bindings WHERE source=? ORDER BY id").all(source).map(row=>JSON.parse(String(row.metadata)));const connectionFromBinding=binding=>{const grantRow=binding.authority?db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' AND json_extract(metadata,'$.audience')=? ORDER BY id LIMIT 1").get(binding.id,binding.authority.resource):db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' ORDER BY id LIMIT 1").get(binding.id);const grant=grantRow?JSON.parse(String(grantRow.metadata)):null;return{source:binding.identity.source,provider:binding.provider,account:binding.account,...binding.identity.subject===void 0?{}:{accountId:binding.identity.subject},...binding.authority?{authority:binding.authority}:{},scopes:grant?[...grant.scopes]:[],state:binding.state,updatedAt:binding.updatedAt}};const rawLegacyRow=source=>db.prepare("SELECT metadata,credential FROM legacy_connections WHERE source=?").get(source);const sourceSelection=source=>{const row=db.prepare("SELECT binding_id,revision,selected_at FROM source_selections WHERE source=?").get(source);return row?{source,bindingId:String(row.binding_id),revision:Number(row.revision),selectedAt:String(row.selected_at)}:null};const selectedBinding=source=>{const selection=sourceSelection(source);if(!selection)return null;const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=? AND source=?").get(selection.bindingId,source);return row?JSON.parse(String(row.metadata)):null};const legacyRefreshClaim=source=>db.prepare("SELECT claim_id,fingerprint FROM legacy_refresh_claims WHERE source=?").get(source);const legacyFingerprint=row=>createHash("sha256").update(JSON.stringify([row.metadata,row.credential])).digest("hex");const legacyRow=source=>{const row=rawLegacyRow(source);if(!row)return void 0;const recovered=db.prepare("SELECT binding_id,fingerprint FROM legacy_recoveries WHERE source=?").get(source);return recovered&&recovered.fingerprint===legacyFingerprint({metadata:String(row.metadata),credential:String(row.credential)})&&db.prepare("SELECT 1 FROM account_bindings WHERE id=? AND source=?").get(String(recovered.binding_id),source)?void 0:row};const resolveLegacy=source=>{if(!sourceKey(source))return invalid();const bindings=bindingRows(source);const legacy=legacyRow(source);if(bindings.length===1&&!legacy)return ok({kind:"resolved",binding:bindings[0]});if(bindings.length===0)return ok({kind:"legacy-unattributed",source});return ok({kind:"ambiguous_account",source,bindingIds:bindings.map(binding=>binding.id)})};const ownerKey=resource=>resourceOwnerKey(resource.owner);const materialMatches=(resource,material)=>resource.kind==="oauth"&&material.kind==="oauth"||resource.kind==="mcp-token"&&material.kind==="mcp-token"||resource.kind==="rest-token"&&material.kind==="rest-token"||resource.kind==="local-no-secret"&&isNoSecretMaterial(material);const encodeMaterial=(kind,material)=>kind==="local-no-secret"?Promise.resolve(NO_SECRET_MATERIAL):codec.seal(JSON.stringify(material));const decodeMaterial=async(kind,value)=>kind==="local-no-secret"&&value===NO_SECRET_MATERIAL?{kind:"local-no-secret"}:JSON.parse(await codec.open(value));const flightKey=id=>JSON.stringify([file,id]);function readState(id,authorization){if(!validId(id)||!authorization||!["L1","L2"].includes(authorization.purpose)||!validId(authorization.audience))return invalid();const row=db.prepare("SELECT binding_id,metadata,credential FROM credential_resources WHERE id=?").get(id);if(!row)return businessError("failed_precondition","Credential resource does not exist.","storage");const bindingRow=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(String(row.binding_id));const grants=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')=? AND json_extract(metadata,'$.audience')=?").all(String(row.binding_id),authorization.purpose,authorization.audience);if(!bindingRow||grants.length!==1)return businessError("failed_precondition","Credential use requires one explicit authorization grant.","storage");const binding=JSON.parse(String(bindingRow.metadata));const grant=JSON.parse(String(grants[0].metadata));if(binding.state!=="connected"||grant.state!=="active")return businessError("permission_denied","Credential authority is disconnected or revoked.","storage");const resource=JSON.parse(String(row.metadata));const claim=db.prepare("SELECT claim_id FROM credential_refresh_claims WHERE resource_id=?").get(id);return ok({binding,grant,resource,sealed:String(row.credential),claim:claim?String(claim.claim_id):null})}function readSnapshotState(id,authorization){db.exec("BEGIN");try{const state=readState(id,authorization);db.exec("COMMIT");return state}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}async function joinedSnapshot(flight,id,authorization){const result=await flight.promise;if(!("ok"in result))return result;if(closed)return businessError("unavailable","Vault is inactive.","storage");const current=readSnapshotState(id,authorization);if(!("ok"in current))return current;return current.ok.claim===null&&authorityFence(current.ok)===authorityFence(result.ok)?result:conflict()}async function credentialSnapshot(id,authorization){const stored=readSnapshotState(id,authorization);if(!("ok"in stored))return stored;const joinClaim=state=>{const flight=refreshFlights.get(flightKey(id));return flight&&flight.claim===state.claim&&flight.fence===authorityFence(state)?joinedSnapshot(flight,id,authorization):Promise.resolve(unknownRefresh())};if(stored.ok.claim!==null)return joinClaim(stored.ok);const material=await decodeMaterial(stored.ok.resource.kind,stored.ok.sealed);if(closed)return businessError("unavailable","Vault is inactive.","storage");const current=readSnapshotState(id,authorization);if(!("ok"in current))return current;if(current.ok.claim!==null)return joinClaim(current.ok);if(authorityFence(current.ok)!==authorityFence(stored.ok))return conflict();if(!materialMatches(stored.ok.resource,material))return businessError("data_loss","Credential resource kind does not match.","storage");const{binding,grant,resource}=stored.ok;if(!sessionMaterialMatches(binding,grant,material))return businessError("failed_precondition","MCP session material does not match its selected resource authority.","storage");return ok({binding,grant,resource,material})}async function saveConnection(connection,credential,options={},legacyProof){if(!sourceKey(connection.source)||!connection.provider||!connection.account||!credential.accessToken||!Number.isFinite(credential.expiresAt)||Object.keys(options).some(key=>key!=="signal"&&key!=="expectedCredential"&&key!=="selectSource")||connection.accountId!==void 0&&(typeof connection.accountId!=="string"||!connection.accountId.trim()||connection.accountId.length>1e3||/[\u0000-\u001f\u007f-\u009f]/u.test(connection.accountId)))return invalid();if(connection.authority!==void 0&&(!isMcpSessionAuthority(connection.authority)||credential.clientId!==connection.authority.clientId||!scopesMatch(connection.scopes,credential.scopes)))return invalid();const expected=options.expectedCredential;if(expected!==void 0&&expected!==null&&(typeof expected!=="object"||Object.keys(expected).length!==6||Object.keys(expected).some(key=>!["bindingId","bindingRevision","grantId","grantRevision","resourceId","resourceRevision"].includes(key))||!validId(expected.bindingId)||!validId(expected.grantId)||!validId(expected.resourceId)||![expected.bindingRevision,expected.grantRevision,expected.resourceRevision].every(value=>Number.isSafeInteger(value)&&value>0)||connection.accountId===void 0&&connection.authority===void 0))return invalid();const expectedCredential=expected===void 0||expected===null?expected:structuredClone(expected);const selection=options.selectSource===void 0?void 0:structuredClone(options.selectSource);if(selection!==void 0&&(!selection||typeof selection!=="object"||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["expectedSelectionRevision","expectedBindingRevision"].includes(key))||selection.expectedSelectionRevision!==null&&(!Number.isSafeInteger(selection.expectedSelectionRevision)||selection.expectedSelectionRevision<1)||!Number.isSafeInteger(selection.expectedBindingRevision)||selection.expectedBindingRevision<0||!connection.accountId||connection.state!=="connected"||!Number.isFinite(Date.parse(connection.updatedAt))||selection.expectedBindingRevision>0&&(!expectedCredential||expectedCredential.bindingRevision!==selection.expectedBindingRevision)||selection.expectedBindingRevision===0&&expectedCredential!==void 0&&expectedCredential!==null))return invalid();connection=structuredClone(connection);credential=structuredClone(credential);const signal=options.signal;if(signal?.aborted)return businessError("aborted","Connection consent was cancelled.","storage");if(connection.accountId===void 0&&connection.authority===void 0){const hasBinding=()=>Boolean(db.prepare("SELECT 1 FROM account_bindings WHERE source=? LIMIT 1").get(connection.source));if(legacyRefreshClaim(connection.source))return unknownLegacyRefresh();if(hasBinding())return businessError("failed_precondition","Verified source bindings require an explicit verified account identity; unattributed credentials were not saved.","storage");const previous=legacyRow(connection.source);const metadata=JSON.stringify(connection);const sealed2=await codec.seal(JSON.stringify(credential));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(signal?.aborted)return businessError("aborted","Connection consent was cancelled before commit.","storage");db.exec("BEGIN IMMEDIATE");try{const current=legacyRow(connection.source);if(legacyRefreshClaim(connection.source)||hasBinding()||current?.metadata!==previous?.metadata||current?.credential!==previous?.credential){db.exec("ROLLBACK");return conflict()}db.prepare("INSERT INTO legacy_connections(source,metadata,credential) VALUES(?,?,?) ON CONFLICT(source) DO UPDATE SET metadata=excluded.metadata,credential=excluded.credential").run(connection.source,metadata,sealed2);db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Legacy connection transaction failed.")}return ok({...connection})}const identity={source:connection.source,issuer:connection.accountId===void 0&&connection.authority?.kind==="mcp-session"?connection.authority.issuer:connection.provider,...connection.accountId===void 0?{}:{subject:connection.accountId},tenant:null};const bindingId=opaqueId("binding",connection.accountId===void 0?{identity,authority:connection.authority}:identity);const audience=connection.authority?.resource??connection.provider;const grantId=opaqueId("grant",{bindingId,purpose:"L1",audience});const resourceId=oauthCredentialResourceId(bindingId);if(expectedCredential&&(expectedCredential.bindingId!==bindingId||expectedCredential.grantId!==grantId||expectedCredential.resourceId!==resourceId))return conflict();const existingBinding=db.prepare("SELECT revision FROM account_bindings WHERE id=?").get(bindingId);const existingGrant=db.prepare("SELECT revision,json_extract(metadata,'$.scopeEpoch') AS scope_epoch FROM authorization_grants WHERE id=?").get(grantId);const existingResource=db.prepare("SELECT revision FROM credential_resources WHERE id=?").get(resourceId);const sealed=await codec.seal(JSON.stringify({kind:"oauth",credential}));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(signal?.aborted)return businessError("aborted","Connection consent was cancelled before commit.","storage");const binding={id:bindingId,revision:Number(existingBinding?.revision??0)+1,identity,...connection.authority?{authority:connection.authority}:{},provider:connection.provider,account:connection.account,state:connection.state,verifiedAt:connection.updatedAt,updatedAt:connection.updatedAt};const grant={id:grantId,revision:Number(existingGrant?.revision??0)+1,bindingId,purpose:"L1",audience,scopes:[...new Set(connection.scopes)].sort(),scopeEpoch:Number(existingGrant?.scope_epoch??0)+1,state:connection.state==="connected"?"active":"revoked",updatedAt:connection.updatedAt};const resource={id:resourceId,bindingId,kind:"oauth",owner:{kind:"resident"},revision:Number(existingResource?.revision??0)+1,encryptedRef:encryptedRef(resourceId),updatedAt:connection.updatedAt};db.exec("BEGIN IMMEDIATE");try{if(legacyProof){const current=rawLegacyRow(connection.source);if(legacyRefreshClaim(connection.source)||!current||current.metadata!==legacyProof.metadata||current.credential!==legacyProof.credential||bindingRows(connection.source).length){db.exec("ROLLBACK");return conflict()}}const revision=(table,id)=>Number(db.prepare(`SELECT revision FROM ${table} WHERE id=?`).get(id)?.revision??0);if(selection&&((sourceSelection(connection.source)?.revision??null)!==selection.expectedSelectionRevision||revision("account_bindings",bindingId)!==selection.expectedBindingRevision||selection.expectedBindingRevision===0&&(revision("authorization_grants",grantId)!==0||revision("credential_resources",resourceId)!==0))){db.exec("ROLLBACK");return conflict()}if(expectedCredential===null&&(revision("account_bindings",bindingId)!==0||revision("authorization_grants",grantId)!==0||revision("credential_resources",resourceId)!==0)){db.exec("ROLLBACK");return conflict()}if(expectedCredential&&(revision("account_bindings",bindingId)!==expectedCredential.bindingRevision||revision("authorization_grants",grantId)!==expectedCredential.grantRevision||revision("credential_resources",resourceId)!==expectedCredential.resourceRevision)){db.exec("ROLLBACK");return conflict()}if(revision("account_bindings",bindingId)!==Number(existingBinding?.revision??0)||revision("authorization_grants",grantId)!==Number(existingGrant?.revision??0)||revision("credential_resources",resourceId)!==Number(existingResource?.revision??0)){db.exec("ROLLBACK");return conflict()}db.prepare("INSERT INTO account_bindings(id,source,issuer,subject,tenant_key,revision,metadata) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,metadata=excluded.metadata").run(binding.id,identity.source,identity.issuer,storedSubject(binding),tenantKey(identity.tenant),binding.revision,JSON.stringify(binding));db.prepare("INSERT INTO authorization_grants(id,binding_id,revision,metadata) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,metadata=excluded.metadata").run(grant.id,bindingId,grant.revision,JSON.stringify(grant));db.prepare("INSERT INTO credential_resources(id,binding_id,kind,owner_key,revision,metadata,credential) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,metadata=excluded.metadata,credential=excluded.credential").run(resource.id,bindingId,resource.kind,ownerKey(resource),resource.revision,JSON.stringify(resource),sealed);db.prepare("DELETE FROM credential_refresh_claims WHERE resource_id=?").run(resourceId);const sourceBindings=Number(db.prepare("SELECT COUNT(*) AS count FROM account_bindings WHERE source=?").get(connection.source)?.count??0);if(legacyProof)db.prepare("INSERT INTO legacy_recoveries(source,binding_id,fingerprint,verified_at) VALUES(?,?,?,?) ON CONFLICT(source) DO UPDATE SET binding_id=excluded.binding_id,fingerprint=excluded.fingerprint,verified_at=excluded.verified_at").run(connection.source,binding.id,legacyFingerprint(legacyProof),binding.verifiedAt);const hasLegacy=Boolean(legacyRow(connection.source));if(sourceBindings===1&&!hasLegacy)db.prepare("INSERT INTO connections(source,metadata,credential) VALUES(?,?,?) ON CONFLICT(source) DO UPDATE SET metadata=excluded.metadata,credential=excluded.credential").run(connection.source,JSON.stringify(connection),sealed);else db.prepare("DELETE FROM connections WHERE source=?").run(connection.source);if(selection)db.prepare("INSERT INTO source_selections(source,binding_id,revision,selected_at) VALUES(?,?,?,?) ON CONFLICT(source) DO UPDATE SET binding_id=excluded.binding_id,revision=excluded.revision,selected_at=excluded.selected_at").run(connection.source,bindingId,(selection.expectedSelectionRevision??0)+1,connection.updatedAt);db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Connection transaction failed.")}return ok({...connection})}const bindingCustody={sourceSelection:source=>perform(async()=>sourceKey(source)?ok(sourceSelection(source)):invalid()),selectSourceBinding:(source,bindingId,expectedBindingRevision,expectedSelectionRevision)=>perform(async()=>{if(!sourceKey(source)||!validId(bindingId)||!Number.isInteger(expectedBindingRevision)||expectedBindingRevision<1||expectedSelectionRevision!==null&&(!Number.isInteger(expectedSelectionRevision)||expectedSelectionRevision<1))return invalid();db.exec("BEGIN IMMEDIATE");try{const current=sourceSelection(source),row=db.prepare("SELECT metadata FROM account_bindings WHERE id=? AND source=?").get(bindingId,source);const binding=row?JSON.parse(String(row.metadata)):null;if((current?.revision??null)!==expectedSelectionRevision||!binding||binding.revision!==expectedBindingRevision){db.exec("ROLLBACK");return conflict()}if(binding.authority||binding.state!=="connected"||!binding.identity.subject||!Number.isFinite(Date.parse(binding.verifiedAt))){db.exec("ROLLBACK");return businessError("failed_precondition","Explicit source selection requires a verified connected native account.","storage")}const grant=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' AND json_extract(metadata,'$.audience')=?").get(bindingId,binding.provider);if(!grant||JSON.parse(String(grant.metadata)).state!=="active"){db.exec("ROLLBACK");return conflict()}const next={source,bindingId,revision:(current?.revision??0)+1,selectedAt:new Date().toISOString()};db.prepare("INSERT INTO source_selections(source,binding_id,revision,selected_at) VALUES(?,?,?,?) ON CONFLICT(source) DO UPDATE SET binding_id=excluded.binding_id,revision=excluded.revision,selected_at=excluded.selected_at").run(source,bindingId,next.revision,next.selectedAt);db.exec("COMMIT");return ok(next)}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Source selection transaction failed.")}}),refreshLegacyCredential:(source,expected,refresh)=>perform(async()=>{if(!sourceKey(source)||!expected||typeof refresh!=="function")return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");const expectedJson=JSON.stringify(expected);if(legacyRefreshClaim(source))return unknownLegacyRefresh();const row=legacyRow(source);if(!row||bindingRows(source).length)return conflict();const proof={metadata:String(row.metadata),credential:String(row.credential)};const connection=JSON.parse(proof.metadata);if(connection.source!==source||connection.state!=="connected"||connection.authority)return conflict();const current=JSON.parse(await codec.open(proof.credential));if(JSON.stringify(current)!==expectedJson)return conflict();if(typeof current.refreshToken!=="string"||!current.refreshToken||!current.clientId||!Number.isFinite(current.expiresAt)||!scopesMatch(current.scopes,current.scopes))return invalid();if(closed)return businessError("unavailable","Vault is inactive.","storage");const claim=randomUUID(),fingerprint=legacyFingerprint(proof);const matches=()=>{const candidate=rawLegacyRow(source);return candidate?.metadata===proof.metadata&&candidate?.credential===proof.credential&&!bindingRows(source).length};db.exec("BEGIN IMMEDIATE");try{if(legacyRefreshClaim(source)){db.exec("ROLLBACK");return unknownLegacyRefresh()}if(!matches()){db.exec("ROLLBACK");return conflict()}db.prepare("INSERT INTO legacy_refresh_claims(source,claim_id,fingerprint,started_at) VALUES(?,?,?,?)").run(source,claim,fingerprint,new Date().toISOString());db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}try{const changed=await refresh(structuredClone(connection),structuredClone(current));if(!("ok"in changed))return changed;const next=structuredClone(changed.ok);if(!next||typeof next.accessToken!=="string"||!next.accessToken||typeof next.refreshToken!=="string"||!next.refreshToken||!Number.isFinite(next.expiresAt)||next.expiresAt<=current.expiresAt||next.clientId!==current.clientId||!scopesMatch(current.scopes,next.scopes)||JSON.stringify(next.clientAuthentication)!==JSON.stringify(current.clientAuthentication))return invalid();const sealed=await codec.seal(JSON.stringify(next));if(db.prepare("UPDATE legacy_refresh_claims SET replacement=? WHERE source=? AND claim_id=? AND fingerprint=?").run(sealed,source,claim,fingerprint).changes!==1)return conflict();if(closed)return businessError("unavailable","Vault is inactive.","storage");db.exec("BEGIN IMMEDIATE");try{if(legacyRefreshClaim(source)?.claim_id!==claim||!matches()){db.exec("ROLLBACK");return conflict()}const updated=db.prepare("UPDATE legacy_connections SET credential=? WHERE source=? AND metadata=? AND credential=?").run(sealed,source,proof.metadata,proof.credential).changes;if(updated!==1){db.exec("ROLLBACK");return conflict()}db.prepare("DELETE FROM legacy_refresh_claims WHERE source=? AND claim_id=?").run(source,claim);db.exec("COMMIT");return ok(void 0)}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}catch{return businessError("data_loss","Legacy refresh or durable persistence did not complete; its claim remains fenced. Open zortex help for account recovery.","storage")}}),recoverLegacy:(source,verify)=>perform(async()=>{if(!sourceKey(source)||typeof verify!=="function")return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const row=legacyRow(source);if(!row||bindingRows(source).length)return businessError("failed_precondition","Legacy recovery requires an unattributed credential with no existing account bindings. Select an explicit account for mixed history.","storage");const proof={metadata:String(row.metadata),credential:String(row.credential)};const previous=JSON.parse(proof.metadata);if(previous.source!==source||previous.state!=="connected"||previous.authority)return businessError("failed_precondition","Legacy recovery requires an active native provider credential.","storage");const material=JSON.parse(await codec.open(proof.credential));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const verified=await verify(structuredClone(previous),structuredClone(material));if(!("ok"in verified))return verified;if(!verified.ok||typeof verified.ok.accountId!=="string"||!verified.ok.accountId.trim()||typeof verified.ok.account!=="string"||!verified.ok.account.trim()||previous.accountId!==void 0&&previous.accountId!==verified.ok.accountId)return businessError("failed_precondition","Verified provider identity differs from the legacy native account. Explicit account recovery is required.","storage");const connection={...previous,accountId:verified.ok.accountId,account:verified.ok.account,updatedAt:new Date().toISOString()};const saved=await saveConnection(connection,material,{},proof);if(!("ok"in saved))return saved;const resolved=resolveLegacy(source);return"ok"in resolved&&resolved.ok.kind==="resolved"?ok(resolved.ok.binding):conflict()}),bindings:source=>perform(async()=>sourceKey(source)?ok(bindingRows(source)):invalid()),resolve:selector=>perform(async()=>{if(!selector||Object.keys(selector).some(key=>!["kind","bindingId","source"].includes(key)))return invalid();if(selector.kind==="legacy-source")return resolveLegacy(selector.source);if(selector.kind==="selected-source"){if(!sourceKey(selector.source))return invalid();const selection=sourceSelection(selector.source);if(!selection)return resolveLegacy(selector.source);const binding=selectedBinding(selector.source);return binding&&binding.state==="connected"?ok({kind:"resolved",binding}):businessError("failed_precondition","The explicitly selected account is unavailable; choose an account in zortex help.","storage")}if(selector.kind!=="binding"||!validId(selector.bindingId))return invalid();const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(selector.bindingId);return row?ok({kind:"resolved",binding:JSON.parse(String(row.metadata))}):businessError("failed_precondition","Binding does not exist.","storage")}),binding:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(id);return ok(row?JSON.parse(String(row.metadata)):null)}),bindingInventory:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(id);if(!row)return ok(null);const grants=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? ORDER BY id LIMIT 257").all(id);const resources=db.prepare("SELECT metadata FROM credential_resources WHERE binding_id=? ORDER BY id LIMIT 257").all(id);if(grants.length>256||resources.length>256)return businessError("resource_exhausted","Binding setup inventory exceeds its metadata bound.","storage");return ok({binding:JSON.parse(String(row.metadata)),grants:grants.map(value=>JSON.parse(String(value.metadata))),resources:resources.map(value=>JSON.parse(String(value.metadata)))})}),grant:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM authorization_grants WHERE id=?").get(id);return ok(row?JSON.parse(String(row.metadata)):null)}),grantForBinding:(bindingId,purpose,audience)=>perform(async()=>{if(!validId(bindingId)||!["L1","L2"].includes(purpose)||!audience)return invalid();const grants=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? ORDER BY id").all(bindingId).map(row=>JSON.parse(String(row.metadata))).filter(grant=>grant.purpose===purpose&&grant.audience===audience);if(grants.length>1)return businessError("failed_precondition","Binding has ambiguous authorization grants.","storage");return ok(grants[0]??null)}),resource:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM credential_resources WHERE id=?").get(id);return ok(row?JSON.parse(String(row.metadata)):null)}),credential:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT kind,credential FROM credential_resources WHERE id=?").get(id);if(!row)return businessError("failed_precondition","Credential resource does not exist.","storage");const resource={kind:row.kind};const material=await decodeMaterial(resource.kind,String(row.credential));if(!materialMatches(resource,material))return businessError("data_loss","Credential resource kind does not match.","storage");return ok(material)}),credentialSnapshot:(id,authorization)=>perform(()=>credentialSnapshot(id,authorization)),refreshResource:(expected,owner,refresh)=>perform(async()=>{if(!expected?.resource||!expected.binding||!expected.grant||!owner||typeof refresh!=="function")return invalid();const id=expected.resource.id,authorization={purpose:expected.grant.purpose,audience:expected.grant.audience};const key=flightKey(id),fence=authorityFence(expected),claim=randomUUID();const stored=readSnapshotState(id,authorization);if(!("ok"in stored))return stored;if(ownerKey(stored.ok.resource)!==resourceOwnerKey(owner))return businessError("failed_precondition","Only the credential resource owner may refresh it.","storage");if(authorityFence(stored.ok)!==fence)return conflict();if(stored.ok.claim!==null){const flight2=refreshFlights.get(key);return flight2?.claim===stored.ok.claim&&flight2.fence===fence?joinedSnapshot(flight2,id,authorization):unknownRefresh()}db.exec("BEGIN IMMEDIATE");try{const current=readState(id,authorization);if(!("ok"in current)){db.exec("ROLLBACK");return current}if(authorityFence(current.ok)!==fence){db.exec("ROLLBACK");return conflict()}if(current.ok.claim!==null){db.exec("ROLLBACK");return unknownRefresh()}db.prepare("INSERT INTO credential_refresh_claims(resource_id,claim_id,expected_revision,owner_key) VALUES(?,?,?,?)").run(id,claim,stored.ok.resource.revision,ownerKey(stored.ok.resource));db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}const task=Promise.resolve().then(async()=>{const material=await decodeMaterial(stored.ok.resource.kind,stored.ok.sealed);if(!materialMatches(stored.ok.resource,material))return businessError("data_loss","Credential resource kind does not match.","storage");if(closed)return businessError("unavailable","Vault is inactive.","storage");const beforeEffect=readSnapshotState(id,authorization);if(!("ok"in beforeEffect))return beforeEffect;if(beforeEffect.ok.claim!==claim||authorityFence(beforeEffect.ok)!==fence)return conflict();const{binding,grant,resource}=stored.ok;const changed=await refresh(structuredClone({binding,grant,resource,material}));if(!("ok"in changed))return changed;if(!materialMatches(resource,changed.ok)||!sessionMaterialMatches(binding,grant,changed.ok))return invalid();const nextMaterial=structuredClone(changed.ok);const sealed=await encodeMaterial(resource.kind,nextMaterial);if(closed)return businessError("unavailable","Vault is inactive.","storage");const next={...resource,revision:resource.revision+1,updatedAt:new Date().toISOString()};db.exec("BEGIN IMMEDIATE");try{const current=readState(id,authorization);if(!("ok"in current)){db.exec("ROLLBACK");return current}if(current.ok.claim!==claim||authorityFence(current.ok)!==fence){db.exec("ROLLBACK");return conflict()}const updated=db.prepare("UPDATE credential_resources SET revision=?,metadata=?,credential=? WHERE id=? AND revision=?").run(next.revision,JSON.stringify(next),sealed,id,resource.revision).changes;if(updated!==1){db.exec("ROLLBACK");return conflict()}db.prepare("DELETE FROM credential_refresh_claims WHERE resource_id=? AND claim_id=?").run(id,claim);if(resource.kind==="oauth"&&id===oauthCredentialResourceId(binding.id)){db.prepare("UPDATE connections SET credential=? WHERE source=?").run(sealed,binding.identity.source)}db.exec("COMMIT");return ok({binding,grant,resource:next,material:nextMaterial})}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}).catch(()=>businessError("data_loss","Credential refresh or durable persistence failed; the resource remains fenced.","storage"));const flight={fence,claim,promise:task};refreshFlights.set(key,flight);try{return await task}finally{if(refreshFlights.get(key)===flight)refreshFlights.delete(key)}}),compareAndSwapBinding:(candidate,expectedRevision)=>perform(async()=>{if(!candidate||!validId(candidate.id)||!sourceKey(candidate.identity?.source)||!candidate.identity.issuer||!candidate.identity.subject&&!candidate.authority||!candidate.provider||!candidate.account||candidate.authority!==void 0&&!isConnectionAuthority(candidate.authority)||candidate.identity.tenant!==null&&typeof candidate.identity.tenant!=="string"||!Number.isSafeInteger(expectedRevision)||expectedRevision<0)return invalid();const next={...candidate,revision:expectedRevision+1};if(expectedRevision===0){try{db.prepare("INSERT INTO account_bindings(id,source,issuer,subject,tenant_key,revision,metadata) VALUES(?,?,?,?,?,?,?)").run(next.id,next.identity.source,next.identity.issuer,storedSubject(next),tenantKey(next.identity.tenant),next.revision,JSON.stringify(next))}catch{return conflict()}}else{const current=db.prepare("SELECT source,issuer,subject,tenant_key,metadata FROM account_bindings WHERE id=?").get(next.id);if(!current||current.source!==next.identity.source||current.issuer!==next.identity.issuer||current.subject!==storedSubject(next)||current.tenant_key!==tenantKey(next.identity.tenant)||JSON.stringify(JSON.parse(String(current.metadata)).authority)!==JSON.stringify(next.authority))return businessError("failed_precondition","Binding identity and session authority are immutable.","storage");const changed=db.prepare("UPDATE account_bindings SET source=?,issuer=?,subject=?,tenant_key=?,revision=?,metadata=? WHERE id=? AND revision=?").run(next.identity.source,next.identity.issuer,storedSubject(next),tenantKey(next.identity.tenant),next.revision,JSON.stringify(next),next.id,expectedRevision).changes;if(!changed)return conflict()}return ok(next)}),compareAndSwapGrant:(candidate,expectedRevision)=>perform(async()=>{if(!candidate||!validId(candidate.id)||!validId(candidate.bindingId)||!["L1","L2"].includes(candidate.purpose)||!candidate.audience||!Array.isArray(candidate.scopes)||!Number.isSafeInteger(candidate.scopeEpoch)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0)return invalid();if(!db.prepare("SELECT 1 FROM account_bindings WHERE id=?").get(candidate.bindingId))return businessError("failed_precondition","Grant binding does not exist.","storage");const next={...candidate,scopes:[...new Set(candidate.scopes)].sort(),revision:expectedRevision+1};if(expectedRevision===0){try{db.prepare("INSERT INTO authorization_grants(id,binding_id,revision,metadata) VALUES(?,?,?,?)").run(next.id,next.bindingId,next.revision,JSON.stringify(next))}catch{return conflict()}}else{const currentRow=db.prepare("SELECT binding_id,metadata FROM authorization_grants WHERE id=?").get(next.id);const current=currentRow?JSON.parse(String(currentRow.metadata)):null;if(!current||currentRow.binding_id!==next.bindingId||current.purpose!==next.purpose||current.audience!==next.audience)return businessError("failed_precondition","Grant ownership is immutable.","storage");const changed=db.prepare("UPDATE authorization_grants SET binding_id=?,revision=?,metadata=? WHERE id=? AND revision=?").run(next.bindingId,next.revision,JSON.stringify(next),next.id,expectedRevision).changes;if(!changed)return conflict()}return ok(next)}),compareAndSwapResource:(candidate,material,expectedRevision)=>perform(async()=>{if(!candidate||!validId(candidate.id)||!validId(candidate.bindingId)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||!materialMatches(candidate,material)||candidate.owner.kind==="managed-sidecar-profile"&&candidate.owner.bindingId!==candidate.bindingId)return invalid();if(!db.prepare("SELECT 1 FROM account_bindings WHERE id=?").get(candidate.bindingId))return businessError("failed_precondition","Credential binding does not exist.","storage");if(expectedRevision>0){const current=db.prepare("SELECT binding_id,kind,owner_key FROM credential_resources WHERE id=?").get(candidate.id);if(!current||current.binding_id!==candidate.bindingId||current.kind!==candidate.kind||current.owner_key!==ownerKey(candidate))return businessError("failed_precondition","Credential resource ownership is immutable.","storage")}const sealed=await encodeMaterial(candidate.kind,material);if(closed)return businessError("unavailable","Vault is inactive.","storage");const next={...candidate,revision:expectedRevision+1,encryptedRef:candidate.kind==="local-no-secret"?null:encryptedRef(candidate.id)};db.exec("BEGIN IMMEDIATE");try{if(expectedRevision===0){try{db.prepare("INSERT INTO credential_resources(id,binding_id,kind,owner_key,revision,metadata,credential) VALUES(?,?,?,?,?,?,?)").run(next.id,next.bindingId,next.kind,ownerKey(next),next.revision,JSON.stringify(next),sealed)}catch{db.exec("ROLLBACK");return conflict()}}else{const changed=db.prepare("UPDATE credential_resources SET binding_id=?,kind=?,owner_key=?,revision=?,metadata=?,credential=? WHERE id=? AND revision=?").run(next.bindingId,next.kind,ownerKey(next),next.revision,JSON.stringify(next),sealed,next.id,expectedRevision).changes;if(!changed){db.exec("ROLLBACK");return conflict()}}db.exec("COMMIT");return ok(next)}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Credential resource transaction failed.")}})};const metadataSnapshot=createMetadataSnapshotReader(db);const service={identityContract:BINDING_CUSTODY_CONTRACT,bindingCustody,guardedCache:"atomic-connection",metadataSnapshot:request=>perform(async()=>metadataSnapshot(request)),connections:()=>perform(async()=>{const bindings=db.prepare("SELECT metadata FROM account_bindings ORDER BY source,id").all().map(row=>JSON.parse(String(row.metadata))).map(connectionFromBinding);const sources=new Set(bindings.map(binding=>binding.source));const legacy=db.prepare("SELECT source,metadata FROM legacy_connections ORDER BY source").all().filter(row=>!sources.has(String(row.source))).map(row=>JSON.parse(String(row.metadata)));return ok([...bindings,...legacy].sort((a,b)=>a.source.localeCompare(b.source)||a.account.localeCompare(b.account)))}),connection:source=>perform(async()=>{if(!sourceKey(source))return invalid();if(sourceSelection(source)){const selected=selectedBinding(source);return selected?ok(connectionFromBinding(selected)):businessError("failed_precondition","The selected account is unavailable.","storage")}const bindings=bindingRows(source),legacy=legacyRow(source);if(bindings.length===1&&!legacy){return ok(connectionFromBinding(bindings[0]))}if(bindings.length===0&&legacy)return ok(JSON.parse(String(legacy.metadata)));if(bindings.length===0)return ok(null);return businessError("failed_precondition","Multiple or unattributed accounts exist; select a binding.","storage")}),legacyRevision:source=>perform(async()=>{if(!sourceKey(source))return invalid();if(legacyRefreshClaim(source)||sourceSelection(source)||bindingRows(source).length)return ok(null);const row=legacyRow(source);if(!row)return ok(null);const metadata=JSON.parse(String(row.metadata));if(metadata.source!==source||metadata.state!=="connected")return ok(null);return ok(legacyFingerprint({metadata:String(row.metadata),credential:String(row.credential)}))}),joplinPairingGeneration:()=>perform(async()=>ok(Number(db.prepare("SELECT revision FROM joplin_pairing_generation WHERE id=1").get().revision))),joplinPairingCommit:transactionId=>perform(async()=>{if(!/^[a-f0-9]{32}$/.test(transactionId))return invalid();db.exec("BEGIN");try{const row=db.prepare("SELECT expected_generation,committed_generation FROM joplin_pairing_commits WHERE transaction_id=?").get(transactionId);const currentGeneration=Number(db.prepare("SELECT revision FROM joplin_pairing_generation WHERE id=1").get().revision);const refreshClaimPresent=Boolean(db.prepare("SELECT 1 FROM legacy_refresh_claims WHERE source='joplin'").get());db.exec("COMMIT");return ok({marker:row?{expectedGeneration:Number(row.expected_generation),committedGeneration:Number(row.committed_generation)}:null,currentGeneration,refreshClaimPresent})}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}),beginJoplinPairing:(transactionId,expectedGeneration,account)=>perform(async()=>ok(beginJoplinPairing(db,{transactionId,expectedGeneration,account}))),reconcileJoplinPairing:expected=>perform(async()=>ok(reconcileJoplinPairing(db,expected))),commitJoplinPairing:(transactionId,expectedGeneration,connection,credential,options={})=>perform(async()=>{if(!/^[a-f0-9]{32}$/.test(transactionId)||!Number.isSafeInteger(expectedGeneration)||expectedGeneration<0||!options.authorityAccount||options.authorityAccount!==connection.account||connection.source!=="joplin"||connection.provider!=="joplin"||!connection.account||connection.accountId!==void 0||connection.authority!==void 0||connection.state!=="connected"||!Array.isArray(connection.scopes)||connection.scopes.length!==0||!credential.accessToken||credential.clientId!=="mcp-fields"||credential.expiresAt!==0||!Array.isArray(credential.scopes)||credential.scopes.length!==0)return invalid();const capturedConnection=structuredClone(connection),capturedCredential=structuredClone(credential);if(options.signal?.aborted)return businessError("aborted","Connection consent was cancelled.","storage");const sealedCredential=await codec.seal(JSON.stringify(capturedCredential));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(options.signal?.aborted)return businessError("aborted","Connection consent was cancelled before commit.","storage");const committed=commitJoplinPairing(db,{transactionId,expectedGeneration,metadata:JSON.stringify(capturedConnection),sealedCredential,...options.authorityAccount===void 0?{}:{authorityAccount:options.authorityAccount}});return committed?ok(committed):conflict()}),joplinPairingRevision:()=>perform(async()=>ok(null)),joplinFencedRevision:expectedAccount=>perform(async()=>ok(joplinPairingAuthority(db,expectedAccount))),joplinFencedSnapshot:expectedAccount=>perform(async()=>{const revision=joplinPairingAuthority(db,expectedAccount);if(revision===null)return conflict();const row=legacyRow("joplin");if(!row)return conflict();const connection=JSON.parse(String(row.metadata));if(connection.state!=="connected"||connection.accountId||connection.authority||connection.account!==expectedAccount)return conflict();const credential=JSON.parse(await codec.open(String(row.credential)));if(closed||joplinPairingAuthority(db,expectedAccount)!==revision)return conflict();return ok({revision,connection,credential})}),joplinPairingSnapshot:()=>perform(async()=>conflict()),saveConnection:(connection,credential,options)=>perform(async()=>connection.source==="joplin"?businessError("failed_precondition","Joplin pairing requires fenced custody.","storage"):saveConnection(connection,credential,options)),credential:source=>perform(async()=>{if(!sourceKey(source))return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const bindings=bindingRows(source),legacy=legacyRow(source);if(bindings.length===0&&legacy){const material2=JSON.parse(await codec.open(String(legacy.credential)));if(legacyRefreshClaim(source))return unknownLegacyRefresh();const current=rawLegacyRow(source);if(current?.metadata!==legacy.metadata||current?.credential!==legacy.credential||bindingRows(source).length)return conflict();return ok(material2)}if(bindings.length!==1||legacy)return businessError("failed_precondition",bindings.length?"Multiple or unattributed accounts exist; select a binding.":`${source} is not connected. Start the source connection flow.`,"storage");const row=db.prepare("SELECT credential FROM credential_resources WHERE id=?").get(oauthCredentialResourceId(bindings[0].id));if(!row)return businessError("failed_precondition","OAuth credential resource is missing.","storage");const material=JSON.parse(await codec.open(String(row.credential)));return material.kind==="oauth"?ok(material.credential):businessError("data_loss","Credential resource kind does not match.","storage")}),updateCredential:(source,credential)=>perform(async()=>{if(!sourceKey(source)||!credential.accessToken)return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const bindings=bindingRows(source),legacy=legacyRow(source);if(bindings.length===0&&legacy){const sealed2=await codec.seal(JSON.stringify(credential));if(closed)return businessError("unavailable","Vault is inactive.","storage");const changed=db.prepare("UPDATE legacy_connections SET credential=? WHERE source=? AND metadata=? AND credential=? AND NOT EXISTS (SELECT 1 FROM account_bindings WHERE source=?) AND NOT EXISTS (SELECT 1 FROM legacy_refresh_claims WHERE source=?)").run(sealed2,source,legacy.metadata,legacy.credential,source,source).changes;return changed?ok(void 0):conflict()}if(bindings.length!==1||legacy)return businessError("failed_precondition","Multiple or unattributed accounts exist; select a binding.","storage");const id=oauthCredentialResourceId(bindings[0].id);const row=db.prepare("SELECT revision,metadata FROM credential_resources WHERE id=?").get(id);if(!row)return businessError("failed_precondition","OAuth credential resource is missing.","storage");const sealed=await codec.seal(JSON.stringify({kind:"oauth",credential}));const current=JSON.parse(String(row.metadata));const next={...current,revision:Number(row.revision)+1,updatedAt:new Date().toISOString()};db.exec("BEGIN IMMEDIATE");try{const changed=db.prepare("UPDATE credential_resources SET revision=?,metadata=?,credential=? WHERE id=? AND revision=?").run(next.revision,JSON.stringify(next),sealed,id,Number(row.revision)).changes;if(!changed){db.exec("ROLLBACK");return conflict()}db.prepare("UPDATE connections SET credential=? WHERE source=?").run(sealed,source);db.exec("COMMIT");return ok(void 0)}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Credential update transaction failed.")}}),saveBindingRecords:records=>perform(async()=>{if(!Array.isArray(records)||records.length>100||records.some(record=>!validId(record.bindingId)||!record.stream||record.stream.length>128||!record.nativeId||record.nativeId.length>500||!Number.isFinite(record.timestamp)||Buffer.byteLength(JSON.stringify(record.data))>512e3))return invalid();if([...new Set(records.map(record=>record.bindingId))].some(id=>!db.prepare("SELECT 1 FROM account_bindings WHERE id=?").get(id)))return businessError("failed_precondition","Record binding does not exist.","storage");const sealed=await Promise.all(records.map(async record=>({record,payload:await codec.seal(JSON.stringify(record.data))})));db.exec("BEGIN IMMEDIATE");try{const insert=db.prepare("INSERT INTO binding_records(binding_id,stream,native_id,ts,payload) VALUES(?,?,?,?,?) ON CONFLICT(binding_id,stream,native_id) DO UPDATE SET ts=excluded.ts,payload=excluded.payload");for(const{record,payload}of sealed)insert.run(record.bindingId,record.stream,record.nativeId,record.timestamp,payload);db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Binding record transaction failed.")}return ok(records.length)}),bindingRecords:(bindingId,stream,limit)=>perform(async()=>{if(!validId(bindingId)||!stream||stream.length>128||!Number.isInteger(limit)||limit<1||limit>100)return invalid();const rows=db.prepare("SELECT native_id,ts,payload FROM binding_records WHERE binding_id=? AND stream=? ORDER BY ts DESC,native_id LIMIT ?").all(bindingId,stream,limit);return ok(await Promise.all(rows.map(async row=>({bindingId,stream,nativeId:String(row.native_id),timestamp:Number(row.ts),data:JSON.parse(await codec.open(String(row.payload)))}))))}),saveRecords:(records,guard)=>perform(async()=>{if(guard&&(Object.keys(guard).some(key=>!["source","account","accountId","requiredScopes","signal"].includes(key))||!sourceKey(guard.source)||!guard.account||guard.accountId!==void 0&&!guard.accountId||guard.requiredScopes!==void 0&&(!Array.isArray(guard.requiredScopes)||guard.requiredScopes.length>64||guard.requiredScopes.some(scope=>!scope||scope.length>512))))return invalid();if(guard?.signal?.aborted)return businessError("aborted","Cache write was cancelled before sealing.","storage");if(!Array.isArray(records)||records.length>100||records.some(record=>!sourceKey(record.source)||guard&&record.source!==guard.source||!record.id||record.id.length>500||!Number.isFinite(record.timestamp)||Buffer.byteLength(JSON.stringify(record.data))>512e3))return invalid();const sealed=await Promise.all(records.map(async record=>({...record,payload:await codec.seal(JSON.stringify(record.data))})));if(closed)return businessError("unavailable","Vault is inactive.","storage");db.exec("BEGIN IMMEDIATE");try{if(guard?.signal?.aborted){db.exec("ROLLBACK");return businessError("aborted","Cache write was cancelled before commit.","storage")}if(records.some(record=>sourceSelection(record.source))){db.exec("ROLLBACK");return businessError("failed_precondition","Selected recovery accounts require transient reads or binding-scoped record storage; source history was not changed.","storage")}if(guard){const bindings=bindingRows(guard.source),legacy=legacyRow(guard.source);let current=null;if(records.length===0&&sourceSelection(guard.source)){const selected=selectedBinding(guard.source);if(selected)current=connectionFromBinding(selected)}else if(bindings.length===1&&!legacy){current=connectionFromBinding(bindings[0])}else if(bindings.length===0&&legacy)current=JSON.parse(String(legacy.metadata));if(!current||current.state!=="connected"||current.account!==guard.account||guard.accountId!==void 0&&current.accountId!==guard.accountId||guard.requiredScopes?.some(scope=>!current.scopes.includes(scope))){db.exec("ROLLBACK");return businessError("permission_denied","Source identity or permission changed before cache commit; no rows were written.","storage")}}const insert=db.prepare("INSERT INTO records(source,id,ts,payload) VALUES(?,?,?,?) ON CONFLICT(source,id) DO UPDATE SET ts=excluded.ts,payload=excluded.payload");for(const record of sealed)insert.run(record.source,record.id,record.timestamp,record.payload);if(existingVault){const project=db.prepare("INSERT INTO connector_records(source,source_id,ts,body,payload) VALUES(?,?,?,?,?) ON CONFLICT(source,source_id) DO UPDATE SET ts=excluded.ts,body=excluded.body,payload=excluded.payload");for(const record of records)project.run(record.source,record.id,new Date(record.timestamp).toISOString(),typeof record.data.body==="string"?record.data.body:"",JSON.stringify(record.data))}db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Record transaction failed.")}return ok(records.length)}),records:(source,limit)=>perform(async()=>{if(!sourceKey(source)||!Number.isInteger(limit)||limit<1||limit>100)return invalid();const resolution=resolveLegacy(source);if("ok"in resolution&&resolution.ok.kind==="ambiguous_account")return businessError("failed_precondition","Multiple accounts exist; select a binding and stream.","storage");const rows=db.prepare("SELECT id,source,ts,payload FROM records WHERE source=? ORDER BY ts DESC,id LIMIT ?").all(source,limit);return ok(await Promise.all(rows.map(async row=>({id:String(row.id),source:String(row.source),timestamp:Number(row.ts),data:JSON.parse(await codec.open(String(row.payload)))}))))}),close(){if(!closing){closed=true;closing=(async()=>{await Promise.allSettled([...pending]);db.close()})()}return closing}};return service}export async function apply(ctx,config){if(!config||typeof config.root!=="string"||Object.keys(config).some(key=>key!=="root"))throw Error("Vault root configuration is required.");const store=await createVaultStore(config);ctx.provide("zortexVaultStore",store);ctx.effect(()=>()=>store.close())}
19
+ ${["legacy_connections","account_bindings","source_selections","legacy_refresh_claims"].flatMap(table=>["INSERT","UPDATE","DELETE"].map(op=>{const condition=op==="UPDATE"?"OLD.source='joplin' OR NEW.source='joplin'":`${op==="DELETE"?"OLD":"NEW"}.source='joplin'`;return`CREATE TRIGGER IF NOT EXISTS joplin_generation_${table}_${op.toLowerCase()} AFTER ${op} ON ${table} WHEN ${condition} BEGIN UPDATE joplin_pairing_generation SET revision=revision+1 WHERE id=1; END;`})).join("\n")}`);initializeJoplinPairingCommits(db);if(!db.prepare("SELECT 1 FROM custody_migrations WHERE id='binding-custody-v1'").get()){db.exec("BEGIN IMMEDIATE");try{db.exec("INSERT OR IGNORE INTO legacy_connections(source,metadata,credential) SELECT source,metadata,credential FROM connections; DELETE FROM connections;");db.prepare("INSERT INTO custody_migrations(id,applied_at) VALUES(?,?)").run("binding-custody-v1",new Date().toISOString());db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Binding custody migration failed.")}}let account=existingVault?.identity;if(!providedCodec&&process.platform==="darwin"&&!account){db.exec("CREATE TABLE IF NOT EXISTS custody_identity(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);");db.prepare("INSERT OR IGNORE INTO custody_identity(id,value) VALUES(1,?)").run(randomUUID());account=String(db.prepare("SELECT value FROM custody_identity WHERE id=1").get().value)}codec=providedCodec??createSystemCodec(account?{account}:{})}catch(error){try{db.close()}catch{}throw error}async function perform(operation){if(closed)return businessError("unavailable","Vault is inactive.","storage");let settle;const task=new Promise(done=>settle=done);pending.add(task);void(async()=>{try{const result=await operation();settle(closed?businessError("unavailable","Vault is inactive.","storage"):result)}catch{settle(businessError("data_loss","Vault operation or system credential protection failed.","storage"))}})();try{return await task}finally{pending.delete(task)}}const bindingRows=source=>db.prepare("SELECT metadata FROM account_bindings WHERE source=? ORDER BY id").all(source).map(row=>JSON.parse(String(row.metadata)));const connectionFromBinding=binding=>{const grantRow=binding.authority?db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' AND json_extract(metadata,'$.audience')=? ORDER BY id LIMIT 1").get(binding.id,binding.authority.resource):db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' ORDER BY id LIMIT 1").get(binding.id);const grant=grantRow?JSON.parse(String(grantRow.metadata)):null;return{source:binding.identity.source,provider:binding.provider,account:binding.account,...binding.identity.subject===void 0?{}:{accountId:binding.identity.subject},...binding.authority?{authority:binding.authority}:{},scopes:grant?[...grant.scopes]:[],state:binding.state,updatedAt:binding.updatedAt}};const rawLegacyRow=source=>db.prepare("SELECT metadata,credential FROM legacy_connections WHERE source=?").get(source);const sourceSelection=source=>{const row=db.prepare("SELECT binding_id,revision,selected_at FROM source_selections WHERE source=?").get(source);return row?{source,bindingId:String(row.binding_id),revision:Number(row.revision),selectedAt:String(row.selected_at)}:null};const selectedBinding=source=>{const selection=sourceSelection(source);if(!selection)return null;const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=? AND source=?").get(selection.bindingId,source);return row?JSON.parse(String(row.metadata)):null};const legacyRefreshClaim=source=>db.prepare("SELECT claim_id,fingerprint FROM legacy_refresh_claims WHERE source=?").get(source);const legacyFingerprint=row=>createHash("sha256").update(JSON.stringify([row.metadata,row.credential])).digest("hex");const legacyRow=source=>{const row=rawLegacyRow(source);if(!row)return void 0;const recovered=db.prepare("SELECT binding_id,fingerprint FROM legacy_recoveries WHERE source=?").get(source);return recovered&&recovered.fingerprint===legacyFingerprint({metadata:String(row.metadata),credential:String(row.credential)})&&db.prepare("SELECT 1 FROM account_bindings WHERE id=? AND source=?").get(String(recovered.binding_id),source)?void 0:row};const resolveLegacy=source=>{if(!sourceKey(source))return invalid();const bindings=bindingRows(source);const legacy=legacyRow(source);if(bindings.length===1&&!legacy)return ok({kind:"resolved",binding:bindings[0]});if(bindings.length===0)return ok({kind:"legacy-unattributed",source});return ok({kind:"ambiguous_account",source,bindingIds:bindings.map(binding=>binding.id)})};const resolveBinding=selector=>{if(!selector||Object.keys(selector).some(key=>!["kind","bindingId","source"].includes(key)))return invalid();if(selector.kind==="legacy-source")return resolveLegacy(selector.source);if(selector.kind==="selected-source"){if(!sourceKey(selector.source))return invalid();if(!sourceSelection(selector.source))return resolveLegacy(selector.source);const binding=selectedBinding(selector.source);return binding&&binding.state==="connected"?ok({kind:"resolved",binding}):businessError("failed_precondition","The explicitly selected account is unavailable; choose an account in zortex help.","storage")}if(selector.kind!=="binding"||!validId(selector.bindingId))return invalid();const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(selector.bindingId);return row?ok({kind:"resolved",binding:JSON.parse(String(row.metadata))}):businessError("failed_precondition","Binding does not exist.","storage")};const bindingInventory=id=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(id);if(!row)return ok(null);const grants=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? ORDER BY id LIMIT 257").all(id);const resources=db.prepare("SELECT metadata FROM credential_resources WHERE binding_id=? ORDER BY id LIMIT 257").all(id);if(grants.length>256||resources.length>256)return businessError("resource_exhausted","Binding setup inventory exceeds its metadata bound.","storage");return ok({binding:JSON.parse(String(row.metadata)),grants:grants.map(value=>JSON.parse(String(value.metadata))),resources:resources.map(value=>JSON.parse(String(value.metadata)))})};const authoritySnapshot=selector=>{db.exec("BEGIN");try{const visibilityRevision=Number(db.prepare("SELECT epoch FROM public_visibility WHERE id=1").get().epoch);if(selector&&selector.kind!=="binding"&&sourceKey(selector.source)&&db.prepare("SELECT id FROM account_bindings WHERE source=? LIMIT 257").all(selector.source).length>256){db.exec("COMMIT");return businessError("resource_exhausted","Source authority exceeds its metadata bound.","storage")}const resolved=resolveBinding(selector);if(!("ok"in resolved)){db.exec("COMMIT");return resolved}const resolution=resolved.ok,source=resolution.kind==="resolved"?resolution.binding.identity.source:resolution.source;const inventory=resolution.kind==="resolved"?bindingInventory(resolution.binding.id):ok(null);if(!("ok"in inventory)){db.exec("COMMIT");return inventory}const legacy=legacyRow(source);const value={source,resolution,selection:sourceSelection(source),inventory:inventory.ok,legacy:legacy?JSON.parse(String(legacy.metadata)):null,visibilityRevision};db.exec("COMMIT");return ok(value)}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}};const ownerKey=resource=>resourceOwnerKey(resource.owner);const materialMatches=(resource,material)=>resource.kind==="oauth"&&material.kind==="oauth"||resource.kind==="mcp-token"&&material.kind==="mcp-token"||resource.kind==="rest-token"&&material.kind==="rest-token"||resource.kind==="local-no-secret"&&isNoSecretMaterial(material);const encodeMaterial=(kind,material)=>kind==="local-no-secret"?Promise.resolve(NO_SECRET_MATERIAL):codec.seal(JSON.stringify(material));const decodeMaterial=async(kind,value)=>kind==="local-no-secret"&&value===NO_SECRET_MATERIAL?{kind:"local-no-secret"}:JSON.parse(await codec.open(value));const flightKey=id=>JSON.stringify([file,id]);function readState(id,authorization){if(!validId(id)||!authorization||!["L1","L2"].includes(authorization.purpose)||!validId(authorization.audience))return invalid();const row=db.prepare("SELECT binding_id,metadata,credential FROM credential_resources WHERE id=?").get(id);if(!row)return businessError("failed_precondition","Credential resource does not exist.","storage");const bindingRow=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(String(row.binding_id));const grants=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')=? AND json_extract(metadata,'$.audience')=?").all(String(row.binding_id),authorization.purpose,authorization.audience);if(!bindingRow||grants.length!==1)return businessError("failed_precondition","Credential use requires one explicit authorization grant.","storage");const binding=JSON.parse(String(bindingRow.metadata));const grant=JSON.parse(String(grants[0].metadata));if(binding.state!=="connected"||grant.state!=="active")return businessError("permission_denied","Credential authority is disconnected or revoked.","storage");const resource=JSON.parse(String(row.metadata));const claim=db.prepare("SELECT claim_id FROM credential_refresh_claims WHERE resource_id=?").get(id);return ok({binding,grant,resource,sealed:String(row.credential),claim:claim?String(claim.claim_id):null})}function readSnapshotState(id,authorization){db.exec("BEGIN");try{const state=readState(id,authorization);db.exec("COMMIT");return state}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}async function joinedSnapshot(flight,id,authorization){const result=await flight.promise;if(!("ok"in result))return result;if(closed)return businessError("unavailable","Vault is inactive.","storage");const current=readSnapshotState(id,authorization);if(!("ok"in current))return current;return current.ok.claim===null&&authorityFence(current.ok)===authorityFence(result.ok)?result:conflict()}async function credentialSnapshot(id,authorization){const stored=readSnapshotState(id,authorization);if(!("ok"in stored))return stored;const joinClaim=state=>{const flight=refreshFlights.get(flightKey(id));return flight&&flight.claim===state.claim&&flight.fence===authorityFence(state)?joinedSnapshot(flight,id,authorization):Promise.resolve(unknownRefresh())};if(stored.ok.claim!==null)return joinClaim(stored.ok);const material=await decodeMaterial(stored.ok.resource.kind,stored.ok.sealed);if(closed)return businessError("unavailable","Vault is inactive.","storage");const current=readSnapshotState(id,authorization);if(!("ok"in current))return current;if(current.ok.claim!==null)return joinClaim(current.ok);if(authorityFence(current.ok)!==authorityFence(stored.ok))return conflict();if(!materialMatches(stored.ok.resource,material))return businessError("data_loss","Credential resource kind does not match.","storage");const{binding,grant,resource}=stored.ok;if(!sessionMaterialMatches(binding,grant,material))return businessError("failed_precondition","MCP session material does not match its selected resource authority.","storage");return ok({binding,grant,resource,material})}async function saveConnection(connection,credential,options={},legacyProof){if(!sourceKey(connection.source)||!connection.provider||!connection.account||!credential.accessToken||!Number.isFinite(credential.expiresAt)||Object.keys(options).some(key=>key!=="signal"&&key!=="expectedCredential"&&key!=="expectedSelectionRevision"&&key!=="selectSource")||connection.accountId!==void 0&&(typeof connection.accountId!=="string"||!connection.accountId.trim()||connection.accountId.length>1e3||/[\u0000-\u001f\u007f-\u009f]/u.test(connection.accountId)))return invalid();if(connection.authority!==void 0&&(!isMcpSessionAuthority(connection.authority)||credential.clientId!==connection.authority.clientId||!scopesMatch(connection.scopes,credential.scopes)))return invalid();const expected=options.expectedCredential;if(expected!==void 0&&expected!==null&&(typeof expected!=="object"||Object.keys(expected).length!==6||Object.keys(expected).some(key=>!["bindingId","bindingRevision","grantId","grantRevision","resourceId","resourceRevision"].includes(key))||!validId(expected.bindingId)||!validId(expected.grantId)||!validId(expected.resourceId)||![expected.bindingRevision,expected.grantRevision,expected.resourceRevision].every(value=>Number.isSafeInteger(value)&&value>0)||connection.accountId===void 0&&connection.authority===void 0))return invalid();const expectedCredential=expected===void 0||expected===null?expected:structuredClone(expected);const expectedSelectionRevision=options.expectedSelectionRevision;if(expectedSelectionRevision!==void 0&&expectedSelectionRevision!==null&&(!Number.isSafeInteger(expectedSelectionRevision)||expectedSelectionRevision<1))return invalid();const selection=options.selectSource===void 0?void 0:structuredClone(options.selectSource);if(selection!==void 0&&(!selection||typeof selection!=="object"||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["expectedSelectionRevision","expectedBindingRevision"].includes(key))||selection.expectedSelectionRevision!==null&&(!Number.isSafeInteger(selection.expectedSelectionRevision)||selection.expectedSelectionRevision<1)||!Number.isSafeInteger(selection.expectedBindingRevision)||selection.expectedBindingRevision<0||!connection.accountId||connection.state!=="connected"||!Number.isFinite(Date.parse(connection.updatedAt))||selection.expectedBindingRevision>0&&(!expectedCredential||expectedCredential.bindingRevision!==selection.expectedBindingRevision)||selection.expectedBindingRevision===0&&expectedCredential!==void 0&&expectedCredential!==null))return invalid();connection=structuredClone(connection);credential=structuredClone(credential);const signal=options.signal;if(signal?.aborted)return businessError("aborted","Connection consent was cancelled.","storage");if(connection.accountId===void 0&&connection.authority===void 0){const hasBinding=()=>Boolean(db.prepare("SELECT 1 FROM account_bindings WHERE source=? LIMIT 1").get(connection.source));if(legacyRefreshClaim(connection.source))return unknownLegacyRefresh();if(hasBinding())return businessError("failed_precondition","Verified source bindings require an explicit verified account identity; unattributed credentials were not saved.","storage");const previous=legacyRow(connection.source);const metadata=JSON.stringify(connection);const sealed2=await codec.seal(JSON.stringify(credential));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(signal?.aborted)return businessError("aborted","Connection consent was cancelled before commit.","storage");db.exec("BEGIN IMMEDIATE");try{if(expectedSelectionRevision!==void 0&&(sourceSelection(connection.source)?.revision??null)!==expectedSelectionRevision){db.exec("ROLLBACK");return conflict()}const current=legacyRow(connection.source);if(legacyRefreshClaim(connection.source)||hasBinding()||current?.metadata!==previous?.metadata||current?.credential!==previous?.credential){db.exec("ROLLBACK");return conflict()}db.prepare("INSERT INTO legacy_connections(source,metadata,credential) VALUES(?,?,?) ON CONFLICT(source) DO UPDATE SET metadata=excluded.metadata,credential=excluded.credential").run(connection.source,metadata,sealed2);db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Legacy connection transaction failed.")}return ok({...connection})}const identity={source:connection.source,issuer:connection.accountId===void 0&&connection.authority?.kind==="mcp-session"?connection.authority.issuer:connection.provider,...connection.accountId===void 0?{}:{subject:connection.accountId},tenant:null};const bindingId=opaqueId("binding",connection.accountId===void 0?{identity,authority:connection.authority}:identity);const audience=connection.authority?.resource??connection.provider;const grantId=opaqueId("grant",{bindingId,purpose:"L1",audience});const resourceId=oauthCredentialResourceId(bindingId);if(expectedCredential&&(expectedCredential.bindingId!==bindingId||expectedCredential.grantId!==grantId||expectedCredential.resourceId!==resourceId))return conflict();const existingBinding=db.prepare("SELECT revision FROM account_bindings WHERE id=?").get(bindingId);const existingGrant=db.prepare("SELECT revision,json_extract(metadata,'$.scopeEpoch') AS scope_epoch FROM authorization_grants WHERE id=?").get(grantId);const existingResource=db.prepare("SELECT revision FROM credential_resources WHERE id=?").get(resourceId);const sealed=await codec.seal(JSON.stringify({kind:"oauth",credential}));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(signal?.aborted)return businessError("aborted","Connection consent was cancelled before commit.","storage");const binding={id:bindingId,revision:Number(existingBinding?.revision??0)+1,identity,...connection.authority?{authority:connection.authority}:{},provider:connection.provider,account:connection.account,state:connection.state,verifiedAt:connection.updatedAt,updatedAt:connection.updatedAt};const grant={id:grantId,revision:Number(existingGrant?.revision??0)+1,bindingId,purpose:"L1",audience,scopes:[...new Set(connection.scopes)].sort(),scopeEpoch:Number(existingGrant?.scope_epoch??0)+1,state:connection.state==="connected"?"active":"revoked",updatedAt:connection.updatedAt};const resource={id:resourceId,bindingId,kind:"oauth",owner:{kind:"resident"},revision:Number(existingResource?.revision??0)+1,encryptedRef:encryptedRef(resourceId),updatedAt:connection.updatedAt};db.exec("BEGIN IMMEDIATE");try{if(expectedSelectionRevision!==void 0&&(sourceSelection(connection.source)?.revision??null)!==expectedSelectionRevision){db.exec("ROLLBACK");return conflict()}if(legacyProof){const current=rawLegacyRow(connection.source);if(legacyRefreshClaim(connection.source)||!current||current.metadata!==legacyProof.metadata||current.credential!==legacyProof.credential||bindingRows(connection.source).length){db.exec("ROLLBACK");return conflict()}}const revision=(table,id)=>Number(db.prepare(`SELECT revision FROM ${table} WHERE id=?`).get(id)?.revision??0);if(selection&&((sourceSelection(connection.source)?.revision??null)!==selection.expectedSelectionRevision||revision("account_bindings",bindingId)!==selection.expectedBindingRevision||selection.expectedBindingRevision===0&&(revision("authorization_grants",grantId)!==0||revision("credential_resources",resourceId)!==0))){db.exec("ROLLBACK");return conflict()}if(expectedCredential===null&&(revision("account_bindings",bindingId)!==0||revision("authorization_grants",grantId)!==0||revision("credential_resources",resourceId)!==0)){db.exec("ROLLBACK");return conflict()}if(expectedCredential&&(revision("account_bindings",bindingId)!==expectedCredential.bindingRevision||revision("authorization_grants",grantId)!==expectedCredential.grantRevision||revision("credential_resources",resourceId)!==expectedCredential.resourceRevision)){db.exec("ROLLBACK");return conflict()}if(revision("account_bindings",bindingId)!==Number(existingBinding?.revision??0)||revision("authorization_grants",grantId)!==Number(existingGrant?.revision??0)||revision("credential_resources",resourceId)!==Number(existingResource?.revision??0)){db.exec("ROLLBACK");return conflict()}db.prepare("INSERT INTO account_bindings(id,source,issuer,subject,tenant_key,revision,metadata) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,metadata=excluded.metadata").run(binding.id,identity.source,identity.issuer,storedSubject(binding),tenantKey(identity.tenant),binding.revision,JSON.stringify(binding));db.prepare("INSERT INTO authorization_grants(id,binding_id,revision,metadata) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,metadata=excluded.metadata").run(grant.id,bindingId,grant.revision,JSON.stringify(grant));db.prepare("INSERT INTO credential_resources(id,binding_id,kind,owner_key,revision,metadata,credential) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,metadata=excluded.metadata,credential=excluded.credential").run(resource.id,bindingId,resource.kind,ownerKey(resource),resource.revision,JSON.stringify(resource),sealed);db.prepare("DELETE FROM credential_refresh_claims WHERE resource_id=?").run(resourceId);const sourceBindings=Number(db.prepare("SELECT COUNT(*) AS count FROM account_bindings WHERE source=?").get(connection.source)?.count??0);if(legacyProof)db.prepare("INSERT INTO legacy_recoveries(source,binding_id,fingerprint,verified_at) VALUES(?,?,?,?) ON CONFLICT(source) DO UPDATE SET binding_id=excluded.binding_id,fingerprint=excluded.fingerprint,verified_at=excluded.verified_at").run(connection.source,binding.id,legacyFingerprint(legacyProof),binding.verifiedAt);const hasLegacy=Boolean(legacyRow(connection.source));if(sourceBindings===1&&!hasLegacy)db.prepare("INSERT INTO connections(source,metadata,credential) VALUES(?,?,?) ON CONFLICT(source) DO UPDATE SET metadata=excluded.metadata,credential=excluded.credential").run(connection.source,JSON.stringify(connection),sealed);else db.prepare("DELETE FROM connections WHERE source=?").run(connection.source);if(selection)db.prepare("INSERT INTO source_selections(source,binding_id,revision,selected_at) VALUES(?,?,?,?) ON CONFLICT(source) DO UPDATE SET binding_id=excluded.binding_id,revision=excluded.revision,selected_at=excluded.selected_at").run(connection.source,bindingId,(selection.expectedSelectionRevision??0)+1,connection.updatedAt);db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Connection transaction failed.")}return ok({...connection})}const bindingCustody={sourceSelection:source=>perform(async()=>sourceKey(source)?ok(sourceSelection(source)):invalid()),selectSourceBinding:(source,bindingId,expectedBindingRevision,expectedSelectionRevision)=>perform(async()=>{if(!sourceKey(source)||!validId(bindingId)||!Number.isInteger(expectedBindingRevision)||expectedBindingRevision<1||expectedSelectionRevision!==null&&(!Number.isInteger(expectedSelectionRevision)||expectedSelectionRevision<1))return invalid();db.exec("BEGIN IMMEDIATE");try{const current=sourceSelection(source),row=db.prepare("SELECT metadata FROM account_bindings WHERE id=? AND source=?").get(bindingId,source);const binding=row?JSON.parse(String(row.metadata)):null;if((current?.revision??null)!==expectedSelectionRevision||!binding||binding.revision!==expectedBindingRevision){db.exec("ROLLBACK");return conflict()}if(binding.authority||binding.state!=="connected"||!binding.identity.subject||!Number.isFinite(Date.parse(binding.verifiedAt))){db.exec("ROLLBACK");return businessError("failed_precondition","Explicit source selection requires a verified connected native account.","storage")}const grant=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' AND json_extract(metadata,'$.audience')=?").get(bindingId,binding.provider);if(!grant||JSON.parse(String(grant.metadata)).state!=="active"){db.exec("ROLLBACK");return conflict()}const next={source,bindingId,revision:(current?.revision??0)+1,selectedAt:new Date().toISOString()};db.prepare("INSERT INTO source_selections(source,binding_id,revision,selected_at) VALUES(?,?,?,?) ON CONFLICT(source) DO UPDATE SET binding_id=excluded.binding_id,revision=excluded.revision,selected_at=excluded.selected_at").run(source,bindingId,next.revision,next.selectedAt);db.exec("COMMIT");return ok(next)}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Source selection transaction failed.")}}),refreshLegacyCredential:(source,expected,refresh)=>perform(async()=>{if(!sourceKey(source)||!expected||typeof refresh!=="function")return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");const expectedJson=JSON.stringify(expected);if(legacyRefreshClaim(source))return unknownLegacyRefresh();const row=legacyRow(source);if(!row||bindingRows(source).length)return conflict();const proof={metadata:String(row.metadata),credential:String(row.credential)};const connection=JSON.parse(proof.metadata);if(connection.source!==source||connection.state!=="connected"||connection.authority)return conflict();const current=JSON.parse(await codec.open(proof.credential));if(JSON.stringify(current)!==expectedJson)return conflict();if(typeof current.refreshToken!=="string"||!current.refreshToken||!current.clientId||!Number.isFinite(current.expiresAt)||!scopesMatch(current.scopes,current.scopes))return invalid();if(closed)return businessError("unavailable","Vault is inactive.","storage");const claim=randomUUID(),fingerprint=legacyFingerprint(proof);const matches=()=>{const candidate=rawLegacyRow(source);return candidate?.metadata===proof.metadata&&candidate?.credential===proof.credential&&!bindingRows(source).length};db.exec("BEGIN IMMEDIATE");try{if(legacyRefreshClaim(source)){db.exec("ROLLBACK");return unknownLegacyRefresh()}if(!matches()){db.exec("ROLLBACK");return conflict()}db.prepare("INSERT INTO legacy_refresh_claims(source,claim_id,fingerprint,started_at) VALUES(?,?,?,?)").run(source,claim,fingerprint,new Date().toISOString());db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}try{const changed=await refresh(structuredClone(connection),structuredClone(current));if(!("ok"in changed)){if("err"in changed&&changed.refreshOutcome==="not-consumed"){db.exec("BEGIN IMMEDIATE");try{if(legacyRefreshClaim(source)?.claim_id!==claim||!matches()){db.exec("ROLLBACK");return conflict()}db.prepare("DELETE FROM legacy_refresh_claims WHERE source=? AND claim_id=? AND fingerprint=?").run(source,claim,fingerprint);db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}return"err"in changed?{err:changed.err}:changed}const next=structuredClone(changed.ok);if(!next||typeof next.accessToken!=="string"||!next.accessToken||typeof next.refreshToken!=="string"||!next.refreshToken||!Number.isFinite(next.expiresAt)||next.expiresAt<=current.expiresAt||next.clientId!==current.clientId||!scopesMatch(current.scopes,next.scopes)||JSON.stringify(next.clientAuthentication)!==JSON.stringify(current.clientAuthentication))return invalid();const sealed=await codec.seal(JSON.stringify(next));if(db.prepare("UPDATE legacy_refresh_claims SET replacement=? WHERE source=? AND claim_id=? AND fingerprint=?").run(sealed,source,claim,fingerprint).changes!==1)return conflict();if(closed)return businessError("unavailable","Vault is inactive.","storage");db.exec("BEGIN IMMEDIATE");try{if(legacyRefreshClaim(source)?.claim_id!==claim||!matches()){db.exec("ROLLBACK");return conflict()}const updated=db.prepare("UPDATE legacy_connections SET credential=? WHERE source=? AND metadata=? AND credential=?").run(sealed,source,proof.metadata,proof.credential).changes;if(updated!==1){db.exec("ROLLBACK");return conflict()}db.prepare("DELETE FROM legacy_refresh_claims WHERE source=? AND claim_id=?").run(source,claim);db.exec("COMMIT");return ok(void 0)}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}catch{return businessError("data_loss","Legacy refresh or durable persistence did not complete; its claim remains fenced. Open zortex help for account recovery.","storage")}}),recoverLegacy:(source,verify)=>perform(async()=>{if(!sourceKey(source)||typeof verify!=="function")return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const row=legacyRow(source);if(!row||bindingRows(source).length)return businessError("failed_precondition","Legacy recovery requires an unattributed credential with no existing account bindings. Select an explicit account for mixed history.","storage");const proof={metadata:String(row.metadata),credential:String(row.credential)};const previous=JSON.parse(proof.metadata);if(previous.source!==source||previous.state!=="connected"||previous.authority)return businessError("failed_precondition","Legacy recovery requires an active native provider credential.","storage");const material=JSON.parse(await codec.open(proof.credential));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const verified=await verify(structuredClone(previous),structuredClone(material));if(!("ok"in verified))return verified;if(!verified.ok||typeof verified.ok.accountId!=="string"||!verified.ok.accountId.trim()||typeof verified.ok.account!=="string"||!verified.ok.account.trim()||previous.accountId!==void 0&&previous.accountId!==verified.ok.accountId)return businessError("failed_precondition","Verified provider identity differs from the legacy native account. Explicit account recovery is required.","storage");const connection={...previous,accountId:verified.ok.accountId,account:verified.ok.account,updatedAt:new Date().toISOString()};const saved=await saveConnection(connection,material,{},proof);if(!("ok"in saved))return saved;const resolved=resolveLegacy(source);return"ok"in resolved&&resolved.ok.kind==="resolved"?ok(resolved.ok.binding):conflict()}),bindings:source=>perform(async()=>sourceKey(source)?ok(bindingRows(source)):invalid()),resolve:selector=>perform(async()=>resolveBinding(selector)),authoritySnapshot:selector=>perform(async()=>authoritySnapshot(selector)),binding:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM account_bindings WHERE id=?").get(id);return ok(row?JSON.parse(String(row.metadata)):null)}),bindingInventory:id=>perform(async()=>bindingInventory(id)),grant:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM authorization_grants WHERE id=?").get(id);return ok(row?JSON.parse(String(row.metadata)):null)}),grantForBinding:(bindingId,purpose,audience)=>perform(async()=>{if(!validId(bindingId)||!["L1","L2"].includes(purpose)||!audience)return invalid();const grants=db.prepare("SELECT metadata FROM authorization_grants WHERE binding_id=? ORDER BY id").all(bindingId).map(row=>JSON.parse(String(row.metadata))).filter(grant=>grant.purpose===purpose&&grant.audience===audience);if(grants.length>1)return businessError("failed_precondition","Binding has ambiguous authorization grants.","storage");return ok(grants[0]??null)}),resource:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT metadata FROM credential_resources WHERE id=?").get(id);return ok(row?JSON.parse(String(row.metadata)):null)}),credential:id=>perform(async()=>{if(!validId(id))return invalid();const row=db.prepare("SELECT kind,credential FROM credential_resources WHERE id=?").get(id);if(!row)return businessError("failed_precondition","Credential resource does not exist.","storage");const resource={kind:row.kind};const material=await decodeMaterial(resource.kind,String(row.credential));if(!materialMatches(resource,material))return businessError("data_loss","Credential resource kind does not match.","storage");return ok(material)}),credentialSnapshot:(id,authorization)=>perform(()=>credentialSnapshot(id,authorization)),refreshResource:(expected,owner,refresh)=>perform(async()=>{if(!expected?.resource||!expected.binding||!expected.grant||!owner||typeof refresh!=="function")return invalid();const id=expected.resource.id,authorization={purpose:expected.grant.purpose,audience:expected.grant.audience};const key=flightKey(id),fence=authorityFence(expected),claim=randomUUID();const stored=readSnapshotState(id,authorization);if(!("ok"in stored))return stored;if(ownerKey(stored.ok.resource)!==resourceOwnerKey(owner))return businessError("failed_precondition","Only the credential resource owner may refresh it.","storage");if(authorityFence(stored.ok)!==fence)return conflict();if(stored.ok.claim!==null){const flight2=refreshFlights.get(key);return flight2?.claim===stored.ok.claim&&flight2.fence===fence?joinedSnapshot(flight2,id,authorization):unknownRefresh()}db.exec("BEGIN IMMEDIATE");try{const current=readState(id,authorization);if(!("ok"in current)){db.exec("ROLLBACK");return current}if(authorityFence(current.ok)!==fence){db.exec("ROLLBACK");return conflict()}if(current.ok.claim!==null){db.exec("ROLLBACK");return unknownRefresh()}db.prepare("INSERT INTO credential_refresh_claims(resource_id,claim_id,expected_revision,owner_key) VALUES(?,?,?,?)").run(id,claim,stored.ok.resource.revision,ownerKey(stored.ok.resource));db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}const unconsumed=failure=>{db.exec("BEGIN IMMEDIATE");try{const current=readState(id,authorization);if(!("ok"in current)){db.exec("ROLLBACK");return current}if(current.ok.claim!==claim||authorityFence(current.ok)!==fence){db.exec("ROLLBACK");return conflict()}db.prepare("DELETE FROM credential_refresh_claims WHERE resource_id=? AND claim_id=? AND expected_revision=?").run(id,claim,stored.ok.resource.revision);db.exec("COMMIT");return failure}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}};let dispatched=false;const task=Promise.resolve().then(async()=>{const material=await decodeMaterial(stored.ok.resource.kind,stored.ok.sealed);if(!materialMatches(stored.ok.resource,material))return unconsumed(businessError("data_loss","Credential resource kind does not match.","storage"));if(closed)return unconsumed(businessError("unavailable","Vault is inactive.","storage"));const beforeEffect=readSnapshotState(id,authorization);if(!("ok"in beforeEffect))return beforeEffect;if(beforeEffect.ok.claim!==claim||authorityFence(beforeEffect.ok)!==fence)return conflict();const{binding,grant,resource}=stored.ok;dispatched=true;const changed=await refresh(structuredClone({binding,grant,resource,material}));if(!("ok"in changed))return"err"in changed?changed.refreshOutcome==="not-consumed"?unconsumed({err:changed.err}):{err:changed.err}:changed;if(!materialMatches(resource,changed.ok)||!sessionMaterialMatches(binding,grant,changed.ok))return invalid();const nextMaterial=structuredClone(changed.ok);const sealed=await encodeMaterial(resource.kind,nextMaterial);if(closed)return businessError("unavailable","Vault is inactive.","storage");const next={...resource,revision:resource.revision+1,updatedAt:new Date().toISOString()};db.exec("BEGIN IMMEDIATE");try{const current=readState(id,authorization);if(!("ok"in current)){db.exec("ROLLBACK");return current}if(current.ok.claim!==claim||authorityFence(current.ok)!==fence){db.exec("ROLLBACK");return conflict()}const updated=db.prepare("UPDATE credential_resources SET revision=?,metadata=?,credential=? WHERE id=? AND revision=?").run(next.revision,JSON.stringify(next),sealed,id,resource.revision).changes;if(updated!==1){db.exec("ROLLBACK");return conflict()}db.prepare("DELETE FROM credential_refresh_claims WHERE resource_id=? AND claim_id=?").run(id,claim);if(resource.kind==="oauth"&&id===oauthCredentialResourceId(binding.id)){db.prepare("UPDATE connections SET credential=? WHERE source=?").run(sealed,binding.identity.source)}db.exec("COMMIT");return ok({binding,grant,resource:next,material:nextMaterial})}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}).catch(()=>dispatched?businessError("data_loss","Credential refresh or durable persistence failed; the resource remains fenced.","storage"):unconsumed(businessError("data_loss","Credential custody could not be read before refresh dispatch.","storage")));const flight={fence,claim,promise:task};refreshFlights.set(key,flight);try{return await task}finally{if(refreshFlights.get(key)===flight)refreshFlights.delete(key)}}),compareAndSwapBinding:(candidate,expectedRevision)=>perform(async()=>{if(!candidate||!validId(candidate.id)||!sourceKey(candidate.identity?.source)||!candidate.identity.issuer||!candidate.identity.subject&&!candidate.authority||!candidate.provider||!candidate.account||candidate.authority!==void 0&&!isConnectionAuthority(candidate.authority)||candidate.identity.tenant!==null&&typeof candidate.identity.tenant!=="string"||!Number.isSafeInteger(expectedRevision)||expectedRevision<0)return invalid();const next={...candidate,revision:expectedRevision+1};if(expectedRevision===0){try{db.prepare("INSERT INTO account_bindings(id,source,issuer,subject,tenant_key,revision,metadata) VALUES(?,?,?,?,?,?,?)").run(next.id,next.identity.source,next.identity.issuer,storedSubject(next),tenantKey(next.identity.tenant),next.revision,JSON.stringify(next))}catch{return conflict()}}else{const current=db.prepare("SELECT source,issuer,subject,tenant_key,metadata FROM account_bindings WHERE id=?").get(next.id);if(!current||current.source!==next.identity.source||current.issuer!==next.identity.issuer||current.subject!==storedSubject(next)||current.tenant_key!==tenantKey(next.identity.tenant)||JSON.stringify(JSON.parse(String(current.metadata)).authority)!==JSON.stringify(next.authority))return businessError("failed_precondition","Binding identity and session authority are immutable.","storage");const changed=db.prepare("UPDATE account_bindings SET source=?,issuer=?,subject=?,tenant_key=?,revision=?,metadata=? WHERE id=? AND revision=?").run(next.identity.source,next.identity.issuer,storedSubject(next),tenantKey(next.identity.tenant),next.revision,JSON.stringify(next),next.id,expectedRevision).changes;if(!changed)return conflict()}return ok(next)}),compareAndSwapGrant:(candidate,expectedRevision)=>perform(async()=>{if(!candidate||!validId(candidate.id)||!validId(candidate.bindingId)||!["L1","L2"].includes(candidate.purpose)||!candidate.audience||!Array.isArray(candidate.scopes)||!Number.isSafeInteger(candidate.scopeEpoch)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0)return invalid();if(!db.prepare("SELECT 1 FROM account_bindings WHERE id=?").get(candidate.bindingId))return businessError("failed_precondition","Grant binding does not exist.","storage");const next={...candidate,scopes:[...new Set(candidate.scopes)].sort(),revision:expectedRevision+1};if(expectedRevision===0){try{db.prepare("INSERT INTO authorization_grants(id,binding_id,revision,metadata) VALUES(?,?,?,?)").run(next.id,next.bindingId,next.revision,JSON.stringify(next))}catch{return conflict()}}else{const currentRow=db.prepare("SELECT binding_id,metadata FROM authorization_grants WHERE id=?").get(next.id);const current=currentRow?JSON.parse(String(currentRow.metadata)):null;if(!current||currentRow.binding_id!==next.bindingId||current.purpose!==next.purpose||current.audience!==next.audience)return businessError("failed_precondition","Grant ownership is immutable.","storage");const changed=db.prepare("UPDATE authorization_grants SET binding_id=?,revision=?,metadata=? WHERE id=? AND revision=?").run(next.bindingId,next.revision,JSON.stringify(next),next.id,expectedRevision).changes;if(!changed)return conflict()}return ok(next)}),compareAndSwapResource:(candidate,material,expectedRevision)=>perform(async()=>{if(!candidate||!validId(candidate.id)||!validId(candidate.bindingId)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||!materialMatches(candidate,material)||candidate.owner.kind==="managed-sidecar-profile"&&candidate.owner.bindingId!==candidate.bindingId)return invalid();if(!db.prepare("SELECT 1 FROM account_bindings WHERE id=?").get(candidate.bindingId))return businessError("failed_precondition","Credential binding does not exist.","storage");if(expectedRevision>0){const current=db.prepare("SELECT binding_id,kind,owner_key FROM credential_resources WHERE id=?").get(candidate.id);if(!current||current.binding_id!==candidate.bindingId||current.kind!==candidate.kind||current.owner_key!==ownerKey(candidate))return businessError("failed_precondition","Credential resource ownership is immutable.","storage")}const sealed=await encodeMaterial(candidate.kind,material);if(closed)return businessError("unavailable","Vault is inactive.","storage");const next={...candidate,revision:expectedRevision+1,encryptedRef:candidate.kind==="local-no-secret"?null:encryptedRef(candidate.id)};db.exec("BEGIN IMMEDIATE");try{if(expectedRevision===0){try{db.prepare("INSERT INTO credential_resources(id,binding_id,kind,owner_key,revision,metadata,credential) VALUES(?,?,?,?,?,?,?)").run(next.id,next.bindingId,next.kind,ownerKey(next),next.revision,JSON.stringify(next),sealed)}catch{db.exec("ROLLBACK");return conflict()}}else{const changed=db.prepare("UPDATE credential_resources SET binding_id=?,kind=?,owner_key=?,revision=?,metadata=?,credential=? WHERE id=? AND revision=?").run(next.bindingId,next.kind,ownerKey(next),next.revision,JSON.stringify(next),sealed,next.id,expectedRevision).changes;if(!changed){db.exec("ROLLBACK");return conflict()}}db.exec("COMMIT");return ok(next)}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Credential resource transaction failed.")}})};const metadataSnapshot=createMetadataSnapshotReader(db);const service={identityContract:BINDING_CUSTODY_CONTRACT,bindingCustody,guardedCache:"atomic-connection",metadataSnapshot:request=>perform(async()=>metadataSnapshot(request)),connections:()=>perform(async()=>{const bindings=db.prepare("SELECT metadata FROM account_bindings ORDER BY source,id").all().map(row=>JSON.parse(String(row.metadata))).map(connectionFromBinding);const sources=new Set(bindings.map(binding=>binding.source));const legacy=db.prepare("SELECT source,metadata FROM legacy_connections ORDER BY source").all().filter(row=>!sources.has(String(row.source))).map(row=>JSON.parse(String(row.metadata)));return ok([...bindings,...legacy].sort((a,b)=>a.source.localeCompare(b.source)||a.account.localeCompare(b.account)))}),connection:source=>perform(async()=>{if(!sourceKey(source))return invalid();if(sourceSelection(source)){const selected=selectedBinding(source);return selected?ok(connectionFromBinding(selected)):businessError("failed_precondition","The selected account is unavailable.","storage")}const bindings=bindingRows(source),legacy=legacyRow(source);if(bindings.length===1&&!legacy){return ok(connectionFromBinding(bindings[0]))}if(bindings.length===0&&legacy)return ok(JSON.parse(String(legacy.metadata)));if(bindings.length===0)return ok(null);return businessError("failed_precondition","Multiple or unattributed accounts exist; select a binding.","storage")}),legacyRevision:source=>perform(async()=>{if(!sourceKey(source))return invalid();if(legacyRefreshClaim(source)||sourceSelection(source)||bindingRows(source).length)return ok(null);const row=legacyRow(source);if(!row)return ok(null);const metadata=JSON.parse(String(row.metadata));if(metadata.source!==source||metadata.state!=="connected")return ok(null);return ok(legacyFingerprint({metadata:String(row.metadata),credential:String(row.credential)}))}),joplinPairingGeneration:()=>perform(async()=>ok(Number(db.prepare("SELECT revision FROM joplin_pairing_generation WHERE id=1").get().revision))),joplinPairingCommit:transactionId=>perform(async()=>{if(!/^[a-f0-9]{32}$/.test(transactionId))return invalid();db.exec("BEGIN");try{const row=db.prepare("SELECT expected_generation,committed_generation FROM joplin_pairing_commits WHERE transaction_id=?").get(transactionId);const currentGeneration=Number(db.prepare("SELECT revision FROM joplin_pairing_generation WHERE id=1").get().revision);const refreshClaimPresent=Boolean(db.prepare("SELECT 1 FROM legacy_refresh_claims WHERE source='joplin'").get());db.exec("COMMIT");return ok({marker:row?{expectedGeneration:Number(row.expected_generation),committedGeneration:Number(row.committed_generation)}:null,currentGeneration,refreshClaimPresent})}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}),beginJoplinPairing:(transactionId,expectedGeneration,account)=>perform(async()=>ok(beginJoplinPairing(db,{transactionId,expectedGeneration,account}))),reconcileJoplinPairing:expected=>perform(async()=>ok(reconcileJoplinPairing(db,expected))),commitJoplinPairing:(transactionId,expectedGeneration,connection,credential,options={})=>perform(async()=>{if(!/^[a-f0-9]{32}$/.test(transactionId)||!Number.isSafeInteger(expectedGeneration)||expectedGeneration<0||!options.authorityAccount||options.authorityAccount!==connection.account||connection.source!=="joplin"||connection.provider!=="joplin"||!connection.account||connection.accountId!==void 0||connection.authority!==void 0||connection.state!=="connected"||!Array.isArray(connection.scopes)||connection.scopes.length!==0||!credential.accessToken||credential.clientId!=="mcp-fields"||credential.expiresAt!==0||!Array.isArray(credential.scopes)||credential.scopes.length!==0)return invalid();const capturedConnection=structuredClone(connection),capturedCredential=structuredClone(credential);if(options.signal?.aborted)return businessError("aborted","Connection consent was cancelled.","storage");const sealedCredential=await codec.seal(JSON.stringify(capturedCredential));if(closed)return businessError("unavailable","Vault is inactive.","storage");if(options.signal?.aborted)return businessError("aborted","Connection consent was cancelled before commit.","storage");const committed=commitJoplinPairing(db,{transactionId,expectedGeneration,metadata:JSON.stringify(capturedConnection),sealedCredential,...options.authorityAccount===void 0?{}:{authorityAccount:options.authorityAccount}});return committed?ok(committed):conflict()}),joplinPairingRevision:()=>perform(async()=>ok(null)),joplinFencedRevision:expectedAccount=>perform(async()=>ok(joplinPairingAuthority(db,expectedAccount))),joplinFencedSnapshot:expectedAccount=>perform(async()=>{const revision=joplinPairingAuthority(db,expectedAccount);if(revision===null)return conflict();const row=legacyRow("joplin");if(!row)return conflict();const connection=JSON.parse(String(row.metadata));if(connection.state!=="connected"||connection.accountId||connection.authority||connection.account!==expectedAccount)return conflict();const credential=JSON.parse(await codec.open(String(row.credential)));if(closed||joplinPairingAuthority(db,expectedAccount)!==revision)return conflict();return ok({revision,connection,credential})}),joplinPairingSnapshot:()=>perform(async()=>conflict()),saveConnection:(connection,credential,options)=>perform(async()=>connection.source==="joplin"?businessError("failed_precondition","Joplin pairing requires fenced custody.","storage"):saveConnection(connection,credential,options)),credential:source=>perform(async()=>{if(!sourceKey(source))return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const bindings=bindingRows(source),legacy=legacyRow(source);if(bindings.length===0&&legacy){const material2=JSON.parse(await codec.open(String(legacy.credential)));if(legacyRefreshClaim(source))return unknownLegacyRefresh();const current=rawLegacyRow(source);if(current?.metadata!==legacy.metadata||current?.credential!==legacy.credential||bindingRows(source).length)return conflict();return ok(material2)}if(bindings.length!==1||legacy)return businessError("failed_precondition",bindings.length?"Multiple or unattributed accounts exist; select a binding.":`${source} is not connected. Start the source connection flow.`,"storage");const row=db.prepare("SELECT credential FROM credential_resources WHERE id=?").get(oauthCredentialResourceId(bindings[0].id));if(!row)return businessError("failed_precondition","OAuth credential resource is missing.","storage");const material=JSON.parse(await codec.open(String(row.credential)));return material.kind==="oauth"?ok(material.credential):businessError("data_loss","Credential resource kind does not match.","storage")}),updateCredential:(source,credential)=>perform(async()=>{if(!sourceKey(source)||!credential.accessToken)return invalid();if(source==="joplin")return businessError("failed_precondition","Joplin pairing requires fenced custody.","storage");if(legacyRefreshClaim(source))return unknownLegacyRefresh();const bindings=bindingRows(source),legacy=legacyRow(source);if(bindings.length===0&&legacy){const sealed2=await codec.seal(JSON.stringify(credential));if(closed)return businessError("unavailable","Vault is inactive.","storage");const changed=db.prepare("UPDATE legacy_connections SET credential=? WHERE source=? AND metadata=? AND credential=? AND NOT EXISTS (SELECT 1 FROM account_bindings WHERE source=?) AND NOT EXISTS (SELECT 1 FROM legacy_refresh_claims WHERE source=?)").run(sealed2,source,legacy.metadata,legacy.credential,source,source).changes;return changed?ok(void 0):conflict()}if(bindings.length!==1||legacy)return businessError("failed_precondition","Multiple or unattributed accounts exist; select a binding.","storage");const id=oauthCredentialResourceId(bindings[0].id);const row=db.prepare("SELECT revision,metadata FROM credential_resources WHERE id=?").get(id);if(!row)return businessError("failed_precondition","OAuth credential resource is missing.","storage");const sealed=await codec.seal(JSON.stringify({kind:"oauth",credential}));const current=JSON.parse(String(row.metadata));const next={...current,revision:Number(row.revision)+1,updatedAt:new Date().toISOString()};db.exec("BEGIN IMMEDIATE");try{const changed=db.prepare("UPDATE credential_resources SET revision=?,metadata=?,credential=? WHERE id=? AND revision=?").run(next.revision,JSON.stringify(next),sealed,id,Number(row.revision)).changes;if(!changed){db.exec("ROLLBACK");return conflict()}db.prepare("UPDATE connections SET credential=? WHERE source=?").run(sealed,source);db.exec("COMMIT");return ok(void 0)}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Credential update transaction failed.")}}),saveBindingRecords:records=>perform(async()=>{if(!Array.isArray(records)||records.length>100||records.some(record=>!validId(record.bindingId)||!record.stream||record.stream.length>128||!record.nativeId||record.nativeId.length>500||!Number.isFinite(record.timestamp)||Buffer.byteLength(JSON.stringify(record.data))>512e3))return invalid();if([...new Set(records.map(record=>record.bindingId))].some(id=>!db.prepare("SELECT 1 FROM account_bindings WHERE id=?").get(id)))return businessError("failed_precondition","Record binding does not exist.","storage");const sealed=await Promise.all(records.map(async record=>({record,payload:await codec.seal(JSON.stringify(record.data))})));db.exec("BEGIN IMMEDIATE");try{const insert=db.prepare("INSERT INTO binding_records(binding_id,stream,native_id,ts,payload) VALUES(?,?,?,?,?) ON CONFLICT(binding_id,stream,native_id) DO UPDATE SET ts=excluded.ts,payload=excluded.payload");for(const{record,payload}of sealed)insert.run(record.bindingId,record.stream,record.nativeId,record.timestamp,payload);db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Binding record transaction failed.")}return ok(records.length)}),bindingRecords:(bindingId,stream,limit)=>perform(async()=>{if(!validId(bindingId)||!stream||stream.length>128||!Number.isInteger(limit)||limit<1||limit>100)return invalid();const rows=db.prepare("SELECT native_id,ts,payload FROM binding_records WHERE binding_id=? AND stream=? ORDER BY ts DESC,native_id LIMIT ?").all(bindingId,stream,limit);return ok(await Promise.all(rows.map(async row=>({bindingId,stream,nativeId:String(row.native_id),timestamp:Number(row.ts),data:JSON.parse(await codec.open(String(row.payload)))}))))}),saveRecords:(records,guard)=>perform(async()=>{if(guard&&(Object.keys(guard).some(key=>!["source","account","accountId","requiredScopes","signal"].includes(key))||!sourceKey(guard.source)||!guard.account||guard.accountId!==void 0&&!guard.accountId||guard.requiredScopes!==void 0&&(!Array.isArray(guard.requiredScopes)||guard.requiredScopes.length>64||guard.requiredScopes.some(scope=>!scope||scope.length>512))))return invalid();if(guard?.signal?.aborted)return businessError("aborted","Cache write was cancelled before sealing.","storage");if(!Array.isArray(records)||records.length>100||records.some(record=>!sourceKey(record.source)||guard&&record.source!==guard.source||!record.id||record.id.length>500||!Number.isFinite(record.timestamp)||Buffer.byteLength(JSON.stringify(record.data))>512e3))return invalid();const sealed=await Promise.all(records.map(async record=>({...record,payload:await codec.seal(JSON.stringify(record.data))})));if(closed)return businessError("unavailable","Vault is inactive.","storage");db.exec("BEGIN IMMEDIATE");try{if(guard?.signal?.aborted){db.exec("ROLLBACK");return businessError("aborted","Cache write was cancelled before commit.","storage")}if(records.some(record=>sourceSelection(record.source))){db.exec("ROLLBACK");return businessError("failed_precondition","Selected recovery accounts require transient reads or binding-scoped record storage; source history was not changed.","storage")}if(guard){const bindings=bindingRows(guard.source),legacy=legacyRow(guard.source);let current=null;if(records.length===0&&sourceSelection(guard.source)){const selected=selectedBinding(guard.source);if(selected)current=connectionFromBinding(selected)}else if(bindings.length===1&&!legacy){current=connectionFromBinding(bindings[0])}else if(bindings.length===0&&legacy)current=JSON.parse(String(legacy.metadata));if(!current||current.state!=="connected"||current.account!==guard.account||guard.accountId!==void 0&&current.accountId!==guard.accountId||guard.requiredScopes?.some(scope=>!current.scopes.includes(scope))){db.exec("ROLLBACK");return businessError("permission_denied","Source identity or permission changed before cache commit; no rows were written.","storage")}}const insert=db.prepare("INSERT INTO records(source,id,ts,payload) VALUES(?,?,?,?) ON CONFLICT(source,id) DO UPDATE SET ts=excluded.ts,payload=excluded.payload");for(const record of sealed)insert.run(record.source,record.id,record.timestamp,record.payload);if(existingVault){const project=db.prepare("INSERT INTO connector_records(source,source_id,ts,body,payload) VALUES(?,?,?,?,?) ON CONFLICT(source,source_id) DO UPDATE SET ts=excluded.ts,body=excluded.body,payload=excluded.payload");for(const record of records)project.run(record.source,record.id,new Date(record.timestamp).toISOString(),typeof record.data.body==="string"?record.data.body:"",JSON.stringify(record.data))}db.exec("COMMIT")}catch{try{db.exec("ROLLBACK")}catch{}throw Error("Record transaction failed.")}return ok(records.length)}),records:(source,limit)=>perform(async()=>{if(!sourceKey(source)||!Number.isInteger(limit)||limit<1||limit>100)return invalid();const resolution=resolveLegacy(source);if("ok"in resolution&&resolution.ok.kind==="ambiguous_account")return businessError("failed_precondition","Multiple accounts exist; select a binding and stream.","storage");const rows=db.prepare("SELECT id,source,ts,payload FROM records WHERE source=? ORDER BY ts DESC,id LIMIT ?").all(source,limit);return ok(await Promise.all(rows.map(async row=>({id:String(row.id),source:String(row.source),timestamp:Number(row.ts),data:JSON.parse(await codec.open(String(row.payload)))}))))}),close(){if(!closing){closed=true;closing=(async()=>{await Promise.allSettled([...pending]);db.close()})()}return closing}};return service}export async function apply(ctx,config){if(!config||typeof config.root!=="string"||Object.keys(config).some(key=>key!=="root"))throw Error("Vault root configuration is required.");const store=await createVaultStore(config);ctx.provide("zortexVaultStore",store);ctx.effect(()=>()=>store.close())}
@@ -1 +1 @@
1
- import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{beginContentAcquisition,contentAcquisitionScopes}from"./content-acquisition.js";import{randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{rebuildCurrentRecords,updateCurrentRecords}from"./current-records.js";import{rebuildSearchRecords}from"./search-records.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";import{createStorageMetadataReader}from"./storage-metadata.js";import{createSourceSyncStore}from"./source-sync.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;acquisitionAuthorities=new Map;requiredAuthorities=new Set;readPageRows;reader;snapshots;storageMetadata;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);this.storageMetadata=createStorageMetadataReader(this.db,config.file,()=>this.closed);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const acquisition=this.acquisitionAuthorities.get(origin.source+"\0"+origin.grant);if(acquisition)return acquisition();const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})},event=>updateCurrentRecords(this.db,this.records,event));this.facts=new LiftedRecordRules(this.db,saved,now,"system_events",void 0,void 0,event=>updateCurrentRecords(this.db,this.records,event));for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");rebuildCurrentRecords(this.db,this.records);rebuildSearchRecords(this.db);this.reader=createSqlReader(config.file,readLimits)}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}storageSnapshot(){return this.storageMetadata()}createSourceSyncStore(){return createSourceSyncStore(this.createPrivateStore("source-sync"))}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);return withdraw}contentAcquisitionScopes(){return this.closed?[]:contentAcquisitionScopes(this.db)}beginContentAcquisition(source,resource){return beginContentAcquisition({db:this.db,closed:()=>this.closed,declare:source2=>this.registerStreams([{source:source2,stream:"acquired-content",revOrder:"head-compare",quality:"durable"}]),append:(drafts,origin,check,after)=>{const key=origin.source+"\0"+origin.grant;this.acquisitionAuthorities.set(key,check);try{return this.records.appendCore(drafts,origin,false,{before:check,after})}finally{this.acquisitionAuthorities.delete(key)}}},source,resource)}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const candidate of streams){if(!candidate||Object.keys(candidate).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity","deleteKind"].includes(key2))||candidate.deleteKind!==void 0&&(typeof candidate.deleteKind!=="string"||!candidate.deleteKind)||typeof candidate.source!=="string"||!candidate.source||typeof candidate.stream!=="string"||!candidate.stream||!Original.REV_ORDERS.includes(candidate.revOrder)||candidate.comparator!==void 0&&!["numeric","lex"].includes(candidate.comparator)||candidate.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(candidate.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=candidate.source+"\0"+candidate.stream,prior=incoming.get(key)??this.declarations.get(key);const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const[key,candidate]of incoming){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(candidate.source,candidate.stream);const prior=existing?JSON.parse(existing.definition):void 0;const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}incoming.set(key,row);this.db.query("INSERT INTO source_streams(source,stream,definition) VALUES(?,?,?) ON CONFLICT(source,stream) DO UPDATE SET definition=excluded.definition").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};const guardValid=guard=>guard===void 0||!!guard&&typeof guard==="object"&&valid(guard.key)&&Number.isSafeInteger(guard.revision)&&guard.revision>0;const guarded=guard=>guard===void 0||read(guard.key)?.revision===guard.revision;const remove=(key,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before deleting this value.","storage")}this.db.query("DELETE FROM private_state WHERE namespace=? AND key=?").run(namespace,key);this.db.exec("COMMIT");begun=false;return ok(true)}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state deletion did not complete.","storage")}};return{delete:remove,get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}
1
+ import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{beginContentAcquisition,contentAcquisitionScope,contentAcquisitionScopes}from"./content-acquisition.js";import{randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{rebuildCurrentRecords,updateCurrentRecords}from"./current-records.js";import{initializeSearchColumns,rebuildSearchRecords,refreshAcquiredSearchRecords}from"./search-records.js";import{initializePublicVisibility,publicVisibilityEpoch}from"./public-visibility.js";import{withPublicReadValidation}from"./api/public-result-visibility.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";import{createStorageMetadataReader}from"./storage-metadata.js";import{createSourceSyncStore}from"./source-sync.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;acquisitionAuthorities=new Map;requiredAuthorities=new Set;readPageRows;reader;publicReader;snapshots;storageMetadata;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);initializeSearchColumns(this.db);initializePublicVisibility(this.db);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);this.storageMetadata=createStorageMetadataReader(this.db,config.file,()=>this.closed);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const acquisition=this.acquisitionAuthorities.get(origin.source+"\0"+origin.grant);if(acquisition)return acquisition();const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})},event=>updateCurrentRecords(this.db,this.records,event));this.facts=new LiftedRecordRules(this.db,saved,now,"system_events",void 0,void 0,event=>updateCurrentRecords(this.db,this.records,event));for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");rebuildCurrentRecords(this.db,this.records);rebuildSearchRecords(this.db);this.reader=createSqlReader(config.file,readLimits);this.publicReader=createSqlReader(config.file,readLimits,{surface:"public",visibilityEpoch:()=>publicVisibilityEpoch(this.db)})}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}storageSnapshot(){return this.storageMetadata()}createSourceSyncStore(){return createSourceSyncStore(this.createPrivateStore("source-sync"))}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);return withdraw}contentAcquisitionScopes(){return this.closed?[]:contentAcquisitionScopes(this.db)}beginContentAcquisition(source,resource){return beginContentAcquisition({db:this.db,closed:()=>this.closed,declare:source2=>this.registerStreams([{source:source2,stream:"acquired-content",revOrder:"head-compare",quality:"durable"}]),append:(drafts,origin,check,after)=>{const key=origin.source+"\0"+origin.grant;this.acquisitionAuthorities.set(key,check);try{return this.records.appendCore(drafts,origin,false,{before:check,after})}finally{this.acquisitionAuthorities.delete(key)}}},source,resource)}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const candidate of streams){if(!candidate||Object.keys(candidate).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity","deleteKind"].includes(key2))||candidate.deleteKind!==void 0&&(typeof candidate.deleteKind!=="string"||!candidate.deleteKind)||typeof candidate.source!=="string"||!candidate.source||typeof candidate.stream!=="string"||!candidate.stream||!Original.REV_ORDERS.includes(candidate.revOrder)||candidate.comparator!==void 0&&!["numeric","lex"].includes(candidate.comparator)||candidate.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(candidate.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=candidate.source+"\0"+candidate.stream,prior=incoming.get(key)??this.declarations.get(key);const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const[key,candidate]of incoming){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(candidate.source,candidate.stream);const prior=existing?JSON.parse(existing.definition):void 0;const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}incoming.set(key,row);this.db.query("INSERT INTO source_streams(source,stream,definition) VALUES(?,?,?) ON CONFLICT(source,stream) DO UPDATE SET definition=excluded.definition").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};const guardValid=guard=>guard===void 0||!!guard&&typeof guard==="object"&&valid(guard.key)&&Number.isSafeInteger(guard.revision)&&guard.revision>0;const guarded=guard=>guard===void 0||read(guard.key)?.revision===guard.revision;const remove=(key,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before deleting this value.","storage")}this.db.query("DELETE FROM private_state WHERE namespace=? AND key=?").run(namespace,key);this.db.exec("COMMIT");begun=false;return ok(true)}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state deletion did not complete.","storage")}};return{delete:remove,get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}publicSql(request,signal){if(this.closed)return Promise.resolve(inactive());try{refreshAcquiredSearchRecords(this.db)}catch{return Promise.resolve(businessError("unavailable","Public record visibility could not be refreshed.","storage"))}return this.publicReader.sql(request,signal)}capturePublicReadValidation(){try{const epoch=publicVisibilityEpoch(this.db);return()=>!this.closed&&epoch===publicVisibilityEpoch(this.db)}catch{return()=>false}}readEvidence(id){if(this.closed)return inactive();try{if(!Original.isUlid(id))return businessError("invalid_argument","Exact evidence requires a valid event ID.","storage");if(!this.db.query("SELECT 1 FROM events WHERE id=?").get(id))return businessError("not_found","Public source evidence was not found.","storage");const epoch=publicVisibilityEpoch(this.db),read=createIdReader(this.db,()=>this.closed)(id);if(!Original.isOk(read))return read;const record=read.ok;if(record.nk.stream==="acquired-content"){const authority=contentAcquisitionScope(this.db,record.nk.source),payload=record.payload;const acquisition=payload?.acquisition;if(!Original.isOk(authority)||authority.ok.identity!==acquisition?.identity)return businessError("permission_denied","This evidence is outside the currently selected acquisition authority.","auth")}if(Buffer.byteLength(canonicalJson(record))>1048576)return businessError("resource_exhausted","Exact evidence exceeds its complete-result byte budget.","storage");const current=!!this.db.query("SELECT 1 FROM z_current_records WHERE id=?").get(id);if(epoch!==publicVisibilityEpoch(this.db))return businessError("aborted","Record visibility changed during the evidence read; retry.","storage");return withPublicReadValidation(ok({record,visibility:current?"current":"superseded"}),()=>!this.closed&&epoch===publicVisibilityEpoch(this.db))}catch{return businessError("unavailable","Exact evidence could not be read.","storage")}}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.publicReader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.publicReader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}
@@ -1 +1 @@
1
- import koffi from"koffi";export function createKeychain(account){const security=koffi.load("/System/Library/Frameworks/Security.framework/Security");const core=koffi.load("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");const constant=(library,name)=>koffi.decode(library.symbol(name),"void *");const release=core.func("void CFRelease(void *value)");const string=core.func("void *CFStringCreateWithCString(void *allocator, const char *value, uint32_t encoding)");const data=core.func("void *CFDataCreate(void *allocator, const uint8_t *bytes, long length)");const length=core.func("long CFDataGetLength(void *value)");const bytes=core.func("void *CFDataGetBytePtr(void *value)");const dictionary=core.func("void *CFDictionaryCreate(void *allocator, const void **keys, const void **values, long count, void *keyCallbacks, void *valueCallbacks)");const copy=security.func("int32_t SecItemCopyMatching(void *query, _Out_ void **result)");const add=security.func("int32_t SecItemAdd(void *attributes, void *result)");const defaultKeychain=security.func("int32_t SecKeychainCopyDefault(_Out_ void **keychain)");const keychainStatus=security.func("int32_t SecKeychainGetStatus(void *keychain, _Out_ uint32_t *status)");const getInteraction=security.func("int32_t SecKeychainGetUserInteractionAllowed(_Out_ uint8_t *allowed)");const setInteraction=security.func("int32_t SecKeychainSetUserInteractionAllowed(uint8_t allowed)");const sec=name=>constant(security,name);function query(write,action){const owned=[];const text=value=>{const result=string(null,value,134217984);if(!result)throw Error("Keychain allocation failed.");owned.push(result);return result};const interaction=[0];if(getInteraction(interaction)!==0||setInteraction(0)!==0)throw Error("Keychain non-interactive access unavailable.");try{const current=[null],status=[0];if(defaultKeychain(current)!==0||!current[0])throw Error("Default Keychain unavailable.");try{if(keychainStatus(current[0],status)!==0||!(status[0]&1))throw Error("Keychain is locked; unlock the login Keychain.")}finally{release(current[0])}const pairs=[[sec("kSecClass"),sec("kSecClassGenericPassword")],[sec("kSecAttrService"),text("com.zortex.vault-master")],[sec("kSecAttrAccount"),text(account)],[sec("kSecAttrSynchronizable"),constant(core,"kCFBooleanFalse")],[sec("kSecUseAuthenticationUI"),sec("kSecUseAuthenticationUIFail")]];if(write){const value=data(null,write,write.length);if(!value)throw Error("Keychain allocation failed.");owned.push(value);pairs.push([sec("kSecValueData"),value])}else pairs.push([sec("kSecReturnData"),constant(core,"kCFBooleanTrue")],[sec("kSecMatchLimit"),sec("kSecMatchLimitOne")]);const attributes=dictionary(null,pairs.map(pair=>pair[0]),pairs.map(pair=>pair[1]),pairs.length,null,null);if(!attributes)throw Error("Keychain allocation failed.");owned.push(attributes);return action(attributes)}finally{for(const value of owned.reverse())release(value);if(setInteraction(interaction[0])!==0)throw Error("Keychain interaction state could not be restored.")}}const port={read(){return query(void 0,attributes=>{const result=[null],status=copy(attributes,result);if(status===-25300)return null;if(status!==0||!result[0])throw Error("Keychain master key unavailable; unlock the login Keychain.");try{if(Number(length(result[0]))!==32)throw Error("Keychain master key is invalid.");return Buffer.from(new Uint8Array(koffi.view(bytes(result[0]),32)))}finally{release(result[0])}})},create(value){if(value.length!==32)throw Error("Keychain master key is invalid.");const status=query(value,attributes=>add(attributes,null));if(status!==0&&status!==-25299)throw Error("Keychain master key could not be saved.");const saved=port.read();if(!saved)throw Error("Keychain master key was not persisted.");return saved}};return port}
1
+ import koffi from"koffi";const ERR_SEC_ITEM_NOT_FOUND=-25300;const ERR_SEC_DUPLICATE_ITEM=-25299;const ERR_SEC_INTERACTION_NOT_ALLOWED=-25308;const ERR_SEC_AUTH_FAILED=-25293;export function createKeychain(account){const security=koffi.load("/System/Library/Frameworks/Security.framework/Security");const core=koffi.load("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");const constant=(library,name)=>koffi.decode(library.symbol(name),"void *");const release=core.func("void CFRelease(void *value)");const string=core.func("void *CFStringCreateWithCString(void *allocator, const char *value, uint32_t encoding)");const data=core.func("void *CFDataCreate(void *allocator, const uint8_t *bytes, long length)");const length=core.func("long CFDataGetLength(void *value)");const bytes=core.func("void *CFDataGetBytePtr(void *value)");const dictionary=core.func("void *CFDictionaryCreate(void *allocator, const void **keys, const void **values, long count, void *keyCallbacks, void *valueCallbacks)");const copy=security.func("int32_t SecItemCopyMatching(void *query, _Out_ void **result)");const add=security.func("int32_t SecItemAdd(void *attributes, void *result)");const sec=name=>constant(security,name);function query(write,action){const owned=[];const text=value=>{const result=string(null,value,134217984);if(!result)throw Error("Keychain allocation failed.");owned.push(result);return result};try{const pairs=[[sec("kSecClass"),sec("kSecClassGenericPassword")],[sec("kSecAttrService"),text("com.zortex.vault-master")],[sec("kSecAttrAccount"),text(account)],[sec("kSecAttrSynchronizable"),constant(core,"kCFBooleanFalse")],[sec("kSecUseAuthenticationUI"),sec("kSecUseAuthenticationUIFail")]];if(write){const value=data(null,write,write.length);if(!value)throw Error("Keychain allocation failed.");owned.push(value);pairs.push([sec("kSecValueData"),value])}else{pairs.push([sec("kSecReturnData"),constant(core,"kCFBooleanTrue")],[sec("kSecMatchLimit"),sec("kSecMatchLimitOne")])}const attributes=dictionary(null,pairs.map(pair=>pair[0]),pairs.map(pair=>pair[1]),pairs.length,null,null);if(!attributes)throw Error("Keychain allocation failed.");owned.push(attributes);return action(attributes)}finally{for(const value of owned.reverse())release(value)}}const port={read(){return query(void 0,attributes=>{const result=[null];const status=copy(attributes,result);if(status===ERR_SEC_ITEM_NOT_FOUND)return null;if(status===ERR_SEC_INTERACTION_NOT_ALLOWED||status===ERR_SEC_AUTH_FAILED){throw Error("Keychain is locked; unlock the login Keychain.")}if(status!==0||!result[0])throw Error("Keychain master key unavailable; unlock the login Keychain.");try{if(Number(length(result[0]))!==32)throw Error("Keychain master key is invalid.");return Buffer.from(new Uint8Array(koffi.view(bytes(result[0]),32)))}finally{release(result[0])}})},create(value){if(value.length!==32)throw Error("Keychain master key is invalid.");const status=query(value,attributes=>add(attributes,null));if(status===ERR_SEC_INTERACTION_NOT_ALLOWED||status===ERR_SEC_AUTH_FAILED){throw Error("Keychain is locked; unlock the login Keychain.")}if(status!==0&&status!==ERR_SEC_DUPLICATE_ITEM)throw Error("Keychain master key could not be saved.");const saved=port.read();if(!saved)throw Error("Keychain master key was not persisted.");return saved}};return port}
@@ -0,0 +1,7 @@
1
+ export function initializePublicVisibility(db){db.exec("SAVEPOINT public_visibility_install");try{db.exec("CREATE TABLE IF NOT EXISTS public_visibility(id INTEGER PRIMARY KEY CHECK(id=1),epoch INTEGER NOT NULL); INSERT OR IGNORE INTO public_visibility(id,epoch) VALUES(1,0)");const present=name=>!!("query"in db?db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?"):db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?")).get(name);const projection=present("search_documents")&&present("public_projection_state");for(const table of["account_bindings","authorization_grants","source_selections","credential_resources","isolated_source_subjects"]){if(!present(table))continue;for(const action of["INSERT","UPDATE","DELETE"]){const name=`public_visibility_${table}_${action.toLowerCase()}`;db.exec(`DROP TRIGGER IF EXISTS ${name}; CREATE TRIGGER ${name} AFTER ${action} ON ${table} BEGIN
2
+ UPDATE public_visibility SET epoch=epoch+1 WHERE id=1;
3
+ ${projection?"DELETE FROM search_documents WHERE stream='acquired-content'; UPDATE public_projection_state SET acquisition_dirty=1 WHERE id=1;":""}
4
+ END`)}}if(projection){db.exec(`CREATE TRIGGER IF NOT EXISTS public_projection_withdraw AFTER DELETE ON search_documents BEGIN UPDATE public_visibility SET epoch=epoch+1 WHERE id=1; END;
5
+ CREATE TRIGGER IF NOT EXISTS public_projection_replace AFTER UPDATE ON search_documents BEGIN UPDATE public_visibility SET epoch=epoch+1 WHERE id=1; END;
6
+ CREATE TRIGGER IF NOT EXISTS public_evidence_erase AFTER UPDATE OF erased ON events WHEN NEW.erased<>OLD.erased BEGIN UPDATE public_visibility SET epoch=epoch+1 WHERE id=1; END;
7
+ CREATE TRIGGER IF NOT EXISTS public_evidence_delete AFTER DELETE ON events BEGIN UPDATE public_visibility SET epoch=epoch+1 WHERE id=1; END`)}db.exec("RELEASE public_visibility_install")}catch(error){db.exec("ROLLBACK TO public_visibility_install; RELEASE public_visibility_install");throw error}}export function publicVisibilityEpoch(db){const epoch=db.query("SELECT epoch FROM public_visibility WHERE id=1").get()?.epoch;if(!Number.isSafeInteger(epoch)||epoch<0)throw Error("Public visibility generation is unavailable.");return epoch}
@@ -1 +1 @@
1
- import{existsSync,readFileSync}from"node:fs";import{dirname,join}from"node:path";import{DatabaseSync}from"node:sqlite";export const RECOVERY_MARKER=".zortex-recovery-state";export const RECOVERY_KEY="zortex-recovery-state";export function assertRecoveryReadable(file){const marker=join(dirname(file),RECOVERY_MARKER);if(existsSync(marker)&&readFileSync(marker,"utf8")!=="QUARANTINED")throw Error("Recovery is incomplete.")}export function assertNotRecovery(file,busyTimeoutMs=3e3){if(!Number.isSafeInteger(busyTimeoutMs)||busyTimeoutMs<1||busyTimeoutMs>6e4)throw Error("Invalid recovery probe busy timeout.");if(existsSync(join(dirname(file),RECOVERY_MARKER)))throw Error("Quarantined recovery cannot acquire write authority.");if(!existsSync(file))return;const db=new DatabaseSync(file,{readOnly:true,allowExtension:false});try{db.exec(`PRAGMA busy_timeout=${busyTimeoutMs};`);if(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()&&db.prepare("SELECT value FROM meta WHERE key=?").get(RECOVERY_KEY))throw Error("Quarantined recovery cannot acquire write authority.")}finally{db.close()}}
1
+ import{existsSync,readFileSync}from"node:fs";import{dirname,join}from"node:path";import{DatabaseSync}from"node:sqlite";import{assertVaultRuntime}from"./runtime.js";export const RECOVERY_MARKER=".zortex-recovery-state";export const RECOVERY_KEY="zortex-recovery-state";export function assertRecoveryReadable(file){assertVaultRuntime();const marker=join(dirname(file),RECOVERY_MARKER);if(existsSync(marker)&&readFileSync(marker,"utf8")!=="QUARANTINED")throw Error("Recovery is incomplete.")}export function assertNotRecovery(file,busyTimeoutMs=3e3){assertVaultRuntime();if(!Number.isSafeInteger(busyTimeoutMs)||busyTimeoutMs<1||busyTimeoutMs>6e4)throw Error("Invalid recovery probe busy timeout.");if(existsSync(join(dirname(file),RECOVERY_MARKER)))throw Error("Quarantined recovery cannot acquire write authority.");if(!existsSync(file))return;const db=new DatabaseSync(file,{readOnly:true,allowExtension:false});try{db.exec(`PRAGMA busy_timeout=${busyTimeoutMs};`);if(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()&&db.prepare("SELECT value FROM meta WHERE key=?").get(RECOVERY_KEY))throw Error("Quarantined recovery cannot acquire write authority.")}finally{db.close()}}
@@ -0,0 +1 @@
1
+ import*as sqlite from"node:sqlite";export class UnsupportedVaultRuntimeError extends Error{static code="ERR_INDRA_UNSUPPORTED_RUNTIME";code=UnsupportedVaultRuntimeError.code;constructor(){super("Indra requires Node.js 24.18.1 or later with SQLite authorization support and the WAL-reset fix. Upgrade Node.js, then run indra onboard again.");this.name="UnsupportedVaultRuntimeError"}}export function assertVaultRuntime(){const[major=0,minor=0,patch=0]=process.versions.node.split(".").map(Number);const[sqlMajor=0,sqlMinor=0,sqlPatch=0]=String(process.versions.sqlite??"").split(".").map(Number);const fixedWal=sqlMajor>3||sqlMajor===3&&(sqlMinor>51||sqlMinor===51&&sqlPatch>=3||sqlMinor===50&&sqlPatch>=7||sqlMinor===44&&sqlPatch>=6);if(!(major>24||major===24&&(minor>18||minor===18&&patch>=1))||!fixedWal||typeof sqlite.DatabaseSync?.prototype?.setAuthorizer!=="function"){throw new UnsupportedVaultRuntimeError}}
@@ -13,6 +13,8 @@ CREATE INDEX IF NOT EXISTS current_record_heads_event ON current_record_heads(ev
13
13
  CREATE TABLE IF NOT EXISTS search_documents(id TEXT PRIMARY KEY,source TEXT NOT NULL,source_id TEXT NOT NULL,stream TEXT NOT NULL,title TEXT NOT NULL,body TEXT NOT NULL,ts TEXT NOT NULL);
14
14
  CREATE INDEX IF NOT EXISTS search_documents_source_time ON search_documents(source,ts DESC,id);
15
15
  CREATE TABLE IF NOT EXISTS search_projection(version INTEGER PRIMARY KEY);
16
+ CREATE TABLE IF NOT EXISTS public_projection_state(id INTEGER PRIMARY KEY CHECK(id=1),acquisition_dirty INTEGER NOT NULL);
17
+ INSERT OR IGNORE INTO public_projection_state(id,acquisition_dirty) VALUES(1,1);
16
18
  CREATE TRIGGER IF NOT EXISTS search_documents_erase AFTER UPDATE OF erased ON events WHEN NEW.erased=1 BEGIN DELETE FROM search_documents WHERE id=NEW.id; END;
17
19
  CREATE TRIGGER IF NOT EXISTS search_documents_delete AFTER DELETE ON events BEGIN DELETE FROM search_documents WHERE id=OLD.id; END;
18
20
  DROP VIEW IF EXISTS z_current_records;
@@ -1 +1 @@
1
- import{normalizeSearchDocument}from"./api/search-text.js";export function projectSearchRecord(db,id){const row=db.query("SELECT id,source,source_id,stream,title,body,ts,payload FROM z_current_records WHERE id=?").get(id);if(!row){db.query("DELETE FROM search_documents WHERE id=?").run(id);return}const normalized=normalizeSearchDocument({source:row.source,title:row.title,body:row.body??"",payload:JSON.parse(row.payload)});db.query("INSERT INTO search_documents(id,source,source_id,stream,title,body,ts) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET title=excluded.title,body=excluded.body,ts=excluded.ts").run(row.id,row.source,row.source_id,row.stream,normalized.title.replace(/\s+/gu," "),normalized.body.replace(/\s+/gu," "),row.ts)}export function rebuildSearchRecords(db){db.exec("BEGIN IMMEDIATE");try{if(!db.query("SELECT 1 FROM search_projection WHERE version=2").get()){db.exec("DELETE FROM search_documents");let after="";for(;;){const rows=db.query("SELECT id FROM z_current_records WHERE id>? ORDER BY id LIMIT 200").all(after);if(!rows.length)break;for(const row of rows)projectSearchRecord(db,row.id);after=rows.at(-1).id}db.exec("INSERT INTO search_projection(version) VALUES(2)")}db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}}
1
+ import{normalizeSearchDocument}from"./api/search-text.js";import{contentAcquisitionScope}from"./content-acquisition.js";export function projectSearchRecord(db,id){createSearchProjector(db)(id)}function createSearchProjector(db){const read=db.query("SELECT id,source,source_id,stream,rev,title,body,ts,payload FROM z_current_records WHERE id=?");const remove=db.query("DELETE FROM search_documents WHERE id=?");const write=db.query("INSERT INTO search_documents(id,source,source_id,stream,title,body,ts,rev,original_body,payload) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET title=excluded.title,body=excluded.body,ts=excluded.ts,rev=excluded.rev,original_body=excluded.original_body,payload=excluded.payload");return id=>{const row=read.get(id);if(!row){remove.run(id);return}const payload=JSON.parse(row.payload??"null");if(row.stream==="acquired-content"){const authority=contentAcquisitionScope(db,row.source);if(!("ok"in authority)||authority.ok.identity!==payload?.acquisition?.identity){remove.run(id);return}}const normalized=normalizeSearchDocument({source:row.source,title:row.title,body:row.body??"",payload});write.run(row.id,row.source,row.source_id,row.stream,normalized.title.replace(/\s+/gu," "),normalized.body.replace(/\s+/gu," "),row.ts,row.rev,row.body,row.payload)}}export function rebuildSearchRecords(db){db.exec("BEGIN IMMEDIATE");try{if(!db.query("SELECT 1 FROM search_projection WHERE version=3").get()){db.exec("DELETE FROM search_documents");let after="";const project=createSearchProjector(db);const page=db.query("SELECT DISTINCT event_id AS id FROM current_record_heads WHERE event_id>? ORDER BY event_id LIMIT 200");for(;;){const rows=page.all(after);if(!rows.length)break;for(const row of rows)project(row.id);after=rows.at(-1).id}db.exec("INSERT INTO search_projection(version) VALUES(3); UPDATE public_projection_state SET acquisition_dirty=0 WHERE id=1")}db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}}export function initializeSearchColumns(db){const columns=new Set(db.query("PRAGMA table_info(search_documents)").all().map(row=>row.name));for(const[name,definition]of[["rev","TEXT NOT NULL DEFAULT ''"],["original_body","TEXT"],["payload","TEXT"]]){if(!columns.has(name))db.exec(`ALTER TABLE search_documents ADD COLUMN ${name} ${definition}`)}}export function refreshAcquiredSearchRecords(db){if(!db.query("SELECT acquisition_dirty FROM public_projection_state WHERE id=1").get()?.acquisition_dirty)return;db.exec("BEGIN IMMEDIATE");try{if(db.query("SELECT acquisition_dirty FROM public_projection_state WHERE id=1").get()?.acquisition_dirty){const project=createSearchProjector(db);const page=db.query("SELECT DISTINCT event_id AS id FROM current_record_heads WHERE stream='acquired-content' AND event_id>? ORDER BY event_id LIMIT 200");let after="";for(;;){const rows=page.all(after);if(!rows.length)break;for(const row of rows)project(row.id);after=rows.at(-1).id}db.exec("UPDATE public_projection_state SET acquisition_dirty=0 WHERE id=1")}db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}}