@tearleads/client-sdk 0.1.251 → 0.1.252

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 (141) hide show
  1. package/Tearleads.d.ts +0 -2
  2. package/Tearleads.js +14 -25
  3. package/Tearleads.js.map +1 -1
  4. package/client/organizations/organizationReadModelPresentation.js +7 -4
  5. package/client/organizations/organizationReadModelPresentation.js.map +1 -1
  6. package/client/organizations/organizationReadModels.js +6 -5
  7. package/client/organizations/organizationReadModels.js.map +1 -1
  8. package/client/organizations/organizationWorkflowRuntime.js +1 -1
  9. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  10. package/client/runtime/principalMutationApi.d.ts +4 -0
  11. package/client/runtime/principalMutationApi.js +9 -5
  12. package/client/runtime/principalMutationApi.js.map +1 -1
  13. package/client/runtime/runtimeIdentityResolution.js +23 -0
  14. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  15. package/client/runtime/runtimeSubscription.js +68 -0
  16. package/client/runtime/runtimeSubscription.js.map +1 -0
  17. package/client/runtime/workflowRuntime.d.ts +1 -1
  18. package/client/runtime/workflowRuntime.js +20 -77
  19. package/client/runtime/workflowRuntime.js.map +1 -1
  20. package/client/session/authenticationMachine.js +47 -0
  21. package/client/session/authenticationMachine.js.map +1 -0
  22. package/client/session/index.js +75 -93
  23. package/client/session/index.js.map +1 -1
  24. package/client/session/sessionBlobStore.js +39 -0
  25. package/client/session/sessionBlobStore.js.map +1 -0
  26. package/client/session/sessionContext.js +11 -0
  27. package/client/session/sessionContext.js.map +1 -1
  28. package/client/session/sessionIdentityTrust.d.ts +2 -1
  29. package/client/session/sessionIdentityTrust.js +8 -4
  30. package/client/session/sessionIdentityTrust.js.map +1 -1
  31. package/client/session/sessionLifetime.js +87 -0
  32. package/client/session/sessionLifetime.js.map +1 -0
  33. package/client/session/sessionLogin.js +114 -0
  34. package/client/session/sessionLogin.js.map +1 -0
  35. package/client/session/sessionOrganizationCreation.js +3 -2
  36. package/client/session/sessionOrganizationCreation.js.map +1 -1
  37. package/client/session/sessionPurgeRecovery.js +11 -3
  38. package/client/session/sessionPurgeRecovery.js.map +1 -1
  39. package/client/session/sessionTypes.d.ts +6 -2
  40. package/client/session/sessionTypes.js.map +1 -1
  41. package/data/blobs/blobContracts.d.ts +4 -3
  42. package/data/blobs/blobContracts.js.map +1 -1
  43. package/data/blobs/createBlobStore.js +1 -8
  44. package/data/blobs/createBlobStore.js.map +1 -1
  45. package/data/blobs/encryptedBlobStore.js +17 -12
  46. package/data/blobs/encryptedBlobStore.js.map +1 -1
  47. package/data/blobs/memoryBlobStore.js +8 -5
  48. package/data/blobs/memoryBlobStore.js.map +1 -1
  49. package/data/blobs/opfsBlobFile.js +36 -0
  50. package/data/blobs/opfsBlobFile.js.map +1 -0
  51. package/data/blobs/opfsBlobStore.d.ts +1 -1
  52. package/data/blobs/opfsBlobStore.js +91 -21
  53. package/data/blobs/opfsBlobStore.js.map +1 -1
  54. package/data/principals/principalPolicyCoordinator.js +8 -17
  55. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  56. package/data/shared/domainScope.d.ts +2 -0
  57. package/data/shared/domainScope.js +2 -1
  58. package/data/shared/domainScope.js.map +1 -1
  59. package/data/shared/keyedQueue.js +15 -0
  60. package/data/shared/keyedQueue.js.map +1 -0
  61. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  62. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  63. package/data/sqlite/sqlExec.d.ts +6 -0
  64. package/data/sqlite/sqlExec.js +64 -13
  65. package/data/sqlite/sqlExec.js.map +1 -1
  66. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  67. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  68. package/data/trustedUserIdentity/service.js +2 -1
  69. package/data/trustedUserIdentity/service.js.map +1 -1
  70. package/data/trustedUserIdentity/types.d.ts +1 -1
  71. package/data/trustedUserIdentity/types.js.map +1 -1
  72. package/internal/api-client/ApiClient.d.ts +4 -1
  73. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  74. package/internal/api-client/apiRequestRuntime.js +86 -101
  75. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  76. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  77. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  78. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  79. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  80. package/internal/api-client/client/blobs.d.ts +1 -0
  81. package/internal/api-client/client/blobs.js +12 -3
  82. package/internal/api-client/client/blobs.js.map +1 -1
  83. package/internal/api-client/client/laneListingRequest.js +4 -0
  84. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  85. package/internal/api-client/client/session.d.ts +5 -1
  86. package/internal/api-client/client/session.js +12 -4
  87. package/internal/api-client/client/session.js.map +1 -1
  88. package/internal/api-client/client/writerProjections.js +12 -13
  89. package/internal/api-client/client/writerProjections.js.map +1 -1
  90. package/internal/api-client/operationResponse.d.ts +1 -1
  91. package/internal/api-client/operationResponse.js +10 -23
  92. package/internal/api-client/operationResponse.js.map +1 -1
  93. package/internal/api-client/operationTransport.js +2 -1
  94. package/internal/api-client/operationTransport.js.map +1 -1
  95. package/internal/api-client/principalHistoryRequest.js +25 -20
  96. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  97. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  98. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  99. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  100. package/internal/api-client/principalPolicyPages.js +4 -2
  101. package/internal/api-client/principalPolicyPages.js.map +1 -1
  102. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  103. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  104. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  105. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  106. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  107. package/internal/api-client/routes/blobs/get.js +9 -67
  108. package/internal/api-client/routes/blobs/get.js.map +1 -1
  109. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  110. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  111. package/internal/api-client/sessionRefresh.js +1 -1
  112. package/internal/api-client/sessionRefresh.js.map +1 -1
  113. package/internal/api-client/sessionRenewal.d.ts +31 -0
  114. package/internal/api-client/sessionRenewal.js +91 -6
  115. package/internal/api-client/sessionRenewal.js.map +1 -1
  116. package/internal/api-client/sessionRequestInit.js +22 -0
  117. package/internal/api-client/sessionRequestInit.js.map +1 -0
  118. package/internal/api-client/sessionResponse.js +39 -0
  119. package/internal/api-client/sessionResponse.js.map +1 -0
  120. package/internal/api-client/types.d.ts +1 -0
  121. package/internal/api-client/types.js.map +1 -1
  122. package/internal/api-client/webSocketTickets.d.ts +1 -0
  123. package/internal/api-client/webSocketTickets.js +4 -0
  124. package/internal/api-client/webSocketTickets.js.map +1 -1
  125. package/internal/sqlite-worker/client.d.ts +1 -1
  126. package/internal/sqlite-worker/client.js +6 -1
  127. package/internal/sqlite-worker/client.js.map +1 -1
  128. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  129. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  130. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  131. package/internal/sqlite-worker/types.d.ts +4 -0
  132. package/internal/sqlite-worker/types.js.map +1 -1
  133. package/package.json +1 -1
  134. package/sqlite/worker.js +1 -1
  135. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  136. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  137. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  138. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  139. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  140. package/workflows/registration/registerIdentity.js +2 -0
  141. package/workflows/registration/registerIdentity.js.map +1 -1
