@tearleads/client-sdk 0.1.59 → 0.1.61

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 (142) hide show
  1. package/Tearleads.d.ts +17 -57
  2. package/Tearleads.js +31 -38
  3. package/Tearleads.js.map +1 -1
  4. package/TearleadsOptions.d.ts +49 -0
  5. package/TearleadsOptions.js +2 -0
  6. package/TearleadsOptions.js.map +1 -0
  7. package/client/{blobs.d.ts → blobs/index.d.ts} +1 -1
  8. package/client/{blobs.js → blobs/index.js} +3 -3
  9. package/client/blobs/index.js.map +1 -0
  10. package/client/{containerDocumentDiscovery.js → containerContents/documentDiscovery.js} +11 -11
  11. package/client/containerContents/documentDiscovery.js.map +1 -0
  12. package/client/{containerContents.d.ts → containerContents/index.d.ts} +13 -13
  13. package/client/{containerContents.js → containerContents/index.js} +18 -18
  14. package/client/containerContents/index.js.map +1 -0
  15. package/client/{containerContentsTypes.d.ts → containerContents/types.d.ts} +14 -14
  16. package/client/containerContents/types.js +2 -0
  17. package/client/containerContents/types.js.map +1 -0
  18. package/client/{deviceFirst.d.ts → deviceFirst/index.d.ts} +7 -7
  19. package/client/{deviceFirst.js → deviceFirst/index.js} +11 -11
  20. package/client/deviceFirst/index.js.map +1 -0
  21. package/client/{reconciledDocumentContentPull.js → deviceFirst/reconciledDocumentContentPull.js} +1 -1
  22. package/client/deviceFirst/reconciledDocumentContentPull.js.map +1 -0
  23. package/client/{documents.d.ts → documents/index.d.ts} +5 -5
  24. package/client/{documents.js → documents/index.js} +5 -5
  25. package/client/documents/index.js.map +1 -0
  26. package/client/{identity.d.ts → identity/index.d.ts} +2 -2
  27. package/client/{identity.js → identity/index.js} +5 -5
  28. package/client/identity/index.js.map +1 -0
  29. package/client/{identityKeyPackage.d.ts → identity/keyPackage.d.ts} +1 -1
  30. package/client/{identityKeyPackage.js → identity/keyPackage.js} +4 -4
  31. package/client/identity/keyPackage.js.map +1 -0
  32. package/client/{userIdentities.d.ts → identity/userIdentities.d.ts} +2 -2
  33. package/client/{userIdentities.js → identity/userIdentities.js} +4 -4
  34. package/client/identity/userIdentities.js.map +1 -0
  35. package/client/index.d.ts +17 -17
  36. package/client/index.js +8 -8
  37. package/client/index.js.map +1 -1
  38. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  39. package/client/organizations/index.d.ts +2 -2
  40. package/client/organizations/index.js.map +1 -1
  41. package/client/organizations/organizationDataUsage.d.ts +1 -1
  42. package/client/organizations/organizationDataUsage.js.map +1 -1
  43. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  44. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  45. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  46. package/client/organizations/organizationReadModels.d.ts +1 -1
  47. package/client/organizations/organizationReadModels.js.map +1 -1
  48. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  49. package/client/organizations/organizationsTypes.d.ts +1 -1
  50. package/client/organizations/organizationsTypes.js.map +1 -1
  51. package/client/organizations/principalContainerMutations.js.map +1 -1
  52. package/client/organizations/principalMutationRecovery.d.ts +1 -1
  53. package/client/organizations/principalMutationRecovery.js.map +1 -1
  54. package/client/organizations/principalMutationScope.js.map +1 -1
  55. package/client/organizations/principalMutations.d.ts +2 -2
  56. package/client/organizations/principalMutations.js.map +1 -1
  57. package/client/root/index.d.ts +2 -2
  58. package/client/root/index.js.map +1 -1
  59. package/client/{database.d.ts → runtime/database.d.ts} +1 -1
  60. package/client/{database.js → runtime/database.js} +1 -1
  61. package/client/runtime/database.js.map +1 -0
  62. package/client/{principalHistoryProtection.d.ts → runtime/principalHistoryProtection.d.ts} +1 -1
  63. package/client/{principalHistoryProtection.js → runtime/principalHistoryProtection.js} +2 -2
  64. package/client/runtime/principalHistoryProtection.js.map +1 -0
  65. package/client/{principalMutationApi.d.ts → runtime/principalMutationApi.d.ts} +4 -4
  66. package/client/{principalMutationApi.js → runtime/principalMutationApi.js} +2 -2
  67. package/client/runtime/principalMutationApi.js.map +1 -0
  68. package/client/{principalMutationDispatch.js → runtime/principalMutationDispatch.js} +2 -2
  69. package/client/runtime/principalMutationDispatch.js.map +1 -0
  70. package/client/runtime/rootContainerAdoption.js.map +1 -0
  71. package/client/{workflowRuntime.d.ts → runtime/workflowRuntime.d.ts} +12 -12
  72. package/client/{workflowRuntime.js → runtime/workflowRuntime.js} +5 -5
  73. package/client/runtime/workflowRuntime.js.map +1 -0
  74. package/client/{securityIncidents.d.ts → securityIncidents/index.d.ts} +3 -3
  75. package/client/{securityIncidents.js → securityIncidents/index.js} +5 -5
  76. package/client/securityIncidents/index.js.map +1 -0
  77. package/client/session/index.js +1 -1
  78. package/client/session/index.js.map +1 -1
  79. package/client/session/sessionIdentityTrust.d.ts +1 -1
  80. package/client/session/sessionOrganizationCreation.js.map +1 -1
  81. package/client/session/sessionPurgeRecovery.js.map +1 -1
  82. package/client/session/sessionTypes.d.ts +2 -2
  83. package/client/session/sessionTypes.js.map +1 -1
  84. package/index.d.ts +2 -1
  85. package/index.js +1 -1
  86. package/index.js.map +1 -1
  87. package/package.json +1 -1
  88. package/workflows/container-contents/metadataIncomingUpdateIsolation.js.map +1 -1
  89. package/workflows/container-contents/projectionKeys.d.ts +1 -1
  90. package/workflows/container-contents/projectionKeys.js.map +1 -1
  91. package/workflows/container-contents/runtime.d.ts +1 -1
  92. package/workflows/container-contents/runtime.js.map +1 -1
  93. package/workflows/documents/projectionKeys.d.ts +1 -1
  94. package/workflows/documents/projectionKeys.js.map +1 -1
  95. package/workflows/documents/reportDocumentSyncQuarantine.js.map +1 -1
  96. package/workflows/documents/runtime.d.ts +1 -1
  97. package/workflows/documents/runtime.js.map +1 -1
  98. package/workflows/{runtimeInput.d.ts → shared/runtimeInput.d.ts} +6 -6
  99. package/workflows/shared/runtimeInput.js.map +1 -0
  100. package/client/blobs.js.map +0 -1
  101. package/client/containerContents.js.map +0 -1
  102. package/client/containerContentsTypes.js +0 -2
  103. package/client/containerContentsTypes.js.map +0 -1
  104. package/client/containerDocumentDiscovery.js.map +0 -1
  105. package/client/database.js.map +0 -1
  106. package/client/deviceFirst.js.map +0 -1
  107. package/client/documents.js.map +0 -1
  108. package/client/identity.js.map +0 -1
  109. package/client/identityKeyPackage.js.map +0 -1
  110. package/client/principalHistoryProtection.js.map +0 -1
  111. package/client/principalMutationApi.js.map +0 -1
  112. package/client/principalMutationDispatch.js.map +0 -1
  113. package/client/reconciledDocumentContentPull.js.map +0 -1
  114. package/client/rootContainerAdoption.js.map +0 -1
  115. package/client/securityIncidents.js.map +0 -1
  116. package/client/userIdentities.js.map +0 -1
  117. package/client/workflowRuntime.js.map +0 -1
  118. package/workflows/runtimeInput.js.map +0 -1
  119. /package/client/{fileSaver.d.ts → host/fileSaver.d.ts} +0 -0
  120. /package/client/{fileSaver.js → host/fileSaver.js} +0 -0
  121. /package/client/{fileSaver.js.map → host/fileSaver.js.map} +0 -0
  122. /package/client/{logger.d.ts → host/logger.d.ts} +0 -0
  123. /package/client/{logger.js → host/logger.js} +0 -0
  124. /package/client/{logger.js.map → host/logger.js.map} +0 -0
  125. /package/client/{apiVersion.d.ts → runtime/apiVersion.d.ts} +0 -0
  126. /package/client/{apiVersion.js → runtime/apiVersion.js} +0 -0
  127. /package/client/{apiVersion.js.map → runtime/apiVersion.js.map} +0 -0
  128. /package/client/{events.d.ts → runtime/events.d.ts} +0 -0
  129. /package/client/{events.js → runtime/events.js} +0 -0
  130. /package/client/{events.js.map → runtime/events.js.map} +0 -0
  131. /package/client/{listenerSet.js → runtime/listenerSet.js} +0 -0
  132. /package/client/{listenerSet.js.map → runtime/listenerSet.js.map} +0 -0
  133. /package/client/{network.d.ts → runtime/network.d.ts} +0 -0
  134. /package/client/{network.js → runtime/network.js} +0 -0
  135. /package/client/{network.js.map → runtime/network.js.map} +0 -0
  136. /package/client/{principalMutationDeadline.js → runtime/principalMutationDeadline.js} +0 -0
  137. /package/client/{principalMutationDeadline.js.map → runtime/principalMutationDeadline.js.map} +0 -0
  138. /package/client/{rootContainerAdoption.js → runtime/rootContainerAdoption.js} +0 -0
  139. /package/client/{syncBillingGate.d.ts → runtime/syncBillingGate.d.ts} +0 -0
  140. /package/client/{syncBillingGate.js → runtime/syncBillingGate.js} +0 -0
  141. /package/client/{syncBillingGate.js.map → runtime/syncBillingGate.js.map} +0 -0
  142. /package/workflows/{runtimeInput.js → shared/runtimeInput.js} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutations.js","sourceRoot":"","sources":["principalMutations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,8DAA8D,CAAC;AAC9G,OAAO,EAAE,mDAAmD,EAAE,MAAM,6DAA6D,CAAC;AAClI,OAAO,EAAE,8BAA8B,EAAE,MAAM,8DAA8D,CAAC;AAC9G,OAAO,EAAE,gCAAgC,EAAE,MAAM,oDAAoD,CAAC;AACtG,OAAO,EAAE,wCAAwC,EAAE,MAAM,kEAAkE,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AAGpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAiCpF,SAAS,qBAAqB,CAC5B,OAAqC;IAErC,IACE,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc;QAC5B,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM;QACpB,CAAC,OAAO,CAAC,MAAM,CAAC,kBAAkB;QAClC,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,EAC9B,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;IACjE,CAAC;IAED,OAAO;QACL,cAAc,EAAE,OAAO,CAA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AAE,KAAK,CAAC,OAAO,CAAC,SAAS;oBAClC,WAAW,EAAE,KAAK,CAAC,WAAW;oBAC9B,oBAAoB;oBACpB,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;oBACpC,cAAc,EAAE;wBACd,SAAS,EAAE,KAAK,CAAC,SAAS;wBAC1B,WAAW,EAAE,KAAK,CAAC,WAAW;qBAC/B;oBACD,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;oBAC1C,+BAA+B,EAAE,kCAAkC,CACjE,KAAK,CAAC,OAAO,CACd;oBACD,GAAG,cAAc;iBAClB,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,MAAM,EAAE,CAAC;QAChC,MAAM,KAAK,CAAC,oBAAoB,CAAC,sBAAsB,CACrD,cAAc,CAAC,cAAc,CAC9B,CAAC;QACF,OAAO,QAAQ,CAAC;IAClB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerGrantSubjectType } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { revokeOrganizationContainerGrant } from \"../../workflows/organizations\";\nimport { createCurrentOrganizationGroup } from \"../../workflows/organizations/createCurrentOrganizationGroup\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../workflows/organizations/currentGroupMetadataAuthority\";\nimport { deleteCurrentOrganizationGroup } from \"../../workflows/organizations/deleteCurrentOrganizationGroup\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadataRuntime\";\nimport { createRuntimeCurrentOrganizationMutation } from \"../../workflows/organizations/runtimeCurrentOrganizationMutation\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../workflows/principals/runtimePolicyWarmer\";\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../workflowRuntime\";\nimport { createCurrentPrincipalMutation } from \"./currentPrincipalMutations\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\n\nexport interface OrganizationGrantRef {\n containerId: string;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface OrganizationGroupUserMutationInput {\n groupId: string;\n expectedGroupName: string;\n}\n\nexport interface AddOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n targetUserId: string;\n}\n\nexport interface RemoveOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n removedUserId: string;\n}\n\ninterface OrganizationSigningContext {\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\nfunction requireSigningContext(\n runtime: InternalWorkflowRuntimeInput,\n): OrganizationSigningContext {\n if (\n !runtime.auth.organizationId ||\n !runtime.auth.userId ||\n !runtime.crypto.signingFingerprint ||\n !runtime.crypto.signingKeyPair\n ) {\n throw new Error(\"Organization signing context is unavailable\");\n }\n\n return {\n organizationId: runtime.auth.organizationId,\n signerUserId: runtime.auth.userId,\n signingFingerprint: runtime.crypto.signingFingerprint,\n signingKeyPair: runtime.crypto.signingKeyPair,\n };\n}\n\nfunction requireEncapsulationKeyPair(\n runtime: InternalWorkflowRuntimeInput,\n): NonNullable<InternalWorkflowRuntimeInput[\"crypto\"][\"encapsulationKeyPair\"]> {\n if (!runtime.crypto.encapsulationKeyPair) {\n throw new Error(\"Organization encryption context is unavailable\");\n }\n\n return runtime.crypto.encapsulationKeyPair;\n}\n\ninterface PrincipalMutationRuntime {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime & AddOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.add\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const {\n memberGroupId,\n response: bundle,\n enrolled,\n } = await mutateCurrent(input.groupId, {\n kind: \"add\",\n expectedGroupName: input.expectedGroupName,\n targetUserId: input.targetUserId,\n });\n if (input.groupId === memberGroupId || enrolled) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport function createGroupForOrganization(input: {\n readonly name: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: signingContext.organizationId,\n objectKind: \"principal\",\n operation: \"group.create\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const creatorEncapsulationKeyPair = requireEncapsulationKeyPair(\n input.runtime,\n );\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n createCurrentOrganizationGroup({\n ...signingContext,\n context,\n apiClient: input.runtime.apiClient,\n creatorEncapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n name: input.name,\n metadataAccess: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n context.stillCurrent,\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority: context,\n organizationId: signingContext.organizationId,\n stillCurrent: context.stillCurrent,\n }),\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport function deleteGroupForOrganization(input: {\n readonly groupId: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.delete\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n deleteCurrentOrganizationGroup({\n ...signingContext,\n context,\n groupId: input.groupId,\n apiClient: input.runtime.apiClient,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport async function removeUserFromOrganizationGroup(\n input: PrincipalMutationRuntime & RemoveOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.remove\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const { memberGroupId, response: bundle } = await mutateCurrent(\n input.groupId,\n {\n kind: \"remove\",\n expectedGroupName: input.expectedGroupName,\n removedUserId: input.removedUserId,\n },\n );\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input.runtime);\n const encapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);\n if (input.runtime.infra.dbStatus !== \"ready\") {\n throw new Error(\"Organization local database is unavailable\");\n }\n\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.subjectId,\n objectKind: \"principal\",\n operation: \"principal.grant.revoke\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const revoke = async () => {\n if (input.subjectType === \"group\") {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return (\n await mutateCurrent(input.subjectId, {\n kind: \"revoke\",\n revokedContainerId: input.containerId,\n })\n ).response;\n } else {\n return revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient: input.runtime.apiClient,\n containerId: input.containerId,\n encapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n ...signingContext,\n });\n }\n };\n const response = await revoke();\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return response;\n },\n );\n}\n"]}
