@zortexhq/indra-v2.5 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +11 -4
  2. package/bin/codex-postinstall.mjs +1 -1
  3. package/dist/auto-sync.js +1 -1
  4. package/dist/cli-run.js +1 -1
  5. package/dist/codex-install.js +1 -1
  6. package/dist/codex-setup.js +1 -1
  7. package/dist/connector-worker.js +1 -1
  8. package/dist/content-find.js +2 -2
  9. package/dist/find-snapshots.js +1 -0
  10. package/dist/gateway.js +1 -1
  11. package/dist/imessage-sync.js +1 -0
  12. package/dist/local-cloud-policy.js +1 -1
  13. package/dist/local-cloud.js +1 -1
  14. package/dist/mail-search-body.js +1 -0
  15. package/dist/match-excerpt.js +1 -0
  16. package/dist/mcp.js +1 -1
  17. package/dist/native-connect.js +1 -0
  18. package/dist/native-level1-setup.js +1 -1
  19. package/dist/public-tool.js +1 -1
  20. package/dist/read-route.js +1 -0
  21. package/dist/recovery-support.js +1 -1
  22. package/dist/resident-ensure-ready.js +1 -1
  23. package/dist/resident-host.js +2 -2
  24. package/dist/resident-jobs.js +1 -1
  25. package/dist/resident-platform.js +1 -1
  26. package/dist/source-data.js +1 -0
  27. package/dist/supervised-sync.js +1 -1
  28. package/dist/sync-sources.js +1 -0
  29. package/dist/worker-google-auth.js +1 -0
  30. package/node_modules/@zortexhq/plugin-connector-calendar/dist/provider.js +1 -1
  31. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -0
  32. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/index.js +1 -0
  33. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/policy.js +1 -0
  34. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/result.js +1 -0
  35. package/node_modules/@zortexhq/plugin-connector-computer-files/package.json +18 -0
  36. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  37. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  38. package/node_modules/@zortexhq/plugin-connector-core/dist/native-file-roots.js +1 -0
  39. package/node_modules/@zortexhq/plugin-connector-drive/dist/provider.js +1 -1
  40. package/node_modules/@zortexhq/plugin-connector-framework/dist/manifest.js +1 -1
  41. package/node_modules/@zortexhq/plugin-connector-framework/dist/runtime.js +1 -1
  42. package/node_modules/@zortexhq/plugin-connector-gmail/dist/brokered.js +1 -1
  43. package/node_modules/@zortexhq/plugin-connector-gmail/dist/gmail-source.js +2 -2
  44. package/node_modules/@zortexhq/plugin-connector-gmail/dist/provider.js +1 -1
  45. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-history/dist/provider.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-imessage/dist/attributed-body.js +1 -0
  48. package/node_modules/@zortexhq/plugin-connector-imessage/dist/chatdb-source.js +1 -0
  49. package/node_modules/@zortexhq/plugin-connector-imessage/dist/connector.js +1 -0
  50. package/node_modules/@zortexhq/plugin-connector-imessage/dist/index.js +1 -0
  51. package/node_modules/@zortexhq/plugin-connector-imessage/dist/manifest.js +1 -0
  52. package/node_modules/@zortexhq/plugin-connector-imessage/dist/sqlite-snapshot.js +1 -0
  53. package/node_modules/@zortexhq/plugin-connector-imessage/package.json +16 -0
  54. package/node_modules/@zortexhq/plugin-connector-level1/dist/api/index.js +1 -0
  55. package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files-pages.js +1 -1
  56. package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files.js +1 -0
  57. package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -0
  58. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  59. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
  60. package/node_modules/@zortexhq/plugin-connector-level1/dist/sources.js +1 -1
  61. package/node_modules/@zortexhq/plugin-connector-level1/package.json +5 -1
  62. package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
  63. package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
  64. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  65. package/node_modules/@zortexhq/plugin-device-auth/dist/authority.js +1 -1
  66. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -0
  67. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-renderer.js +1 -0
  68. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
  69. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  70. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
  71. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
  72. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
  73. package/node_modules/@zortexhq/plugin-galaxy-ui/package.json +1 -0
  74. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
  75. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
  76. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  77. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
  78. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +1 -1
  79. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
  80. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/portrait-model.js +1 -1
  81. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
  82. package/node_modules/@zortexhq/plugin-google-auth/default-client.json +1 -0
  83. package/node_modules/@zortexhq/plugin-google-auth/dist/desktop-client.js +1 -1
  84. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  85. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  86. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/search-text.js +1 -0
  87. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/source-sync.js +1 -0
  88. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/current-records.js +1 -0
  89. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  90. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/record-rules.js +1 -1
  91. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +19 -2
  92. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -0
  93. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
  94. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -0
  95. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +1 -1
  96. package/node_modules/@zortexhq/rooktrail/dist/record-rules.js +1 -1
  97. package/node_modules/@zortexhq/rooktrail/dist/registry.js +1 -1
  98. package/package.json +11 -7
  99. package/release-provenance.json +45 -31
  100. package/update-manifest.json +380 -164