@@ -1 +1 @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,MAAM,KAAK,KAAK;gBAAE,OAAO,QAAQ,CAAC,KAAK,CAAC;YACtD,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACjC,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACrD,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC,CAAC;IACH,6EAA6E;IAC7E,uEAAuE;IACvE,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO,CACL,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { recoverJournaledPrincipalMutation } from \"../../workflows/organizations\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalManagement\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n /** Binds a mutation's committed read-model lease to its session. */\n readonly readSessionGeneration?: (() => number) | undefined;\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n domainScope: scope.database,\n sessionGeneration: input.readSessionGeneration?.() ?? 0,\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal principal policy and group lifecycle writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n if (cached && sameScope(scope, cached.scope)) return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n ...createJournaledPrincipalMutations(input.api, context, dispatch),\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.api,\n organizationId,\n mutation,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(input.api, methods);\n cached = { scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = value.bind(target);\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
1
+ {"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EACL,iCAAiC,EACjC,iCAAiC,GAElC,MAAM,6BAA6B,CAAC;AAYrC,SAAS,SAAS,CAChB,OAA6C,EAC7C,KAA2C;IAE3C,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK;QAAE,OAAO,OAAO,KAAK,KAAK,CAAC;IACjD,OAAO,CACL,OAAO,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;QACnC,OAAO,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO;QACjC,OAAO,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;QACvC,OAAO,CAAC,mBAAmB,KAAK,KAAK,CAAC,mBAAmB;QACzD,OAAO,CAAC,kBAAkB,KAAK,KAAK,CAAC,kBAAkB;QACvD,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,CAChC,CAAC;AACJ,CAAC;AAeD,SAAS,eAAe,CACtB,K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GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { recoverJournaledPrincipalMutation } from \"../../workflows/organizations\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalManagement\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n /** Binds a mutation's committed read-model lease to its session. */\n readonly readSessionGeneration?: (() => number) | undefined;\n readonly signIn?: { readonly epoch: number; guard(): () => void };\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n domainScope: scope.database,\n sessionGeneration: input.readSessionGeneration?.() ?? 0,\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal principal policy and group lifecycle writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n epoch: number | undefined;\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n const epoch = input.signIn?.epoch;\n if (cached && epoch === cached.epoch && sameScope(scope, cached.scope))\n return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n ...createJournaledPrincipalMutations(input.api, context, dispatch),\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.api,\n organizationId,\n mutation,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(\n input.api,\n methods,\n input.signIn?.guard(),\n );\n cached = { epoch, scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n assertCurrent?: () => void,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = (...args: unknown[]) => {\n assertCurrent?.();\n return Reflect.apply(value, target, args);\n };\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
@@ -35,4 +35,27 @@ export function createRuntimeIdentityResolution(dependencies, getExecSql, getSco
35
35
  });
36
36
  return { trustedUserIdentityService, resolveTrustedUserIdentity };
37
37
  }