1
+ {"version":3,"file":"principalMutations.js","sourceRoot":"","sources":["principalMutations.ts"],"names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AC1C,+BAA+B,EAAE,kCAAkC,CACjE,KAAK,CAAC,OAAO,CACd;oBACD,GAAG,cAAc;iBAClB,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,MAAM,EAAE,CAAC;QAChC,MAAM,KAAK,CAAC,oBAAoB,CAAC,sBAAsB,CACrD,cAAc,CAAC,cAAc,CAC9B,CAAC;QACF,OAAO,QAAQ,CAAC;IAClB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerGrantSubjectType } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { revokeOrganizationContainerGrant } from \"../../workflows/organizations\";\nimport { createCurrentOrganizationGroup } from \"../../workflows/organizations/createCurrentOrganizationGroup\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../workflows/organizations/currentGroupMetadataAuthority\";\nimport { deleteCurrentOrganizationGroup } from \"../../workflows/organizations/deleteCurrentOrganizationGroup\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadataRuntime\";\nimport { createRuntimeCurrentOrganizationMutation } from \"../../workflows/organizations/runtimeCurrentOrganizationMutation\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../workflows/principals/runtimePolicyWarmer\";\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport { createCurrentPrincipalMutation } from \"./currentPrincipalMutations\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\n\nexport interface OrganizationGrantRef {\n containerId: string;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface OrganizationGroupUserMutationInput {\n groupId: string;\n expectedGroupName: string;\n}\n\nexport interface AddOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n targetUserId: string;\n}\n\nexport interface RemoveOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n removedUserId: string;\n}\n\ninterface OrganizationSigningContext {\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\nfunction requireSigningContext(\n runtime: InternalWorkflowRuntimeInput,\n): OrganizationSigningContext {\n if (\n !runtime.auth.organizationId ||\n !runtime.auth.userId ||\n !runtime.crypto.signingFingerprint ||\n !runtime.crypto.signingKeyPair\n ) {\n throw new Error(\"Organization signing context is unavailable\");\n }\n\n return {\n organizationId: runtime.auth.organizationId,\n signerUserId: runtime.auth.userId,\n signingFingerprint: runtime.crypto.signingFingerprint,\n signingKeyPair: runtime.crypto.signingKeyPair,\n };\n}\n\nfunction requireEncapsulationKeyPair(\n runtime: InternalWorkflowRuntimeInput,\n): NonNullable<InternalWorkflowRuntimeInput[\"crypto\"][\"encapsulationKeyPair\"]> {\n if (!runtime.crypto.encapsulationKeyPair) {\n throw new Error(\"Organization encryption context is unavailable\");\n }\n\n return runtime.crypto.encapsulationKeyPair;\n}\n\ninterface PrincipalMutationRuntime {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime & AddOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.add\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const {\n memberGroupId,\n response: bundle,\n enrolled,\n } = await mutateCurrent(input.groupId, {\n kind: \"add\",\n expectedGroupName: input.expectedGroupName,\n targetUserId: input.targetUserId,\n });\n if (input.groupId === memberGroupId || enrolled) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport function createGroupForOrganization(input: {\n readonly name: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: signingContext.organizationId,\n objectKind: \"principal\",\n operation: \"group.create\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const creatorEncapsulationKeyPair = requireEncapsulationKeyPair(\n input.runtime,\n );\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n createCurrentOrganizationGroup({\n ...signingContext,\n context,\n apiClient: input.runtime.apiClient,\n creatorEncapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n name: input.name,\n metadataAccess: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n context.stillCurrent,\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority: context,\n organizationId: signingContext.organizationId,\n stillCurrent: context.stillCurrent,\n }),\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport function deleteGroupForOrganization(input: {\n readonly groupId: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.delete\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n deleteCurrentOrganizationGroup({\n ...signingContext,\n context,\n groupId: input.groupId,\n apiClient: input.runtime.apiClient,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport async function removeUserFromOrganizationGroup(\n input: PrincipalMutationRuntime & RemoveOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.remove\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const { memberGroupId, response: bundle } = await mutateCurrent(\n input.groupId,\n {\n kind: \"remove\",\n expectedGroupName: input.expectedGroupName,\n removedUserId: input.removedUserId,\n },\n );\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input.runtime);\n const encapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);\n if (input.runtime.infra.dbStatus !== \"ready\") {\n throw new Error(\"Organization local database is unavailable\");\n }\n\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.subjectId,\n objectKind: \"principal\",\n operation: \"principal.grant.revoke\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const revoke = async () => {\n if (input.subjectType === \"group\") {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return (\n await mutateCurrent(input.subjectId, {\n kind: \"revoke\",\n revokedContainerId: input.containerId,\n })\n ).response;\n } else {\n return revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient: input.runtime.apiClient,\n containerId: input.containerId,\n encapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n ...signingContext,\n });\n }\n };\n const response = await revoke();\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return response;\n },\n );\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import type { OrganizationDataUsageResponse } from "../../internal/validators/response/index.js";
2
2
  import { type RootDataUsageApi, type RootDataUsageReportPage, type RootIdentitiesApi, type RootIdentitiesPage, type RootIdentitiesQueryInput, type RootIdentityDetail, type RootIdentityOrganization, type RootOrganizationDetail, type RootOrganizationIdentitiesPage, type RootOrganizationPageQueryInput, type RootOrganizationsApi, type RootOrganizationsPage, type RootOrganizationsQueryInput, type RootRequestOutcome } from "../../workflows/root/index.js";
3
- import type { WorkflowRuntimeAuthInput, WorkflowRuntimeCryptoInput } from "../../workflows/runtimeInput.js";
3
+ import type { WorkflowRuntimeAuthInput, WorkflowRuntimeCryptoInput } from "../../workflows/shared/runtimeInput.js";
4
+ import type { InternalRuntime } from "../runtime/workflowRuntime.js";
4
5
  import type { Session } from "../session/sessionTypes.js";
5
- import type { InternalRuntime } from "../workflowRuntime.js";
6
6
  /**
7
7
  * Platform-operator lookups. Every call is refused locally unless the session
8
8
  * is authenticated and the server reported it as root at login; the API still
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAe9B,MAAM,sBAAsB,CAAC;AA4D9B,6EAA6E;AAC7E,MAAM,UAAU,aAAa,CAC3B,OAAiE,EACjE,OAAmC;IAEnC,OAAO;QACL,SAAS,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,SAAS;QAClC,SAAS,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,aAAa,CAAC,SAAS,CAAC,QAAQ,CAAC;QAClE,aAAa,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,aAAa,EAAE;KAC7C,CAAC;AACJ,CAAC;AAED,MAAM,aAAa,GAA8B;IAC/C,OAAO,EAAE,iDAAiD;IAC1D,EAAE,EAAE,KAAK;IACT,MAAM,EAAE,IAAI;CACb,CAAC;AAEF,MAAM,eAAe,GAA8B;IACjD,OAAO,EAAE,sDAAsD;IAC/D,EAAE,EAAE,KAAK;IACT,MAAM,EAAE,IAAI;CACb,CAAC;AAEF,MAAM,UAAU,UAAU,CAAC,cAA2B;IACpD,MAAM,SAAS,GAAG,GAAG,EAAE;QACrB,MAAM,OAAO,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;QAC/C,OAAO;YACL,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,kBAAkB;Y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,EAAE,CAAC,cAAc,EAAE,EAAE,CAC5C,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,6BAA6B,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QACtE,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE,CAC7B,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACvD,iBAAiB,EAAE,CAAC,KAAK,EAAE,EAAE,CAC3B,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,qBAAqB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACrD,gBAAgB,EAAE,CAAC,cAAc,EAAE,EAAE,CACnC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oBAAoB,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC7D,0BAA0B,EAAE,CAAC,cAAc,EAAE,KAAK,EAAE,EAAE,CACpD,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CACd,8BAA8B,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,CAAC,CAC3D;QACH,cAAc,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,kBAAkB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3E,yBAAyB,EAAE,CAAC,MAAM,EAAE,EAAE,CACpC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,6BAA6B,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9D,YAAY,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;KAC1E,CAAC;AACJ,CAAC","sourcesContent":["import type { OrganizationDataUsageResponse } from \"@tearleads/validators/response\";\nimport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootIdentitiesApi,\n type RootIdentitiesPage,\n type RootIdentitiesQueryInput,\n type RootIdentityDetail,\n type RootIdentityOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRequestOutcome,\n} from \"../../workflows/root\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n} from \"../../workflows/runtimeInput\";\nimport type { Session } from \"../session/sessionTypes\";\nimport type { InternalRuntime } from \"../workflowRuntime\";\n\n/**\n * Platform-operator lookups. Every call is refused locally unless the session\n * is authenticated and the server reported it as root at login; the API still\n * enforces root access on its own, so this gate only avoids doomed requests.\n */\ntype RootApi = RootIdentitiesApi & RootOrganizationsApi & RootDataUsageApi;\n\nexport interface Root {\n loadOrganizationDataUsage(\n organizationId: string,\n ): Promise<RootRequestOutcome<OrganizationDataUsageResponse>>;\n listDataUsageReport(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootDataUsageReportPage>>;\n listOrganizations(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationsPage>>;\n loadOrganization(\n organizationId: string,\n ): Promise<RootRequestOutcome<RootOrganizationDetail>>;\n listOrganizationIdentities(\n organizationId: string,\n query?: RootOrganizationPageQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationIdentitiesPage>>;\n /** Whether the current session may use the root surface at all. */\n readonly isAvailable: boolean;\n listIdentities(\n query?: RootIdentitiesQueryInput,\n ): Promise<RootRequestOutcome<RootIdentitiesPage>>;\n listIdentityOrganizations(\n userId: string,\n ): Promise<RootRequestOutcome<RootIdentityOrganization[]>>;\n loadIdentity(userId: string): Promise<RootRequestOutcome<RootIdentityDetail>>;\n}\n\n/**\n * What the facade needs from the runtime: change notifications, the current\n * auth snapshot, the signing identity (which can change or vanish without\n * touching the session), and the api client. Narrower than the full runtime\n * so tests can drive it with a fake.\n */\nexport interface RootRuntime {\n /** The session's current auth token; a new one marks a fresh login. */\n authToken(): string | null;\n subscribe(listener: () => void): () => void;\n workflowInput(): {\n readonly apiClient: RootApi;\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: Pick<WorkflowRuntimeCryptoInput, \"signingFingerprint\">;\n };\n}\n\n/** The SDK's internal runtime, narrowed to what the root facade observes. */\nexport function rootRuntimeOf(\n runtime: Pick<InternalRuntime, \"publicRuntime\" | \"workflowInput\">,\n session: Pick<Session, \"authToken\">,\n): RootRuntime {\n return {\n authToken: () => session.authToken,\n subscribe: (listener) => runtime.publicRuntime.subscribe(listener),\n workflowInput: () => runtime.workflowInput(),\n };\n}\n\nconst NOT_AVAILABLE: RootRequestOutcome<never> = {\n message: \"The current session is not a platform operator.\",\n ok: false,\n status: null,\n};\n\nconst SESSION_CHANGED: RootRequestOutcome<never> = {\n message: \"The session changed while the request was in flight.\",\n ok: false,\n status: null,\n};\n\nexport function createRoot(runtimeService: RootRuntime): Root {\n const principal = () => {\n const runtime = runtimeService.workflowInput();\n return {\n fingerprint: runtime.crypto.signingFingerprint,\n isAuthenticated: runtime.auth.isAuthenticated,\n isRoot: runtime.auth.isRoot === true,\n userId: runtime.auth.userId,\n };\n };\n\n // Root standing belongs to the signing identity that authenticated, not to\n // whichever key pair is loaded now. The fingerprint is bound whenever a\n // login completes, which is observable as a new auth token carrying the\n // server's verdict, or when the session first becomes root. A principal\n // change without a new token (a key swap while the old token lingers)\n // unbinds root until the next login. Every principal change is also\n // counted as it happens, so a round trip such as logout then login, or a\n // switch to another identity and back, is still two changes even though\n // the endpoints match; a token renewal alone changes no principal, so a\n // retried lookup is still returned.\n let observed = principal();\n let observedToken = runtimeService.authToken();\n let boundFingerprint: string | null =\n observed.isAuthenticated && observed.isRoot ? observed.fingerprint : null;\n let lifecycle = 0;\n runtimeService.subscribe(() => {\n const next = principal();\n const token = runtimeService.authToken();\n const freshToken = token !== null && token !== observedToken;\n const wasRoot = observed.isAuthenticated && observed.isRoot;\n const isRootNow = next.isAuthenticated && next.isRoot;\n const changed =\n next.fingerprint !== observed.fingerprint ||\n next.isAuthenticated !== observed.isAuthenticated ||\n next.isRoot !== observed.isRoot ||\n next.userId !== observed.userId;\n if (changed) {\n lifecycle += 1;\n }\n if (!isRootNow) {\n boundFingerprint = null;\n } else if (freshToken || !wasRoot) {\n boundFingerprint = next.fingerprint;\n } else if (changed) {\n boundFingerprint = null;\n }\n observed = next;\n observedToken = token;\n });\n\n const activeApi = (): RootApi | null => {\n const runtime = runtimeService.workflowInput();\n return runtime.auth.isAuthenticated &&\n runtime.auth.isRoot === true &&\n boundFingerprint !== null &&\n runtime.crypto.signingFingerprint === boundFingerprint\n ? runtime.apiClient\n : null;\n };\n\n const guarded = async <Data>(\n request: (api: RootApi) => Promise<RootRequestOutcome<Data>>,\n ): Promise<RootRequestOutcome<Data>> => {\n const api = activeApi();\n if (!api) {\n return NOT_AVAILABLE;\n }\n const startedIn = lifecycle;\n const outcome = await request(api);\n if (activeApi() === null || lifecycle !== startedIn) {\n return SESSION_CHANGED;\n }\n return outcome;\n };\n\n return {\n get isAvailable() {\n return activeApi() !== null;\n },\n loadOrganizationDataUsage: (organizationId) =>\n guarded((api) => loadRootOrganizationDataUsage(api, organizationId)),\n listDataUsageReport: (query) =>\n guarded((api) => listRootDataUsageReport(api, query)),\n listOrganizations: (query) =>\n guarded((api) => listRootOrganizations(api, query)),\n loadOrganization: (organizationId) =>\n guarded((api) => loadRootOrganization(api, organizationId)),\n listOrganizationIdentities: (organizationId, query) =>\n guarded((api) =>\n listRootOrganizationIdentities(api, organizationId, query),\n ),\n listIdentities: (query) => guarded((api) => listRootIdentities(api, query)),\n listIdentityOrganizations: (userId) =>\n guarded((api) => listRootIdentityOrganizations(api, userId)),\n loadIdentity: (userId) => guarded((api) => loadRootIdentity(api, userId)),\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAe9B,MAAM,sBAAsB,CAAC;AA4D9B,6EAA6E;AAC7E,MAAM,UAAU,aAAa,CAC3B,OAAiE,EACjE,OAAmC;IAEnC,OAAO;QACL,SAAS,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,SAAS;QAClC,SAAS,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,aAAa,CAAC,SAAS,CAAC,QAAQ,CAAC;QAClE,aAAa,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,aAAa,EAAE;KAC7C,CAAC;AACJ,CAAC;AAED,MAAM,aAAa,GAA8B;IAC/C,OAAO,EAAE,iDAAiD;IAC1D,EAAE,EAAE,KAAK;IACT,MAAM,EAAE,IAAI;CACb,CAAC;AAEF,MAAM,eAAe,GAA8B;IACjD,OAAO,EAAE,sDAAsD;IAC/D,EAAE,EAAE,KAAK;IACT,MAAM,EAAE,IAAI;CACb,CAAC;AAEF,MAAM,UAAU,UAAU,CAAC,cAA2B;IACpD,MAAM,SAAS,GAAG,GAAG,EAAE;QACrB,MAAM,OAAO,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;QAC/C,OAAO;YACL,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,kBAAkB;YAC9C,eAAe,EAAE,OAAO,CAAC,IAAI,CAAC,eAAe;YAC7C,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,IAAI;YACpC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,MAAM;SAC5B,CAAC;IACJ,CAAC,CAAC;IAEF,2EAA2E;IAC3E,wEAAwE;IACxE,wEAAwE;IACxE,w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AAE,KAAK,CAAC,CAAC;QACvD,iBAAiB,EAAE,CAAC,KAAK,EAAE,EAAE,CAC3B,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,qBAAqB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACrD,gBAAgB,EAAE,CAAC,cAAc,EAAE,EAAE,CACnC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oBAAoB,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC7D,0BAA0B,EAAE,CAAC,cAAc,EAAE,KAAK,EAAE,EAAE,CACpD,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CACd,8BAA8B,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,CAAC,CAC3D;QACH,cAAc,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,kBAAkB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3E,yBAAyB,EAAE,CAAC,MAAM,EAAE,EAAE,CACpC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,6BAA6B,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9D,YAAY,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;KAC1E,CAAC;AACJ,CAAC","sourcesContent":["import type { OrganizationDataUsageResponse } from \"@tearleads/validators/response\";\nimport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootIdentitiesApi,\n type RootIdentitiesPage,\n type RootIdentitiesQueryInput,\n type RootIdentityDetail,\n type RootIdentityOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRequestOutcome,\n} from \"../../workflows/root\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport type { Session } from \"../session/sessionTypes\";\n\n/**\n * Platform-operator lookups. Every call is refused locally unless the session\n * is authenticated and the server reported it as root at login; the API still\n * enforces root access on its own, so this gate only avoids doomed requests.\n */\ntype RootApi = RootIdentitiesApi & RootOrganizationsApi & RootDataUsageApi;\n\nexport interface Root {\n loadOrganizationDataUsage(\n organizationId: string,\n ): Promise<RootRequestOutcome<OrganizationDataUsageResponse>>;\n listDataUsageReport(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootDataUsageReportPage>>;\n listOrganizations(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationsPage>>;\n loadOrganization(\n organizationId: string,\n ): Promise<RootRequestOutcome<RootOrganizationDetail>>;\n listOrganizationIdentities(\n organizationId: string,\n query?: RootOrganizationPageQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationIdentitiesPage>>;\n /** Whether the current session may use the root surface at all. */\n readonly isAvailable: boolean;\n listIdentities(\n query?: RootIdentitiesQueryInput,\n ): Promise<RootRequestOutcome<RootIdentitiesPage>>;\n listIdentityOrganizations(\n userId: string,\n ): Promise<RootRequestOutcome<RootIdentityOrganization[]>>;\n loadIdentity(userId: string): Promise<RootRequestOutcome<RootIdentityDetail>>;\n}\n\n/**\n * What the facade needs from the runtime: change notifications, the current\n * auth snapshot, the signing identity (which can change or vanish without\n * touching the session), and the api client. Narrower than the full runtime\n * so tests can drive it with a fake.\n */\nexport interface RootRuntime {\n /** The session's current auth token; a new one marks a fresh login. */\n authToken(): string | null;\n subscribe(listener: () => void): () => void;\n workflowInput(): {\n readonly apiClient: RootApi;\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: Pick<WorkflowRuntimeCryptoInput, \"signingFingerprint\">;\n };\n}\n\n/** The SDK's internal runtime, narrowed to what the root facade observes. */\nexport function rootRuntimeOf(\n runtime: Pick<InternalRuntime, \"publicRuntime\" | \"workflowInput\">,\n session: Pick<Session, \"authToken\">,\n): RootRuntime {\n return {\n authToken: () => session.authToken,\n subscribe: (listener) => runtime.publicRuntime.subscribe(listener),\n workflowInput: () => runtime.workflowInput(),\n };\n}\n\nconst NOT_AVAILABLE: RootRequestOutcome<never> = {\n message: \"The current session is not a platform operator.\",\n ok: false,\n status: null,\n};\n\nconst SESSION_CHANGED: RootRequestOutcome<never> = {\n message: \"The session changed while the request was in flight.\",\n ok: false,\n status: null,\n};\n\nexport function createRoot(runtimeService: RootRuntime): Root {\n const principal = () => {\n const runtime = runtimeService.workflowInput();\n return {\n fingerprint: runtime.crypto.signingFingerprint,\n isAuthenticated: runtime.auth.isAuthenticated,\n isRoot: runtime.auth.isRoot === true,\n userId: runtime.auth.userId,\n };\n };\n\n // Root standing belongs to the signing identity that authenticated, not to\n // whichever key pair is loaded now. The fingerprint is bound whenever a\n // login completes, which is observable as a new auth token carrying the\n // server's verdict, or when the session first becomes root. A principal\n // change without a new token (a key swap while the old token lingers)\n // unbinds root until the next login. Every principal change is also\n // counted as it happens, so a round trip such as logout then login, or a\n // switch to another identity and back, is still two changes even though\n // the endpoints match; a token renewal alone changes no principal, so a\n // retried lookup is still returned.\n let observed = principal();\n let observedToken = runtimeService.authToken();\n let boundFingerprint: string | null =\n observed.isAuthenticated && observed.isRoot ? observed.fingerprint : null;\n let lifecycle = 0;\n runtimeService.subscribe(() => {\n const next = principal();\n const token = runtimeService.authToken();\n const freshToken = token !== null && token !== observedToken;\n const wasRoot = observed.isAuthenticated && observed.isRoot;\n const isRootNow = next.isAuthenticated && next.isRoot;\n const changed =\n next.fingerprint !== observed.fingerprint ||\n next.isAuthenticated !== observed.isAuthenticated ||\n next.isRoot !== observed.isRoot ||\n next.userId !== observed.userId;\n if (changed) {\n lifecycle += 1;\n }\n if (!isRootNow) {\n boundFingerprint = null;\n } else if (freshToken || !wasRoot) {\n boundFingerprint = next.fingerprint;\n } else if (changed) {\n boundFingerprint = null;\n }\n observed = next;\n observedToken = token;\n });\n\n const activeApi = (): RootApi | null => {\n const runtime = runtimeService.workflowInput();\n return runtime.auth.isAuthenticated &&\n runtime.auth.isRoot === true &&\n boundFingerprint !== null &&\n runtime.crypto.signingFingerprint === boundFingerprint\n ? runtime.apiClient\n : null;\n };\n\n const guarded = async <Data>(\n request: (api: RootApi) => Promise<RootRequestOutcome<Data>>,\n ): Promise<RootRequestOutcome<Data>> => {\n const api = activeApi();\n if (!api) {\n return NOT_AVAILABLE;\n }\n const startedIn = lifecycle;\n const outcome = await request(api);\n if (activeApi() === null || lifecycle !== startedIn) {\n return SESSION_CHANGED;\n }\n return outcome;\n };\n\n return {\n get isAvailable() {\n return activeApi() !== null;\n },\n loadOrganizationDataUsage: (organizationId) =>\n guarded((api) => loadRootOrganizationDataUsage(api, organizationId)),\n listDataUsageReport: (query) =>\n guarded((api) => listRootDataUsageReport(api, query)),\n listOrganizations: (query) =>\n guarded((api) => listRootOrganizations(api, query)),\n loadOrganization: (organizationId) =>\n guarded((api) => loadRootOrganization(api, organizationId)),\n listOrganizationIdentities: (organizationId, query) =>\n guarded((api) =>\n listRootOrganizationIdentities(api, organizationId, query),\n ),\n listIdentities: (query) => guarded((api) => listRootIdentities(api, query)),\n listIdentityOrganizations: (userId) =>\n guarded((api) => listRootIdentityOrganizations(api, userId)),\n loadIdentity: (userId) => guarded((api) => loadRootIdentity(api, userId)),\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type ExecSql, type ExecSqlClientLike } from "../data/sqlite/sqlSchema.js";
1
+ import { type ExecSql, type ExecSqlClientLike } from "../../data/sqlite/sqlSchema.js";
2
2
  export type DatabaseStatus = "idle" | "ready" | "error" | "terminated";
3
3
  export interface DatabaseSnapshot {
4
4
  client: ExecSqlClientLike | null;
@@ -1,4 +1,4 @@
1
- import { createExecSql, } from "../data/sqlite/sqlSchema.js";
1
+ import { createExecSql, } from "../../data/sqlite/sqlSchema.js";
2
2
  import { createListenerSet } from "./listenerSet.js";
3
3
  export class Database {
4
4
  listeners = createListenerSet();
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.js","sourceRoot":"","sources":["database.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,GAGd,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAoBlD,MAAM,OAAO,QAAQ;IACF,SAAS,GAAG,iBAAiB,EAAE,CAAC;IACzC,aAAa,GAAqB;QACxC,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,IAAI;QACb,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,MAAM;KACf,CAAC;IAEF,YAAY,OAAqC;QAC/C,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IACnC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;IACpC,CAAC;IAED,IAAI,EAAE;QACJ,OAAO,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,SAAyB,MAAM;QACnC,IAAI,CAAC,WAAW,CAAC;YACf,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,IAAI;YACb,EAAE,EAAE,IAAI;YACR,MAAM;SACP,CAAC,CAAC;IACL,CAAC;IAED,SAA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,GAAG,IAAI,CAAC,aAAa,CAAC;QACpC,IACE,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM;YAC/B,QAAQ,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO;YACjC,QAAQ,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE;YACvB,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,EAC/B,CAAC;YACD,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n} from \"../../data/sqlite/sqlSchema\";\nimport { createListenerSet } from \"./listenerSet\";\n\nexport type DatabaseStatus = \"idle\" | \"ready\" | \"error\" | \"terminated\";\n\nexport interface DatabaseSnapshot {\n client: ExecSqlClientLike | null;\n execSql: ExecSql | null;\n id: string | null;\n status: DatabaseStatus;\n}\n\nexport type DatabaseListener = () => void;\n\nexport interface DatabaseOptions {\n client?: ExecSqlClientLike | null | undefined;\n execSql?: ExecSql | null | undefined;\n id?: string | null | undefined;\n status?: DatabaseStatus | undefined;\n}\n\nexport class Database {\n private readonly listeners = createListenerSet();\n private snapshotValue: DatabaseSnapshot = {\n client: null,\n execSql: null,\n id: null,\n status: \"idle\",\n };\n\n constructor(options?: DatabaseOptions | undefined) {\n if (options) {\n this.configure(options);\n }\n }\n\n get client(): ExecSqlClientLike | null {\n return this.snapshotValue.client;\n }\n\n get execSql(): ExecSql | null {\n return this.snapshotValue.execSql;\n }\n\n get id(): string | null {\n return this.snapshotValue.id;\n }\n\n get snapshot(): DatabaseSnapshot {\n return this.snapshotValue;\n }\n\n get status(): DatabaseStatus {\n return this.snapshotValue.status;\n }\n\n clear(status: DatabaseStatus = \"idle\"): void {\n this.setSnapshot({\n client: null,\n execSql: null,\n id: null,\n status,\n });\n }\n\n configure(options: DatabaseOptions): void {\n const client = options.client ?? null;\n const execSql = options.execSql ?? (client ? createExecSql(client) : null);\n if (options.status === \"ready\" && !execSql) {\n throw new Error(\n \"A ready SQLite database requires a configured executor or client.\",\n );\n }\n\n this.setSnapshot({\n client,\n execSql,\n id: options.id ?? null,\n status: options.status ?? (execSql ? \"ready\" : \"idle\"),\n });\n }\n\n requireExecSql(operation = \"This operation\"): ExecSql {\n if (!this.snapshotValue.execSql) {\n throw new Error(`${operation} requires a configured SQLite executor.`);\n }\n\n return this.snapshotValue.execSql;\n }\n\n setClient(\n client: ExecSqlClientLike,\n options: Omit<DatabaseOptions, \"client\" | \"execSql\"> = {},\n ): void {\n this.configure({ ...options, client });\n }\n\n setExecSql(\n execSql: ExecSql,\n options: Omit<DatabaseOptions, \"client\" | \"execSql\"> = {},\n ): void {\n this.configure({ ...options, execSql });\n }\n\n subscribe = (listener: DatabaseListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: DatabaseSnapshot): void {\n const previous = this.snapshotValue;\n if (\n previous.client === next.client &&\n previous.execSql === next.execSql &&\n previous.id === next.id &&\n previous.status === next.status\n ) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { PrincipalHistoryProtectionLease } from "../data/principals/principalHistoryProtection.js";
1
+ import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
2
2
  export interface PrincipalHistoryKeyScope {
3
3
  readonly identityTrustDomain: string;
4
4
  readonly signingFingerprint: string;
@@ -1,5 +1,5 @@
1
- import { KeyingVerificationError } from "../internal/crypto/index.js";
2
- import { assertProjectionVerificationCurrent } from "../data/keyingProjectionVerification/types.js";
1
+ import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
+ import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
3
  function sameKeyScope(a, b) {
4
4
  return (a?.database === b.database &&
5
5
  a.identityTrustDomain === b.identityTrustDomain &&
@@ -0,0 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AS,CAAC;oBACT,IAAI,GAAG,YAAY,UAAU;wBAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBAC7C,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\n\nexport interface PrincipalHistoryKeyScope {\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n}\n\n/** Return a fresh owned 32-byte key. The SDK clears it after each operation. */\nexport type PrincipalHistoryKeyProvider = (\n scope: PrincipalHistoryKeyScope,\n) => Promise<Uint8Array>;\n\ninterface RuntimeProtectionScope extends PrincipalHistoryKeyScope {\n readonly database: object;\n readonly generation: number;\n}\n\nfunction sameKeyScope(\n a: RuntimeProtectionScope | null,\n b: RuntimeProtectionScope,\n): boolean {\n return (\n a?.database === b.database &&\n a.identityTrustDomain === b.identityTrustDomain &&\n a.signingFingerprint === b.signingFingerprint\n );\n}\n\nexport function createPrincipalHistoryProtectionCustody(input: {\n readonly readScope: () => RuntimeProtectionScope | null;\n readonly keyProvider?: PrincipalHistoryKeyProvider | undefined;\n}) {\n let retirement = 0;\n let ephemeral: { scope: RuntimeProtectionScope; key: Uint8Array } | null =\n null;\n const clearEphemeral = () => {\n ephemeral?.key.fill(0);\n ephemeral = null;\n };\n return {\n retire() {\n retirement += 1;\n clearEphemeral();\n },\n bind(): PrincipalHistoryProtectionLease | undefined {\n const scope = input.readScope();\n if (!scope) {\n clearEphemeral();\n return undefined;\n }\n if (ephemeral && !sameKeyScope(ephemeral.scope, scope)) clearEphemeral();\n const boundRetirement = retirement;\n const boundGeneration = scope.generation;\n const stillCurrent = () => {\n const current = input.readScope();\n return (\n retirement === boundRetirement &&\n current?.generation === boundGeneration &&\n sameKeyScope(current, scope)\n );\n };\n const context = JSON.stringify([\n \"tearleads.sdk.principal-history.runtime.v1\",\n scope.identityTrustDomain,\n scope.signingFingerprint,\n ]);\n return async (operation) => {\n assertProjectionVerificationCurrent(stillCurrent);\n let key: Uint8Array | undefined;\n try {\n if (input.keyProvider) {\n key = await input.keyProvider({\n identityTrustDomain: scope.identityTrustDomain,\n signingFingerprint: scope.signingFingerprint,\n });\n } else {\n ephemeral ??= {\n scope,\n key: crypto.getRandomValues(new Uint8Array(32)),\n };\n key = new Uint8Array(ephemeral.key);\n }\n if (!(key instanceof Uint8Array) || key.byteLength !== 32)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal history key provider must return 32 private bytes\",\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await operation({\n protection: { localKey: key, context },\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n if (key instanceof Uint8Array) key.fill(0);\n }\n };\n },\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
- import type { ApiClient } from "../internal/api-client/index.js";
2
- import type { SigningKeyPair } from "../internal/crypto/index.js";
3
- import type { ExecSql } from "../data/sqlite/sqlSchema.js";
4
- import { type PrincipalMutationRecoveryApi } from "../workflows/organizations/principalMutationJournalManagement.js";
1
+ import type { ApiClient } from "../../internal/api-client/index.js";
2
+ import type { SigningKeyPair } from "../../internal/crypto/index.js";
3
+ import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
4
+ import { type PrincipalMutationRecoveryApi } from "../../workflows/organizations/principalMutationJournalManagement.js";
5
5
  export interface PrincipalMutationRuntimeScope {
6
6
  readonly database: object;
7
7
  readonly execSql: ExecSql;
@@ -1,5 +1,5 @@
1
- import { abandonJournaledPrincipalMutation, discardUnreadableJournaledPrincipalMutation, readJournaledPrincipalMutation, } from "../workflows/organizations/principalMutationJournalManagement.js";
2
- import { recoverJournaledPrincipalMutation } from "../workflows/organizations/principalMutationJournalSession.js";
1
+ import { abandonJournaledPrincipalMutation, discardUnreadableJournaledPrincipalMutation, readJournaledPrincipalMutation, } from "../../workflows/organizations/principalMutationJournalManagement.js";
2
+ import { recoverJournaledPrincipalMutation } from "../../workflows/organizations/principalMutationJournalSession.js";
3
3
  import { createPrincipalMutationDispatcher } from "./principalMutationDeadline.js";
4
4
  import { createJournaledPrincipalMutations, dispatchAuthoredPrincipalMutation, } from "./principalMutationDispatch.js";
5
5
  function sameScope(current, bound) {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,+DAA+D,CAAC;AAClH,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;AAYD,SAAS,eAAe,CACtB,KAAuC,EACvC,KAA2C,EAC3C,cAAsB;IAEtB,IAAI,CAAC,KAAK;QACR,MAAM,IAAI,KAAK,CACb,+GAA+G,CAChH,CAAC;IACJ,OA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I,OAAO,KAAK,KAAK,UAAU;gBAAE,OAAO,KAAK,CAAC;YAC9C,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YAC5C,IAAI,QAAQ,EAAE,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 {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutationJournalManagement\";\nimport { recoverJournaledPrincipalMutation } from \"../../workflows/organizations/principalMutationJournalSession\";\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 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 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,5 +1,5 @@
1
- import { isCommitOrganizationGroupPolicyResponse, isCreateOrganizationGroupResponse, isDeleteOrganizationGroupResponse, isPrincipalPolicyMutationResponse, } from "../internal/validators/response/index.js";
2
- import { submitJournaledPrincipalMutation, } from "../workflows/organizations/principalMutationJournalSession.js";
1
+ import { isCommitOrganizationGroupPolicyResponse, isCreateOrganizationGroupResponse, isDeleteOrganizationGroupResponse, isPrincipalPolicyMutationResponse, } from "../../internal/validators/response/index.js";
2
+ import { submitJournaledPrincipalMutation, } from "../../workflows/organizations/principalMutationJournalSession.js";
3
3
  /** Dispatch the authenticated operation, with no application planning callback. */
4
4
  export function dispatchAuthoredPrincipalMutation(api, organizationId, mutation, options = {}) {
5
5
  switch (mutation.kind) {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAEL,gCAAgC,GACjC,MAAM,+DAA+D,CAAC;AAiBvE,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,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GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,wBAAwB,EAAE,GAAG;QAC7B,kBAAkB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAI,MAAwB;IAC3C,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutationJournalSession\";\nimport type { PrincipalMutationResponse } from \"../../workflows/organizations/principalOperationReceipt\";\n\nimport type { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport type JournaledPrincipalMutationMethods = Pick<\n ApiClient,\n | \"commitOrganizationGroupPolicy\"\n | \"commitOrganizationGroupPolicyResult\"\n | \"createOrganizationGroup\"\n | \"createOrganizationGroupResult\"\n | \"deleteOrganizationGroup\"\n | \"deleteOrganizationGroupResult\"\n | \"putPrincipalPolicy\"\n | \"putPrincipalPolicyResult\"\n>;\n\n/** Dispatch the authenticated operation, with no application planning callback. */\nexport function dispatchAuthoredPrincipalMutation(\n api: ApiClient,\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n options: RequestResultOptions = {},\n): Promise<RequestResult<PrincipalMutationResponse>> {\n switch (mutation.kind) {\n case \"organization\":\n return api.putPrincipalPolicyResult(\n \"organization\",\n organizationId,\n mutation.request,\n options,\n );\n case \"group-create\":\n return api.createOrganizationGroupResult(\n organizationId,\n mutation.request,\n options,\n );\n case \"group-delete\":\n return api.deleteOrganizationGroupResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n case \"compound\":\n return api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n default:\n return unsupportedMutation(mutation);\n }\n}\n\nfunction unsupportedMutation(_mutation: never): never {\n throw new Error(\"Unsupported principal mutation operation\");\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: (\n organizationId: string,\n ) => Omit<PrincipalMutationJournalContext, \"submit\">,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n async function submit<T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<T>> {\n const result = await submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n submit: (saved) =>\n dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n api,\n organizationId,\n saved,\n dispatchOptions,\n ),\n ),\n });\n if (!result.ok) return result;\n // The session already verified this operation before clearing its row.\n // This check narrows the union for each existing public API signature.\n if (!validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n return { ok: true, data: result.data };\n }\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"compound\", groupId, request },\n isCommitOrganizationGroupPolicyResponse,\n options,\n );\n const create: ApiClient[\"createOrganizationGroupResult\"] = (\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-create\", groupId: request.groupId, request },\n isCreateOrganizationGroupResponse,\n options,\n );\n const remove: ApiClient[\"deleteOrganizationGroupResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-delete\", groupId, request },\n isDeleteOrganizationGroupResponse,\n options,\n );\n const put: ApiClient[\"putPrincipalPolicyResult\"] = (\n _type,\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"organization\", groupId: null, request },\n isPrincipalPolicyMutationResponse,\n options,\n );\n return {\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) =>\n nullable(await commit(...args)),\n createOrganizationGroupResult: create,\n createOrganizationGroup: async (...args) => nullable(await create(...args)),\n deleteOrganizationGroupResult: remove,\n deleteOrganizationGroup: async (...args) => nullable(await remove(...args)),\n putPrincipalPolicyResult: put,\n putPrincipalPolicy: async (...args) => nullable(await put(...args)),\n };\n}\n\nfunction nullable<T>(result: RequestResult<T>): T | null {\n return result.ok ? result.data : null;\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rootContainerAdoption.js","sourceRoot":"","sources":["rootContainerAdoption.ts"],"names":[],"mappings":"AAmBA,MAAM,UAAU,yBAAyB,CACvC,YAA+C,EAC/C,KAAyC;IAEzC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;IACrC,IACE,YAAY,CAAC,cAAc,EAAE,KAAK,KAAK,CAAC,WAAW;QACnD,CAAC,OAAO,CAAC,eAAe;QACxB,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAC/B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,eAAe,EAAE,CAAC;QAClD,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB,EAAE,CAAC;QACtD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAC9C,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n} from \"../../workflows/container-contents/runtime\";\nimport type { Session } from \"../session/sessionTypes\";\n\ninterface RootContainerAdoptionDependencies {\n readonly getDomainScope: () => DomainScope;\n readonly session: Pick<\n Session,\n | \"containerId\"\n | \"isAuthenticated\"\n | \"organizationId\"\n | \"setContainerId\"\n | \"userId\"\n >;\n}\n\nexport function adoptSessionRootContainer(\n dependencies: RootContainerAdoptionDependencies,\n input: ContainerContentsRootAdoptionInput,\n): ReturnType<ContainerContentsRootAdopter> {\n const session = dependencies.session;\n if (\n dependencies.getDomainScope() !== input.domainScope ||\n !session.isAuthenticated ||\n session.organizationId !== input.organizationId ||\n session.userId !== input.userId\n ) {\n return false;\n }\n if (session.containerId === input.nextContainerId) {\n return \"already-adopted\";\n }\n if (session.containerId !== input.expectedContainerId) {\n return false;\n }\n\n session.setContainerId(input.nextContainerId);\n return true;\n}\n"]}
@@ -1,20 +1,20 @@
1
- import type { ApiClient } from "../internal/api-client/index.js";
2
- import type { DocumentProjectorRegistry } from "../data/documents/documentKinds.js";
3
- import type { PrincipalHistoryProtectionLease } from "../data/principals/principalHistoryProtection.js";
4
- import type { DomainScope } from "../data/shared/domainScope.js";
5
- import type { SecurityIncidentReporter } from "../data/shared/securityIncidents.js";
6
- import { type LocalUserIdentityCandidate, type TrustedUserIdentityResolver, type TrustedUserIdentityService } from "../data/trustedUserIdentity/index.js";
7
- import type { ContainerContentsRootAdopter } from "../workflows/container-contents/runtime.js";
8
- import { type ProvisionedPrincipalHistoryPrimer } from "../workflows/registration/provisionedPrincipalHistory.js";
9
- import type { WorkflowRuntimeGroups, WorkflowRuntimeUtilInput } from "../workflows/runtimeInput.js";
10
- import type { Blobs } from "./blobs.js";
1
+ import type { ApiClient } from "../../internal/api-client/index.js";
2
+ import type { DocumentProjectorRegistry } from "../../data/documents/documentKinds.js";
3
+ import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
4
+ import type { DomainScope } from "../../data/shared/domainScope.js";
5
+ import type { SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
6
+ import { type LocalUserIdentityCandidate, type TrustedUserIdentityResolver, type TrustedUserIdentityService } from "../../data/trustedUserIdentity/index.js";
7
+ import type { ContainerContentsRootAdopter } from "../../workflows/container-contents/runtime.js";
8
+ import { type ProvisionedPrincipalHistoryPrimer } from "../../workflows/registration/provisionedPrincipalHistory.js";
9
+ import type { WorkflowRuntimeGroups, WorkflowRuntimeUtilInput } from "../../workflows/shared/runtimeInput.js";
10
+ import type { Blobs } from "../blobs/index.js";
11
+ import type { Identity } from "../identity/index.js";
12
+ import type { Session } from "../session/sessionTypes.js";
11
13
  import type { Database } from "./database.js";
12
14
  import type { Events } from "./events.js";
13
- import type { Identity } from "./identity.js";
14
15
  import type { Network } from "./network.js";
15
16
  import { type PrincipalHistoryKeyProvider } from "./principalHistoryProtection.js";
16
17
  import { type PrincipalMutationApi } from "./principalMutationApi.js";
17
- import type { Session } from "./session/sessionTypes.js";
18
18
  import type { SyncBillingGate } from "./syncBillingGate.js";
19
19
  type HostWorkflowRuntimeUtilInput = Omit<WorkflowRuntimeUtilInput, "reportSecurityIncident">;
20
20
  export interface WorkflowRuntimeInput extends Omit<WorkflowRuntimeGroups, "util"> {
@@ -1,12 +1,12 @@
1
- import { runWithSecurityIncidentReporting } from "../data/keyingProjectionVerification/error.js";
2
- import { unavailableExecSql } from "../data/sqlite/sqlSchema.js";
3
- import { createApiUserIdentitySource, createTrustedUserIdentityService, loadPinnedUserIdentity, } from "../data/trustedUserIdentity/index.js";
4
- import { createProvisionedPrincipalHistoryPrimer, } from "../workflows/registration/provisionedPrincipalHistory.js";
1
+ import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
2
+ import { unavailableExecSql } from "../../data/sqlite/sqlSchema.js";
3
+ import { createApiUserIdentitySource, createTrustedUserIdentityService, loadPinnedUserIdentity, } from "../../data/trustedUserIdentity/index.js";
4
+ import { createProvisionedPrincipalHistoryPrimer, } from "../../workflows/registration/provisionedPrincipalHistory.js";
5
+ import { acknowledgedSessionRoot } from "../session/sessionRootAuthority.js";
5
6
  import { createListenerSet } from "./listenerSet.js";
6
7
  import { createPrincipalHistoryProtectionCustody, } from "./principalHistoryProtection.js";
7
8
  import { createPrincipalMutationApiCustody, } from "./principalMutationApi.js";
8
9
  import { adoptSessionRootContainer } from "./rootContainerAdoption.js";
9
- import { acknowledgedSessionRoot } from "./session/sessionRootAuthority.js";
10
10
  function createRuntimeMutationApi(dependencies, readGeneration) {
11
11
  return createPrincipalMutationApiCustody({
12
12
  api: dependencies.api,
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AAIjG,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAEhC,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,uCAAuC,GAExC,MAAM,0DAA0D,CAAC;AAWlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAI1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;A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QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents/runtime\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\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 { createListenerSet } from \"./listenerSet\";\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 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 readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\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) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\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\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\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): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\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 trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\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 ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\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 primeProvisionedPrincipalHistory: 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 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 });\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) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\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\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { type KeyingVerificationError } from "../internal/crypto/index.js";
2
- import type { SecurityIncident, SecurityIncidentContext, SecurityIncidentObjectKind, SecurityIncidentReporter } from "../data/shared/securityIncidents.js";
3
- import type { Database } from "./database.js";
1
+ import { type KeyingVerificationError } from "../../internal/crypto/index.js";
2
+ import type { SecurityIncident, SecurityIncidentContext, SecurityIncidentObjectKind, SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
3
+ import type { Database } from "../runtime/database.js";
4
4
  export type { SecurityIncident, SecurityIncidentObjectKind };
5
5
  export type SecurityIncidentListener = (incident: SecurityIncident) => void;
6
6
  /**
@@ -1,7 +1,7 @@
1
- import { compareCanonicalStrings, isKeyingVerificationCode, } from "../internal/crypto/index.js";
2
- import { isKeyingVerificationError } from "../data/keyingProjectionVerification/error.js";
3
- import { appendSecurityIncident, listSecurityIncidents, } from "../data/persistence/securityIncidentPersistence.js";
4
- import { createListenerSet } from "./listenerSet.js";
1
+ import { compareCanonicalStrings, isKeyingVerificationCode, } from "../../internal/crypto/index.js";
2
+ import { isKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
3
+ import { appendSecurityIncident, listSecurityIncidents, } from "../../data/persistence/securityIncidentPersistence.js";
4
+ import { createListenerSet } from "../runtime/listenerSet.js";
5
5
  const MAX_BUFFERED_SECURITY_INCIDENTS = 100;
6
6
  const MAX_EVIDENCE_HASH_COUNT = 32;
7
7
  const MAX_EVIDENCE_HASH_KEY_LENGTH = 64;
@@ -284,4 +284,4 @@ export function createSecurityIncidentService(options) {
284
284
  report,
285
285
  };
286
286
  }
287
- //# sourceMappingURL=securityIncidents.js.map
287
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wBAAwB,GAEzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAC1F,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,oDAAoD,CAAC;AAQ5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAc3D,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,6BAA6B,GAAG,GAAG,CAAC;AAC1C,MAAM,gCAAgC,GAAG,GAAG,CAAC;AAC7C,MAAM,oCAAoC,GAAG,MAAM,CAAC;AAgCpD,SAAS,gBAAgB,CAAC,KAAc;IACtC,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACnD,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACxC,OAAO,wBAAwB,CAAC,IAAI,CAAC;QACnC,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,gCAAgC,CAAC;AACvC,CAAC;AAUD,SAAS,iBAAiB,CAAC,KAAa,EAAE,SAAiB;IACzD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,yBAAyB,CAAC,KAAoB;IACrD,OAAO,KAAK,KAAK,IAAI;QACnB,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,iBAAi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eAAe,CAAC,KAAK,EAAE,OAAO,CAAC;aAC5C,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;YACf,IAAI,MAAM,KAAK,QAAQ;gBAAE,cAAc,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;YAC3D,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC;aACD,OAAO,CAAC,GAAG,EAAE;YACZ,eAAe,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC,CAAC,CAAC;QACL,eAAe,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACpC,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;IACF,MAAM,MAAM,GAA6B,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;QAChE,MAAM,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC/B,CAAC,CAAC;IAEF,OAAO;QACL,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE;QAC7B,SAAS,EAAE;YACT,KAAK,CAAC,IAAI;gBACR,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;gBACnB,MAAM,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;gBACzC,OAAO,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,IAAI,OAAO;oBACnD,CAAC,CAAC,qBAAqB,CAAC,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC;oBACrD,CAAC,CAAC,IAAI,CAAC;YACX,CAAC;YACD,MAAM;YACN,SAAS,EAAE,SAAS,CAAC,SAAS;SAC/B;QACD,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n isKeyingVerificationCode,\n type KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport { isKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n appendSecurityIncident,\n listSecurityIncidents,\n} from \"../../data/persistence/securityIncidentPersistence\";\nimport type {\n SecurityIncident,\n SecurityIncidentContext,\n SecurityIncidentObjectKind,\n SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport type { Database } from \"../runtime/database\";\nimport { createListenerSet } from \"../runtime/listenerSet\";\n\nexport type { SecurityIncident, SecurityIncidentObjectKind };\n\nexport type SecurityIncidentListener = (incident: SecurityIncident) => void;\n\n/**\n * Where a reported incident ended up: `recorded` rows are durable in the local\n * ledger, `buffered` ones wait in memory for a retried write, and `failed`\n * ones were dropped, so only `recorded` justifies telling a user it was kept.\n * Hosts name it as `Awaited<ReturnType<SecurityIncidents[\"record\"]>>`.\n */\ntype SecurityIncidentRecordingStatus = \"buffered\" | \"failed\" | \"recorded\";\n\nconst MAX_BUFFERED_SECURITY_INCIDENTS = 100;\nconst MAX_EVIDENCE_HASH_COUNT = 32;\nconst MAX_EVIDENCE_HASH_KEY_LENGTH = 64;\nconst MAX_EVIDENCE_HASH_VALUE_LENGTH = 256;\nconst MAX_INCIDENT_IDENTIFIER_LENGTH = 256;\nconst MAX_INCIDENT_OPERATION_LENGTH = 128;\nconst SECURITY_INCIDENT_RETRY_DELAY_MS = 250;\nconst SECURITY_INCIDENT_MAX_RETRY_DELAY_MS = 30_000;\n\nexport interface SecurityIncidents {\n /** Returns null while the local database is unavailable. */\n list(): Promise<ReadonlyArray<SecurityIncident> | null>;\n /**\n * Durably record a terminal verification failure the host detected itself,\n * such as conflicting purge proofs found while merging a local backup. The\n * report is redacted, coalesced, retained, and buffered exactly like an\n * SDK-detected incident; one error instance is recorded at most once, and\n * repeats of it resolve with the status of the first report.\n */\n record(\n error: KeyingVerificationError,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus>;\n subscribe(listener: SecurityIncidentListener): () => void;\n}\n\ninterface SecurityIncidentServiceOptions {\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly onIncident?: SecurityIncidentListener | undefined;\n readonly trustDomain: string | null;\n}\n\ninterface SecurityIncidentServiceResult {\n readonly dispose: () => void;\n readonly incidents: SecurityIncidents;\n readonly report: SecurityIncidentReporter;\n}\n\nfunction verificationCode(error: unknown): SecurityIncident[\"code\"] | null {\n if (!isKeyingVerificationError(error)) return null;\n const code = Reflect.get(error, \"code\");\n return isKeyingVerificationCode(code)\n ? code\n : \"unrecognized_verification_code\";\n}\n\ninterface RedactedIncident {\n readonly code: SecurityIncident[\"code\"];\n readonly context: SecurityIncidentContext;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nfunction boundIncidentText(value: string, maxLength: number): string {\n return value.slice(0, maxLength);\n}\n\nfunction boundNullableIncidentText(value: string | null): string | null {\n return value === null\n ? null\n : boundIncidentText(value, MAX_INCIDENT_IDENTIFIER_LENGTH);\n}\n\nfunction redactIncidentContext(\n context: SecurityIncidentContext,\n): SecurityIncidentContext {\n return {\n evidenceHashes: Object.fromEntries(\n Object.entries(context.evidenceHashes ?? {})\n .filter(\n ([key, value]) =>\n key.length > 0 &&\n key.length <= MAX_EVIDENCE_HASH_KEY_LENGTH &&\n value.length <= MAX_EVIDENCE_HASH_VALUE_LENGTH,\n )\n // Code-unit order: the retained keys feed the incident id hash, so\n // truncation must pick the same keys on every runtime and locale.\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .slice(0, MAX_EVIDENCE_HASH_COUNT),\n ),\n objectId: boundNullableIncidentText(context.objectId),\n objectKind: context.objectKind,\n operation: boundIncidentText(\n context.operation,\n MAX_INCIDENT_OPERATION_LENGTH,\n ),\n organizationId: boundNullableIncidentText(context.organizationId ?? null),\n };\n}\n\nfunction redactedIncidentKey(incident: RedactedIncident): string {\n return JSON.stringify([\n incident.code,\n incident.context.operation,\n incident.context.objectKind,\n incident.context.objectId,\n incident.context.organizationId ?? null,\n incident.context.evidenceHashes,\n ]);\n}\n\ntype SecurityIncidentListeners = ReturnType<\n typeof createListenerSet<[SecurityIncident]>\n>;\n\nclass SecurityIncidentSink {\n private readonly bufferedIncidents = new Map<string, RedactedIncident>();\n private flushPromise: Promise<boolean> | null = null;\n private retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n private retryTimeout: ReturnType<typeof setTimeout> | null = null;\n private readonly unsubscribeDatabase: () => void;\n private disposed = false;\n\n constructor(\n private readonly options: SecurityIncidentServiceOptions,\n private readonly listeners: SecurityIncidentListeners,\n ) {\n this.unsubscribeDatabase = options.database.subscribe(() => {\n void this.flush();\n });\n }\n\n dispose(): void {\n this.disposed = true;\n this.unsubscribeDatabase();\n if (this.retryTimeout) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n this.bufferedIncidents.clear();\n }\n\n async persist(\n code: SecurityIncident[\"code\"],\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> {\n if (this.disposed) return \"failed\";\n const detectedAt = new Date().toISOString();\n const incident: RedactedIncident = {\n code,\n context: redactIncidentContext(context),\n detectedAt,\n lastDetectedAt: detectedAt,\n occurrenceCount: 1,\n };\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) {\n return this.bufferStatus(incident);\n }\n\n try {\n const persisted = await this.append(execSql, incident);\n if (this.bufferedIncidents.size === 0) this.resetFlushRetry();\n if (!persisted) {\n this.options.logError(\n \"Security incident was dropped by the local retention limit\",\n );\n return \"failed\";\n }\n this.notify(persisted);\n return \"recorded\";\n } catch (persistenceError) {\n const status = this.bufferStatus(incident);\n if (status === \"buffered\") this.scheduleFlushRetry();\n this.options.logError(\n \"Security incident could not be persisted\",\n persistenceError,\n );\n return status;\n }\n }\n\n private bufferStatus(\n incident: RedactedIncident,\n ): SecurityIncidentRecordingStatus {\n return this.buffer(incident) ? \"buffered\" : \"failed\";\n }\n\n async flush(): Promise<void> {\n if (this.disposed) return;\n for (;;) {\n const activeFlush = this.flushPromise ?? this.startFlushBatch();\n if (!activeFlush) return;\n const succeeded = await activeFlush;\n if (succeeded) this.resetFlushRetry();\n if (this.flushPromise && this.flushPromise !== activeFlush) continue;\n if (this.flushPromise === activeFlush) this.flushPromise = null;\n if (\n !succeeded ||\n this.bufferedIncidents.size === 0 ||\n this.options.database.status !== \"ready\"\n ) {\n return;\n }\n }\n }\n\n private startFlushBatch(): Promise<boolean> | null {\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) return null;\n\n const pending = [...this.bufferedIncidents.values()];\n if (pending.length === 0) return null;\n this.bufferedIncidents.clear();\n const flush = this.flushPending(execSql, pending);\n this.flushPromise = flush;\n return flush;\n }\n\n private append(\n execSql: NonNullable<Database[\"execSql\"]>,\n incident: RedactedIncident,\n ): Promise<SecurityIncident | null> {\n return appendSecurityIncident(execSql, {\n code: incident.code,\n detectedAt: incident.detectedAt,\n evidenceHashes: incident.context.evidenceHashes,\n lastDetectedAt: incident.lastDetectedAt,\n objectId: incident.context.objectId,\n objectKind: incident.context.objectKind,\n occurrenceCount: incident.occurrenceCount,\n operation: incident.context.operation,\n organizationId: incident.context.organizationId,\n trustDomain: this.options.trustDomain,\n });\n }\n\n private buffer(incident: RedactedIncident): boolean {\n if (this.disposed) return false;\n const key = redactedIncidentKey(incident);\n const existing = this.bufferedIncidents.get(key);\n if (existing) {\n this.bufferedIncidents.set(key, {\n ...existing,\n lastDetectedAt: incident.lastDetectedAt,\n occurrenceCount: existing.occurrenceCount + incident.occurrenceCount,\n });\n return true;\n }\n if (this.bufferedIncidents.size >= MAX_BUFFERED_SECURITY_INCIDENTS) {\n this.options.logError(\n \"Security incident could not be buffered because the startup buffer is full\",\n );\n return false;\n }\n this.bufferedIncidents.set(key, incident);\n return true;\n }\n\n private async flushPending(\n execSql: NonNullable<Database[\"execSql\"]>,\n pending: ReadonlyArray<RedactedIncident>,\n ): Promise<boolean> {\n let succeeded = true;\n for (const incident of pending) {\n try {\n const persisted = await this.append(execSql, incident);\n if (persisted) this.notify(persisted);\n } catch (persistenceError) {\n succeeded = false;\n if (this.buffer(incident)) this.scheduleFlushRetry();\n this.options.logError(\n \"Buffered security incident could not be persisted\",\n persistenceError,\n );\n }\n }\n return succeeded;\n }\n\n private notify(incident: SecurityIncident): void {\n if (this.disposed) return;\n this.listeners.notify(incident);\n try {\n this.options.onIncident?.(incident);\n } catch (callbackError) {\n this.options.logError(\"Security incident callback failed\", callbackError);\n }\n }\n\n private scheduleFlushRetry(): void {\n if (this.disposed || this.retryTimeout) return;\n const retryDelayMs = this.retryDelayMs;\n this.retryDelayMs = Math.min(\n this.retryDelayMs * 2,\n SECURITY_INCIDENT_MAX_RETRY_DELAY_MS,\n );\n this.retryTimeout = setTimeout(() => {\n this.retryTimeout = null;\n if (this.disposed) return;\n void this.flush();\n }, retryDelayMs);\n }\n\n private resetFlushRetry(): void {\n this.retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n if (!this.retryTimeout) return;\n clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n}\n\nexport function createSecurityIncidentService(\n options: SecurityIncidentServiceOptions,\n): SecurityIncidentServiceResult {\n const listeners = createListenerSet<[SecurityIncident]>();\n const recordedErrors = new WeakMap<object, SecurityIncidentRecordingStatus>();\n const incidentReports = new WeakMap<\n object,\n Promise<SecurityIncidentRecordingStatus>\n >();\n const sink = new SecurityIncidentSink(options, listeners);\n\n const persistIncident = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n const code = verificationCode(error);\n if (!code) {\n return \"failed\";\n }\n if (code === \"unrecognized_verification_code\") {\n options.logError(\n \"Security incident used the fallback code because its verification code is unrecognized\",\n );\n }\n\n return sink.persist(code, context);\n };\n\n const record = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n if (typeof error !== \"object\" || error === null) {\n return \"failed\";\n }\n const recorded = recordedErrors.get(error);\n if (recorded) return recorded;\n const inFlight = incidentReports.get(error);\n if (inFlight) return inFlight;\n const pending = persistIncident(error, context)\n .then((status) => {\n if (status !== \"failed\") recordedErrors.set(error, status);\n return status;\n })\n .finally(() => {\n incidentReports.delete(error);\n });\n incidentReports.set(error, pending);\n return pending;\n };\n const report: SecurityIncidentReporter = async (error, context) => {\n await record(error, context);\n };\n\n return {\n dispose: () => sink.dispose(),\n incidents: {\n async list() {\n await sink.flush();\n const execSql = options.database.execSql;\n return options.database.status === \"ready\" && execSql\n ? listSecurityIncidents(execSql, options.trustDomain)\n : null;\n },\n record,\n subscribe: listeners.subscribe,\n },\n report,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { removeNativeSubscriptionRestoreProvisioningAttempt } from "../../workflows/organizations/createOrganization.js";
2
2
  import { bootstrapRootContainer, registerIdentity as registerIdentityWorkflow, } from "../../workflows/registration/index.js";
3
- import { createListenerSet } from "../listenerSet.js";
3
+ import { createListenerSet } from "../runtime/listenerSet.js";
4
4
  import { emptySessionSnapshot, mergeSessionContext, sessionSnapshotsEqual, } from "./sessionContext.js";
5
5
  import { registrationKeyAlreadyBound, requireRegistrationIdentityPinner, requireUserIdentityAvailable, SessionIdentityAcknowledgments, } from "./sessionIdentityTrust.js";
6
6
  import { userSessionsFromResponse } from "./sessionListing.js";