@@ -1 +1 @@
1
- import{createServer}from"node:http";import{createHash,randomBytes,randomUUID}from"node:crypto";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{isTransientConnectorAction}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{GOOGLE_TOKEN_URL,localGoogleDesktopClient,usesDirectGoogleOAuth}from"./desktop-client.js";import{isGmailReadBatch}from"./read-batch.js";import{createTraceRecorder}from"@zortexhq/plugin-telemetry/api";export const GOOGLE_PUBLIC_CLIENT_ID="230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com";export const DEFAULT_GOOGLE_BROKER_URL="https://zortex-google-oauth.google-oauth-broker.workers.dev";export const name="zortex-google-auth";export const inject=["zortexVaultStore","zortexConnectorHttp"];class GoogleHttpFailure extends Error{status;constructor(status){super("Google endpoint returned a failed status.");this.status=status}}const scopes={gmail:"https://mail.google.com/ openid email","google-drive":"https://www.googleapis.com/auth/drive","google-calendar":"https://www.googleapis.com/auth/calendar",youtube:"https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/yt-analytics.readonly openid email","google-tasks":"https://www.googleapis.com/auth/tasks openid email"};const gmailReadScope="https://www.googleapis.com/auth/gmail.readonly";const gmailReadScopes=[gmailReadScope,"https://www.googleapis.com/auth/gmail.modify","https://mail.google.com/"];const driveReadScopes=["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive"];const oidc="https://openidconnect.googleapis.com/v1/userinfo";const identity={gmail:oidc,"google-drive":"https://www.googleapis.com/drive/v3/about?fields=user(permissionId,emailAddress)","google-calendar":"https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=1",youtube:oidc,"google-tasks":oidc};const allowed={gmail:{origin:"https://gmail.googleapis.com",prefix:"/gmail/v1/"},"google-drive":{origin:"https://www.googleapis.com",prefix:"/drive/v3/"},"google-calendar":{origin:"https://www.googleapis.com",prefix:"/calendar/v3/"},youtube:{origin:"https://www.googleapis.com",prefix:"/youtube/v3/"},"google-tasks":{origin:"https://tasks.googleapis.com",prefix:"/tasks/v1/"}};const permitted=(source,endpoint,method)=>{if(endpoint.username||endpoint.password||endpoint.hash)return false;const boundary=allowed[source];if(boundary&&endpoint.origin===boundary.origin&&endpoint.pathname.startsWith(boundary.prefix))return true;if(source==="youtube"&&method==="GET"&&(endpoint.origin==="https://youtubeanalytics.googleapis.com"&&endpoint.pathname.startsWith("/v2/")||endpoint.origin==="https://youtubereporting.googleapis.com"&&endpoint.pathname.startsWith("/v1/")))return true;return source==="google-drive"&&method==="GET"&&(endpoint.origin==="https://docs.googleapis.com"&&/^\/v1\/documents\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname)||endpoint.origin==="https://sheets.googleapis.com"&&/^\/v4\/spreadsheets\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname))};export const openSystemUrl=openConnectionUrl;export function createGoogleAuth({vault,desktopClient=localGoogleDesktopClient,transport=fetch,tokenTransport=transport,openUrl=openSystemUrl,timeoutMs=6e5,now=Date.now,metrics,feedback}){const jobs=new Map,jobModes=new WeakMap;const listeners=new Map;const stop=new AbortController;const refreshing=new Map,callbacks=new Set;let closed=false,closing;const fail=(code,message)=>businessError(code,message,"plugin");async function json(url,options={},send=transport){if(closed)throw Error("google_auth_inactive");const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const response=await send(url,{...options,redirect:"error",signal});if(!response.ok){await response.body?.cancel().catch(()=>{});throw new GoogleHttpFailure(response.status)}const reader=response.body?.getReader();if(!reader)throw Error("empty_response");const chunks=[];let size=0;for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>2*1024*1024){await reader.cancel();throw Error("response_too_large")}chunks.push(part.value)}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}function directToken(client,fields,signal){return json(GOOGLE_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:client.clientId,client_secret:client.clientSecret,...fields}),...signal?{signal}:{}},tokenTransport)}const missingDesktopClient=source=>fail("failed_precondition",`Google Desktop OAuth client is missing or invalid. Configure ~/.zortex/google-oauth/${source}.json.`);const configuredClient=async source=>{const client=await desktopClient(source);return client?.clientId===GOOGLE_PUBLIC_CLIENT_ID?void 0:client};function releaseListener(id){const entry=listeners.get(id);if(entry?.finished&&entry.serverClosed&&!entry.task)listeners.delete(id)}function finish(job){const resources=listeners.get(job.id);if(resources&&!resources.finished){resources.finished=true;clearTimeout(resources.timer);resources.detach?.();resources.server.closeAllConnections();resources.server.close(error=>{resources.serverClosed=!error||error.code==="ERR_SERVER_NOT_RUNNING";releaseListener(job.id)});releaseListener(job.id)}delete job.authorizationUrl;delete job.instructions}async function access(source,bindingId){if(isTransientConnectorAction()&&!bindingId)return readAccess(source);const key=bindingId?source+":"+bindingId:source;let task=refreshing.get(key);if(!task){task=readAccess(source,bindingId);refreshing.set(key,task)}try{const result=await task;return closed?fail("unavailable","Google authorization is inactive."):result}finally{if(refreshing.get(key)===task)refreshing.delete(key)}}async function readAccess(source,bindingId){const custody=vault.bindingCustody;let found,snapshot;const choices=source==="google-tasks"?["https://www.googleapis.com/auth/tasks.readonly","https://www.googleapis.com/auth/tasks"]:source==="youtube"?["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]:source==="google-calendar"?["https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/calendar"]:source==="gmail"?["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.modify","https://mail.google.com/"]:driveReadScopes;const hasReadScope=granted=>Array.isArray(granted)&&choices.some(scope=>granted.includes(scope));const direct=usesDirectGoogleOAuth(source);const client=direct?await configuredClient(source):void 0;const requiresTasksReconnect=credential=>source==="google-tasks"&&credential.clientId!==client?.clientId;const reconnect=()=>fail("failed_precondition","Reconnect this source with its Google Desktop OAuth client.");const reconnectTasks=()=>client?reconnect():missingDesktopClient("google-tasks");const refreshConfigurationError=credential=>{if(direct&&!client)return missingDesktopClient(source);if(client&&credential.clientId!==client.clientId)return reconnect()};const authorized=current=>current.material.kind!=="oauth"||current.resource.owner.kind!=="resident"?fail("failed_precondition","Google credential resource is not owned by the resident."):!hasReadScope(current.grant.scopes)||!hasReadScope(current.material.credential.scopes)?fail("permission_denied","The stored grant lacks the selected source read scope."):requiresTasksReconnect(current.material.credential)?reconnectTasks():ok({credential:current.material.credential,snapshot:current});if(custody){let resolution=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!bindingId&&"ok"in resolution&&resolution.ok.kind==="legacy-unattributed"&&custody.recoverLegacy){let expired;const verify=async(connection,credential)=>{if(requiresTasksReconnect(credential))return reconnectTasks();if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(credential.scopes))return fail("permission_denied","The legacy Google credential lacks the selected read scope. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(credential.expiresAt<=now()+6e4){if(credential.refreshToken)expired=credential;return fail("failed_precondition","The legacy Google credential has expired. Open zortex help for explicit account recovery; ordinary reconnect does not resolve mixed legacy history.")}try{return ok(await verifyLegacyIdentity(source,credential.accessToken))}catch{return fail("failed_precondition","Google could not verify the original legacy account. Open zortex help for explicit account recovery; preserve its legacy history and do not retry ordinary reconnect to clear ambiguity.")}};let recovered=await custody.recoverLegacy(source,verify);if(!("ok"in recovered)&&expired&&custody.refreshLegacyCredential){const configurationError2=refreshConfigurationError(expired);if(configurationError2)return configurationError2;const refreshedLegacy=await custody.refreshLegacyCredential(source,expired,async(connection,current2)=>{if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(current2.scopes)||!current2.refreshToken)return fail("failed_precondition","Legacy Google authorization cannot be recovered with its original grant. Open zortex help for account recovery.");const next2=await refreshed(current2);return"ok"in next2?next2:fail("err"in next2?next2.err.code:"internal","The original legacy Google grant could not be refreshed. Preserve this Vault and open zortex help for account recovery; do not repeat ordinary reconnect to clear mixed history.")});if(!("ok"in refreshedLegacy))return refreshedLegacy;recovered=await custody.recoverLegacy(source,verify)}if(!("ok"in recovered))return recovered;resolution=ok({kind:"resolved",binding:recovered.ok})}if(!("ok"in resolution)||resolution.ok.kind!=="resolved")return"err"in resolution?resolution:fail("failed_precondition","Google source needs an explicitly selected account binding. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(resolution.ok.binding.identity.source!==source)return fail("permission_denied","The selected account binding belongs to another source.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"google"});if(!("ok"in current))return current;snapshot=current.ok;found=authorized(snapshot)}else{const legacy=await vault.credential(source);found="ok"in legacy?ok({credential:legacy.ok}):legacy}if(!("ok"in found))return"err"in found?found:fail("failed_precondition","Google source is not connected.");if(requiresTasksReconnect(found.ok.credential))return reconnectTasks();if((source==="google-tasks"||source==="youtube")&&!hasReadScope(found.ok.credential.scopes))return fail("permission_denied","The stored grant lacks the selected source read scope.");if(found.ok.credential.expiresAt>now()+6e4)return found;if(!found.ok.credential.refreshToken)return fail("failed_precondition","Google authorization expired. Start the connection flow again.");const configurationError=refreshConfigurationError(found.ok.credential);if(configurationError)return configurationError;async function refreshed(current){const configurationError2=refreshConfigurationError(current);if(configurationError2)return configurationError2;if(!current.refreshToken)return fail("failed_precondition","Google authorization expired. Start the connection flow again.");try{const token=client?await directToken(client,{grant_type:"refresh_token",refresh_token:current.refreshToken}):await json(DEFAULT_GOOGLE_BROKER_URL+"/google/refresh",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId:current.clientId,refreshToken:current.refreshToken})});if(typeof token.access_token!=="string"||!token.access_token||!Number.isFinite(token.expires_in)||token.expires_in<=0||token.refresh_token!==void 0&&(typeof token.refresh_token!=="string"||!token.refresh_token))throw Error("invalid_token_response");return ok({...current,accessToken:token.access_token,...token.refresh_token!==void 0?{refreshToken:token.refresh_token}:{},expiresAt:now()+token.expires_in*1e3})}catch(error){return error instanceof GoogleHttpFailure&&[400,401,403].includes(error.status)?fail("failed_precondition","Google authorization is no longer accepted. Reconnect this source."):fail("unavailable","Google authorization refresh did not complete; no missing grant was assumed.")}}if(custody&&snapshot){const stored2=await custody.refreshResource(snapshot,{kind:"resident"},async current2=>{const permitted2=authorized(current2);if(!("ok"in permitted2))return permitted2;const next2=await refreshed(permitted2.ok.credential);return"ok"in next2?ok({kind:"oauth",credential:next2.ok}):next2});if("ok"in stored2)return authorized(stored2.ok);if(!("err"in stored2)||stored2.err.code!=="failed_precondition")return stored2;const current=await custody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const winner=authorized(current.ok);return current.ok.resource.revision>snapshot.resource.revision&&"ok"in winner&&winner.ok.credential.expiresAt>now()+6e4?winner:stored2}const next=await refreshed(found.ok.credential);if(!("ok"in next))return next;const stored=await vault.updateCredential(source,next.ok);return"ok"in stored?ok({credential:next.ok}):"err"in stored?stored:fail("internal","Credential update was not confirmed.")}async function checkAccess(source,selected,bindingId){const custody=vault.bindingCustody,expected=selected.snapshot;if(!custody)return ok(void 0);const changed=()=>fail("permission_denied","The selected Google account, grant or credential changed during the request; its response was withheld.");if(!expected)return changed();const current=await custody.credentialSnapshot(expected.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const resolved=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved"||resolved.ok.binding.id!==expected.binding.id||resolved.ok.binding.revision!==expected.binding.revision)return changed();return current.ok.binding.id===expected.binding.id&&current.ok.binding.revision===expected.binding.revision&&current.ok.grant.id===expected.grant.id&&current.ok.grant.revision===expected.grant.revision&&current.ok.grant.scopeEpoch===expected.grant.scopeEpoch&&current.ok.resource.id===expected.resource.id&&current.ok.resource.revision===expected.resource.revision?ok(void 0):changed()}async function captureSelection(source,readOnly=true){const custody=vault.bindingCustody;if(!custody?.sourceSelection)return ok(async()=>ok(void 0));const found=await custody.sourceSelection(source);if(!("ok"in found))return found;if(found.ok&&!isTransientConnectorAction())return fail("failed_precondition","This explicitly recovered account supports transient L1 reads. Source-only history sync remains disabled; use zortex help to read the selected account.");if(found.ok&&!readOnly)return fail("permission_denied","Explicit account recovery authorizes bounded reads only.");const expected=found.ok;return ok(async()=>{const current=await custody.sourceSelection(source);if(!("ok"in current))return current;return current.ok?.bindingId===expected?.bindingId&&current.ok?.revision===expected?.revision?ok(void 0):fail("permission_denied","The selected account changed during this request; its response was withheld.")})}async function verifyLegacyIdentity(source,accessToken){const headers={Authorization:"Bearer "+accessToken};let profile=await json(identity[source],{headers});if(source==="google-drive"){const subject=profile.user?.permissionId,account=profile.user?.emailAddress??subject;if(typeof subject!=="string"||!subject.trim()||subject.length>500||typeof account!=="string"||!account)throw Error("drive_identity_not_confirmed");return{accountId:subject,account}}if(source==="google-calendar"){const seen=new Set;for(let page=0;page<20;page++){if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){const subject=primary[0].id;if(typeof subject!=="string"||!subject.trim()||subject.length>500)throw Error("invalid_calendar_identity");return{accountId:subject,account:subject}}const next=profile.nextPageToken;if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("primary_calendar_not_found");seen.add(next);const url=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url.searchParams.set("maxResults","250");url.searchParams.set("pageToken",next);url.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url.href,{headers})}throw Error("calendar_identity_budget_exceeded")}if(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)||typeof profile.email!=="string"||!profile.email)throw Error("account_not_confirmed");return{accountId:profile.sub,account:profile.email}}const service={async connect(source,options={}){if(options.automatic===true)return fail("invalid_argument","Automatic enrollment is retired. Open the source connection gateway.");options={...options,automatic:false};if(options.signal?.aborted)return fail("aborted","Google authorization cancelled.");if(options.selectAccount!==void 0&&(options.selectAccount!==true||options.automatic!==false))return fail("invalid_argument","Explicit account selection requires manual recovery.");if(options.gmailWrite!==void 0&&(options.gmailWrite!==true||source!=="gmail"||options.automatic!==false||options.selectAccount||options.reauthorize))return fail("invalid_argument","Gmail write consent requires an explicit same-account manual authorization.");const custodyForWrite=options.gmailWrite?vault.bindingCustody:void 0;if(options.gmailWrite&&(!custodyForWrite?.sourceSelection||!custodyForWrite.resolve))return fail("failed_precondition","A selected Gmail account is required before requesting write access.");const writeSelection=options.gmailWrite?await custodyForWrite.sourceSelection("gmail"):void 0;if(writeSelection&&!("ok"in writeSelection))return writeSelection;const writeBinding=options.gmailWrite?await custodyForWrite.resolve(writeSelection&&"ok"in writeSelection&&writeSelection.ok?{kind:"binding",bindingId:writeSelection.ok.bindingId}:{kind:"legacy-source",source:"gmail"}):void 0;if(writeBinding&&(!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeBinding.ok.binding.identity.source!=="gmail"||writeBinding.ok.binding.provider!=="google"||!writeBinding.ok.binding.identity.subject))return fail("failed_precondition","Select a verified Gmail account before requesting write access.");const writeInventory=writeBinding&&"ok"in writeBinding&&writeBinding.ok.kind==="resolved"?await custodyForWrite.bindingInventory(writeBinding.ok.binding.id):void 0;if(options.gmailWrite&&(!writeInventory||!("ok"in writeInventory)||!writeInventory.ok))return fail("failed_precondition","Gmail credential custody is unavailable.");const writeTarget=writeInventory&&"ok"in writeInventory?writeInventory.ok:void 0;const writeGrant=writeTarget?.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const writeResource=writeTarget?.resources.find(r=>r.id===oauthCredentialResourceId(writeTarget.binding.id));if(options.gmailWrite&&(!writeTarget||!writeGrant||!writeResource||!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeTarget.binding.revision!==writeBinding.ok.binding.revision))return fail("failed_precondition","Gmail credential custody changed.");if(options.selectAccount&&(!vault.bindingCustody?.sourceSelection||!vault.bindingCustody.selectSourceBinding))return fail("failed_precondition","This Vault does not support explicit account recovery.");const selectionBefore=options.selectAccount?await vault.bindingCustody.sourceSelection(source):ok(null);if(!("ok"in selectionBefore))return selectionBefore;const direct=usesDirectGoogleOAuth(source);const client=direct?await configuredClient(source):void 0;if(direct&&!client)return missingDesktopClient(source);const clientId=client?.clientId??GOOGLE_PUBLIC_CLIENT_ID;const requestedScopes=source==="gmail"&&!options.gmailWrite?`${gmailReadScope} openid email`:scopes[source];const interactionMode=options.manualPresentation==="return-url"?"manual-return-url":"manual-open";const deadline=timeoutMs;if(closed)return fail("unavailable","Google authorization is inactive.");if(!Object.hasOwn(scopes,source))return fail("invalid_argument","Unknown Google source.");const running=[...jobs.values()].find(job2=>job2.source===source&&job2.state==="waiting-user");if(running&&(options.selectAccount||options.gmailWrite))return fail("failed_precondition","Wait for the current authorization to finish before explicit account recovery.");if(running)return jobModes.get(running)!==interactionMode?fail("failed_precondition","Previous source authorization uses a different interaction mode. Wait for its owned cleanup."):ok({...running});if([...listeners].some(([id])=>jobs.get(id)?.source===source))return fail("failed_precondition","Previous source authorization still owns active work. Wait for cleanup.");const job={id:randomUUID(),source,state:"waiting-user",startedAt:new Date(now()).toISOString()};jobModes.set(job,interactionMode);jobs.set(job.id,job);const jobStop=new AbortController,jobSignal=AbortSignal.any([stop.signal,jobStop.signal,...options.signal?[options.signal]:[]]);const trace=createTraceRecorder(metrics,source);let stage="callback_received";await trace.step("authorization_started","started");const verifier=randomBytes(48).toString("base64url"),state=randomBytes(24).toString("base64url");let used=false;let redirectUri="";const server=createServer((request,response)=>{const url=new URL(request.url??"/",redirectUri);if(request.method!=="GET"||url.pathname!=="/callback"){response.writeHead(404).end("Not found.");return}if(url.searchParams.get("state")!==state){response.writeHead(400).end("Invalid authorization state.");return}if(used){response.writeHead(409).end("Authorization callback already received.");return}const code=url.searchParams.get("code"),error=url.searchParams.get("error");if(error||!code){used=true;job.state="failed";job.error={code:"authorization_denied",message:"Google authorization was not completed."};void trace.step("callback_received","failed",{error:"denied"});response.writeHead(400).end("Authorization was not completed.");finish(job);return}used=true;response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}).end("Authorization received. Zortex is validating the connection. You may close this page.");const callback=(async()=>{try{await trace.step("callback_received","completed");stage="token_exchange";await trace.step(stage,"started");const exchange=()=>client?directToken(client,{grant_type:"authorization_code",code,code_verifier:verifier,redirect_uri:redirectUri},jobSignal):json(DEFAULT_GOOGLE_BROKER_URL+"/google/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId,code,codeVerifier:verifier,redirectUri}),signal:jobSignal});const token=await exchange();if(!token.access_token||!Number.isFinite(token.expires_in))throw Error("invalid_token_response");const granted=(token.scope??requestedScopes).split(" ");if(source==="google-drive"?!driveReadScopes.some(scope=>granted.includes(scope)):source==="gmail"?!((options.gmailWrite?granted.includes("https://mail.google.com/"):gmailReadScopes.some(scope=>granted.includes(scope)))&&granted.includes("openid")&&(granted.includes("email")||granted.includes("https://www.googleapis.com/auth/userinfo.email"))):!requestedScopes.split(" ").every(scope=>granted.includes(scope)||scope==="email"&&granted.includes("https://www.googleapis.com/auth/userinfo.email")))throw Error("required_scope_missing");await trace.step(stage,"completed");stage="identity_verified";await trace.step(stage,"started");let profile=await json(identity[source],{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal});let calendarAccount;if(source==="google-calendar"){const seen=new Set;for(let page=0;page<50;page++){if(closed||job.state!=="waiting-user")throw Error("connection_cancelled");if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){if(typeof primary[0].id!=="string"||!primary[0].id.trim()||primary[0].id.length>500)throw Error("invalid_calendar_identity");calendarAccount=primary[0].id;break}const next=profile.nextPageToken;if(next===void 0)throw Error("primary_calendar_not_found");if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("invalid_calendar_identity_cursor");seen.add(next);const url2=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url2.searchParams.set("maxResults","250");url2.searchParams.set("pageToken",next);url2.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url2.href,{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal})}if(!calendarAccount)throw Error("calendar_identity_budget_exceeded")}const oidcSource=source==="gmail"||source==="youtube"||source==="google-tasks";const account=source==="google-drive"?profile.user?.emailAddress??profile.user?.permissionId:oidcSource?profile.email:calendarAccount;if(source==="google-drive"&&(typeof profile.user?.permissionId!=="string"||!profile.user.permissionId.trim()||profile.user.permissionId.length>500))throw Error("drive_identity_not_confirmed");if(oidcSource&&(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)))throw Error("account_not_confirmed");if(typeof account!=="string"||!account)throw Error("account_not_confirmed");let readGuard=null;if(source==="gmail"&&!options.gmailWrite&&vault.bindingCustody){const known=await vault.bindingCustody.bindings("gmail");if(!("ok"in known))throw Error("gmail_existing_grant_unavailable");const previous=known.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===profile.sub);if(previous.length>1)throw Error("gmail_existing_grant_unavailable");readGuard=null;for(const binding of previous){const inventory=await vault.bindingCustody.bindingInventory(binding.id);if(!("ok"in inventory)||!inventory.ok)throw Error("gmail_existing_grant_unavailable");const existing=inventory.ok.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const resource=inventory.ok.resources.find(r=>r.id===oauthCredentialResourceId(binding.id));if(!existing||!resource||inventory.ok.binding.revision!==binding.revision)throw Error("gmail_existing_grant_unavailable");readGuard={bindingId:binding.id,bindingRevision:binding.revision,grantId:existing.id,grantRevision:existing.revision,resourceId:resource.id,resourceRevision:resource.revision};const writable=(existing.scopes??[]).filter(scope=>scope==="https://mail.google.com/"||/^https:\/\/www\.googleapis\.com\/auth\/gmail\.(modify|compose|send|insert|labels|settings\.basic|settings\.sharing)$/.test(scope));if(writable.some(scope=>!granted.includes(scope))&&!granted.includes("https://mail.google.com/"))throw Error("gmail_write_scope_would_be_lost")}}if(options.gmailWrite){if(!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||profile.sub!==writeBinding.ok.binding.identity.subject)throw Error("gmail_write_account_mismatch");const selection=await custodyForWrite.sourceSelection("gmail");if(!("ok"in selection)||!writeSelection||!("ok"in writeSelection)||selection.ok?.revision!==writeSelection.ok?.revision||selection.ok?.bindingId!==writeSelection.ok?.bindingId)throw Error("gmail_write_selection_changed");const current=await custodyForWrite.resolve(selection.ok?{kind:"binding",bindingId:selection.ok.bindingId}:{kind:"legacy-source",source:"gmail"});if(!("ok"in current)||current.ok.kind!=="resolved"||current.ok.binding.id!==writeBinding.ok.binding.id||current.ok.binding.revision!==writeBinding.ok.binding.revision||current.ok.binding.identity.subject!==profile.sub)throw Error("gmail_write_binding_changed")}if(closed||job.state!=="waiting-user")return;const credential={accessToken:token.access_token,...token.refresh_token?{refreshToken:token.refresh_token}:{},expiresAt:now()+token.expires_in*1e3,clientId,scopes:granted};await trace.step(stage,"completed");stage="credentials_saved";await trace.step(stage,"started");if(closed||job.state!=="waiting-user")return;const stored=await vault.saveConnection({source,provider:"google",account,...oidcSource?{accountId:String(profile.sub)}:source==="google-calendar"?{accountId:account}:source==="google-drive"?{accountId:String(profile.user.permissionId)}:{},scopes:granted,state:"connected",updatedAt:new Date(now()).toISOString()},credential,{signal:jobSignal,...source==="gmail"&&!options.gmailWrite&&vault.bindingCustody?{expectedCredential:readGuard}:{},...options.gmailWrite&&writeTarget&&writeGrant&&writeResource&&writeSelection&&"ok"in writeSelection?{expectedCredential:{bindingId:writeTarget.binding.id,bindingRevision:writeTarget.binding.revision,grantId:writeGrant.id,grantRevision:writeGrant.revision,resourceId:writeResource.id,resourceRevision:writeResource.revision},selectSource:{expectedSelectionRevision:writeSelection.ok?.revision??null,expectedBindingRevision:writeTarget.binding.revision}}:{}});if(!("ok"in stored))throw Error("credential_store_failed");if(closed)return;if(options.selectAccount){if(jobSignal.aborted||job.state!=="waiting-user")return;const custody=vault.bindingCustody,found=await custody.bindings(source);if(!("ok"in found))throw Error("account_selection_failed");const matches=found.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===stored.ok.accountId&&binding.account===stored.ok.account&&binding.updatedAt===stored.ok.updatedAt);if(matches.length!==1||jobSignal.aborted||job.state!=="waiting-user")throw Error("account_selection_failed");const selected=await custody.selectSourceBinding(source,matches[0].id,matches[0].revision,selectionBefore.ok?.revision??null);if(!("ok"in selected))throw Error("account_selection_failed")}if(closed||job.state!=="waiting-user")return;await trace.step(stage,"completed");await feedback?.()?.bind(stored.ok,trace.flow);if(closed||job.state!=="waiting-user")return;job.state="connected";job.account=account}catch(error2){await trace.step(stage,stop.signal.aborted?"cancelled":"failed",{error:jobStop.signal.aborted?"timeout":stage==="credentials_saved"?"storage":error2 instanceof GoogleHttpFailure?"provider":"unknown",...error2 instanceof GoogleHttpFailure&&error2.status>=100&&error2.status<=599?{statusCode:error2.status}:{}});if(!closed&&job.state==="waiting-user"){job.state="failed";job.error=error2 instanceof Error&&error2.message==="gmail_write_scope_would_be_lost"?{code:"permission_denied",message:"The existing Gmail account has write access. To preserve it, open Zortex Help and choose Grant full Gmail access."}:{code:"google_connection_failed",message:"Google authorization or account validation failed. No successful connection was confirmed."}}}finally{finish(job)}})();callbacks.add(callback);const owned=listeners.get(job.id);if(owned)owned.task=callback;const release=()=>{callbacks.delete(callback);if(owned)delete owned.task;releaseListener(job.id)};void callback.then(release,release)});try{await new Promise((done,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error("callback_unavailable");redirectUri=`http://127.0.0.1:${address.port}/callback`;const url=new URL("https://accounts.google.com/o/oauth2/v2/auth");for(const[key,value]of Object.entries({response_type:"code",client_id:clientId,redirect_uri:redirectUri,scope:requestedScopes,access_type:"offline",prompt:options.selectAccount?"select_account consent":"consent",code_challenge:createHash("sha256").update(verifier).digest("base64url"),code_challenge_method:"S256",state}))url.searchParams.set(key,value);job.authorizationUrl=url.toString();const timer=setTimeout(()=>{if(job.state!=="waiting-user")return;jobStop.abort();void trace.step("waiting_for_user","failed",{error:"timeout"});job.state="failed";job.error={code:"authorization_timeout",message:"Google authorization timed out; start a new connection."};finish(job)},deadline);const cancel=()=>{if(job.state==="waiting-user")job.state="cancelled";jobStop.abort();finish(job)};listeners.set(job.id,{server,timer,cancel,detach:()=>options.signal?.removeEventListener("abort",cancel)});options.signal?.addEventListener("abort",cancel,{once:true});if(options.signal?.aborted){cancel();return ok({...job})}await trace.step("waiting_for_user","waiting",{mode:"manual",action:"request_manual"});job.instructions="Complete this source\u2019s Google authorization in the existing signed-in browser. The original state-checked callback verifies the account and saves its grant.";if(options.manualPresentation!=="return-url"){try{await trace.step("browser_opened","started");await openUrl(job.authorizationUrl);await trace.step("browser_opened","completed")}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.instructions+=" The page could not be opened automatically; use authorizationUrl with the available browser tools."}}return ok({...job})}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.state="failed";job.error={code:"browser_open_failed",message:"Could not open the Google consent page."};finish(job);return ok({...job})}},job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","Authorization job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const resources=listeners.get(id);if(job.state==="waiting-user"){if(resources?.cancel)resources.cancel();else{job.state="cancelled";finish(job)}}else if(resources&&!resources.finished)resources.cancel?.();delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:listeners.has(id)?"pending":"confirmed"})},async accounts(source){const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition","Account binding custody is unavailable.");const rows=await custody.bindings(source);if(!("ok"in rows))return rows;const accounts=[];for(const binding of rows.ok){const subject=binding.identity.subject;if(typeof subject!=="string"||!subject)continue;const grant=await custody.grantForBinding(binding.id,"L1","google");if(!("ok"in grant))return grant;accounts.push({bindingId:binding.id,account:binding.account,subject,state:binding.state,scopes:grant.ok?[...grant.ok.scopes]:[]})}return ok(accounts)},async request(source,url,options={}){if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}if(!permitted(source,endpoint,"GET"))return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;try{const value=await json(url,{headers:{Authorization:"Bearer "+selected.ok.credential.accessToken,Accept:"application/json"},...options.signal?{signal:options.signal}:{}});const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return after;const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;return closed?fail("unavailable","Google authorization is inactive."):options.signal?.aborted?fail("aborted","Google request cancelled."):ok(value)}catch{return fail(options.signal?.aborted?"aborted":"unavailable",options.signal?.aborted?"Google request cancelled.":"Google API request failed; reconnect if the grant has expired.")}},async requestRaw(source,url,options={}){if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");const method=options.method??"GET";if(!["GET","POST","PUT","PATCH","DELETE"].includes(method)||options.body!==void 0&&(typeof options.body!=="string"||Buffer.byteLength(options.body)>2097152)||method==="GET"&&options.body!==void 0)return fail("invalid_argument","Google request method/body is outside the bounded source contract.");if(options.responseType!==void 0&&options.responseType!=="text"&&options.responseType!=="bytes")return fail("invalid_argument","Google response type must be text or bytes.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}const readBatch=source==="gmail"&&isGmailReadBatch(endpoint,method,options.contentType,options.body);if(options.contentType!==void 0&&!/^(application\/(json|octet-stream)|text\/plain|(?:video|audio)\/[a-z0-9.+-]+)$/.test(options.contentType)&&!readBatch)return fail("invalid_argument","Google content type is outside the bounded source contract.");if(!permitted(source,endpoint,method)&&!readBatch)return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source,method==="GET"||readBatch);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const credential=selected.ok.credential;if(method!=="GET"&&!readBatch){const required=source==="google-tasks"?["https://www.googleapis.com/auth/tasks"]:source==="youtube"?["https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]:source==="google-calendar"?["https://www.googleapis.com/auth/calendar"]:[];if(!required.some(scope=>credential.scopes.includes(scope))||selected.ok.snapshot&&!required.some(scope=>selected.ok.snapshot.grant.scopes.includes(scope)))return fail("permission_denied","This source grant does not authorize mutation; use its explicit write enrollment.")}if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(options.body?.includes(secret)||endpoint.href.includes(secret)||endpoint.href.includes(encodeURIComponent(secret)))))return fail("permission_denied","Credential material may not appear in a provider object or destination.");const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);if(signal.aborted)return fail("aborted","Google request was stopped.");try{const response=await transport(endpoint.href,{method,headers:{Authorization:"Bearer "+credential.accessToken,Accept:"*/*",...options.body!==void 0?{"Content-Type":options.contentType??"application/json"}:{}},...options.body!==void 0?{body:options.body}:{},redirect:"error",signal});const chunks=[];let size=0;const reader=response.body?.getReader();if(!reader&&response.status!==204)return fail("data_loss","Google returned an empty response stream.");if(reader)for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>2*1024*1024){await reader.cancel();return fail("resource_exhausted","Google response exceeds the 2097152-byte body I-7 return-guard limit.")}chunks.push(part.value)}const raw=Buffer.concat(chunks),body=raw.toString("utf8");if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(body.includes(secret)||raw.includes(secret))))return fail("permission_denied","Google response reflected credential material; content was withheld.");const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return method!=="GET"&&!readBatch?fail("permission_denied","Google authorization could not be confirmed after the request. The mutation may have completed; its outcome is unknown and must not be automatically retried."):after;if(closed||signal.aborted)return fail("aborted","Google request was stopped.");const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;const headers={};for(const name2 of["content-type","retry-after"]){const value=response.headers.get(name2);if(value!==null)headers[name2]=value}return ok({status:response.status,body,headers,...options.responseType==="bytes"?{bytes:new Uint8Array(raw)}:{}})}catch{return fail(signal.aborted?"aborted":"unavailable",signal.aborted?"Google request cancelled.":"Google raw response could not be read.")}},close(){if(!closing){closed=true;stop.abort();for(const job of jobs.values())if(job.state==="waiting-user"){job.state="cancelled";finish(job)}closing=(async()=>{await Promise.allSettled([...callbacks,...refreshing.values()])})()}return closing}};return service}export function apply(ctx){const service=createGoogleAuth({vault:ctx.zortexVaultStore,transport:(input,options)=>(ctx.get("zortexConnectorHttp")??fetch)(input,options),tokenTransport:fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>ctx.get("zortexConnectionFeedback")});ctx.provide("zortexGoogleAuth",service);ctx.effect(()=>()=>service.close())}
1
+ import{createServer}from"node:http";import{createHash,randomBytes,randomUUID}from"node:crypto";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{isTransientConnectorAction}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{GOOGLE_TOKEN_URL,localGoogleDesktopClient,usesDirectGoogleOAuth}from"./desktop-client.js";import{isGmailReadBatch}from"./read-batch.js";import{createTraceRecorder}from"@zortexhq/plugin-telemetry/api";export const GOOGLE_PUBLIC_CLIENT_ID="230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com";export const DEFAULT_GOOGLE_BROKER_URL="https://zortex-google-oauth.google-oauth-broker.workers.dev";export const name="zortex-google-auth";export const inject=["zortexVaultStore","zortexConnectorHttp"];class GoogleHttpFailure extends Error{status;constructor(status){super("Google endpoint returned a failed status.");this.status=status}}const scopes={gmail:"https://mail.google.com/ openid email","google-drive":"https://www.googleapis.com/auth/drive","google-calendar":"https://www.googleapis.com/auth/calendar",youtube:"https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/yt-analytics.readonly openid email","google-tasks":"https://www.googleapis.com/auth/tasks openid email"};const gmailReadScope="https://www.googleapis.com/auth/gmail.readonly";const gmailReadScopes=[gmailReadScope,"https://www.googleapis.com/auth/gmail.modify","https://mail.google.com/"];const driveReadScopes=["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive"];const oidc="https://openidconnect.googleapis.com/v1/userinfo";const identity={gmail:oidc,"google-drive":"https://www.googleapis.com/drive/v3/about?fields=user(permissionId,emailAddress)","google-calendar":"https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=1",youtube:oidc,"google-tasks":oidc};const allowed={gmail:{origin:"https://gmail.googleapis.com",prefix:"/gmail/v1/"},"google-drive":{origin:"https://www.googleapis.com",prefix:"/drive/v3/"},"google-calendar":{origin:"https://www.googleapis.com",prefix:"/calendar/v3/"},youtube:{origin:"https://www.googleapis.com",prefix:"/youtube/v3/"},"google-tasks":{origin:"https://tasks.googleapis.com",prefix:"/tasks/v1/"}};const permitted=(source,endpoint,method)=>{if(endpoint.username||endpoint.password||endpoint.hash)return false;const boundary=allowed[source];if(boundary&&endpoint.origin===boundary.origin&&endpoint.pathname.startsWith(boundary.prefix))return true;if(source==="youtube"&&method==="GET"&&(endpoint.origin==="https://youtubeanalytics.googleapis.com"&&endpoint.pathname.startsWith("/v2/")||endpoint.origin==="https://youtubereporting.googleapis.com"&&endpoint.pathname.startsWith("/v1/")))return true;return source==="google-drive"&&method==="GET"&&(endpoint.origin==="https://docs.googleapis.com"&&/^\/v1\/documents\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname)||endpoint.origin==="https://sheets.googleapis.com"&&/^\/v4\/spreadsheets\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname))};export const openSystemUrl=openConnectionUrl;export function createGoogleAuth({vault,desktopClient=localGoogleDesktopClient,transport=fetch,tokenTransport=transport,openUrl=openSystemUrl,timeoutMs=6e5,now=Date.now,metrics,feedback}){const jobs=new Map,jobModes=new WeakMap;const listeners=new Map;const stop=new AbortController;const refreshing=new Map,callbacks=new Set;let closed=false,closing;const fail=(code,message)=>businessError(code,message,"plugin");async function json(url,options={},send=transport){if(closed)throw Error("google_auth_inactive");const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const response=await send(url,{...options,redirect:"error",signal});if(!response.ok){await response.body?.cancel().catch(()=>{});throw new GoogleHttpFailure(response.status)}const reader=response.body?.getReader();if(!reader)throw Error("empty_response");const chunks=[];let size=0;for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>2*1024*1024){await reader.cancel();throw Error("response_too_large")}chunks.push(part.value)}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}function directToken(client,fields,signal){return json(GOOGLE_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:client.clientId,client_secret:client.clientSecret,...fields}),...signal?{signal}:{}},tokenTransport)}const missingDesktopClient=source=>businessError("failed_precondition",`Zortex Google OAuth client configuration is unavailable. The product administrator must restore the registered client; reconnecting the account cannot repair product configuration. For self-managed installs, save the Google-downloaded Desktop app client JSON with {"installed":{"client_id":"<id>.apps.googleusercontent.com","client_secret":"<secret>"}} as ~/.zortex/google-oauth/${source}.json (directory 0700, file 0600), or set ZORTEX_GOOGLE_OAUTH_CLIENT_ID and ZORTEX_GOOGLE_OAUTH_CLIENT_SECRET, then retry the connection.`,"plugin");const configuredClient=async source=>{const client=await desktopClient(source);return client?.clientId===GOOGLE_PUBLIC_CLIENT_ID?void 0:client};function releaseListener(id){const entry=listeners.get(id);if(entry?.finished&&entry.serverClosed&&!entry.task)listeners.delete(id)}function finish(job){const resources=listeners.get(job.id);if(resources&&!resources.finished){resources.finished=true;clearTimeout(resources.timer);resources.detach?.();resources.server.closeAllConnections();resources.server.close(error=>{resources.serverClosed=!error||error.code==="ERR_SERVER_NOT_RUNNING";releaseListener(job.id)});releaseListener(job.id)}delete job.authorizationUrl;delete job.instructions}async function access(source,bindingId){if(isTransientConnectorAction()&&!bindingId)return readAccess(source);const key=bindingId?source+":"+bindingId:source;let task=refreshing.get(key);if(!task){task=readAccess(source,bindingId);refreshing.set(key,task)}try{const result=await task;return closed?fail("unavailable","Google authorization is inactive."):result}finally{if(refreshing.get(key)===task)refreshing.delete(key)}}async function readAccess(source,bindingId){const custody=vault.bindingCustody;let found,snapshot;const choices=source==="google-tasks"?["https://www.googleapis.com/auth/tasks.readonly","https://www.googleapis.com/auth/tasks"]:source==="youtube"?["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]:source==="google-calendar"?["https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/calendar"]:source==="gmail"?["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.modify","https://mail.google.com/"]:driveReadScopes;const hasReadScope=granted=>Array.isArray(granted)&&choices.some(scope=>granted.includes(scope));const direct=usesDirectGoogleOAuth(source);const client=direct?await configuredClient(source):void 0;const sealedClient=credential=>credential.clientAuthentication?.method==="client_secret_post"&&credential.clientAuthentication.secret&&(credential.clientAuthentication.expiresAt===void 0||credential.clientAuthentication.expiresAt>now())?{clientId:credential.clientId,clientSecret:credential.clientAuthentication.secret}:void 0;const originalBroker=credential=>source!=="google-tasks"&&credential.clientId===GOOGLE_PUBLIC_CLIENT_ID&&!credential.clientAuthentication;const requiresTasksReconnect=credential=>source==="google-tasks"&&!sealedClient(credential)&&credential.clientId!==client?.clientId;const reconnect=()=>fail("failed_precondition","Reconnect this source with its Google Desktop OAuth client.");const reconnectTasks=()=>client?reconnect():missingDesktopClient("google-tasks");const refreshConfigurationError=credential=>{if(sealedClient(credential)||originalBroker(credential))return;if(direct&&!client)return missingDesktopClient(source);if(!direct&&credential.clientId!==GOOGLE_PUBLIC_CLIENT_ID)return fail("failed_precondition","The original Google OAuth client configuration is unavailable. Product configuration must be restored before refreshing this grant.");if(client&&credential.clientId!==client.clientId)return missingDesktopClient(source)};const authorized=current=>current.material.kind!=="oauth"||current.resource.owner.kind!=="resident"?fail("failed_precondition","Google credential resource is not owned by the resident."):!hasReadScope(current.grant.scopes)||!hasReadScope(current.material.credential.scopes)?fail("permission_denied","The stored grant lacks the selected source read scope."):requiresTasksReconnect(current.material.credential)?reconnectTasks():ok({credential:current.material.credential,snapshot:current});if(custody){let resolution=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!bindingId&&"ok"in resolution&&resolution.ok.kind==="legacy-unattributed"&&custody.recoverLegacy){let expired;const verify=async(connection,credential)=>{if(requiresTasksReconnect(credential))return reconnectTasks();if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(credential.scopes))return fail("permission_denied","The legacy Google credential lacks the selected read scope. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(credential.expiresAt<=now()+6e4){if(credential.refreshToken)expired=credential;return fail("failed_precondition","The legacy Google credential has expired. Open zortex help for explicit account recovery; ordinary reconnect does not resolve mixed legacy history.")}try{return ok(await verifyLegacyIdentity(source,credential.accessToken))}catch{return fail("failed_precondition","Google could not verify the original legacy account. Open zortex help for explicit account recovery; preserve its legacy history and do not retry ordinary reconnect to clear ambiguity.")}};let recovered=await custody.recoverLegacy(source,verify);if(!("ok"in recovered)&&expired&&custody.refreshLegacyCredential){const configurationError2=refreshConfigurationError(expired);if(configurationError2)return configurationError2;const refreshedLegacy=await custody.refreshLegacyCredential(source,expired,async(connection,current2)=>{if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(current2.scopes)||!current2.refreshToken)return fail("failed_precondition","Legacy Google authorization cannot be recovered with its original grant. Open zortex help for account recovery.");const next2=await refreshed(current2,false);return"ok"in next2?next2:fail("err"in next2?next2.err.code:"internal","The original legacy Google grant could not be refreshed. Preserve this Vault and open zortex help for account recovery; do not repeat ordinary reconnect to clear mixed history.")});if(!("ok"in refreshedLegacy))return refreshedLegacy;recovered=await custody.recoverLegacy(source,verify)}if(!("ok"in recovered))return recovered;resolution=ok({kind:"resolved",binding:recovered.ok})}if(!("ok"in resolution)||resolution.ok.kind!=="resolved")return"err"in resolution?resolution:fail("failed_precondition","Google source needs an explicitly selected account binding. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(resolution.ok.binding.identity.source!==source)return fail("permission_denied","The selected account binding belongs to another source.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"google"});if(!("ok"in current))return current;snapshot=current.ok;found=authorized(snapshot)}else{const legacy=await vault.credential(source);found="ok"in legacy?ok({credential:legacy.ok}):legacy}if(!("ok"in found))return"err"in found?found:fail("failed_precondition","Google source is not connected.");if(requiresTasksReconnect(found.ok.credential))return reconnectTasks();if((source==="google-tasks"||source==="youtube")&&!hasReadScope(found.ok.credential.scopes))return fail("permission_denied","The stored grant lacks the selected source read scope.");if(found.ok.credential.expiresAt>now()+6e4)return found;if(!found.ok.credential.refreshToken)return fail("unauthenticated","Google authorization expired. Start the connection flow again.");const configurationError=refreshConfigurationError(found.ok.credential);if(configurationError)return configurationError;async function refreshed(current,pinClient=true){const configurationError2=refreshConfigurationError(current);if(configurationError2)return configurationError2;if(!current.refreshToken)return fail("unauthenticated","Google authorization expired. Start the connection flow again.");const issuingClient=originalBroker(current)?void 0:sealedClient(current)??client;try{const token=issuingClient?await directToken(issuingClient,{grant_type:"refresh_token",refresh_token:current.refreshToken}):await json(DEFAULT_GOOGLE_BROKER_URL+"/google/refresh",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId:current.clientId,refreshToken:current.refreshToken})});if(typeof token.access_token!=="string"||!token.access_token||!Number.isFinite(token.expires_in)||token.expires_in<=0||token.refresh_token!==void 0&&(typeof token.refresh_token!=="string"||!token.refresh_token))throw Error("invalid_token_response");return ok({...current,...issuingClient&&pinClient?{clientAuthentication:{method:"client_secret_post",secret:issuingClient.clientSecret}}:{},accessToken:token.access_token,...token.refresh_token!==void 0?{refreshToken:token.refresh_token}:{},expiresAt:now()+token.expires_in*1e3})}catch(error){return error instanceof GoogleHttpFailure&&[400,401,403].includes(error.status)?fail("unauthenticated","Google authorization is no longer accepted. Reconnect this source."):fail("unavailable","Google authorization refresh did not complete; no missing grant was assumed.")}}if(custody&&snapshot){const stored2=await custody.refreshResource(snapshot,{kind:"resident"},async current2=>{const permitted2=authorized(current2);if(!("ok"in permitted2))return permitted2;const next2=await refreshed(permitted2.ok.credential);return"ok"in next2?ok({kind:"oauth",credential:next2.ok}):next2});if("ok"in stored2)return authorized(stored2.ok);if(!("err"in stored2)||stored2.err.code!=="failed_precondition")return stored2;const current=await custody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const winner=authorized(current.ok);return current.ok.resource.revision>snapshot.resource.revision&&"ok"in winner&&winner.ok.credential.expiresAt>now()+6e4?winner:stored2}const next=await refreshed(found.ok.credential);if(!("ok"in next))return next;const stored=await vault.updateCredential(source,next.ok);return"ok"in stored?ok({credential:next.ok}):"err"in stored?stored:fail("internal","Credential update was not confirmed.")}async function checkAccess(source,selected,bindingId){const custody=vault.bindingCustody,expected=selected.snapshot;if(!custody)return ok(void 0);const changed=()=>fail("permission_denied","The selected Google account, grant or credential changed during the request; its response was withheld.");if(!expected)return changed();const current=await custody.credentialSnapshot(expected.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const resolved=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved"||resolved.ok.binding.id!==expected.binding.id||resolved.ok.binding.revision!==expected.binding.revision)return changed();return current.ok.binding.id===expected.binding.id&&current.ok.binding.revision===expected.binding.revision&&current.ok.grant.id===expected.grant.id&&current.ok.grant.revision===expected.grant.revision&&current.ok.grant.scopeEpoch===expected.grant.scopeEpoch&&current.ok.resource.id===expected.resource.id&&current.ok.resource.revision===expected.resource.revision?ok(void 0):changed()}async function captureSelection(source,readOnly=true){const custody=vault.bindingCustody;if(!custody?.sourceSelection)return ok(async()=>ok(void 0));const found=await custody.sourceSelection(source);if(!("ok"in found))return found;if(found.ok&&!isTransientConnectorAction())return fail("failed_precondition","This explicitly recovered account supports transient L1 reads. Source-only history sync remains disabled; use zortex help to read the selected account.");if(found.ok&&!readOnly)return fail("permission_denied","Explicit account recovery authorizes bounded reads only.");const expected=found.ok;return ok(async()=>{const current=await custody.sourceSelection(source);if(!("ok"in current))return current;return current.ok?.bindingId===expected?.bindingId&&current.ok?.revision===expected?.revision?ok(void 0):fail("permission_denied","The selected account changed during this request; its response was withheld.")})}async function verifyLegacyIdentity(source,accessToken){const headers={Authorization:"Bearer "+accessToken};let profile=await json(identity[source],{headers});if(source==="google-drive"){const subject=profile.user?.permissionId,account=profile.user?.emailAddress??subject;if(typeof subject!=="string"||!subject.trim()||subject.length>500||typeof account!=="string"||!account)throw Error("drive_identity_not_confirmed");return{accountId:subject,account}}if(source==="google-calendar"){const seen=new Set;for(let page=0;page<20;page++){if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){const subject=primary[0].id;if(typeof subject!=="string"||!subject.trim()||subject.length>500)throw Error("invalid_calendar_identity");return{accountId:subject,account:subject}}const next=profile.nextPageToken;if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("primary_calendar_not_found");seen.add(next);const url=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url.searchParams.set("maxResults","250");url.searchParams.set("pageToken",next);url.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url.href,{headers})}throw Error("calendar_identity_budget_exceeded")}if(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)||typeof profile.email!=="string"||!profile.email)throw Error("account_not_confirmed");return{accountId:profile.sub,account:profile.email}}const service={async connect(source,options={}){if(options.automatic===true)return fail("invalid_argument","Automatic enrollment is retired. Open the source connection gateway.");options={...options,automatic:false};if(options.signal?.aborted)return fail("aborted","Google authorization cancelled.");if(options.selectAccount!==void 0&&(options.selectAccount!==true||options.automatic!==false))return fail("invalid_argument","Explicit account selection requires manual recovery.");if(options.gmailWrite!==void 0&&(options.gmailWrite!==true||source!=="gmail"||options.automatic!==false||options.selectAccount||options.reauthorize))return fail("invalid_argument","Gmail write consent requires an explicit same-account manual authorization.");const custodyForWrite=options.gmailWrite?vault.bindingCustody:void 0;if(options.gmailWrite&&(!custodyForWrite?.sourceSelection||!custodyForWrite.resolve))return fail("failed_precondition","A selected Gmail account is required before requesting write access.");const writeSelection=options.gmailWrite?await custodyForWrite.sourceSelection("gmail"):void 0;if(writeSelection&&!("ok"in writeSelection))return writeSelection;const writeBinding=options.gmailWrite?await custodyForWrite.resolve(writeSelection&&"ok"in writeSelection&&writeSelection.ok?{kind:"binding",bindingId:writeSelection.ok.bindingId}:{kind:"legacy-source",source:"gmail"}):void 0;if(writeBinding&&(!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeBinding.ok.binding.identity.source!=="gmail"||writeBinding.ok.binding.provider!=="google"||!writeBinding.ok.binding.identity.subject))return fail("failed_precondition","Select a verified Gmail account before requesting write access.");const writeInventory=writeBinding&&"ok"in writeBinding&&writeBinding.ok.kind==="resolved"?await custodyForWrite.bindingInventory(writeBinding.ok.binding.id):void 0;if(options.gmailWrite&&(!writeInventory||!("ok"in writeInventory)||!writeInventory.ok))return fail("failed_precondition","Gmail credential custody is unavailable.");const writeTarget=writeInventory&&"ok"in writeInventory?writeInventory.ok:void 0;const writeGrant=writeTarget?.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const writeResource=writeTarget?.resources.find(r=>r.id===oauthCredentialResourceId(writeTarget.binding.id));if(options.gmailWrite&&(!writeTarget||!writeGrant||!writeResource||!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeTarget.binding.revision!==writeBinding.ok.binding.revision))return fail("failed_precondition","Gmail credential custody changed.");if(options.selectAccount&&(!vault.bindingCustody?.sourceSelection||!vault.bindingCustody.selectSourceBinding))return fail("failed_precondition","This Vault does not support explicit account recovery.");const selectionBefore=options.selectAccount?await vault.bindingCustody.sourceSelection(source):ok(null);if(!("ok"in selectionBefore))return selectionBefore;const direct=usesDirectGoogleOAuth(source);const client=direct?await configuredClient(source):void 0;if(direct&&!client)return missingDesktopClient(source);const clientId=client?.clientId??GOOGLE_PUBLIC_CLIENT_ID;const requestedScopes=source==="gmail"&&!options.gmailWrite?`${gmailReadScope} openid email`:scopes[source];const interactionMode=options.manualPresentation==="return-url"?"manual-return-url":"manual-open";const deadline=timeoutMs;if(closed)return fail("unavailable","Google authorization is inactive.");if(!Object.hasOwn(scopes,source))return fail("invalid_argument","Unknown Google source.");const running=[...jobs.values()].find(job2=>job2.source===source&&job2.state==="waiting-user");if(running&&(options.selectAccount||options.gmailWrite))return fail("failed_precondition","Wait for the current authorization to finish before explicit account recovery.");if(running)return jobModes.get(running)!==interactionMode?fail("failed_precondition","Previous source authorization uses a different interaction mode. Wait for its owned cleanup."):ok({...running});if([...listeners].some(([id])=>jobs.get(id)?.source===source))return fail("failed_precondition","Previous source authorization still owns active work. Wait for cleanup.");const job={id:randomUUID(),source,state:"waiting-user",startedAt:new Date(now()).toISOString()};jobModes.set(job,interactionMode);jobs.set(job.id,job);const jobStop=new AbortController,jobSignal=AbortSignal.any([stop.signal,jobStop.signal,...options.signal?[options.signal]:[]]);const trace=createTraceRecorder(metrics,source);let stage="callback_received";await trace.step("authorization_started","started");const verifier=randomBytes(48).toString("base64url"),state=randomBytes(24).toString("base64url");let used=false;let redirectUri="";const server=createServer((request,response)=>{const url=new URL(request.url??"/",redirectUri);if(request.method!=="GET"||url.pathname!=="/callback"){response.writeHead(404).end("Not found.");return}if(url.searchParams.get("state")!==state){response.writeHead(400).end("Invalid authorization state.");return}if(used){response.writeHead(409).end("Authorization callback already received.");return}const code=url.searchParams.get("code"),error=url.searchParams.get("error");if(error||!code){used=true;job.state="failed";job.error={code:"authorization_denied",message:"Google authorization was not completed."};void trace.step("callback_received","failed",{error:"denied"});response.writeHead(400).end("Authorization was not completed.");finish(job);return}used=true;response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}).end("Authorization received. Zortex is validating the connection. You may close this page.");const callback=(async()=>{try{await trace.step("callback_received","completed");stage="token_exchange";await trace.step(stage,"started");const exchange=()=>client?directToken(client,{grant_type:"authorization_code",code,code_verifier:verifier,redirect_uri:redirectUri},jobSignal):json(DEFAULT_GOOGLE_BROKER_URL+"/google/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId,code,codeVerifier:verifier,redirectUri}),signal:jobSignal});const token=await exchange();if(!token.access_token||!Number.isFinite(token.expires_in))throw Error("invalid_token_response");const granted=(token.scope??requestedScopes).split(" ");if(source==="google-drive"?!driveReadScopes.some(scope=>granted.includes(scope)):source==="gmail"?!((options.gmailWrite?granted.includes("https://mail.google.com/"):gmailReadScopes.some(scope=>granted.includes(scope)))&&granted.includes("openid")&&(granted.includes("email")||granted.includes("https://www.googleapis.com/auth/userinfo.email"))):!requestedScopes.split(" ").every(scope=>granted.includes(scope)||scope==="email"&&granted.includes("https://www.googleapis.com/auth/userinfo.email")))throw Error("required_scope_missing");await trace.step(stage,"completed");stage="identity_verified";await trace.step(stage,"started");let profile=await json(identity[source],{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal});let calendarAccount;if(source==="google-calendar"){const seen=new Set;for(let page=0;page<50;page++){if(closed||job.state!=="waiting-user")throw Error("connection_cancelled");if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){if(typeof primary[0].id!=="string"||!primary[0].id.trim()||primary[0].id.length>500)throw Error("invalid_calendar_identity");calendarAccount=primary[0].id;break}const next=profile.nextPageToken;if(next===void 0)throw Error("primary_calendar_not_found");if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("invalid_calendar_identity_cursor");seen.add(next);const url2=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url2.searchParams.set("maxResults","250");url2.searchParams.set("pageToken",next);url2.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url2.href,{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal})}if(!calendarAccount)throw Error("calendar_identity_budget_exceeded")}const oidcSource=source==="gmail"||source==="youtube"||source==="google-tasks";const account=source==="google-drive"?profile.user?.emailAddress??profile.user?.permissionId:oidcSource?profile.email:calendarAccount;if(source==="google-drive"&&(typeof profile.user?.permissionId!=="string"||!profile.user.permissionId.trim()||profile.user.permissionId.length>500))throw Error("drive_identity_not_confirmed");if(oidcSource&&(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)))throw Error("account_not_confirmed");if(typeof account!=="string"||!account)throw Error("account_not_confirmed");let readGuard=null;if(source==="gmail"&&!options.gmailWrite&&vault.bindingCustody){const known=await vault.bindingCustody.bindings("gmail");if(!("ok"in known))throw Error("gmail_existing_grant_unavailable");const previous=known.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===profile.sub);if(previous.length>1)throw Error("gmail_existing_grant_unavailable");readGuard=null;for(const binding of previous){const inventory=await vault.bindingCustody.bindingInventory(binding.id);if(!("ok"in inventory)||!inventory.ok)throw Error("gmail_existing_grant_unavailable");const existing=inventory.ok.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const resource=inventory.ok.resources.find(r=>r.id===oauthCredentialResourceId(binding.id));if(!existing||!resource||inventory.ok.binding.revision!==binding.revision)throw Error("gmail_existing_grant_unavailable");readGuard={bindingId:binding.id,bindingRevision:binding.revision,grantId:existing.id,grantRevision:existing.revision,resourceId:resource.id,resourceRevision:resource.revision};const writable=(existing.scopes??[]).filter(scope=>scope==="https://mail.google.com/"||/^https:\/\/www\.googleapis\.com\/auth\/gmail\.(modify|compose|send|insert|labels|settings\.basic|settings\.sharing)$/.test(scope));if(writable.some(scope=>!granted.includes(scope))&&!granted.includes("https://mail.google.com/"))throw Error("gmail_write_scope_would_be_lost")}}if(options.gmailWrite){if(!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||profile.sub!==writeBinding.ok.binding.identity.subject)throw Error("gmail_write_account_mismatch");const selection=await custodyForWrite.sourceSelection("gmail");if(!("ok"in selection)||!writeSelection||!("ok"in writeSelection)||selection.ok?.revision!==writeSelection.ok?.revision||selection.ok?.bindingId!==writeSelection.ok?.bindingId)throw Error("gmail_write_selection_changed");const current=await custodyForWrite.resolve(selection.ok?{kind:"binding",bindingId:selection.ok.bindingId}:{kind:"legacy-source",source:"gmail"});if(!("ok"in current)||current.ok.kind!=="resolved"||current.ok.binding.id!==writeBinding.ok.binding.id||current.ok.binding.revision!==writeBinding.ok.binding.revision||current.ok.binding.identity.subject!==profile.sub)throw Error("gmail_write_binding_changed")}if(closed||job.state!=="waiting-user")return;const credential={accessToken:token.access_token,...token.refresh_token?{refreshToken:token.refresh_token}:{},...client?{clientAuthentication:{method:"client_secret_post",secret:client.clientSecret}}:{},expiresAt:now()+token.expires_in*1e3,clientId,scopes:granted};await trace.step(stage,"completed");stage="credentials_saved";await trace.step(stage,"started");if(closed||job.state!=="waiting-user")return;const stored=await vault.saveConnection({source,provider:"google",account,...oidcSource?{accountId:String(profile.sub)}:source==="google-calendar"?{accountId:account}:source==="google-drive"?{accountId:String(profile.user.permissionId)}:{},scopes:granted,state:"connected",updatedAt:new Date(now()).toISOString()},credential,{signal:jobSignal,...source==="gmail"&&!options.gmailWrite&&vault.bindingCustody?{expectedCredential:readGuard}:{},...options.gmailWrite&&writeTarget&&writeGrant&&writeResource&&writeSelection&&"ok"in writeSelection?{expectedCredential:{bindingId:writeTarget.binding.id,bindingRevision:writeTarget.binding.revision,grantId:writeGrant.id,grantRevision:writeGrant.revision,resourceId:writeResource.id,resourceRevision:writeResource.revision},selectSource:{expectedSelectionRevision:writeSelection.ok?.revision??null,expectedBindingRevision:writeTarget.binding.revision}}:{}});if(!("ok"in stored))throw Error("credential_store_failed");if(closed)return;if(options.selectAccount){if(jobSignal.aborted||job.state!=="waiting-user")return;const custody=vault.bindingCustody,found=await custody.bindings(source);if(!("ok"in found))throw Error("account_selection_failed");const matches=found.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===stored.ok.accountId&&binding.account===stored.ok.account&&binding.updatedAt===stored.ok.updatedAt);if(matches.length!==1||jobSignal.aborted||job.state!=="waiting-user")throw Error("account_selection_failed");const selected=await custody.selectSourceBinding(source,matches[0].id,matches[0].revision,selectionBefore.ok?.revision??null);if(!("ok"in selected))throw Error("account_selection_failed")}if(closed||job.state!=="waiting-user")return;await trace.step(stage,"completed");await feedback?.()?.bind(stored.ok,trace.flow);if(closed||job.state!=="waiting-user")return;job.state="connected";job.account=account}catch(error2){await trace.step(stage,stop.signal.aborted?"cancelled":"failed",{error:jobStop.signal.aborted?"timeout":stage==="credentials_saved"?"storage":error2 instanceof GoogleHttpFailure?"provider":"unknown",...error2 instanceof GoogleHttpFailure&&error2.status>=100&&error2.status<=599?{statusCode:error2.status}:{}});if(!closed&&job.state==="waiting-user"){job.state="failed";job.error=error2 instanceof Error&&error2.message==="gmail_write_scope_would_be_lost"?{code:"permission_denied",message:"The existing Gmail account has write access. To preserve it, open Zortex Help and choose Grant full Gmail access."}:{code:"google_connection_failed",message:"Google authorization or account validation failed. No successful connection was confirmed."}}}finally{finish(job)}})();callbacks.add(callback);const owned=listeners.get(job.id);if(owned)owned.task=callback;const release=()=>{callbacks.delete(callback);if(owned)delete owned.task;releaseListener(job.id)};void callback.then(release,release)});try{await new Promise((done,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error("callback_unavailable");redirectUri=`http://127.0.0.1:${address.port}/callback`;const url=new URL("https://accounts.google.com/o/oauth2/v2/auth");for(const[key,value]of Object.entries({response_type:"code",client_id:clientId,redirect_uri:redirectUri,scope:requestedScopes,access_type:"offline",prompt:options.selectAccount?"select_account consent":"consent",code_challenge:createHash("sha256").update(verifier).digest("base64url"),code_challenge_method:"S256",state}))url.searchParams.set(key,value);job.authorizationUrl=url.toString();const timer=setTimeout(()=>{if(job.state!=="waiting-user")return;jobStop.abort();void trace.step("waiting_for_user","failed",{error:"timeout"});job.state="failed";job.error={code:"authorization_timeout",message:"Google authorization timed out; start a new connection."};finish(job)},deadline);const cancel=()=>{if(job.state==="waiting-user")job.state="cancelled";jobStop.abort();finish(job)};listeners.set(job.id,{server,timer,cancel,detach:()=>options.signal?.removeEventListener("abort",cancel)});options.signal?.addEventListener("abort",cancel,{once:true});if(options.signal?.aborted){cancel();return ok({...job})}await trace.step("waiting_for_user","waiting",{mode:"manual",action:"request_manual"});job.instructions="Complete this source\u2019s Google authorization in the existing signed-in browser. The original state-checked callback verifies the account and saves its grant.";if(options.manualPresentation!=="return-url"){try{await trace.step("browser_opened","started");await openUrl(job.authorizationUrl);await trace.step("browser_opened","completed")}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.instructions+=" The page could not be opened automatically; use authorizationUrl with the available browser tools."}}return ok({...job})}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.state="failed";job.error={code:"browser_open_failed",message:"Could not open the Google consent page."};finish(job);return ok({...job})}},job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","Authorization job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const resources=listeners.get(id);if(job.state==="waiting-user"){if(resources?.cancel)resources.cancel();else{job.state="cancelled";finish(job)}}else if(resources&&!resources.finished)resources.cancel?.();delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:listeners.has(id)?"pending":"confirmed"})},async accounts(source){const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition","Account binding custody is unavailable.");const rows=await custody.bindings(source);if(!("ok"in rows))return rows;const accounts=[];for(const binding of rows.ok){const subject=binding.identity.subject;if(typeof subject!=="string"||!subject)continue;const grant=await custody.grantForBinding(binding.id,"L1","google");if(!("ok"in grant))return grant;accounts.push({bindingId:binding.id,account:binding.account,subject,state:binding.state,scopes:grant.ok?[...grant.ok.scopes]:[]})}return ok(accounts)},async request(source,url,options={}){if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}if(!permitted(source,endpoint,"GET"))return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;try{const value=await json(url,{headers:{Authorization:"Bearer "+selected.ok.credential.accessToken,Accept:"application/json"},...options.signal?{signal:options.signal}:{}});const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return after;const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;return closed?fail("unavailable","Google authorization is inactive."):options.signal?.aborted?fail("aborted","Google request cancelled."):ok(value)}catch{return fail(options.signal?.aborted?"aborted":"unavailable",options.signal?.aborted?"Google request cancelled.":"Google API request failed; reconnect if the grant has expired.")}},async requestRaw(source,url,options={}){if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");const method=options.method??"GET";if(!["GET","POST","PUT","PATCH","DELETE"].includes(method)||options.body!==void 0&&(typeof options.body!=="string"||Buffer.byteLength(options.body)>2097152)||method==="GET"&&options.body!==void 0)return fail("invalid_argument","Google request method/body is outside the bounded source contract.");if(options.responseType!==void 0&&options.responseType!=="text"&&options.responseType!=="bytes")return fail("invalid_argument","Google response type must be text or bytes.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}const readBatch=source==="gmail"&&isGmailReadBatch(endpoint,method,options.contentType,options.body);if(options.contentType!==void 0&&!/^(application\/(json|octet-stream)|text\/plain|(?:video|audio)\/[a-z0-9.+-]+)$/.test(options.contentType)&&!readBatch)return fail("invalid_argument","Google content type is outside the bounded source contract.");if(!permitted(source,endpoint,method)&&!readBatch)return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source,method==="GET"||readBatch);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const credential=selected.ok.credential;if(method!=="GET"&&!readBatch){const required=source==="google-tasks"?["https://www.googleapis.com/auth/tasks"]:source==="youtube"?["https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]:source==="google-calendar"?["https://www.googleapis.com/auth/calendar"]:[];if(!required.some(scope=>credential.scopes.includes(scope))||selected.ok.snapshot&&!required.some(scope=>selected.ok.snapshot.grant.scopes.includes(scope)))return fail("permission_denied","This source grant does not authorize mutation; use its explicit write enrollment.")}if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(options.body?.includes(secret)||endpoint.href.includes(secret)||endpoint.href.includes(encodeURIComponent(secret)))))return fail("permission_denied","Credential material may not appear in a provider object or destination.");const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);if(signal.aborted)return fail("aborted","Google request was stopped.");try{const response=await transport(endpoint.href,{method,headers:{Authorization:"Bearer "+credential.accessToken,Accept:"*/*",...options.body!==void 0?{"Content-Type":options.contentType??"application/json"}:{}},...options.body!==void 0?{body:options.body}:{},redirect:"error",signal});const chunks=[];let size=0;const reader=response.body?.getReader();if(!reader&&response.status!==204)return fail("data_loss","Google returned an empty response stream.");if(reader)for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>2*1024*1024){await reader.cancel();return fail("resource_exhausted","Google response exceeds the 2097152-byte body I-7 return-guard limit.")}chunks.push(part.value)}const raw=Buffer.concat(chunks),body=raw.toString("utf8");if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(body.includes(secret)||raw.includes(secret))))return fail("permission_denied","Google response reflected credential material; content was withheld.");const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return method!=="GET"&&!readBatch?fail("permission_denied","Google authorization could not be confirmed after the request. The mutation may have completed; its outcome is unknown and must not be automatically retried."):after;if(closed||signal.aborted)return fail("aborted","Google request was stopped.");const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;const headers={};for(const name2 of["content-type","retry-after"]){const value=response.headers.get(name2);if(value!==null)headers[name2]=value}return ok({status:response.status,body,headers,...options.responseType==="bytes"?{bytes:new Uint8Array(raw)}:{}})}catch{return fail(signal.aborted?"aborted":"unavailable",signal.aborted?"Google request cancelled.":"Google raw response could not be read.")}},close(){if(!closing){closed=true;stop.abort();for(const job of jobs.values())if(job.state==="waiting-user"){job.state="cancelled";finish(job)}closing=(async()=>{await Promise.allSettled([...callbacks,...refreshing.values()])})()}return closing}};return service}export function apply(ctx){const service=createGoogleAuth({vault:ctx.zortexVaultStore,transport:(input,options)=>(ctx.get("zortexConnectorHttp")??fetch)(input,options),tokenTransport:fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>ctx.get("zortexConnectionFeedback")});ctx.provide("zortexGoogleAuth",service);ctx.effect(()=>()=>service.close())}
@@ -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";
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";
@@ -0,0 +1 @@
1
+ import{Parser}from"htmlparser2";const object=value=>value&&typeof value==="object"&&!Array.isArray(value)?value:{};const text=value=>typeof value==="string"?value:"";const first=(...values)=>values.map(text).find(value=>value.trim())??"";const ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};export function normalizeSearchText(input){let value=input.replace(/\r\n?/gu,"\n");if(/<\/?(?:html|body|div|p|br|a|span|table|script|style)\b/iu.test(value)){const output=[],hidden=[];const block=/^(?:div|p|br|li|tr|h[1-6]|blockquote)$/u;const parser=new Parser({onopentag(name,attrs){const suppress=!!hidden.at(-1)||/^(?:script|style|head)$/u.test(name)||Object.hasOwn(attrs,"hidden")||attrs["aria-hidden"]==="true"||/(?:display\s*:\s*none|visibility\s*:\s*hidden)/iu.test(attrs["style"]??"");hidden.push(suppress);if(!suppress&&block.test(name))output.push("\n")},ontext(value2){if(!hidden.at(-1))output.push(value2)},onclosetag(name){const suppress=hidden.pop();if(!suppress&&block.test(name))output.push("\n")}},{decodeEntities:true});parser.end(value);value=output.join("")}value=value.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/giu,(_,entity)=>{if(entity[0]!=="#")return ENTITIES[entity.toLowerCase()]??" ";const code=entity[1]?.toLowerCase()==="x"?parseInt(entity.slice(2),16):parseInt(entity.slice(1),10);return code>0&&code<=1114111&&!(code>=55296&&code<=57343)?String.fromCodePoint(code):" "});value=value.replace(/https?:\/\/[^\s<>]+/giu,url=>{try{const parsed=new URL(url);for(const key of[...parsed.searchParams.keys()])if(/^(?:utm_.+|fbclid|gclid|mc_cid|mc_eid|tracking_?id)$/iu.test(key))parsed.searchParams.delete(key);return parsed.toString()}catch{return url}});return value.normalize("NFKC").replace(/[\u200b-\u200d\u2060\ufeff]/gu,"").replace(/[\t\p{Zs}]+/gu," ").replace(/ *\n */gu,"\n").replace(/\n{3,}/gu,"\n\n").trim()}export function normalizeSearchDocument(input){const payload=object(input.payload),event=object(payload.event),message=object(payload.message);const title=normalizeSearchText(first(payload.title,payload.subject,payload.name,event.summary,message.subject,input.title));let body=input.source==="google-drive"?first(payload.content,input.body):input.source==="google-calendar"?[input.body,text(event.description),text(event.location)].filter(Boolean).join("\n"):input.body;body=normalizeSearchText(body);if(input.source==="gmail"||input.source==="outlook"){const at=body.search(/(?:^|\n)\s*(?:此邮件发送给|此邮件发送至|此电子邮件已发送至|this email was intended for|this email was sent to|this message was sent to)/iu);if(at>=0)body=body.slice(0,at).trimEnd()}return{title,body}}
@@ -0,0 +1 @@
1
+ import{projectSearchRecord}from"./search-records.js";function update(db,engine,base){const chain=engine.currentChain(base);if(!chain.head)return;const old=new Set;for(const identity of chain.identities){const row=db.query("SELECT event_id FROM current_record_heads WHERE source=? AND stream=? AND source_id=?").get(identity.source,identity.stream,identity.sourceId);if(row)old.add(row.event_id)}for(const identity of chain.identities)db.query("INSERT INTO current_record_heads(source,stream,source_id,event_id) VALUES(?,?,?,?) ON CONFLICT(source,stream,source_id) DO UPDATE SET event_id=excluded.event_id").run(identity.source,identity.stream,identity.sourceId,chain.head.id);for(const id of old)if(id!==chain.head.id&&!db.query("SELECT 1 FROM current_record_heads WHERE event_id=? LIMIT 1").get(id))db.query("DELETE FROM search_documents WHERE id=?").run(id);projectSearchRecord(db,chain.head.id)}export function updateCurrentRecords(db,engine,event){if(event.kind==="identity.rebind"){const payload=event.payload;if(payload?.from)update(db,engine,payload.from)}else update(db,engine,event.nk)}export function rebuildCurrentRecords(db,engine){db.exec("BEGIN IMMEDIATE");try{if(db.query("SELECT 1 FROM current_record_projection WHERE version=1").get()){db.exec("COMMIT");return}db.exec("DELETE FROM current_record_heads");for(const row of db.query("SELECT DISTINCT source,stream,source_id FROM events").all())update(db,engine,{source:row.source,stream:row.stream,sourceId:row.source_id});db.exec("INSERT INTO current_record_projection(version) VALUES(1)");db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}}
@@ -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{randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.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";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;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 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."})});this.facts=new LiftedRecordRules(this.db,saved,now,"system_events");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.");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()}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}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 row of streams){if(!row||Object.keys(row).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity"].includes(key2))||typeof row.source!=="string"||!row.source||typeof row.stream!=="string"||!row.stream||!Original.REV_ORDERS.includes(row.revOrder)||row.comparator!==void 0&&!["numeric","lex"].includes(row.comparator)||row.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(row.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=row.source+"\0"+row.stream,prior=incoming.get(key)??this.declarations.get(key);if(prior&&canonicalJson(prior)!==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 row of incoming.values()){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(row.source,row.stream);if(existing&&existing.definition!==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."})}this.db.query("INSERT OR IGNORE INTO source_streams(source,stream,definition) VALUES(?,?,?)").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")}};return{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)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0)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;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{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;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 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}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 +1 @@
1
- import{RecordEngine}from"@zortexhq/rooktrail/integration";import{buildStreamMap,lookupKind}from"./registry.js";import{ok,errResult}from"./original-contracts.js";export class LiftedRecordRules extends RecordEngine{constructor(db,streams,now,table,execution,authorizeConnector){super(db,streams,now,table,lookupKind,{systemSource:"zortex",buildStreams:buildStreamMap,...authorizeConnector?{authorizeConnector}:{},afterInsert(event,recordTable){if(recordTable==="events"&&execution){const owner=db.query("SELECT phase FROM connector_process_runs WHERE run_id=?").get(execution.runId);if(owner?.phase!=="active")return errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Execution no longer owns an active process run."});db.query("INSERT INTO event_executions(event_id,run_id,code_version) VALUES (?,?,?)").run(event.id,execution.runId,execution.codeVersion)}return ok(true)},authorityIncident(kind,origin){const entry=lookupKind(kind);if(!entry||!entry.verdictClass&&!entry.securityOnForgery&&!entry.fm15OnForgery)return void 0;return{class:entry.verdictClass?"verdict-forgery":entry.securityOnForgery?"erasure-forgery":"fm15-append-authority",kind,origin:origin.kind,detail:"write-authority violation at the single write gate (I-5 isolation, event-log \xA72.2; flywheel \xA73.2)"}}})}}
1
+ import{RecordEngine}from"@zortexhq/rooktrail/integration";import{buildStreamMap,lookupKind}from"./registry.js";import{ok,errResult}from"./original-contracts.js";export class LiftedRecordRules extends RecordEngine{constructor(db,streams,now,table,execution,authorizeConnector,onInserted){super(db,streams,now,table,lookupKind,{systemSource:"zortex",buildStreams:buildStreamMap,...authorizeConnector?{authorizeConnector}:{},afterInsert(event,recordTable){if(recordTable==="events"&&execution){const owner=db.query("SELECT phase FROM connector_process_runs WHERE run_id=?").get(execution.runId);if(owner?.phase!=="active")return errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Execution no longer owns an active process run."});db.query("INSERT INTO event_executions(event_id,run_id,code_version) VALUES (?,?,?)").run(event.id,execution.runId,execution.codeVersion)}onInserted?.(event);return ok(true)},authorityIncident(kind,origin){const entry=lookupKind(kind);if(!entry||!entry.verdictClass&&!entry.securityOnForgery&&!entry.fm15OnForgery)return void 0;return{class:entry.verdictClass?"verdict-forgery":entry.securityOnForgery?"erasure-forgery":"fm15-append-authority",kind,origin:origin.kind,detail:"write-authority violation at the single write gate (I-5 isolation, event-log \xA72.2; flywheel \xA73.2)"}}})}}
@@ -1,10 +1,27 @@
1
- import{EVENT_SCHEMA,projectionEpochTriggers}from"@zortexhq/rooktrail/integration";export const SCHEMA=EVENT_SCHEMA+`
1
+ import{EVENT_SCHEMA,projectionEpochTriggers}from"@zortexhq/rooktrail/integration";const title=(prefix="")=>{const payload=prefix+"payload",source=prefix+"source",id=prefix+"source_id";const subject=`(SELECT nullif(trim(json_extract(h.value,'$.value')),'') FROM json_each(${payload},CASE WHEN json_type(${payload},'$.message')='object' THEN '$.message.payload.headers' WHEN json_type(${payload},'$.messages')='array' THEN '$.messages[0].payload.headers' ELSE '$.payload.headers' END) h WHERE lower(json_extract(h.value,'$.name'))='subject' LIMIT 1)`;return`COALESCE(nullif(trim(json_extract(${payload},'$.title')),''),nullif(trim(json_extract(${payload},'$.subject')),''),nullif(trim(json_extract(${payload},'$.name')),''),CASE WHEN ${source}='gmail' THEN ${subject} END,${id})`};export const SCHEMA=EVENT_SCHEMA+`
2
2
  CREATE TABLE IF NOT EXISTS user_blob_contents(sha256 TEXT PRIMARY KEY,metadata TEXT NOT NULL,data BLOB NOT NULL);
3
3
  CREATE TABLE IF NOT EXISTS private_state(namespace TEXT NOT NULL,key TEXT NOT NULL,revision INTEGER NOT NULL,value TEXT NOT NULL,PRIMARY KEY(namespace,key));
4
4
  CREATE TABLE IF NOT EXISTS binding_sync_checkpoints(key TEXT PRIMARY KEY,revision INTEGER NOT NULL,value TEXT NOT NULL);
5
5
  CREATE TABLE IF NOT EXISTS source_authority_required(source TEXT PRIMARY KEY);
6
6
  CREATE TABLE IF NOT EXISTS isolated_source_subjects(source TEXT PRIMARY KEY,subject TEXT NOT NULL);
7
7
  CREATE TABLE IF NOT EXISTS isolated_verified_grants(source TEXT NOT NULL,grant_id TEXT NOT NULL,binding_id TEXT NOT NULL,subject TEXT NOT NULL,PRIMARY KEY(source,grant_id));
8
- CREATE VIEW IF NOT EXISTS z_events AS SELECT id,source AS app,source,stream,source_id,rev,COALESCE(json_extract(payload,'$.title'),json_extract(payload,'$.subject'),json_extract(payload,'$.name'),source_id) AS title,body AS text,body,ts,payload FROM events WHERE erased=0;
8
+ DROP VIEW IF EXISTS z_events;
9
+ CREATE VIEW z_events AS SELECT id,source AS app,source,stream,source_id,rev,${title()} AS title,body AS text,body,ts,payload FROM events WHERE erased=0;
10
+ CREATE TABLE IF NOT EXISTS current_record_heads(source TEXT NOT NULL,stream TEXT NOT NULL,source_id TEXT NOT NULL,event_id TEXT NOT NULL,PRIMARY KEY(source,stream,source_id));
11
+ CREATE TABLE IF NOT EXISTS current_record_projection(version INTEGER PRIMARY KEY);
12
+ CREATE INDEX IF NOT EXISTS current_record_heads_event ON current_record_heads(event_id);
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
+ CREATE INDEX IF NOT EXISTS search_documents_source_time ON search_documents(source,ts DESC,id);
15
+ CREATE TABLE IF NOT EXISTS search_projection(version INTEGER PRIMARY KEY);
16
+ 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
+ CREATE TRIGGER IF NOT EXISTS search_documents_delete AFTER DELETE ON events BEGIN DELETE FROM search_documents WHERE id=OLD.id; END;
18
+ DROP VIEW IF EXISTS z_current_records;
19
+ CREATE VIEW z_current_records AS SELECT e.id,e.source AS app,e.source,e.stream,e.source_id,e.rev,
20
+ ${title("e.")} AS title,
21
+ e.body AS text,e.body,e.ts,e.payload FROM events e WHERE e.erased=0
22
+ AND EXISTS(SELECT 1 FROM current_record_heads h WHERE h.event_id=e.id)
23
+ AND NOT EXISTS(SELECT 1 FROM source_streams s WHERE s.source=e.source AND s.stream=e.stream AND json_extract(s.definition,'$.deleteKind')=e.kind);
24
+ DROP VIEW IF EXISTS z_search_records;
25
+ CREATE VIEW z_search_records AS SELECT d.* FROM search_documents d WHERE EXISTS(SELECT 1 FROM z_current_records r WHERE r.id=d.id);
9
26
  CREATE TABLE IF NOT EXISTS event_executions(event_id TEXT PRIMARY KEY,run_id TEXT NOT NULL,code_version TEXT NOT NULL);
10
27
  `+projectionEpochTriggers(["trace.span"]);
@@ -0,0 +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 +1 @@
1
- const EVENT="id source stream source_id rev content_hash canon ts observed_ts trust origin tier kind schema_version policy_version coverage mentions body lang payload blobs refs segment line unique_nk erased tomb".split(" ");export const SNAPSHOT_LOCAL_ONLY_TABLES={binding_sync_checkpoints:["key","revision","value"],joplin_pairing_generation:["id","revision"],joplin_pairing_commits:["transaction_id","expected_generation","committed_generation"],joplin_pairing_fence:["id","transaction_id","expected_generation","account","state","committed_generation"],joplin_pairing_previous:["id","transaction_id","expected_generation","account","committed_generation"],joplin_pairing_aborts:["transaction_id","expected_generation","account","previous_transaction_id","previous_expected_generation","previous_account","previous_committed_generation"],joplin_pairing_epoch:["id","epoch"],isolated_source_subjects:["source","subject"],isolated_verified_grants:["source","grant_id","binding_id","subject"],legacy_connections:["source","metadata","credential"],legacy_recoveries:["source","binding_id","fingerprint","verified_at"],legacy_refresh_claims:["source","claim_id","fingerprint","started_at","replacement"],source_selections:["source","binding_id","revision","selected_at"],custody_migrations:["id","applied_at"],custody_identity:["id","value"],account_bindings:["id","source","issuer","subject","tenant_key","revision","metadata"],authorization_grants:["id","binding_id","revision","metadata"],credential_resources:["id","binding_id","kind","owner_key","revision","metadata","credential"],credential_refresh_claims:["resource_id","claim_id","expected_revision","owner_key"],binding_records:["binding_id","stream","native_id","ts","payload"],analytics_connection_ids:["binding_id","connection_ref"]};export const SNAPSHOT_TABLES={events:EVENT,system_events:EVENT,source_streams:["source","stream","definition"],source_authority_required:["source"],pending_refs:["from_id","rel","source","stream","source_id"],resolved_refs:["from_id","rel","to_id"],claims:["from_id","rel","ns","value"],tombstones:["source","stream","source_id","rev","content_hash","tomb_id","future_too","ts","kind"],rebinds:["from_source","from_stream","from_source_id","to_source","to_stream","to_source_id","event_id"],unknown_kinds:["source","kind","first_event_id"],blob_refs:["sha256","refcount"],meta:["key","value"],event_executions:["event_id","run_id","code_version"],private_state:["namespace","key","revision","value"],local_source_permissions:["source","location","connected_at","enabled"],connector_process_runs:["run_id","request_id","state_key","signature","owner","phase","started_at","outcome"],connector_business_receipts:["run_id","source","result","code_version","recorded_at"],connections:["source","metadata","credential"],records:["source","id","ts","payload"],connector_records:["source","source_id","ts","body","payload"],user_blob_contents:["sha256","metadata","data"]};
1
+ const EVENT="id source stream source_id rev content_hash canon ts observed_ts trust origin tier kind schema_version policy_version coverage mentions body lang payload blobs refs segment line unique_nk erased tomb".split(" ");export const SNAPSHOT_LOCAL_ONLY_TABLES={current_record_heads:["source","stream","source_id","event_id"],current_record_projection:["version"],search_documents:["id","source","source_id","stream","title","body","ts"],search_projection:["version"],binding_sync_checkpoints:["key","revision","value"],joplin_pairing_generation:["id","revision"],joplin_pairing_commits:["transaction_id","expected_generation","committed_generation"],joplin_pairing_fence:["id","transaction_id","expected_generation","account","state","committed_generation"],joplin_pairing_previous:["id","transaction_id","expected_generation","account","committed_generation"],joplin_pairing_aborts:["transaction_id","expected_generation","account","previous_transaction_id","previous_expected_generation","previous_account","previous_committed_generation"],joplin_pairing_epoch:["id","epoch"],isolated_source_subjects:["source","subject"],isolated_verified_grants:["source","grant_id","binding_id","subject"],legacy_connections:["source","metadata","credential"],legacy_recoveries:["source","binding_id","fingerprint","verified_at"],legacy_refresh_claims:["source","claim_id","fingerprint","started_at","replacement"],source_selections:["source","binding_id","revision","selected_at"],custody_migrations:["id","applied_at"],custody_identity:["id","value"],account_bindings:["id","source","issuer","subject","tenant_key","revision","metadata"],authorization_grants:["id","binding_id","revision","metadata"],credential_resources:["id","binding_id","kind","owner_key","revision","metadata","credential"],credential_refresh_claims:["resource_id","claim_id","expected_revision","owner_key"],binding_records:["binding_id","stream","native_id","ts","payload"],analytics_connection_ids:["binding_id","connection_ref"]};export const SNAPSHOT_TABLES={events:EVENT,system_events:EVENT,source_streams:["source","stream","definition"],source_authority_required:["source"],pending_refs:["from_id","rel","source","stream","source_id"],resolved_refs:["from_id","rel","to_id"],claims:["from_id","rel","ns","value"],tombstones:["source","stream","source_id","rev","content_hash","tomb_id","future_too","ts","kind"],rebinds:["from_source","from_stream","from_source_id","to_source","to_stream","to_source_id","event_id"],unknown_kinds:["source","kind","first_event_id"],blob_refs:["sha256","refcount"],meta:["key","value"],event_executions:["event_id","run_id","code_version"],private_state:["namespace","key","revision","value"],local_source_permissions:["source","location","connected_at","enabled"],connector_process_runs:["run_id","request_id","state_key","signature","owner","phase","started_at","outcome"],connector_business_receipts:["run_id","source","result","code_version","recorded_at"],connections:["source","metadata","credential"],records:["source","id","ts","payload"],connector_records:["source","source_id","ts","body","payload"],user_blob_contents:["sha256","metadata","data"]};
@@ -0,0 +1 @@
1
+ import{createHash}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const bounded=value=>typeof value==="string"&&value.length>0&&value.length<=256;const instant=value=>typeof value==="string"&&Number.isFinite(Date.parse(value));function key(authority){if(!authority||!/^[a-z][a-z0-9-]{0,63}$/.test(authority.source)||!bounded(authority.account)||!bounded(authority.revision)||authority.bindingId!==void 0&&!bounded(authority.bindingId)||authority.scopeEpoch!==void 0&&(!Number.isSafeInteger(authority.scopeEpoch)||authority.scopeEpoch<0)||!Array.isArray(authority.scopes)||authority.scopes.length>100||authority.scopes.some(scope=>!bounded(scope)))return;return createHash("sha256").update(JSON.stringify({source:authority.source,account:authority.account,binding:authority.bindingId??null,revision:authority.revision,scopes:[...new Set(authority.scopes)].sort(),scopeEpoch:authority.scopeEpoch??null})).digest("hex")}function valid(state,source){if(!object(state)||state.source!==source||!["pending","syncing","ready","partial","paused","blocked"].includes(String(state.phase))||Object.keys(state).some(field=>!["source","phase","coverage","appended","initialCompletedAt","lastAttemptAt","lastSuccessAt","checkedAt","nextAt","errorCode"].includes(field))||!Number.isSafeInteger(state.appended)||Number(state.appended)<0||!object(state.coverage))return false;const coverage=state.coverage;if(Object.keys(coverage).some(field=>!["status","resources","since","until","limitations"].includes(field))||!["unknown","partial","complete"].includes(String(coverage.status))||!Array.isArray(coverage.resources)||coverage.resources.length>100||coverage.resources.some(item=>!bounded(item))||!Array.isArray(coverage.limitations)||coverage.limitations.length>100||coverage.limitations.some(item=>!bounded(item)))return false;for(const field of["initialCompletedAt","lastAttemptAt","lastSuccessAt","checkedAt","nextAt"])if(state[field]!==void 0&&!instant(state[field]))return false;for(const field of["since","until"])if(coverage[field]!==void 0&&!instant(coverage[field]))return false;if(coverage.since&&coverage.until&&Date.parse(String(coverage.since))>Date.parse(String(coverage.until)))return false;if(state.errorCode!==void 0&&(typeof state.errorCode!=="string"||!/^[a-z][a-z0-9_]{0,63}$/.test(state.errorCode)))return false;return state.phase!=="ready"||coverage.status==="complete"&&coverage.resources.length>0&&coverage.limitations.length===0&&instant(state.checkedAt)&&instant(state.initialCompletedAt)}export function createSourceSyncStore(store){const invalid=()=>businessError("invalid_argument","Invalid source data state or authority.","storage");return{read(authority){const id=key(authority);if(!id)return invalid();const found=store.get(id);if(!("ok"in found))return found;if(!found.ok)return ok(null);return valid(found.ok.value,authority.source)?ok({revision:found.ok.revision,state:found.ok.value}):businessError("data_loss","Source data state is invalid.","storage")},write(authority,state,expectedRevision){const id=key(authority);if(!id||!valid(state,authority.source))return invalid();const saved=store.put(id,state,expectedRevision);return"ok"in saved?ok({revision:saved.ok.revision,state:structuredClone(state)}):saved}}}
@@ -1 +1 @@
1
- import{DatabaseSync,constants}from"node:sqlite";import{assertRecoveryReadable}from"./recovery-guard.js";let input="";process.stdin.setEncoding("utf8");process.stdin.on("data",part=>{input+=part;if(Buffer.byteLength(input)>1048576)process.exit(1)});process.stdin.on("end",()=>{let db;const error=(code,message,retryability="non-retryable")=>({err:{code,message,layer:"storage",retryability}});try{const request=JSON.parse(input);const sql=request.sql.trim().replace(/;\s*$/,"");if(!/^(SELECT|WITH|VALUES|EXPLAIN)\b/i.test(sql)||sql.includes(";"))throw Error("invalid");assertRecoveryReadable(request.file);db=new DatabaseSync(request.file,{readOnly:true,allowExtension:false});db.exec("PRAGMA busy_timeout=500;PRAGMA query_only=ON");const version=db.prepare("PRAGMA user_version").get()?.user_version;if(version!==1||db.prepare("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("format");const tables=new Set(["events","z_events","z_records","connector_records","system_events","pending_refs","resolved_refs","claims","blob_refs","rebinds","unknown_kinds","tombstones","event_executions"]);const functions=new Set(["count","sum","avg","min","max","like","glob","lower","upper","length","substr","coalesce","ifnull","nullif","date","datetime","strftime","julianday","round","abs","json_extract","json_type","printf"]);db.setAuthorizer((action,a,b,database)=>{if(action===constants.SQLITE_SELECT||action===constants.SQLITE_RECURSIVE)return constants.SQLITE_OK;if(action===constants.SQLITE_READ)return(database==="main"||database===null)&&tables.has(String(a))?constants.SQLITE_OK:constants.SQLITE_DENY;if(action===constants.SQLITE_FUNCTION&&functions.has(String(b??a).toLowerCase()))return constants.SQLITE_OK;return constants.SQLITE_DENY});const statement=db.prepare(sql);statement.setReadBigInts(true);const rows=[];let bytes=64;for(const row of statement.iterate(...request.params)){const record=Object.fromEntries(Object.entries(row).map(([key,value])=>[key,typeof value==="bigint"?value<=BigInt(Number.MAX_SAFE_INTEGER)&&value>=BigInt(Number.MIN_SAFE_INTEGER)?Number(value):value.toString():value instanceof Uint8Array?Array.from(value):value]));bytes+=Buffer.byteLength(JSON.stringify(record))+1;if(rows.length>=request.maxRows||bytes>request.maxBytes){process.stdout.write(JSON.stringify(error("resource_exhausted","SQL result exceeded its row or byte budget.")));return}rows.push(record)}process.stdout.write(JSON.stringify({ok:{rows,truncated:false}}))}catch(cause){const native=cause;const primary=native?.code==="ERR_SQLITE_ERROR"&&Number.isInteger(native.errcode)?native.errcode&255:0;const result=primary===5||primary===6?error("unavailable","Vault is busy; retry the query shortly.","transient"):primary===11||primary===26?error("data_loss","Vault storage is corrupt or is not a SQLite database."):primary===7||primary===13||primary===18?error("resource_exhausted","Vault storage exceeded an available resource limit."):primary===10||primary===14?error("unavailable","Vault storage could not be opened or read."):error("invalid_argument","SQL is invalid or outside the read-only Vault surface.");process.stdout.write(JSON.stringify(result))}finally{db?.close()}});
1
+ import{DatabaseSync,constants}from"node:sqlite";import{assertRecoveryReadable}from"./recovery-guard.js";let input="";process.stdin.setEncoding("utf8");process.stdin.on("data",part=>{input+=part;if(Buffer.byteLength(input)>1048576)process.exit(1)});process.stdin.on("end",()=>{let db;const error=(code,message,retryability="non-retryable")=>({err:{code,message,layer:"storage",retryability}});try{const request=JSON.parse(input);const sql=request.sql.trim().replace(/;\s*$/,"");if(!/^(SELECT|WITH|VALUES|EXPLAIN)\b/i.test(sql)||sql.includes(";"))throw Error("invalid");assertRecoveryReadable(request.file);db=new DatabaseSync(request.file,{readOnly:true,allowExtension:false});db.exec("PRAGMA busy_timeout=500;PRAGMA query_only=ON");const version=db.prepare("PRAGMA user_version").get()?.user_version;if(version!==1||db.prepare("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("format");db.prepare("SELECT value FROM json_each('[]')").all();const tables=new Set(["json_each","events","search_documents","z_search_records","z_current_records","current_record_heads","source_streams","z_events","z_records","connector_records","system_events","pending_refs","resolved_refs","claims","blob_refs","rebinds","unknown_kinds","tombstones","event_executions"]);const functions=new Set(["count","sum","avg","min","max","like","glob","lower","upper","length","substr","coalesce","ifnull","nullif","date","datetime","strftime","julianday","round","abs","json_extract","json_type","trim","replace","char","instr","printf"]);db.setAuthorizer((action,a,b,database)=>{if(action===constants.SQLITE_SELECT||action===constants.SQLITE_RECURSIVE)return constants.SQLITE_OK;if(action===constants.SQLITE_READ)return(database==="main"||database===null)&&tables.has(String(a))?constants.SQLITE_OK:constants.SQLITE_DENY;if(action===constants.SQLITE_FUNCTION&&functions.has(String(b??a).toLowerCase()))return constants.SQLITE_OK;return constants.SQLITE_DENY});const statement=db.prepare(sql);statement.setReadBigInts(true);const rows=[];let bytes=64;for(const row of statement.iterate(...request.params)){const record=Object.fromEntries(Object.entries(row).map(([key,value])=>[key,typeof value==="bigint"?value<=BigInt(Number.MAX_SAFE_INTEGER)&&value>=BigInt(Number.MIN_SAFE_INTEGER)?Number(value):value.toString():value instanceof Uint8Array?Array.from(value):value]));bytes+=Buffer.byteLength(JSON.stringify(record))+1;if(rows.length>=request.maxRows||bytes>request.maxBytes){process.stdout.write(JSON.stringify(error("resource_exhausted","SQL result exceeded its row or byte budget.")));return}rows.push(record)}process.stdout.write(JSON.stringify({ok:{rows,truncated:false}}))}catch(cause){const native=cause;const primary=native?.code==="ERR_SQLITE_ERROR"&&Number.isInteger(native.errcode)?native.errcode&255:0;const result=primary===5||primary===6?error("unavailable","Vault is busy; retry the query shortly.","transient"):primary===11||primary===26?error("data_loss","Vault storage is corrupt or is not a SQLite database."):primary===7||primary===13||primary===18?error("resource_exhausted","Vault storage exceeded an available resource limit."):primary===10||primary===14?error("unavailable","Vault storage could not be opened or read."):error("invalid_argument","SQL is invalid or outside the read-only Vault surface.");process.stdout.write(JSON.stringify(result))}finally{db?.close()}});
@@ -1,4 +1,4 @@
1
- import{buildStreamMap,streamKey}from"./registry.js";import{cachedQuery,insertEventRow,projectEvent}from"./effects.js";import{CANON_PROFILE_VERSION,compareRevsWithConflicts,contentHash,errResult,isOk,makeUlidFactory,mintConflictRev,noneSourceId,ok,parseConflictRev,toRfc3339UtcMillis,validateOrigin,validateProtoEvent,validateIdentityRebindPayload}from"./contracts/index.js";const MAX_BATCH=500;function err(code,message,retryability="non-retryable",layer="storage"){return errResult({code,layer,retryability,message})}function stampTrust(origin,nk){if(origin.kind==="connector")return{level:"untrusted",sources:[nk.source]};if(origin.kind==="user")return{level:"user",sources:[]};return{level:"system",sources:[]}}function numericThenLex(a,b){const na=Number(a);const nb=Number(b);if(Number.isFinite(na)&&Number.isFinite(nb)&&na!==nb)return na<nb?-1:1;if(Number.isFinite(na)&&Number.isFinite(nb))return 0;return a<b?-1:a>b?1:0}function lex(a,b){return a<b?-1:a>b?1:0}class CheckpointAuthorityConflictError extends Error{}class RecordHookError extends Error{error;constructor(error){super(error.message);this.error=error}}export class LiftedRecordRules{db;now;table;kinds;policy;streams;declarations;ulid;policyVersion=()=>1;registerStream(registration){const key=streamKey(registration.source,registration.stream),snapshot={...registration};this.declarations.set(key,snapshot);this.streams.set(key,snapshot)}constructor(db,streams,now,table,kinds,policy={}){this.db=db;this.now=now;this.table=table;this.kinds=kinds;this.policy=policy;this.declarations=new Map(streams.map(row=>[streamKey(row.source,row.stream),{...row}]));this.streams=this.makeStreams(streams);this.ulid=makeUlidFactory({now:()=>Date.parse(now())})}makeStreams(streams){return(this.policy.buildStreams??buildStreamMap)(streams)}lookupKind(kind){return typeof this.kinds==="function"?this.kinds(kind):this.kinds.get(kind)}appendCore(batch,origin,internal=false,transaction,withinTransaction=false){if(!Array.isArray(batch))return err("invalid_argument","append: batch must be an array");if(batch.length===0)return transaction?err("invalid_argument","Guarded append requires a fact."):ok([]);if(batch.length>MAX_BATCH)return err("invalid_argument",`append: batch exceeds the txn unit (${MAX_BATCH})`);const originV=validateOrigin(origin);if(!isOk(originV))return originV;try{this.refreshStreams()}catch{return err("data_loss","Stored stream declarations are invalid.")}for(const proto of batch){const hard=this.validateHard(proto,origin,internal,false);if(hard!==null)return{err:hard}}const results=[],toWrite=[];const rollback=()=>this.db.exec(withinTransaction?"ROLLBACK TO rooktrail_page_append; RELEASE rooktrail_page_append":"ROLLBACK");try{this.db.exec(withinTransaction?"SAVEPOINT rooktrail_page_append":"BEGIN IMMEDIATE")}catch{return err("unavailable","SQLite writer busy","transient")}try{this.refreshStreams();for(const proto of batch){const hard=this.validateHard(proto,origin,internal);if(hard!==null){rollback();return{err:hard}}}if(origin.kind==="connector"&&this.policy.authorizeConnector){const admitted=this.policy.authorizeConnector(origin);if(!isOk(admitted)||admitted.ok!==true){rollback();return"err"in admitted?admitted:err("permission_denied","Connector authority was not confirmed.")}}if(transaction){const check=transaction.before();if(!isOk(check)||check.ok!==true){rollback();return"err"in check?check:err("permission_denied","Checkpoint authority was not confirmed.")}}const stampAndInsert=(ev,uniqueNk,table=this.table)=>{insertEventRow(this.db,ev,"",0,uniqueNk,table);toWrite.push(ev);projectEvent(this.db,ev);if(this.policy.afterInsert){const result=this.policy.afterInsert(ev,table);if(!isOk(result)||result.ok!==true)throw new RecordHookError("err"in result?result.err:{code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Host record effect was not confirmed."})}};const sideEvent=(kind,payload,sideOrigin={kind:"kernel"})=>{const ev=this.stampInternal({kind,payload,origin:sideOrigin});stampAndInsert(ev,true,"system_events");return ev};for(const proto of batch){const reg=this.streams.get(streamKey(proto.nk.source,proto.nk.stream));const hash=contentHash({kind:proto.kind,body:proto.body,...proto.payload===void 0?{}:{payload:proto.payload},...proto.blobs===void 0?{}:{blobs:proto.blobs}});let sourceId;let rev;let headCompare=false;if(reg?.quality==="none"){sourceId=noneSourceId(reg.noneIdentity??"occurrence",hash,proto.ts);rev="0"}else{sourceId=proto.nk.sourceId;const draftRev=proto.nk.rev??"";if(reg?.revOrder==="head-compare"||reg===void 0&&draftRev===""){rev=hash;headCompare=true}else if(reg?.revOrder==="event-ts"){rev=toRfc3339UtcMillis(proto.ts)}else{rev=draftRev}}const nk={source:proto.nk.source,stream:proto.nk.stream,sourceId,rev};const phase=proto.coverage?.phase??"live";const suppression=this.checkTombstones(nk,hash,sideEvent);if(suppression!==null){results.push(suppression);continue}let outcome=null;let conflictAnomaly=null;if(!headCompare){const existing=cachedQuery(this.db,`SELECT id, content_hash FROM ${this.table} WHERE source = ? AND stream = ? AND source_id = ? AND rev = ?`).get(nk.source,nk.stream,nk.sourceId,nk.rev);if(existing!==null){if(existing.content_hash===hash){results.push({id:existing.id,outcome:"duplicate"});continue}if(this.lookupKind(proto.kind)?.conflictIsDataLoss===true){throw new CheckpointAuthorityConflictError(`authority kind '${proto.kind}' reused an NK with changed bytes`)}const sibling=this.conflictSiblingWithHash(nk,rev,hash);if(sibling!==null){results.push({id:sibling.id,outcome:"duplicate"});continue}const n=this.nextConflictN(nk);conflictAnomaly={existingId:existing.id,existingHash:existing.content_hash};nk.rev=mintConflictRev(rev,n)}}else{const chainRows=this.chainRowsForBase({source:nk.source,stream:nk.stream,sourceId:nk.sourceId});const live=chainRows.filter(r=>r.erased===0);const head=live.length>0?live[live.length-1]:null;if(phase==="live"){if(head!==null&&head.content_hash===hash){results.push({id:head.id,outcome:"head-noop"});continue}}else if(live.some(r=>r.content_hash===hash)){results.push({id:head.id,outcome:"head-noop"});continue}}const ev={id:this.nextEventId(),nk,contentHash:hash,canon:CANON_PROFILE_VERSION,ts:proto.ts,observedTs:this.now(),trust:stampTrust(origin,nk),origin,tier:proto.tier,kind:proto.kind,schemaVersion:proto.schemaVersion,policyVersion:this.policyVersion(),mentions:proto.mentions,body:proto.body};if(proto.coverage!==void 0)ev.coverage=proto.coverage;if(proto.lang!==void 0)ev.lang=proto.lang;if(proto.payload!==void 0)ev.payload=proto.payload;if(proto.blobs!==void 0)ev.blobs=proto.blobs;if(proto.refs!==void 0)ev.refs=proto.refs;const rebindConflict=this.detectRebindConflict(ev);stampAndInsert(ev,!headCompare);if(conflictAnomaly!==null){const anomaly=sideEvent("ingest.anomaly",{class:"nk-conflict",nk:{source:nk.source,stream:nk.stream,sourceId:nk.sourceId,rev},existingId:conflictAnomaly.existingId,newId:ev.id,hashes:[conflictAnomaly.existingHash,hash]});outcome={id:ev.id,outcome:"anomaly",anomalyId:anomaly.id}}else if(rebindConflict!==null){const anomaly=sideEvent("ingest.anomaly",{class:"rebind-conflict",...rebindConflict,eventId:ev.id});outcome={id:ev.id,outcome:"anomaly",anomalyId:anomaly.id}}else{const kindEntry=this.lookupKind(ev.kind);if(kindEntry===void 0){const seen=this.db.query(`SELECT 1 AS x FROM unknown_kinds WHERE source = ? AND kind = ?`).get(nk.source,ev.kind);if(seen===null){sideEvent("ingest.unknown-kind",{source:nk.source,kind:ev.kind,firstEventId:ev.id})}outcome={id:ev.id,outcome:"appended"}}else if(kindEntry.validatePayload!==void 0){const v=kindEntry.validatePayload(ev.payload);if(!isOk(v)){const detail="err"in v?v.err.message:"payload empty";const anomaly=sideEvent("ingest.anomaly",{class:"schema-violation",eventId:ev.id,kind:ev.kind,detail});outcome={id:ev.id,outcome:"anomaly",anomalyId:anomaly.id}}else{outcome={id:ev.id,outcome:"appended"}}}else{outcome={id:ev.id,outcome:"appended"}}}results.push(outcome)}if(transaction){const check=transaction.after(results);if(!isOk(check)||check.ok!==true){rollback();return"err"in check?check:err("data_loss","Checkpoint fact was not committed.")}}if(toWrite.length)this.db.query("INSERT OR REPLACE INTO meta(key,value) VALUES ('watermark',?)").run(toWrite[toWrite.length-1].id);this.db.exec(withinTransaction?"RELEASE rooktrail_page_append":"COMMIT");return ok(results)}catch(failure){try{rollback()}catch{throw new AggregateError([failure],"SQLite append rollback failed")}if(failure instanceof RecordHookError)return{err:failure.error};if(failure instanceof CheckpointAuthorityConflictError)return err("data_loss",failure.message);return err("internal","SQLite record transaction rolled back","transient")}}refreshStreams(){const rows=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all();const latest=this.makeStreams([...this.declarations.values(),...rows.map(row=>JSON.parse(row.definition))]);this.streams.clear();for(const[key,declaration]of latest)this.streams.set(key,declaration)}validateHard(proto,origin,internal,eventValidation=true){if(proto===null||typeof proto!=="object"){return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"protoEvent: expected an object"}}const reg=this.streams.get(streamKey(proto.nk?.source,proto.nk?.stream));const ctx=reg===void 0?void 0:{revOrder:reg.revOrder,...reg.quality!==void 0&&reg.quality!=="synthetic"?{quality:reg.quality}:{}};const v=validateProtoEvent(proto,ctx);if(!isOk(v))return v.err;const sourceId=proto.nk.sourceId??"";if(reg?.quality==="synthetic"&&sourceId===""){return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`nk.sourceId: quality 'synthetic' stream reached the appender un-synthesized \u2014 the host's '${reg.stream}' synthesizer runs BEFORE append`}}if(reg===void 0&&sourceId===""){return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`nk.sourceId: undeclared stream '${proto.nk.source}/${proto.nk.stream}' cannot synthesize identity \u2014 declare the stream identity quality`}}if(origin.kind==="connector"&&proto.nk.source!==origin.source){return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:`origin 'connector:${origin.source}' may append only nk.source == its own source; got '${proto.nk.source}'`}}const kindEntry=this.lookupKind(proto.kind);if(kindEntry!==void 0){const forgedInternal=kindEntry.internalOnly===true&&!internal;const aclViolation=!kindEntry.allowedOrigins.includes(origin.kind);if(forgedInternal||aclViolation){const incident=this.policy.authorityIncident?.(proto.kind,origin)??(kindEntry.reportForgery===true?{class:"write-authority",kind:proto.kind,origin:origin.kind}:void 0);if(incident!==void 0)this.recordWriteAuthorityIncident(incident);return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:forgedInternal?`kind '${proto.kind}' is appender/erasure-job emitted only \u2014 a caller append is a forgery`:`kind '${proto.kind}' allows origins [${kindEntry.allowedOrigins.join(", ")}]; origin '${origin.kind}' denied`}}if(eventValidation&&kindEntry.validateEvent!==void 0){const validated=kindEntry.validateEvent({nk:proto.nk,payload:proto.payload});if(!isOk(validated))return"err"in validated?validated.err:{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`kind '${proto.kind}' event validation checked empty`}}}return null}checkTombstones(nk,hash,sideEvent){const sameContent=cachedQuery(this.db,`SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND content_hash = ?`).get(nk.source,nk.stream,nk.sourceId,hash);if(sameContent!==null)return{id:sameContent.tomb_id,outcome:"erased-suppressed"};const ban=cachedQuery(this.db,`SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND future_too = 1`).get(nk.source,nk.stream,nk.sourceId);if(ban!==null){const marker=this.db.query(`SELECT id FROM system_events
1
+ import{buildStreamMap,streamKey}from"./registry.js";import{cachedQuery,insertEventRow,projectEvent}from"./effects.js";import{CANON_PROFILE_VERSION,compareRevsWithConflicts,contentHash,errResult,isOk,makeUlidFactory,mintConflictRev,noneSourceId,ok,parseConflictRev,toRfc3339UtcMillis,validateOrigin,validateProtoEvent,validateIdentityRebindPayload}from"./contracts/index.js";const MAX_BATCH=500;function err(code,message,retryability="non-retryable",layer="storage"){return errResult({code,layer,retryability,message})}function stampTrust(origin,nk){if(origin.kind==="connector")return{level:"untrusted",sources:[nk.source]};if(origin.kind==="user")return{level:"user",sources:[]};return{level:"system",sources:[]}}function numericThenLex(a,b){const na=Number(a);const nb=Number(b);if(Number.isFinite(na)&&Number.isFinite(nb)&&na!==nb)return na<nb?-1:1;if(Number.isFinite(na)&&Number.isFinite(nb))return 0;return a<b?-1:a>b?1:0}function lex(a,b){return a<b?-1:a>b?1:0}class CheckpointAuthorityConflictError extends Error{}class RecordHookError extends Error{error;constructor(error){super(error.message);this.error=error}}export class LiftedRecordRules{db;now;table;kinds;policy;streams;declarations;ulid;policyVersion=()=>1;registerStream(registration){const key=streamKey(registration.source,registration.stream),snapshot={...registration};this.declarations.set(key,snapshot);this.streams.set(key,snapshot)}constructor(db,streams,now,table,kinds,policy={}){this.db=db;this.now=now;this.table=table;this.kinds=kinds;this.policy=policy;this.declarations=new Map(streams.map(row=>[streamKey(row.source,row.stream),{...row}]));this.streams=this.makeStreams(streams);this.ulid=makeUlidFactory({now:()=>Date.parse(now())})}currentChain(base){this.refreshStreams();return{identities:this.rebindClosure(base),head:this.chainRowsForBase(base).at(-1)??null}}makeStreams(streams){return(this.policy.buildStreams??buildStreamMap)(streams)}lookupKind(kind){return typeof this.kinds==="function"?this.kinds(kind):this.kinds.get(kind)}appendCore(batch,origin,internal=false,transaction,withinTransaction=false){if(!Array.isArray(batch))return err("invalid_argument","append: batch must be an array");if(batch.length===0)return transaction?err("invalid_argument","Guarded append requires a fact."):ok([]);if(batch.length>MAX_BATCH)return err("invalid_argument",`append: batch exceeds the txn unit (${MAX_BATCH})`);const originV=validateOrigin(origin);if(!isOk(originV))return originV;try{this.refreshStreams()}catch{return err("data_loss","Stored stream declarations are invalid.")}for(const proto of batch){const hard=this.validateHard(proto,origin,internal,false);if(hard!==null)return{err:hard}}const results=[],toWrite=[];const rollback=()=>this.db.exec(withinTransaction?"ROLLBACK TO rooktrail_page_append; RELEASE rooktrail_page_append":"ROLLBACK");try{this.db.exec(withinTransaction?"SAVEPOINT rooktrail_page_append":"BEGIN IMMEDIATE")}catch{return err("unavailable","SQLite writer busy","transient")}try{this.refreshStreams();for(const proto of batch){const hard=this.validateHard(proto,origin,internal);if(hard!==null){rollback();return{err:hard}}}if(origin.kind==="connector"&&this.policy.authorizeConnector){const admitted=this.policy.authorizeConnector(origin);if(!isOk(admitted)||admitted.ok!==true){rollback();return"err"in admitted?admitted:err("permission_denied","Connector authority was not confirmed.")}}if(transaction){const check=transaction.before();if(!isOk(check)||check.ok!==true){rollback();return"err"in check?check:err("permission_denied","Checkpoint authority was not confirmed.")}}const stampAndInsert=(ev,uniqueNk,table=this.table)=>{insertEventRow(this.db,ev,"",0,uniqueNk,table);toWrite.push(ev);projectEvent(this.db,ev);if(this.policy.afterInsert){const result=this.policy.afterInsert(ev,table);if(!isOk(result)||result.ok!==true)throw new RecordHookError("err"in result?result.err:{code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Host record effect was not confirmed."})}};const sideEvent=(kind,payload,sideOrigin={kind:"kernel"})=>{const ev=this.stampInternal({kind,payload,origin:sideOrigin});stampAndInsert(ev,true,"system_events");return ev};for(const proto of batch){const reg=this.streams.get(streamKey(proto.nk.source,proto.nk.stream));const hash=contentHash({kind:proto.kind,body:proto.body,...proto.payload===void 0?{}:{payload:proto.payload},...proto.blobs===void 0?{}:{blobs:proto.blobs}});let sourceId;let rev;let headCompare=false;if(reg?.quality==="none"){sourceId=noneSourceId(reg.noneIdentity??"occurrence",hash,proto.ts);rev="0"}else{sourceId=proto.nk.sourceId;const draftRev=proto.nk.rev??"";if(reg?.revOrder==="head-compare"||reg===void 0&&draftRev===""){rev=hash;headCompare=true}else if(reg?.revOrder==="event-ts"){rev=toRfc3339UtcMillis(proto.ts)}else{rev=draftRev}}const nk={source:proto.nk.source,stream:proto.nk.stream,sourceId,rev};const phase=proto.coverage?.phase??"live";const suppression=this.checkTombstones(nk,hash,sideEvent);if(suppression!==null){results.push(suppression);continue}let outcome=null;let conflictAnomaly=null;if(!headCompare){const existing=cachedQuery(this.db,`SELECT id, content_hash FROM ${this.table} WHERE source = ? AND stream = ? AND source_id = ? AND rev = ?`).get(nk.source,nk.stream,nk.sourceId,nk.rev);if(existing!==null){if(existing.content_hash===hash){results.push({id:existing.id,outcome:"duplicate"});continue}if(this.lookupKind(proto.kind)?.conflictIsDataLoss===true){throw new CheckpointAuthorityConflictError(`authority kind '${proto.kind}' reused an NK with changed bytes`)}const sibling=this.conflictSiblingWithHash(nk,rev,hash);if(sibling!==null){results.push({id:sibling.id,outcome:"duplicate"});continue}const n=this.nextConflictN(nk);conflictAnomaly={existingId:existing.id,existingHash:existing.content_hash};nk.rev=mintConflictRev(rev,n)}}else{const chainRows=this.chainRowsForBase({source:nk.source,stream:nk.stream,sourceId:nk.sourceId});const live=chainRows.filter(r=>r.erased===0);const head=live.length>0?live[live.length-1]:null;if(phase==="live"){if(head!==null&&head.content_hash===hash){results.push({id:head.id,outcome:"head-noop"});continue}}else if(live.some(r=>r.content_hash===hash)){results.push({id:head.id,outcome:"head-noop"});continue}}const ev={id:this.nextEventId(),nk,contentHash:hash,canon:CANON_PROFILE_VERSION,ts:proto.ts,observedTs:this.now(),trust:stampTrust(origin,nk),origin,tier:proto.tier,kind:proto.kind,schemaVersion:proto.schemaVersion,policyVersion:this.policyVersion(),mentions:proto.mentions,body:proto.body};if(proto.coverage!==void 0)ev.coverage=proto.coverage;if(proto.lang!==void 0)ev.lang=proto.lang;if(proto.payload!==void 0)ev.payload=proto.payload;if(proto.blobs!==void 0)ev.blobs=proto.blobs;if(proto.refs!==void 0)ev.refs=proto.refs;const rebindConflict=this.detectRebindConflict(ev);stampAndInsert(ev,!headCompare);if(conflictAnomaly!==null){const anomaly=sideEvent("ingest.anomaly",{class:"nk-conflict",nk:{source:nk.source,stream:nk.stream,sourceId:nk.sourceId,rev},existingId:conflictAnomaly.existingId,newId:ev.id,hashes:[conflictAnomaly.existingHash,hash]});outcome={id:ev.id,outcome:"anomaly",anomalyId:anomaly.id}}else if(rebindConflict!==null){const anomaly=sideEvent("ingest.anomaly",{class:"rebind-conflict",...rebindConflict,eventId:ev.id});outcome={id:ev.id,outcome:"anomaly",anomalyId:anomaly.id}}else{const kindEntry=this.lookupKind(ev.kind);if(kindEntry===void 0){const seen=this.db.query(`SELECT 1 AS x FROM unknown_kinds WHERE source = ? AND kind = ?`).get(nk.source,ev.kind);if(seen===null){sideEvent("ingest.unknown-kind",{source:nk.source,kind:ev.kind,firstEventId:ev.id})}outcome={id:ev.id,outcome:"appended"}}else if(kindEntry.validatePayload!==void 0){const v=kindEntry.validatePayload(ev.payload);if(!isOk(v)){const detail="err"in v?v.err.message:"payload empty";const anomaly=sideEvent("ingest.anomaly",{class:"schema-violation",eventId:ev.id,kind:ev.kind,detail});outcome={id:ev.id,outcome:"anomaly",anomalyId:anomaly.id}}else{outcome={id:ev.id,outcome:"appended"}}}else{outcome={id:ev.id,outcome:"appended"}}}results.push(outcome)}if(transaction){const check=transaction.after(results);if(!isOk(check)||check.ok!==true){rollback();return"err"in check?check:err("data_loss","Checkpoint fact was not committed.")}}if(toWrite.length)this.db.query("INSERT OR REPLACE INTO meta(key,value) VALUES ('watermark',?)").run(toWrite[toWrite.length-1].id);this.db.exec(withinTransaction?"RELEASE rooktrail_page_append":"COMMIT");return ok(results)}catch(failure){try{rollback()}catch{throw new AggregateError([failure],"SQLite append rollback failed")}if(failure instanceof RecordHookError)return{err:failure.error};if(failure instanceof CheckpointAuthorityConflictError)return err("data_loss",failure.message);return err("internal","SQLite record transaction rolled back","transient")}}refreshStreams(){const rows=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all();const latest=this.makeStreams([...this.declarations.values(),...rows.map(row=>JSON.parse(row.definition))]);this.streams.clear();for(const[key,declaration]of latest)this.streams.set(key,declaration)}validateHard(proto,origin,internal,eventValidation=true){if(proto===null||typeof proto!=="object"){return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"protoEvent: expected an object"}}const reg=this.streams.get(streamKey(proto.nk?.source,proto.nk?.stream));const ctx=reg===void 0?void 0:{revOrder:reg.revOrder,...reg.quality!==void 0&&reg.quality!=="synthetic"?{quality:reg.quality}:{}};const v=validateProtoEvent(proto,ctx);if(!isOk(v))return v.err;const sourceId=proto.nk.sourceId??"";if(reg?.quality==="synthetic"&&sourceId===""){return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`nk.sourceId: quality 'synthetic' stream reached the appender un-synthesized \u2014 the host's '${reg.stream}' synthesizer runs BEFORE append`}}if(reg===void 0&&sourceId===""){return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`nk.sourceId: undeclared stream '${proto.nk.source}/${proto.nk.stream}' cannot synthesize identity \u2014 declare the stream identity quality`}}if(origin.kind==="connector"&&proto.nk.source!==origin.source){return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:`origin 'connector:${origin.source}' may append only nk.source == its own source; got '${proto.nk.source}'`}}const kindEntry=this.lookupKind(proto.kind);if(kindEntry!==void 0){const forgedInternal=kindEntry.internalOnly===true&&!internal;const aclViolation=!kindEntry.allowedOrigins.includes(origin.kind);if(forgedInternal||aclViolation){const incident=this.policy.authorityIncident?.(proto.kind,origin)??(kindEntry.reportForgery===true?{class:"write-authority",kind:proto.kind,origin:origin.kind}:void 0);if(incident!==void 0)this.recordWriteAuthorityIncident(incident);return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:forgedInternal?`kind '${proto.kind}' is appender/erasure-job emitted only \u2014 a caller append is a forgery`:`kind '${proto.kind}' allows origins [${kindEntry.allowedOrigins.join(", ")}]; origin '${origin.kind}' denied`}}if(eventValidation&&kindEntry.validateEvent!==void 0){const validated=kindEntry.validateEvent({nk:proto.nk,payload:proto.payload});if(!isOk(validated))return"err"in validated?validated.err:{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`kind '${proto.kind}' event validation checked empty`}}}return null}checkTombstones(nk,hash,sideEvent){const sameContent=cachedQuery(this.db,`SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND content_hash = ?`).get(nk.source,nk.stream,nk.sourceId,hash);if(sameContent!==null)return{id:sameContent.tomb_id,outcome:"erased-suppressed"};const ban=cachedQuery(this.db,`SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND future_too = 1`).get(nk.source,nk.stream,nk.sourceId);if(ban!==null){const marker=this.db.query(`SELECT id FROM system_events
2
2
  WHERE kind = 'erasure.suppressed' AND erased = 0
3
3
  AND json_extract(payload, '$.tomb') = ?
4
4
  AND json_extract(payload, '$.nk.source') = ?
@@ -1 +1 @@
1
- import{DECLARABLE_IDENTITY_QUALITIES,ORIGIN_KINDS,REV_ORDERS,validateIdentityRebindPayload}from"./contracts/index.js";const SYSTEM_STREAMS=["identity","ingest","erasure","security","system"].map(stream=>({source:"rooktrail",stream,revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"}));const STORAGE_KINDS={"identity.rebind":{allowedOrigins:["kernel","derivation"],validatePayload:validateIdentityRebindPayload},"ingest.anomaly":{allowedOrigins:["kernel"],internalOnly:true},"ingest.unknown-kind":{allowedOrigins:["kernel"],internalOnly:true},"erasure.tombstone":{allowedOrigins:["kernel"],internalOnly:true,reportForgery:true},"erasure.suppressed":{allowedOrigins:["kernel"],internalOnly:true,reportForgery:true},"security.incident":{allowedOrigins:["kernel"],internalOnly:true}};export function streamKey(source,stream){return`${source}\0${stream}`}export function validateStream(row){const name=value=>typeof value==="string"&&value.length>0&&value.length<=1024&&!value.includes("\0");if(!row||Object.keys(row).some(key=>!["source","stream","revOrder","comparator","quality","noneIdentity"].includes(key))||!name(row.source)||!name(row.stream)||row.source==="rooktrail"||!REV_ORDERS.includes(row.revOrder)||row.comparator!==void 0&&!["numeric","lex"].includes(row.comparator)||row.quality!==void 0&&!DECLARABLE_IDENTITY_QUALITIES.includes(row.quality)||row.quality==="none"&&!["state","occurrence"].includes(row.noneIdentity??"")||row.quality!=="none"&&row.noneIdentity!==void 0){throw new TypeError("Invalid stream declaration. The rooktrail source is reserved for storage facts.")}}export function buildStreamMap(registrations){const map=new Map;for(const row of SYSTEM_STREAMS)map.set(streamKey(row.source,row.stream),{...row});for(const row of registrations){validateStream(row);map.set(streamKey(row.source,row.stream),{...row})}return map}export function buildKindMap(registrations={}){const map=new Map;for(const[name,entry]of Object.entries(STORAGE_KINDS))map.set(name,Object.freeze({...entry,allowedOrigins:Object.freeze([...entry.allowedOrigins])}));for(const[name,entry]of Object.entries(registrations)){if(map.has(name))throw new TypeError(`Storage kind '${name}' cannot be overridden.`);if(!name||!entry||Object.keys(entry).some(key=>!["allowedOrigins","validatePayload","validateEvent","conflictIsDataLoss"].includes(key))||!Array.isArray(entry.allowedOrigins)||entry.allowedOrigins.length===0||entry.allowedOrigins.some(origin=>!ORIGIN_KINDS.includes(origin))||entry.validatePayload!==void 0&&typeof entry.validatePayload!=="function"||entry.validateEvent!==void 0&&typeof entry.validateEvent!=="function"||entry.conflictIsDataLoss!==void 0&&typeof entry.conflictIsDataLoss!=="boolean"){throw new TypeError(`Invalid registration for kind '${name}'.`)}map.set(name,Object.freeze({...entry,allowedOrigins:Object.freeze([...entry.allowedOrigins])}))}return map}export function streamJson(row){return{...row}}
1
+ import{DECLARABLE_IDENTITY_QUALITIES,ORIGIN_KINDS,REV_ORDERS,validateIdentityRebindPayload}from"./contracts/index.js";const SYSTEM_STREAMS=["identity","ingest","erasure","security","system"].map(stream=>({source:"rooktrail",stream,revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"}));const STORAGE_KINDS={"identity.rebind":{allowedOrigins:["kernel","derivation"],validatePayload:validateIdentityRebindPayload},"ingest.anomaly":{allowedOrigins:["kernel"],internalOnly:true},"ingest.unknown-kind":{allowedOrigins:["kernel"],internalOnly:true},"erasure.tombstone":{allowedOrigins:["kernel"],internalOnly:true,reportForgery:true},"erasure.suppressed":{allowedOrigins:["kernel"],internalOnly:true,reportForgery:true},"security.incident":{allowedOrigins:["kernel"],internalOnly:true}};export function streamKey(source,stream){return`${source}\0${stream}`}export function validateStream(row){const name=value=>typeof value==="string"&&value.length>0&&value.length<=1024&&!value.includes("\0");if(!row||Object.keys(row).some(key=>!["source","stream","revOrder","comparator","quality","noneIdentity","deleteKind"].includes(key))||row.deleteKind!==void 0&&!name(row.deleteKind)||!name(row.source)||!name(row.stream)||row.source==="rooktrail"||!REV_ORDERS.includes(row.revOrder)||row.comparator!==void 0&&!["numeric","lex"].includes(row.comparator)||row.quality!==void 0&&!DECLARABLE_IDENTITY_QUALITIES.includes(row.quality)||row.quality==="none"&&!["state","occurrence"].includes(row.noneIdentity??"")||row.quality!=="none"&&row.noneIdentity!==void 0){throw new TypeError("Invalid stream declaration. The rooktrail source is reserved for storage facts.")}}export function buildStreamMap(registrations){const map=new Map;for(const row of SYSTEM_STREAMS)map.set(streamKey(row.source,row.stream),{...row});for(const row of registrations){validateStream(row);map.set(streamKey(row.source,row.stream),{...row})}return map}export function buildKindMap(registrations={}){const map=new Map;for(const[name,entry]of Object.entries(STORAGE_KINDS))map.set(name,Object.freeze({...entry,allowedOrigins:Object.freeze([...entry.allowedOrigins])}));for(const[name,entry]of Object.entries(registrations)){if(map.has(name))throw new TypeError(`Storage kind '${name}' cannot be overridden.`);if(!name||!entry||Object.keys(entry).some(key=>!["allowedOrigins","validatePayload","validateEvent","conflictIsDataLoss"].includes(key))||!Array.isArray(entry.allowedOrigins)||entry.allowedOrigins.length===0||entry.allowedOrigins.some(origin=>!ORIGIN_KINDS.includes(origin))||entry.validatePayload!==void 0&&typeof entry.validatePayload!=="function"||entry.validateEvent!==void 0&&typeof entry.validateEvent!=="function"||entry.conflictIsDataLoss!==void 0&&typeof entry.conflictIsDataLoss!=="boolean"){throw new TypeError(`Invalid registration for kind '${name}'.`)}map.set(name,Object.freeze({...entry,allowedOrigins:Object.freeze([...entry.allowedOrigins])}))}return map}export function streamJson(row){return{...row}}