38
+ /** A delayed workflow cannot start resolving or pinning an identity in the
39
+ * session that replaced it. The service fences an ongoing pin at commit. */
40
+ export function bindSessionIdentityResolver(resolve, signIn) {
41
+ let cached;
42
+ return () => {
43
+ if (cached?.epoch === signIn.epoch)
44
+ return cached.resolve;
45
+ const guard = signIn.guard();
46
+ const bound = Object.assign(async (userId) => {
47
+ guard();
48
+ return resolve(userId);
49
+ }, {
50
+ withPinnedIdentities: async (userIds, verify, options) => {
51
+ guard();
52
+ if (!resolve.withPinnedIdentities)
53
+ throw new Error("Trusted identity batch reader is unavailable");
54
+ return resolve.withPinnedIdentities(userIds, verify, options);
55
+ },
56
+ });
57
+ cached = { epoch: signIn.epoch, resolve: bound };
58
+ return bound;
59
+ };
60
+ }
38
61
  //# sourceMappingURL=runtimeIdentityResolution.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeIdentityResolution.js","sourceRoot":"","sources":["runtimeIdentityResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,GAEjC,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GAIjC,MAAM,gCAAgC,CAAC;AAIxC,qFAAqF;AACrF,MAAM,UAAU,+BAA+B,CAC7C,YASC,EACD,UAAgC,EAChC,kBAAiC;IAEjC,MAAM,0BAA0B,GAAG,gCAAgC,CAAC;QAClE,UAAU;QACV,kBAAkB;QAClB,gBAAgB,EAAE,GAAG,EAAE;YACrB,MAAM,EAAE,oBAAoB,EAAE,cAAc,EAAE,kBAAkB,EAAE,GAChE,YAAY,CAAC,QAAQ,CAAC;YACxB,OAAO,oBAAoB,IAAI,cAAc;gBAC3C,CAAC,CAAC;oBACE,sBAAsB,EAAE,oBAAoB,CAAC,SAAS;oBACtD,gBAAgB,EAAE,cAAc,CAAC,gBAAgB;oBACjD,qBAAqB,EAAE,kBAAkB;iBAC1C;g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\"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type StagedUserIdentityOptions,\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport type { Identity } from \"../identity\";\nimport type { Session } from \"../session/sessionTypes\";\n\n/** Compose both direct resolution and scoped structural pin reads with reporting. */\nexport function createRuntimeIdentityResolution(\n dependencies: {\n readonly api: Parameters<typeof createApiUserIdentitySource>[0];\n readonly identity: Pick<\n Identity,\n \"encapsulationKeyPair\" | \"signingKeyPair\" | \"signingFingerprint\"\n >;\n readonly identityTrustDomain: string | null;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly session: Pick<Session, \"userId\" | \"organizationId\">;\n },\n getExecSql: () => ExecSql | null,\n getScopeGeneration: () => unknown,\n) {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql,\n getScopeGeneration,\n getLocalIdentity: () => {\n const { encapsulationKeyPair, signingKeyPair, signingFingerprint } =\n dependencies.identity;\n return encapsulationKeyPair && signingKeyPair\n ? {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingPublicKey: signingKeyPair.signingPublicKey,\n signingKeyFingerprint: signingFingerprint,\n }\n : null;\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const report = <T>(userId: string, operation: () => Promise<T>) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n operation,\n );\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = Object.assign(\n (userId: string) =>\n report(userId, () => trustedUserIdentityService.resolve(userId)),\n {\n withPinnedIdentities: <T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ) => {\n const withPinnedIdentities =\n trustedUserIdentityService.resolve.withPinnedIdentities;\n if (!withPinnedIdentities)\n throw new Error(\"Trusted identity batch reader is unavailable\");\n return withPinnedIdentities(\n userIds,\n (resolve) =>\n verify((userId) => report(userId, () => resolve(userId))),\n options,\n );\n },\n },\n );\n return { trustedUserIdentityService, resolveTrustedUserIdentity };\n}\n"]}
1
+ {"version":3,"file":"runtimeIdentityResolution.js","sourceRoot":"","sources":["runtimeIdentityResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,GAEjC,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GAIjC,MAAM,gCAAgC,CAAC;AAIxC,qFAAqF;AACrF,MAAM,UAAU,+BAA+B,CAC7C,YASC,EACD,UAAgC,EAChC,kBAAiC;IAEjC,MAAM,0BAA0B,GAAG,gCAAgC,CAAC;QAClE,UAAU;QACV,kBAAkB;QAClB,gBAAgB,EAAE,GAAG,EAAE;YACrB,MAAM,EAAE,oBAAoB,EAAE,cAAc,EAAE,kBAAkB,EAAE,GAChE,YAAY,CAAC,QAAQ,CAAC;YACxB,OAAO,oBAAoB,IAAI,cAAc;gBAC3C,CAAC,CAAC;oBACE,sBAAsB,EAAE,oBAAoB,CAAC,SAAS;oBACtD,gBAAgB,EAAE,cAAc,CAAC,gBAAgB;oBACjD,qBAAqB,EAAE,kBAAkB;iBAC1C;gBACH,CAAC,CAAC,IAAI,CAAC;QACX,CAAC;QACD,cAAc,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM;QACjD,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;QACrD,YAAY,EAAE,2BAA2B,CAAC,YAAY,CAAC,GAAG,CAAC;KAC5D,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,CAAI,MAAc,EAAE,SAA2B,EAAE,EAAE,CAChE,gCAAgC,CAC9B,YAAY,CAAC,sBAAsB,EACnC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,MAAM,CAAC,CAAC;QACzB,CAAC,EACD;YACE,oBAAoB,EAAE,KAAK,EACzB,OAA0B,EAC1B,MAA2D,EAC3D,OAAkC,EAClC,EAAE;gBACF,KAAK,EAAE,CAAC;gBACR,IAAI,CAAC,OAAO,CAAC,oBAAoB;oBAC/B,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBAClE,OAAO,OAAO,CAAC,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;YAChE,CAAC;SACF,CACF,CAAC;QACF,MAAM,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QACjD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type StagedUserIdentityOptions,\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport type { Identity } from \"../identity\";\nimport type { Session } from \"../session/sessionTypes\";\n\n/** Compose both direct resolution and scoped structural pin reads with reporting. */\nexport function createRuntimeIdentityResolution(\n dependencies: {\n readonly api: Parameters<typeof createApiUserIdentitySource>[0];\n readonly identity: Pick<\n Identity,\n \"encapsulationKeyPair\" | \"signingKeyPair\" | \"signingFingerprint\"\n >;\n readonly identityTrustDomain: string | null;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly session: Pick<Session, \"userId\" | \"organizationId\">;\n },\n getExecSql: () => ExecSql | null,\n getScopeGeneration: () => unknown,\n) {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql,\n getScopeGeneration,\n getLocalIdentity: () => {\n const { encapsulationKeyPair, signingKeyPair, signingFingerprint } =\n dependencies.identity;\n return encapsulationKeyPair && signingKeyPair\n ? {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingPublicKey: signingKeyPair.signingPublicKey,\n signingKeyFingerprint: signingFingerprint,\n }\n : null;\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const report = <T>(userId: string, operation: () => Promise<T>) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n operation,\n );\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = Object.assign(\n (userId: string) =>\n report(userId, () => trustedUserIdentityService.resolve(userId)),\n {\n withPinnedIdentities: <T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ) => {\n const withPinnedIdentities =\n trustedUserIdentityService.resolve.withPinnedIdentities;\n if (!withPinnedIdentities)\n throw new Error(\"Trusted identity batch reader is unavailable\");\n return withPinnedIdentities(\n userIds,\n (resolve) =>\n verify((userId) => report(userId, () => resolve(userId))),\n options,\n );\n },\n },\n );\n return { trustedUserIdentityService, resolveTrustedUserIdentity };\n}\n\n/** A delayed workflow cannot start resolving or pinning an identity in the\n * session that replaced it. The service fences an ongoing pin at commit. */\nexport function bindSessionIdentityResolver(\n resolve: TrustedUserIdentityResolver,\n signIn: { readonly epoch: number; guard(): () => void },\n): () => TrustedUserIdentityResolver {\n let cached:\n | { epoch: number; resolve: TrustedUserIdentityResolver }\n | undefined;\n return () => {\n if (cached?.epoch === signIn.epoch) return cached.resolve;\n const guard = signIn.guard();\n const bound = Object.assign(\n async (userId: string) => {\n guard();\n return resolve(userId);\n },\n {\n withPinnedIdentities: async <T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ) => {\n guard();\n if (!resolve.withPinnedIdentities)\n throw new Error(\"Trusted identity batch reader is unavailable\");\n return resolve.withPinnedIdentities(userIds, verify, options);\n },\n },\n );\n cached = { epoch: signIn.epoch, resolve: bound };\n return bound;\n };\n}\n"]}
@@ -0,0 +1,68 @@
1
+ import { createListenerSet } from "../../data/shared/listenerSet.js";
2
+ import { sessionLifetime } from "../session/index.js";
3
+ export function createRuntimeSubscription(dependencies) {
4
+ const listeners = createListenerSet();
5
+ let version = 0;
6
+ let sessionGeneration = 0;
7
+ let recoveryGeneration = 0;
8
+ let mutationGeneration = 0;
9
+ const lifetime = sessionLifetime(dependencies.session);
10
+ let epoch = lifetime.epoch;
11
+ let sessionSnapshot = dependencies.session.snapshot;
12
+ const notifyListeners = () => {
13
+ version += 1;
14
+ listeners.notify();
15
+ };
16
+ const notifyAuthority = () => {
17
+ recoveryGeneration += 1;
18
+ mutationGeneration += 1;
19
+ notifyListeners();
20
+ };
21
+ dependencies.database.subscribe(notifyAuthority);
22
+ dependencies.events.subscribe(notifyListeners);
23
+ dependencies.identity.subscribe(notifyAuthority);
24
+ dependencies.network.subscribe(() => notifyListeners());
25
+ dependencies.session.subscribe(() => {
26
+ const next = dependencies.session.snapshot;
27
+ const replaced = epoch !== lifetime.epoch;
28
+ epoch = lifetime.epoch;
29
+ const changed = replaced || sessionScopeChanged(sessionSnapshot, next);
30
+ if (changed ||
31
+ (next.authToken !== sessionSnapshot.authToken &&
32
+ lifetime.lastRenewal !== next)) {
33
+ sessionGeneration += 1;
34
+ recoveryGeneration += 1;
35
+ }
36
+ if (changed)
37
+ mutationGeneration += 1;
38
+ sessionSnapshot = next;
39
+ notifyListeners();
40
+ });
41
+ dependencies.syncBillingGate?.subscribe(notifyListeners);
42
+ return {
43
+ get mutationGeneration() {
44
+ return mutationGeneration;
45
+ },
46
+ get recoveryGeneration() {
47
+ return recoveryGeneration;
48
+ },
49
+ get sessionGeneration() {
50
+ return sessionGeneration;
51
+ },
52
+ get version() {
53
+ return version;
54
+ },
55
+ subscribe(listener) {
56
+ return listeners.subscribe(listener);
57
+ },
58
+ };
59
+ }
60
+ // A transport token renewal cannot turn a definite write refusal into saved work.
61
+ // Journal custody still expires on every change to its identity or storage scope.
62
+ function sessionScopeChanged(previous, next) {
63
+ return (next.isAuthenticated !== previous.isAuthenticated ||
64
+ next.isRoot !== previous.isRoot ||
65
+ next.organizationId !== previous.organizationId ||
66
+ next.userId !== previous.userId);
67
+ }
68
+ //# sourceMappingURL=runtimeSubscription.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeSubscription.js","sourceRoot":"","sources":["runtimeSubscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAe7C,MAAM,UAAU,yBAAyB,CAAC,YAAiC;IACzE,MAAM,SAAS,GAAG,iBAAiB,EAAE,CAAC;IACtC,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,iBAAiB,GAAG,CAAC,CAAC;IAC1B,IAAI,kBAAkB,GAAG,CAAC,CAAC;IAC3B,IAAI,kBAAkB,GAAG,CAAC,CAAC;IAC3B,MAAM,QAAQ,GAAG,eAAe,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACvD,IAAI,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAC3B,IAAI,eAAe,GAAG,YAAY,CAAC,OAAO,CAAC,QAAQ,CAAC;IACpD,MAAM,eAAe,GAAG,GAAG,EAAE;QAC3B,OAAO,IAAI,CAAC,CAAC;QACb,SAAS,CAAC,MAAM,EAAE,CAAC;IACrB,CAAC,CAAC;IAEF,MAAM,eAAe,GAAG,GAAG,EAAE;QAC3B,kBAAkB,IAAI,CAAC,CAAC;QACxB,kBAAkB,IAAI,CAAC,CAAC;QACxB,eAAe,EAAE,CAAC;IACpB,CAAC,CAAC;IACF,YAAY,CAAC,QAAQ,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACjD,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KACF,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,kFAAkF;AAClF,SAAS,mBAAmB,CAC1B,QAAyB,EACzB,IAAqB;IAErB,OAAO,CACL,IAAI,CAAC,eAAe,KAAK,QAAQ,CAAC,eAAe;QACjD,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM;QAC/B,IAAI,CAAC,cAAc,KAAK,QAAQ,CAAC,cAAc;QAC/C,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,CAChC,CAAC;AACJ,CAAC","sourcesContent":["import { createListenerSet } from \"../../data/shared/listenerSet\";\nimport { sessionLifetime } from \"../session\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\n\ninterface Subscribable {\n subscribe(listener: () => void): () => void;\n}\ninterface SubscriptionSources {\n database: Subscribable;\n events: Subscribable;\n identity: Subscribable;\n network: Subscribable;\n session: Session;\n syncBillingGate?: Subscribable | undefined;\n}\n\nexport function createRuntimeSubscription(dependencies: SubscriptionSources) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n const lifetime = sessionLifetime(dependencies.session);\n let epoch = lifetime.epoch;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n const replaced = epoch !== lifetime.epoch;\n epoch = lifetime.epoch;\n const changed = replaced || sessionScopeChanged(sessionSnapshot, next);\n if (\n changed ||\n (next.authToken !== sessionSnapshot.authToken &&\n lifetime.lastRenewal !== next)\n ) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (changed) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: () => void): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n"]}
@@ -44,7 +44,7 @@ export interface InternalRuntime {
44
44
  readonly containerContentsOrganizations: ContainerContentsOrganizationHost;
45
45
  readonly publicRuntime: Runtime;
46
46
  boundUserId(signingKeyFingerprint: string): Promise<string | null>;
47
- pinLocalUserIdentity(userId: string, candidate: LocalUserIdentityCandidate): Promise<void>;
47
+ pinLocalUserIdentity(userId: string, candidate: LocalUserIdentityCandidate, assertCurrent?: () => void): Promise<void>;
48
48
  readonly primeProvisionedState: ProvisionedStatePrimer;
49
49
  workflowInput(containerId?: string | null | undefined): InternalWorkflowRuntimeInput;
50
50
  }
@@ -1,5 +1,4 @@
1
1
  import { deleteDocumentPlacements } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
- import { createListenerSet } from "../../data/shared/listenerSet.js";
3
2
  import { runWithSecurityIncidentReporting, } from "../../data/shared/securityIncidents.js";
4
3
  import { unavailableExecSql } from "../../data/sqlite/sqlSchema.js";
5
4
  import { loadPinnedUserIdentity, } from "../../data/trustedUserIdentity/index.js";
@@ -7,16 +6,19 @@ import { createContainerContentsOrganizationHost } from "../../workflows/organiz
7
6
  import { PrincipalPolicyService } from "../../workflows/principals/principalPolicyService.js";
8
7
  import { createProvisionedStatePrimer, } from "../../workflows/registration/provisionedStatePrimer.js";
9
8
  import { getOrCreateOrganizationSyncPauses } from "../../workflows/sync/coordination.js";
9
+ import { sessionLifetime } from "../session/index.js";
10
10
  import { acknowledgedSessionRoot } from "../session/sessionRootAuthority.js";
11
11
  import { createPrincipalHistoryProtectionCustody, } from "./principalHistoryProtection.js";
12
12
  import { createPrincipalMutationApiCustody, } from "./principalMutationApi.js";
13
13
  import { adoptSessionRootContainer } from "./rootContainerAdoption.js";
14
- import { createRuntimeIdentityResolution } from "./runtimeIdentityResolution.js";
14
+ import { bindSessionIdentityResolver, createRuntimeIdentityResolution, } from "./runtimeIdentityResolution.js";
15
15
  import { reuseIfShallowEqual } from "./runtimeInputReuse.js";
16
+ import { createRuntimeSubscription } from "./runtimeSubscription.js";
16
17
  function createRuntimeMutationApi(dependencies, readGeneration, readSessionGeneration) {
17
18
  return createPrincipalMutationApiCustody({
18
19
  api: dependencies.api,
19
20
  readSessionGeneration,
21
+ signIn: sessionLifetime(dependencies.session),
20
22
  principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,
21
23
  readScope: () => {
22
24
  const { signingKeyPair, signingFingerprint } = dependencies.identity;
@@ -31,7 +33,7 @@ function createRuntimeMutationApi(dependencies, readGeneration, readSessionGener
31
33
  return null;
32
34
  return {
33
35
  database: dependencies.getDomainScope(),
34
- execSql: dependencies.database.requireExecSql("principal mutation"),
36
+ execSql: sessionLifetime(dependencies.session).bind(dependencies.database.requireExecSql("principal mutation")),
35
37
  generation: readGeneration(),
36
38
  identityTrustDomain,
37
39
  signingFingerprint,
@@ -57,10 +59,14 @@ function createRuntimeProvisioningPrimer(dependencies, bindLease, readyExecSql)
57
59
  signingFingerprint: () => dependencies.identity.signingFingerprint,
58
60
  });
59
61
  }
60
- export function createRuntime(dependencies) {
61
- const readyExecSql = () => dependencies.database.status === "ready"
62
- ? dependencies.database.requireExecSql("trusted user identity")
62
+ function sessionExecutor(dependencies) {
63
+ const execSql = dependencies.database.execSql;
64
+ return dependencies.database.status === "ready" && execSql
65
+ ? sessionLifetime(dependencies.session).bind(execSql)
63
66
  : null;
67
+ }
68
+ export function createRuntime(dependencies) {
69
+ const readyExecSql = () => sessionExecutor(dependencies);
64
70
  const runtimeSubscription = createRuntimeSubscription(dependencies);
65
71
  const { trustedUserIdentityService, resolveTrustedUserIdentity } = createRuntimeIdentityResolution(dependencies, readyExecSql, () => runtimeSubscription.recoveryGeneration);
66
72
  const historyProtection = createPrincipalHistoryProtectionCustody({
@@ -75,12 +81,12 @@ export function createRuntime(dependencies) {
75
81
  return {
76
82
  signingFingerprint,
77
83
  identityTrustDomain,
78
- database: dependencies.getDomainScope(),
84
+ database: dependencies.database.requireExecSql("principal history protection"),
79
85
  generation: runtimeSubscription.recoveryGeneration,
80
86
  };
81
87
  },
82
88
  });
83
- const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, historyProtection.bind, createRuntimeMutationApi(dependencies, () => runtimeSubscription.mutationGeneration, () => runtimeSubscription.sessionGeneration).bind);
89
+ const runtimeInput = createRuntimeInputFactory(dependencies, bindSessionIdentityResolver(resolveTrustedUserIdentity, sessionLifetime(dependencies.session)), historyProtection.bind, createRuntimeMutationApi(dependencies, () => runtimeSubscription.mutationGeneration, () => runtimeSubscription.sessionGeneration).bind);
84
90
  return {
85
91
  identityTrustDomain: dependencies.identityTrustDomain,
86
92
  identityLinks: trustedUserIdentityService,
@@ -92,13 +98,13 @@ export function createRuntime(dependencies) {
92
98
  deleteDocumentPlacements,
93
99
  containerContentsOrganizations: createContainerContentsOrganizationHost(() => runtimeSubscription.sessionGeneration),
94
100
  boundUserId: (signingKeyFingerprint) => trustedUserIdentityService.boundUserId(signingKeyFingerprint),
95
- async pinLocalUserIdentity(userId, candidate) {
101
+ async pinLocalUserIdentity(userId, candidate, assertCurrent) {
96
102
  await runWithSecurityIncidentReporting(dependencies.reportSecurityIncident, {
97
103
  objectId: userId,
98
104
  objectKind: "user",
99
105
  operation: "user.identity.pin_local",
100
106
  organizationId: dependencies.session.organizationId,
101
- }, () => trustedUserIdentityService.pinLocal(userId, candidate));
107
+ }, () => trustedUserIdentityService.pinLocal(userId, candidate, assertCurrent));
102
108
  },
103
109
  primeProvisionedState: createRuntimeProvisioningPrimer(dependencies, historyProtection.bind, readyExecSql),
104
110
  publicRuntime: {
@@ -111,56 +117,6 @@ export function createRuntime(dependencies) {
111
117
  workflowInput: runtimeInput.workflowInput,
112
118
  };
113
119
  }
114
- function createRuntimeSubscription(dependencies) {
115
- const listeners = createListenerSet();
116
- let version = 0;
117
- let sessionGeneration = 0;
118
- let recoveryGeneration = 0;
119
- let mutationGeneration = 0;
120
- let sessionSnapshot = dependencies.session.snapshot;
121
- const notifyListeners = () => {
122
- version += 1;
123
- listeners.notify();
124
- };
125
- const notifyAuthority = () => {
126
- recoveryGeneration += 1;
127
- mutationGeneration += 1;
128
- notifyListeners();
129
- };
130
- dependencies.database.subscribe(notifyAuthority);
131
- dependencies.events.subscribe(notifyListeners);
132
- dependencies.identity.subscribe(notifyAuthority);
133
- dependencies.network.subscribe(() => notifyListeners());
134
- dependencies.session.subscribe(() => {
135
- const next = dependencies.session.snapshot;
136
- if (sessionAuthorityChanged(sessionSnapshot, next)) {
137
- sessionGeneration += 1;
138
- recoveryGeneration += 1;
139
- }
140
- if (sessionScopeChanged(sessionSnapshot, next))
141
- mutationGeneration += 1;
142
- sessionSnapshot = next;
143
- notifyListeners();
144
- });
145
- dependencies.syncBillingGate?.subscribe(notifyListeners);
146
- return {
147
- get mutationGeneration() {
148
- return mutationGeneration;
149
- },
150
- get recoveryGeneration() {
151
- return recoveryGeneration;
152
- },
153
- get sessionGeneration() {
154
- return sessionGeneration;
155
- },
156
- get version() {
157
- return version;
158
- },
159
- subscribe(listener) {
160
- return listeners.subscribe(listener);
161
- },
162
- };
163
- }
164
120
  function sessionAuthInput({ session, identity, }) {
165
121
  const signingFingerprint = identity.snapshot.signingFingerprint;
166
122
  return {
@@ -172,18 +128,6 @@ function sessionAuthInput({ session, identity, }) {
172
128
  userId: session.userId,
173
129
  };
174
130
  }
175
- /** Fields whose change invalidates work keyed on the session's authority. */
176
- function sessionAuthorityChanged(previous, next) {
177
- return (next.authToken !== previous.authToken || sessionScopeChanged(previous, next));
178
- }
179
- // A transport token renewal cannot turn a definite write refusal into saved work.
180
- // Journal custody still expires on every change to its identity or storage scope.
181
- function sessionScopeChanged(previous, next) {
182
- return (next.isAuthenticated !== previous.isAuthenticated ||
183
- next.isRoot !== previous.isRoot ||
184
- next.organizationId !== previous.organizationId ||
185
- next.userId !== previous.userId);
186
- }
187
131
  function runtimeInputUtilities(dependencies, util) {
188
132
  if (!util ||
189
133
  util.log !== dependencies.log ||
@@ -201,7 +145,7 @@ function runtimeInputUtilities(dependencies, util) {
201
145
  }
202
146
  return util;
203
147
  }
204
- function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bindHistoryProtection, bindMutationApi) {
148
+ function createRuntimeInputFactory(dependencies, bindIdentityResolver, bindHistoryProtection, bindMutationApi) {
205
149
  let auth;
206
150
  let crypto;
207
151
  let infra;
@@ -210,9 +154,7 @@ function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bin
210
154
  let hostUtil;
211
155
  const workflowInput = (containerId) => {
212
156
  const dbStatus = dependencies.database.status;
213
- const execSql = dbStatus === "ready"
214
- ? dependencies.database.requireExecSql("tearleads.runtime.input")
215
- : unavailableExecSql;
157
+ const execSql = sessionExecutor(dependencies) ?? unavailableExecSql;
216
158
  const nextContainerId = (containerId === undefined
217
159
  ? dependencies.session.containerId
218
160
  : containerId) ?? null;
@@ -223,7 +165,7 @@ function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bin
223
165
  signingKeyPair: dependencies.identity.signingKeyPair,
224
166
  });
225
167
  infra = reuseIfShallowEqual(infra, {
226
- blobStore: dependencies.blobs.store,
168
+ blobStore: sessionLifetime(dependencies.session).bindBlobStore(dependencies.blobs.store),
227
169
  dbStatus,
228
170
  documentProjectors: dependencies.documentProjectors,
229
171
  // Runtime consumers branch on dbStatus before touching SQLite. The
@@ -244,6 +186,7 @@ function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bin
244
186
  });
245
187
  util = runtimeInputUtilities(dependencies, util);
246
188
  const apiClient = bindMutationApi();
189
+ const resolveTrustedUserIdentity = bindIdentityResolver();
247
190
  return {
248
191
  apiClient,
249
192
  auth,
@@ -1 +1 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAI5H,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EACL,gCAAgC,GAEjC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAEL,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAC9G,OAAO,EAAE,sBAAsB,EAAE,MAAM,mDAAmD,CAAC;AAC3F,OAAO,EACL,4BAA4B,GAE7B,MAAM,qDAAqD,CAAC;AAS7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,mCAAmC,CAAC;AAGtF,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAK1E,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AA8E1D,SAAS,wBAAwB,CAC/B,YAAyC,EACzC,cAA4B,EAC5B,qBAAmC;IAEnC,OAAO,iCAAiC,CAAC;QACvC,GAAG,EAAE,YAAY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,GAAG,eAAe,EAAE,CAAC;QACpC,OAAO;YACL,SAAS;YACT,IAAI;YACJ,MAAM;YACN,KAAK;YACL,KAAK;YACL,IAAI;YACJ,0BAA0B;YAC1B,4EAA4E;YAC5E,iBAAiB,EAAE,IAAI,sBAAsB,CAAC;gBAC5C,SAAS;gBACT,KAAK;gBACL,KAAK;gBACL,IAAI;gBACJ,0BAA0B;gBAC1B,8BAA8B,EAAE,qBAAqB,EAAE;aACxD,CAAC;SACH,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,SAAS,CAAC,WAAW;YACnB,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,0BAA0B,EAAE,2BAA2B,EACvD,iBAAiB,EAAE,kBAAkB,EACrC,IAAI,EAAE,YAAY,EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport type { DocumentPlacementCleanup } from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport { createListenerSet } from \"../../data/shared/listenerSet\";\nimport {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n ContainerContentsOrganizationHost,\n ContainerContentsRootAdopter,\n} from \"../../workflows/container-contents\";\nimport { createContainerContentsOrganizationHost } from \"../../workflows/organizations/containerContentsHost\";\nimport { PrincipalPolicyService } from \"../../workflows/principals/principalPolicyService\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../workflows/sync/coordination\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { createRuntimeIdentityResolution } from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Bound to this snapshot's API client, executor, and history custody. */\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nexport interface InternalRuntime {\n /** Resolved once by the composition root; constant for the client's life. */\n readonly identityTrustDomain: string | null;\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly deleteDocumentPlacements: DocumentPlacementCleanup;\n readonly containerContentsOrganizations: ContainerContentsOrganizationHost;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n readSessionGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n readSessionGeneration,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n () => runtimeSubscription.sessionGeneration,\n ).bind,\n );\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n deleteDocumentPlacements,\n containerContentsOrganizations: createContainerContentsOrganizationHost(\n () => runtimeSubscription.sessionGeneration,\n ),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId, direction = \"push\") =>\n getOrCreateOrganizationSyncPauses(\n dependencies.getDomainScope(),\n ).holdsSync(organizationId) ||\n (direction === \"push\" &&\n (dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ??\n false)),\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n const apiClient = bindMutationApi();\n return {\n apiClient,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n // Binds this snapshot's lease now; work on an older snapshot keeps its own.\n principalPolicies: new PrincipalPolicyService({\n apiClient,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n }),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n principalPolicies: _principalPolicies,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,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EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport type { DocumentPlacementCleanup } from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n ContainerContentsOrganizationHost,\n ContainerContentsRootAdopter,\n} from \"../../workflows/container-contents\";\nimport { createContainerContentsOrganizationHost } from \"../../workflows/organizations/containerContentsHost\";\nimport { PrincipalPolicyService } from \"../../workflows/principals/principalPolicyService\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../workflows/sync/coordination\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { sessionLifetime } from \"../session\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport {\n bindSessionIdentityResolver,\n createRuntimeIdentityResolution,\n} from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport { createRuntimeSubscription } from \"./runtimeSubscription\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Bound to this snapshot's API client, executor, and history custody. */\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nexport interface InternalRuntime {\n /** Resolved once by the composition root; constant for the client's life. */\n readonly identityTrustDomain: string | null;\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly deleteDocumentPlacements: DocumentPlacementCleanup;\n readonly containerContentsOrganizations: ContainerContentsOrganizationHost;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n assertCurrent?: () => void,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n readSessionGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n readSessionGeneration,\n signIn: sessionLifetime(dependencies.session),\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: sessionLifetime(dependencies.session).bind(\n dependencies.database.requireExecSql(\"principal mutation\"),\n ),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nfunction sessionExecutor(\n dependencies: WorkflowRuntimeDependencies,\n): ExecSql | null {\n const execSql = dependencies.database.execSql;\n return dependencies.database.status === \"ready\" && execSql\n ? sessionLifetime(dependencies.session).bind(execSql)\n : null;\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () => sessionExecutor(dependencies);\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.database.requireExecSql(\n \"principal history protection\",\n ),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n bindSessionIdentityResolver(\n resolveTrustedUserIdentity,\n sessionLifetime(dependencies.session),\n ),\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n () => runtimeSubscription.sessionGeneration,\n ).bind,\n );\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n deleteDocumentPlacements,\n containerContentsOrganizations: createContainerContentsOrganizationHost(\n () => runtimeSubscription.sessionGeneration,\n ),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate, assertCurrent) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () =>\n trustedUserIdentityService.pinLocal(userId, candidate, assertCurrent),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId, direction = \"push\") =>\n getOrCreateOrganizationSyncPauses(\n dependencies.getDomainScope(),\n ).holdsSync(organizationId) ||\n (direction === \"push\" &&\n (dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ??\n false)),\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n bindIdentityResolver: () => TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql = sessionExecutor(dependencies) ?? unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: sessionLifetime(dependencies.session).bindBlobStore(\n dependencies.blobs.store,\n ),\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n const apiClient = bindMutationApi();\n const resolveTrustedUserIdentity = bindIdentityResolver();\n return {\n apiClient,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n // Binds this snapshot's lease now; work on an older snapshot keeps its own.\n principalPolicies: new PrincipalPolicyService({\n apiClient,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n }),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n principalPolicies: _principalPolicies,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
@@ -0,0 +1,47 @@
1
+ function transitionAuthentication(state, event) {
2
+ switch (event.type) {
3
+ case "login":
4
+ return { status: "login", attempt: event.attempt };
5
+ case "renewal":
6
+ return state.status === "idle"
7
+ ? { status: "renewal", attempt: event.attempt }
8
+ : state;
9
+ case "finished":
10
+ return state.status !== "idle" && state.attempt === event.attempt
11
+ ? { status: "idle" }
12
+ : state;
13
+ case "invalidated":
14
+ return { status: "idle" };
15
+ }
16
+ }
17
+ export class SessionAuthentication {
18
+ state = { status: "idle" };
19
+ lastLogin;
20
+ captureRestore() {
21
+ const login = this.lastLogin;
22
+ const allowed = this.state.status !== "login";
23
+ return () => allowed && login === this.lastLogin;
24
+ }
25
+ start(renewal) {
26
+ const attempt = Symbol();
27
+ if (!renewal)
28
+ this.lastLogin = attempt;
29
+ this.state = transitionAuthentication(this.state, {
30
+ type: renewal ? "renewal" : "login",
31
+ attempt,
32
+ });
33
+ return {
34
+ current: () => this.state.status !== "idle" && this.state.attempt === attempt,
35
+ finish: () => {
36
+ this.state = transitionAuthentication(this.state, {
37
+ type: "finished",
38
+ attempt,
39
+ });
40
+ },
41
+ };
42
+ }
43
+ invalidate() {
44
+ this.state = transitionAuthentication(this.state, { type: "invalidated" });
45
+ }
46
+ }
47
+ //# sourceMappingURL=authenticationMachine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticationMachine.js","sourceRoot":"","sources":["authenticationMachine.ts"],"names":[],"mappings":"AAWA,SAAS,wBAAwB,CAC/B,KAA0B,EAC1B,KAA0B;IAE1B,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,OAAO;YACV,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QACrD,KAAK,SAAS;YACZ,OAAO,KAAK,CAAC,MAAM,KAAK,MAAM;gBAC5B,CAAC,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE;gBAC/C,CAAC,CAAC,KAAK,CAAC;QACZ,KAAK,UAAU;YACb,OAAO,KAAK,CAAC,MAAM,KAAK,MAAM,IAAI,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO;gBAC/D,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE;gBACpB,CAAC,CAAC,KAAK,CAAC;QACZ,KAAK,aAAa;YAChB,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;IAC9B,CAAC;AACH,CAAC;AAED,MAAM,OAAO,qBAAqB;IACxB,KAAK,GAAwB,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;IAEhD,SAAS,CAAqB;IAEtC,cAAc;QACZ,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;QAC7B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,OAAO,CAAC;QAC9C,OAAO,GAAG,EAAE,CAAC,OAAO,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,KAAK,CAAC,OAAgB;QACpB,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC;QACzB,IAAI,CAAC,OAAO;YAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC;QACvC,IAAI,CAAC,KAAK,GAAG,wBAAwB,CAAC,IAAI,CAAC,KAAK,EAAE;YAChD,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO;YACnC,OAAO;SACR,CAAC,CAAC;QACH,OAAO;YACL,OAAO,EAAE,GAAG,EAAE,CACZ,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO;YAChE,MAAM,EAAE,GAAG,EAAE;gBACX,IAAI,CAAC,KAAK,GAAG,wBAAwB,CAAC,IAAI,CAAC,KAAK,EAAE;oBAChD,IAAI,EAAE,UAAU;oBAChB,OAAO;iBACR,CAAC,CAAC;YACL,CAAC;SACF,CAAC;IACJ,CAAC;IAED,UAAU;QACR,IAAI,CAAC,KAAK,GAAG,wBAAwB,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;IAC7E,CAAC;CACF","sourcesContent":["type AuthenticationState =\n | { readonly status: \"idle\" }\n | { readonly status: \"login\" | \"renewal\"; readonly attempt: symbol };\n\ntype AuthenticationEvent =\n | {\n readonly type: \"login\" | \"renewal\" | \"finished\";\n readonly attempt: symbol;\n }\n | { readonly type: \"invalidated\" };\n\nfunction transitionAuthentication(\n state: AuthenticationState,\n event: AuthenticationEvent,\n): AuthenticationState {\n switch (event.type) {\n case \"login\":\n return { status: \"login\", attempt: event.attempt };\n case \"renewal\":\n return state.status === \"idle\"\n ? { status: \"renewal\", attempt: event.attempt }\n : state;\n case \"finished\":\n return state.status !== \"idle\" && state.attempt === event.attempt\n ? { status: \"idle\" }\n : state;\n case \"invalidated\":\n return { status: \"idle\" };\n }\n}\n\nexport class SessionAuthentication {\n private state: AuthenticationState = { status: \"idle\" };\n\n private lastLogin: symbol | undefined;\n\n captureRestore(): () => boolean {\n const login = this.lastLogin;\n const allowed = this.state.status !== \"login\";\n return () => allowed && login === this.lastLogin;\n }\n\n start(renewal: boolean) {\n const attempt = Symbol();\n if (!renewal) this.lastLogin = attempt;\n this.state = transitionAuthentication(this.state, {\n type: renewal ? \"renewal\" : \"login\",\n attempt,\n });\n return {\n current: () =>\n this.state.status !== \"idle\" && this.state.attempt === attempt,\n finish: () => {\n this.state = transitionAuthentication(this.state, {\n type: \"finished\",\n attempt,\n });\n },\n };\n }\n\n invalidate(): void {\n this.state = transitionAuthentication(this.state, { type: \"invalidated\" });\n }\n}\n"]}