@tearleads/client-sdk 0.1.247 → 0.1.249

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 (151) hide show
  1. package/Tearleads.js +4 -2
  2. package/Tearleads.js.map +1 -1
  3. package/client/organizations/index.js +5 -3
  4. package/client/organizations/index.js.map +1 -1
  5. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  6. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  7. package/client/organizations/organizationLeaveRequestVerifier.js +21 -0
  8. package/client/organizations/organizationLeaveRequestVerifier.js.map +1 -0
  9. package/client/organizations/{organizationReadModels.d.ts → organizationReadModelCoordinator.d.ts} +18 -16
  10. package/client/organizations/organizationReadModelCoordinator.js +2 -0
  11. package/client/organizations/organizationReadModelCoordinator.js.map +1 -0
  12. package/client/organizations/organizationReadModelPresentation.js +51 -0
  13. package/client/organizations/organizationReadModelPresentation.js.map +1 -0
  14. package/client/organizations/organizationReadModelScopes.js +37 -0
  15. package/client/organizations/organizationReadModelScopes.js.map +1 -0
  16. package/client/organizations/organizationReadModels.js +131 -88
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationsTypes.d.ts +13 -5
  19. package/client/organizations/organizationsTypes.js.map +1 -1
  20. package/client/organizations/principalMutations.d.ts +18 -2
  21. package/client/organizations/principalMutations.js +29 -15
  22. package/client/organizations/principalMutations.js.map +1 -1
  23. package/client/runtime/principalMutationApi.d.ts +2 -0
  24. package/client/runtime/principalMutationApi.js +2 -0
  25. package/client/runtime/principalMutationApi.js.map +1 -1
  26. package/client/runtime/principalMutationDispatch.js +47 -10
  27. package/client/runtime/principalMutationDispatch.js.map +1 -1
  28. package/client/runtime/workflowRuntime.js +5 -4
  29. package/client/runtime/workflowRuntime.js.map +1 -1
  30. package/data/containers/shared/mutationRequestOptions.d.ts +2 -0
  31. package/data/containers/shared/mutationRequestOptions.js.map +1 -1
  32. package/data/containers/shared/types.d.ts +12 -2
  33. package/data/containers/shared/types.js.map +1 -1
  34. package/data/persistence/organizations/organizationReadModelRepository.js +20 -2
  35. package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -1
  36. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +53 -0
  37. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -0
  38. package/data/persistence/verifiedManifestBundlePersistence.d.ts +8 -3
  39. package/data/persistence/verifiedManifestBundlePersistence.js +34 -15
  40. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  41. package/internal/api-client/ApiClient.d.ts +4 -1
  42. package/internal/api-client/client/containerMutations.d.ts +2 -2
  43. package/internal/api-client/client/containerMutations.js +2 -1
  44. package/internal/api-client/client/containerMutations.js.map +1 -1
  45. package/internal/api-client/client/principalPolicies.d.ts +3 -0
  46. package/internal/api-client/heldDirectoryCitations.d.ts +19 -0
  47. package/internal/api-client/heldDirectoryCitations.js +37 -0
  48. package/internal/api-client/heldDirectoryCitations.js.map +1 -0
  49. package/internal/api-client/index.d.ts +1 -1
  50. package/internal/api-client/index.js.map +1 -1
  51. package/internal/api-client/principalPolicyRequests.d.ts +2 -0
  52. package/internal/api-client/principalPolicyRequests.js +6 -4
  53. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  54. package/internal/api-client/routes/containers/mutations.js +3 -3
  55. package/internal/api-client/routes/containers/mutations.js.map +1 -1
  56. package/internal/api-client/routes/organizations/createGroup.js +3 -5
  57. package/internal/api-client/routes/organizations/createGroup.js.map +1 -1
  58. package/internal/api-client/routes/principals/policy.js +2 -5
  59. package/internal/api-client/routes/principals/policy.js.map +1 -1
  60. package/internal/api-client/types.d.ts +6 -0
  61. package/internal/api-client/types.js.map +1 -1
  62. package/internal/api-client/verifiedManifestCitations.d.ts +16 -6
  63. package/internal/api-client/verifiedManifestCitations.js +32 -13
  64. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  65. package/internal/api-client/writerProjectionRequests.js +5 -3
  66. package/internal/api-client/writerProjectionRequests.js.map +1 -1
  67. package/internal/validators/knownManifestsRefinements.js +1 -1
  68. package/internal/validators/knownManifestsRefinements.js.map +1 -1
  69. package/internal/validators/operation/containerMutations.d.ts +20 -3
  70. package/internal/validators/operation/containerMutations.js +18 -20
  71. package/internal/validators/operation/containerMutations.js.map +1 -1
  72. package/internal/validators/operation/index.d.ts +1 -1
  73. package/internal/validators/operation/index.js +1 -1
  74. package/internal/validators/operation/index.js.map +1 -1
  75. package/internal/validators/operation/organizations.d.ts +17 -1
  76. package/internal/validators/operation/organizations.js +4 -2
  77. package/internal/validators/operation/organizations.js.map +1 -1
  78. package/internal/validators/operation/principals.d.ts +17 -1
  79. package/internal/validators/operation/principals.js +5 -2
  80. package/internal/validators/operation/principals.js.map +1 -1
  81. package/internal/validators/operation/writerProjections.d.ts +11 -11
  82. package/internal/validators/operation/writerProjections.js +1 -1
  83. package/internal/validators/operation/writerProjections.js.map +1 -1
  84. package/internal/validators/request/index.d.ts +1 -1
  85. package/internal/validators/request/index.js +1 -1
  86. package/internal/validators/request/index.js.map +1 -1
  87. package/internal/validators/request/organization.d.ts +15 -0
  88. package/internal/validators/request/organization.js +8 -0
  89. package/internal/validators/request/organization.js.map +1 -1
  90. package/internal/validators/response/areas/organizations.d.ts +3 -2
  91. package/internal/validators/response/areas/organizations.js +3 -2
  92. package/internal/validators/response/areas/organizations.js.map +1 -1
  93. package/internal/validators/response/areas/principals.d.ts +3 -2
  94. package/internal/validators/response/areas/principals.js +2 -2
  95. package/internal/validators/response/areas/principals.js.map +1 -1
  96. package/internal/validators/response/committedReadModel.d.ts +697 -0
  97. package/internal/validators/response/committedReadModel.js +52 -0
  98. package/internal/validators/response/committedReadModel.js.map +1 -0
  99. package/internal/validators/response/container.d.ts +56 -4
  100. package/internal/validators/response/container.js +5 -5
  101. package/internal/validators/response/container.js.map +1 -1
  102. package/internal/validators/response/documentMutation.d.ts +4 -4
  103. package/internal/validators/response/documentMutation.js +2 -2
  104. package/internal/validators/response/documentMutation.js.map +1 -1
  105. package/internal/validators/response/organization.d.ts +0 -191
  106. package/internal/validators/response/organization.js +0 -7
  107. package/internal/validators/response/organization.js.map +1 -1
  108. package/internal/validators/response/organizationReadModel.d.ts +167 -0
  109. package/internal/validators/response/organizationReadModel.js +5 -0
  110. package/internal/validators/response/organizationReadModel.js.map +1 -1
  111. package/internal/validators/response/policyEvidenceWire.d.ts +17 -0
  112. package/internal/validators/response/policyEvidenceWire.js +36 -0
  113. package/internal/validators/response/policyEvidenceWire.js.map +1 -0
  114. package/internal/validators/response/principal.d.ts +0 -403
  115. package/internal/validators/response/principal.js +0 -8
  116. package/internal/validators/response/principal.js.map +1 -1
  117. package/internal/validators/response/projectionPolicyEvidence.d.ts +175 -0
  118. package/internal/validators/response/projectionPolicyEvidence.js +13 -0
  119. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  120. package/internal/validators/response/writerProjectionWire.d.ts +11 -7
  121. package/internal/validators/response/writerProjectionWire.js +19 -10
  122. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  123. package/internal/validators/util/index.d.ts +1 -1
  124. package/internal/validators/util/index.js +1 -1
  125. package/internal/validators/util/index.js.map +1 -1
  126. package/internal/validators/util/knownManifestWire.d.ts +9 -3
  127. package/internal/validators/util/knownManifestWire.js +24 -8
  128. package/internal/validators/util/knownManifestWire.js.map +1 -1
  129. package/package.json +1 -1
  130. package/workflows/container-contents/container-state/organizationHost.d.ts +9 -0
  131. package/workflows/container-contents/container-state/organizationHost.js.map +1 -1
  132. package/workflows/container-contents/container-state/remote.js +6 -0
  133. package/workflows/container-contents/container-state/remote.js.map +1 -1
  134. package/workflows/containers/child/share/index.d.ts +4 -2
  135. package/workflows/containers/child/share/index.js +37 -20
  136. package/workflows/containers/child/share/index.js.map +1 -1
  137. package/workflows/organizations/containerContentsHost.js +20 -1
  138. package/workflows/organizations/containerContentsHost.js.map +1 -1
  139. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +5 -1
  140. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  141. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +8 -1
  142. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  143. package/workflows/organizations/index.d.ts +1 -0
  144. package/workflows/organizations/index.js +1 -0
  145. package/workflows/organizations/index.js.map +1 -1
  146. package/workflows/organizations/readModel/committedReadModel.d.ts +66 -0
  147. package/workflows/organizations/readModel/committedReadModel.js +150 -0
  148. package/workflows/organizations/readModel/committedReadModel.js.map +1 -0
  149. package/workflows/organizations/readModel/readModelProjection.d.ts +15 -2
  150. package/workflows/organizations/readModel/readModelProjection.js +26 -4
  151. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
@@ -46,7 +46,9 @@ export async function addUserToOrganizationGroup(input) {
46
46
  });
47
47
  if (!mutateCurrent)
48
48
  throw new ProjectionDependencyUnavailableError("Principal history recovery is unavailable");
49
- const { memberGroupId, response: bundle, enrolled, } = await mutateCurrent(input.groupId, {
49
+ // The post-commit read belongs to the session the mutation began in.
50
+ const startedIn = input.readModelCoordinator.sessionGuard(signingContext.organizationId);
51
+ const { memberGroupId, response: { readModel, ...bundle }, enrolled, } = await mutateCurrent(input.groupId, {
50
52
  kind: "add",
51
53
  expectedGroupName: input.expectedGroupName,
52
54
  targetUserId: input.targetUserId,
@@ -59,9 +61,10 @@ export async function addUserToOrganizationGroup(input) {
59
61
  organizationId: signingContext.organizationId,
60
62
  });
61
63
  }
62
- // The verified post-commit read is the mutation's own: callers apply
63
- // this directory instead of reading the read model a second time.
64
- const directoryAndGroups = await input.readModelCoordinator.reconcileAfterMutation(signingContext.organizationId);
64
+ // The verified post-commit read is the mutation's own, from the delta
65
+ // its response carried when that applies: callers apply this directory
66
+ // instead of reading the read model a second time.
67
+ const directoryAndGroups = await input.readModelCoordinator.reconcileAfterOwnMutation(signingContext.organizationId, readModel, startedIn);
65
68
  return { directoryAndGroups, receipt: bundle };
66
69
  });
67
70
  }
@@ -72,12 +75,12 @@ export function createGroupForOrganization(input) {
72
75
  objectKind: "principal",
73
76
  operation: "group.create",
74
77
  organizationId: signingContext.organizationId,
75
- }, () => {
78
+ }, async () => {
76
79
  const creatorEncapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);
77
80
  const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);
78
81
  if (!mutate)
79
82
  throw new ProjectionDependencyUnavailableError("Principal history recovery is unavailable");
80
- return mutate({ ...signingContext, stillCurrent: input.stillCurrent }, (context) => createCurrentOrganizationGroup({
83
+ const { readModel, ...group } = await mutate({ ...signingContext, stillCurrent: input.stillCurrent }, (context) => createCurrentOrganizationGroup({
81
84
  ...signingContext,
82
85
  context,
83
86
  apiClient: input.runtime.apiClient,
@@ -92,6 +95,10 @@ export function createGroupForOrganization(input) {
92
95
  reportSecurityIncident: input.runtime.util.reportSecurityIncident,
93
96
  resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
94
97
  }));
98
+ // The create's own post-commit read, from the delta its response
99
+ // carried; `undefined` leaves the caller's after-mutation read to it.
100
+ const directoryAndGroups = (await input.readModelCoordinator.applyCommittedReadModel(signingContext.organizationId, readModel)) ?? undefined;
101
+ return { ...group, directoryAndGroups };
95
102
  });
96
103
  }
97
104
  export function deleteGroupForOrganization(input) {
@@ -130,7 +137,9 @@ export async function removeUserFromOrganizationGroup(input) {
130
137
  });
131
138
  if (!mutateCurrent)
132
139
  throw new ProjectionDependencyUnavailableError("Principal history recovery is unavailable");
133
- const { memberGroupId, response: bundle } = await mutateCurrent(input.groupId, {
140
+ // The post-commit read belongs to the session the mutation began in.
141
+ const startedIn = input.readModelCoordinator.sessionGuard(signingContext.organizationId);
142
+ const { memberGroupId, response: { readModel, ...bundle }, } = await mutateCurrent(input.groupId, {
134
143
  kind: "remove",
135
144
  expectedGroupName: input.expectedGroupName,
136
145
  removedUserId: input.removedUserId,
@@ -142,9 +151,10 @@ export async function removeUserFromOrganizationGroup(input) {
142
151
  organizationId: signingContext.organizationId,
143
152
  });
144
153
  }
145
- // The verified post-commit read is the mutation's own: callers apply
146
- // this directory instead of reading the read model a second time.
147
- const directoryAndGroups = await input.readModelCoordinator.reconcileAfterMutation(signingContext.organizationId);
154
+ // The verified post-commit read is the mutation's own, from the delta
155
+ // its response carried when that applies: callers apply this directory
156
+ // instead of reading the read model a second time.
157
+ const directoryAndGroups = await input.readModelCoordinator.reconcileAfterOwnMutation(signingContext.organizationId, readModel, startedIn);
148
158
  return { directoryAndGroups, receipt: bundle };
149
159
  });
150
160
  }
@@ -169,12 +179,15 @@ export async function revokeOrganizationGrant(input) {
169
179
  });
170
180
  if (!mutateCurrent)
171
181
  throw new ProjectionDependencyUnavailableError("Principal history recovery is unavailable");
172
- return (await mutateCurrent(input.subjectId, {
182
+ // The post-commit read belongs to the session the revoke began in.
183
+ const startedIn = input.readModelCoordinator.sessionGuard(signingContext.organizationId);
184
+ const { readModel, ...receipt } = (await mutateCurrent(input.subjectId, {
173
185
  kind: "revoke",
174
186
  revokedContainerId: input.containerId,
175
187
  })).response;
188
+ return { readModel, receipt, startedIn };
176
189
  }
177
- return revokeOrganizationContainerGrant({
190
+ const receipt = await revokeOrganizationContainerGrant({
178
191
  stillCurrent: input.stillCurrent,
179
192
  containerId: input.containerId,
180
193
  containers: new ContainerMutationService({
@@ -192,10 +205,11 @@ export async function revokeOrganizationGrant(input) {
192
205
  warmReferencedPrincipalPolicies: input.runtime.principalPolicies.createWarmer(),
193
206
  ...signingContext,
194
207
  });
208
+ return { readModel: undefined, receipt, startedIn: undefined };
195
209
  };
196
- const response = await revoke();
197
- await input.readModelCoordinator.reconcileAfterMutation(signingContext.organizationId);
198
- return response;
210
+ const { readModel, receipt, startedIn } = await revoke();
211
+ await input.readModelCoordinator.reconcileAfterOwnMutation(signingContext.organizationId, readModel, startedIn);
212
+ return receipt;
199
213
  });
200
214
  }
201
215
  //# sourceMappingURL=principalMutations.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutations.js","sourceRoot":"","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AG,EAAE,KAAK,CAAC,OAAO,CAAC,SAAS;oBAC5B,sBAAsB,EAAE,oBAAoB,CAAC,SAAS;oBACtD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;oBACpC,sBAAsB,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,sBAAsB;oBACjE,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;iBAC3C,CAAC;gBACF,cAAc,EAAE;oBACd,SAAS,EAAE,KAAK,CAAC,SAAS;oBAC1B,WAAW,EAAE,KAAK,CAAC,WAAW;iBAC/B;gBACD,0BAA0B,EAAE,KAAK,CAAC,OAAO,CAAC,0BAA0B;gBACpE,+BAA+B,EAC7B,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,YAAY,EAAE;gBAChD,GAAG,cAAc;aAClB,CAAC,CAAC;QACL,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/shared/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/shared/securityIncidents\";\nimport { ContainerMutationService } from \"../../workflows/containers\";\nimport { revokeOrganizationContainerGrant } from \"../../workflows/organizations\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../workflows/organizations/groupMetadata/currentGroupMetadataAuthority\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadata/groupMetadataRuntime\";\nimport { createCurrentOrganizationGroup } from \"../../workflows/organizations/groups/createCurrentOrganizationGroup\";\nimport { deleteCurrentOrganizationGroup } from \"../../workflows/organizations/groups/deleteCurrentOrganizationGroup\";\nimport { createRuntimeCurrentOrganizationMutation } from \"../../workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation\";\n\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport { createCurrentPrincipalMutation } from \"./currentPrincipalMutations\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport type { GroupMemberAdmission } from \"./recipientAdmission\";\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 identityTrustDomain: string;\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\n/** The client's fixed trust domain and the mutation's runtime snapshot. */\ninterface OrganizationMutationScope {\n readonly identityTrustDomain: string | null;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nfunction requireSigningContext({\n identityTrustDomain,\n runtime,\n}: OrganizationMutationScope): OrganizationSigningContext {\n if (\n !identityTrustDomain ||\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 identityTrustDomain,\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 extends OrganizationMutationScope {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime &\n AddOrganizationGroupUserInput & {\n readonly admission: GroupMemberAdmission;\n },\n) {\n const signingContext = requireSigningContext(input);\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 admission: input.admission,\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 // The verified post-commit read is the mutation's own: callers apply\n // this directory instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport function createGroupForOrganization(\n input: OrganizationMutationScope & {\n readonly name: string;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\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(\n input: OrganizationMutationScope & {\n readonly groupId: string;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\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 currentUserSecretKey:\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,\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);\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 // The verified post-commit read is the mutation's own: callers apply\n // this directory instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input);\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 }\n return revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n containerId: input.containerId,\n containers: new ContainerMutationService({\n api: input.runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: input.runtime.infra.execSql,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n ...signingContext,\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":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACvF,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,mDAAmD,EAAE,MAAM,2EAA2E,CAAC;AAChJ,OAAO,EAAE,gCAAgC,EAAE,MAAM,kEAAkE,CAAC;AACpH,OAAO,EAAE,8BAA8B,EAAE,MAAM,qEAAqE,CAAC;AACrH,OAAO,EAAE,8BAA8B,EAAE,MAAM,qEAAqE,CAAC;AACrH,OAAO,EAAE,wCAAwC,EAAE,MAAM,qFAAqF,CAAC;AAI/I,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAyCpF,SAAS,qBAAqB,CAAC,EAC7B,mBAAmB,EAC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SAAS,EAAE,CAAC;YAC3C,CAAC;YACD,MAAM,OAAO,GAAG,MAAM,gCAAgC,CAAC;gBACrD,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,UAAU,EAAE,IAAI,wBAAwB,CAAC;oBACvC,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,SAAS;oBAC5B,sBAAsB,EAAE,oBAAoB,CAAC,SAAS;oBACtD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;oBACpC,sBAAsB,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,sBAAsB;oBACjE,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;iBAC3C,CAAC;gBACF,cAAc,EAAE;oBACd,SAAS,EAAE,KAAK,CAAC,SAAS;oBAC1B,WAAW,EAAE,KAAK,CAAC,WAAW;iBAC/B;gBACD,0BAA0B,EAAE,KAAK,CAAC,OAAO,CAAC,0BAA0B;gBACpE,+BAA+B,EAC7B,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,YAAY,EAAE;gBAChD,GAAG,cAAc;aAClB,CAAC,CAAC;YACH,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;QACjE,CAAC,CAAC;QACF,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,EAAE,CAAC;QACzD,MAAM,KAAK,CAAC,oBAAoB,CAAC,yBAAyB,CACxD,cAAc,CAAC,cAAc,EAC7B,SAAS,EACT,SAAS,CACV,CAAC;QACF,OAAO,OAAO,CAAC;IACjB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerGrantSubjectType } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/shared/securityIncidents\";\nimport { ContainerMutationService } from \"../../workflows/containers\";\nimport { revokeOrganizationContainerGrant } from \"../../workflows/organizations\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../workflows/organizations/groupMetadata/currentGroupMetadataAuthority\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadata/groupMetadataRuntime\";\nimport { createCurrentOrganizationGroup } from \"../../workflows/organizations/groups/createCurrentOrganizationGroup\";\nimport { deleteCurrentOrganizationGroup } from \"../../workflows/organizations/groups/deleteCurrentOrganizationGroup\";\nimport { createRuntimeCurrentOrganizationMutation } from \"../../workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation\";\n\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport { createCurrentPrincipalMutation } from \"./currentPrincipalMutations\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\nimport type { GroupMemberAdmission } from \"./recipientAdmission\";\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 identityTrustDomain: string;\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\n/** The client's fixed trust domain and the mutation's runtime snapshot. */\ninterface OrganizationMutationScope {\n readonly identityTrustDomain: string | null;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nfunction requireSigningContext({\n identityTrustDomain,\n runtime,\n}: OrganizationMutationScope): OrganizationSigningContext {\n if (\n !identityTrustDomain ||\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 identityTrustDomain,\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 extends OrganizationMutationScope {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime &\n AddOrganizationGroupUserInput & {\n readonly admission: GroupMemberAdmission;\n },\n) {\n const signingContext = requireSigningContext(input);\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 // The post-commit read belongs to the session the mutation began in.\n const startedIn = input.readModelCoordinator.sessionGuard(\n signingContext.organizationId,\n );\n const {\n memberGroupId,\n response: { readModel, ...bundle },\n enrolled,\n } = await mutateCurrent(input.groupId, {\n kind: \"add\",\n expectedGroupName: input.expectedGroupName,\n targetUserId: input.targetUserId,\n admission: input.admission,\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 // The verified post-commit read is the mutation's own, from the delta\n // its response carried when that applies: callers apply this directory\n // instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterOwnMutation(\n signingContext.organizationId,\n readModel,\n startedIn,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport function createGroupForOrganization(\n input: OrganizationMutationScope & {\n readonly name: string;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\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 async () => {\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 const { readModel, ...group } = await 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 // The create's own post-commit read, from the delta its response\n // carried; `undefined` leaves the caller's after-mutation read to it.\n const directoryAndGroups =\n (await input.readModelCoordinator.applyCommittedReadModel(\n signingContext.organizationId,\n readModel,\n )) ?? undefined;\n return { ...group, directoryAndGroups };\n },\n );\n}\n\nexport function deleteGroupForOrganization(\n input: OrganizationMutationScope & {\n readonly groupId: string;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\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 currentUserSecretKey:\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,\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);\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 // The post-commit read belongs to the session the mutation began in.\n const startedIn = input.readModelCoordinator.sessionGuard(\n signingContext.organizationId,\n );\n const {\n memberGroupId,\n response: { readModel, ...bundle },\n } = await mutateCurrent(input.groupId, {\n kind: \"remove\",\n expectedGroupName: input.expectedGroupName,\n removedUserId: input.removedUserId,\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 // The verified post-commit read is the mutation's own, from the delta\n // its response carried when that applies: callers apply this directory\n // instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterOwnMutation(\n signingContext.organizationId,\n readModel,\n startedIn,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input);\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 // The post-commit read belongs to the session the revoke began in.\n const startedIn = input.readModelCoordinator.sessionGuard(\n signingContext.organizationId,\n );\n const { readModel, ...receipt } = (\n await mutateCurrent(input.subjectId, {\n kind: \"revoke\",\n revokedContainerId: input.containerId,\n })\n ).response;\n return { readModel, receipt, startedIn };\n }\n const receipt = await revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n containerId: input.containerId,\n containers: new ContainerMutationService({\n api: input.runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: input.runtime.infra.execSql,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n ...signingContext,\n });\n return { readModel: undefined, receipt, startedIn: undefined };\n };\n const { readModel, receipt, startedIn } = await revoke();\n await input.readModelCoordinator.reconcileAfterOwnMutation(\n signingContext.organizationId,\n readModel,\n startedIn,\n );\n return receipt;\n },\n );\n}\n"]}
@@ -14,6 +14,8 @@ export interface PrincipalMutationRuntimeScope {
14
14
  export type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;
15
15
  interface PrincipalMutationApiCustodyInput {
16
16
  readonly api: ApiClient;
17
+ /** Binds a mutation's committed read-model lease to its session. */
18
+ readonly readSessionGeneration?: (() => number) | undefined;
17
19
  readonly readScope: () => PrincipalMutationRuntimeScope | null;
18
20
  readonly principalMutationTimeoutMs?: number | undefined;
19
21
  }
@@ -17,6 +17,8 @@ function mutationContext(input, scope, organizationId) {
17
17
  if (!scope)
18
18
  throw new Error("Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage");
19
19
  return {
20
+ domainScope: scope.database,
21
+ sessionGeneration: input.readSessionGeneration?.() ?? 0,
20
22
  execSql: scope.execSql,
21
23
  signingKeyPair: scope.signingKeyPair,
22
24
  scope: {
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EACL,iCAAiC,EACjC,iCAAiC,GAElC,MAAM,6BAA6B,CAAC;AAYrC,SAAS,SAAS,CAChB,OAA6C,EAC7C,KAA2C;IAE3C,IAAI,CAAC,OAAO,IAAI,CA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AG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { recoverJournaledPrincipalMutation } from \"../../workflows/organizations\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalManagement\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n 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
+ {"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B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KACF,CAAC,CAAC;IACH,6EAA6E;IAC7E,uEAAuE;IACvE,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO,CACL,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { recoverJournaledPrincipalMutation } from \"../../workflows/organizations\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalManagement\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n /** Binds a mutation's committed read-model lease to its session. */\n readonly readSessionGeneration?: (() => number) | undefined;\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n domainScope: scope.database,\n sessionGeneration: input.readSessionGeneration?.() ?? 0,\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal principal policy and group lifecycle writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n if (cached && sameScope(scope, cached.scope)) return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n ...createJournaledPrincipalMutations(input.api, context, dispatch),\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.api,\n organizationId,\n mutation,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(input.api, methods);\n cached = { scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = value.bind(target);\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { isCommitOrganizationGroupPolicyResponse, isCreateOrganizationGroupResponse, isDeleteOrganizationGroupResponse, isPrincipalPolicyMutationResponse, } from "../../internal/validators/response/index.js";
2
- import { submitJournaledPrincipalMutation, } from "../../workflows/organizations/index.js";
1
+ import { committedReadModelDelta, isCommitOrganizationGroupPolicyResponse, isCreateOrganizationGroupResponse, isDeleteOrganizationGroupResponse, isPrincipalPolicyMutationResponse, } from "../../internal/validators/response/index.js";
2
+ import { beginCommittedReadModel, submitJournaledPrincipalMutation, } from "../../workflows/organizations/index.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) {
@@ -18,23 +18,60 @@ export function dispatchAuthoredPrincipalMutation(api, organizationId, mutation,
18
18
  function unsupportedMutation(_mutation) {
19
19
  throw new Error("Unsupported principal mutation operation");
20
20
  }
21
- export function createJournaledPrincipalMutations(api, context, dispatch) {
22
- async function submit(organizationId, mutation, validator, options = {}) {
21
+ /** A group create stamps twice: its group row, then its first policy. */
22
+ const GROUP_CREATE_READ_MODEL_STAMPS = 2;
23
+ async function submitJournaled(input) {
24
+ const { organizationId } = input;
25
+ const journal = input.context(organizationId);
26
+ // A group create or group commit sends the read-model cursor its caller
27
+ // holds, so the response can carry the delta from it.
28
+ const lease = input.committedReadModel
29
+ ? await beginCommittedReadModel({
30
+ domainScope: journal.domainScope,
31
+ execSql: journal.execSql,
32
+ sessionGeneration: journal.sessionGeneration,
33
+ organizationId,
34
+ userId: journal.scope.userId,
35
+ }, input.mutation.kind === "group-create"
36
+ ? GROUP_CREATE_READ_MODEL_STAMPS
37
+ : undefined)
38
+ : undefined;
39
+ const options = lease?.heldCursor
40
+ ? { ...input.options, readModelCursor: lease.heldCursor }
41
+ : input.options;
42
+ let delta;
43
+ try {
23
44
  const result = await submitJournaledPrincipalMutation({
24
- ...context(organizationId),
25
- mutation,
26
- submit: (saved) => dispatch(options, (dispatchOptions) => dispatchAuthoredPrincipalMutation(api, organizationId, saved, dispatchOptions)),
45
+ ...journal,
46
+ mutation: input.mutation,
47
+ submit: (saved) => input.dispatch(options, (dispatchOptions) => dispatchAuthoredPrincipalMutation(input.api, organizationId, saved, dispatchOptions)),
27
48
  });
28
49
  if (!result.ok)
29
50
  return result;
30
51
  // The session already verified this operation before clearing its row.
31
52
  // This check narrows the union for each existing public API signature.
32
- if (!validator(result.data))
53
+ if (!input.validator(result.data))
33
54
  throw new Error("Unexpected principal receipt operation");
55
+ delta = committedReadModelDelta(input.committedReadModel?.(result.data), organizationId);
34
56
  return { ok: true, data: result.data };
35
57
  }
36
- const commit = (organizationId, groupId, request, options) => submit(organizationId, { kind: "compound", groupId, request }, isCommitOrganizationGroupPolicyResponse, options);
37
- const create = (organizationId, request, options) => submit(organizationId, { kind: "group-create", groupId: request.groupId, request }, isCreateOrganizationGroupResponse, options);
58
+ finally {
59
+ lease?.settle(delta);
60
+ }
61
+ }
62
+ export function createJournaledPrincipalMutations(api, context, dispatch) {
63
+ const submit = (organizationId, mutation, validator, options, committedReadModel) => submitJournaled({
64
+ api,
65
+ committedReadModel,
66
+ context,
67
+ dispatch,
68
+ mutation,
69
+ options,
70
+ organizationId,
71
+ validator,
72
+ });
73
+ const commit = (organizationId, groupId, request, options) => submit(organizationId, { kind: "compound", groupId, request }, isCommitOrganizationGroupPolicyResponse, options, (response) => response.readModel);
74
+ const create = (organizationId, request, options) => submit(organizationId, { kind: "group-create", groupId: request.groupId, request }, isCreateOrganizationGroupResponse, options, (response) => response.readModel);
38
75
  const remove = (organizationId, groupId, request, options) => submit(organizationId, { kind: "group-delete", groupId, request }, isDeleteOrganizationGroupResponse, options);
39
76
  const put = (_type, organizationId, request, options) => submit(organizationId, { kind: "organization", groupId: null, request }, isPrincipalPolicyMutationResponse, options);
40
77
  return {
@@ -1 +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;AAGxC,OAAO,EAEL,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAgBvC,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,wBAAwB,CACjC,cAAc,EACd,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,UAAU;YACb,OAAO,GAAG,CAAC,mCAAmC,CAC5C,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ;YACE,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,SAAgB;IAC3C,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,OAEoD,EACpD,QAA8D;IAE9D,KAAK,UAAU,MAAM,CACnB,cAAsB,EACtB,QAAmC,EACnC,SAAyC,EACzC,UA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K,EACL,cAAc,EACd,OAAO,EACP,OAAO,EACP,EAAE,CACF,MAAM,CACJ,cAAc,EACd,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAChD,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,OAAO;QACL,mCAAmC,EAAE,MAAM;QAC3C,6BAA6B,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAC/C,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QACjC,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,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 type { PrincipalMutationResponse } from \"../../workflows/organizations\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../../workflows/organizations\";\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"]}
1
+ {"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uBAAuB,EACvB,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAElC,M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,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAChD,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,OAAO;QACL,mCAAmC,EAAE,MAAM;QAC3C,6BAA6B,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAC/C,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QACjC,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,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 committedReadModelDelta,\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n type OrganizationReadModelDeltaResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport type { PrincipalMutationResponse } from \"../../workflows/organizations\";\nimport {\n beginCommittedReadModel,\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../../workflows/organizations\";\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\ntype JournalContext = (organizationId: string) => Omit<\n PrincipalMutationJournalContext,\n \"submit\"\n> & {\n /** The runtime's domain scope, which keys committed read-model offers. */\n readonly domainScope: object;\n /** The session generation the mutation's committed lease belongs to. */\n readonly sessionGeneration: number;\n};\n\ninterface JournaledSubmission<T extends PrincipalMutationResponse> {\n readonly api: ApiClient;\n readonly context: JournalContext;\n readonly dispatch: ReturnType<typeof createPrincipalMutationDispatcher>;\n readonly mutation: AuthoredPrincipalMutation;\n readonly options: RequestResultOptions | undefined;\n readonly organizationId: string;\n readonly validator: (value: unknown) => value is T;\n /** Reads the read-model delta field a response carries; set to send a cursor. */\n readonly committedReadModel?: ((response: T) => unknown) | undefined;\n}\n\n/** A group create stamps twice: its group row, then its first policy. */\nconst GROUP_CREATE_READ_MODEL_STAMPS = 2;\n\nasync function submitJournaled<T extends PrincipalMutationResponse>(\n input: JournaledSubmission<T>,\n): Promise<RequestResult<T>> {\n const { organizationId } = input;\n const journal = input.context(organizationId);\n // A group create or group commit sends the read-model cursor its caller\n // holds, so the response can carry the delta from it.\n const lease = input.committedReadModel\n ? await beginCommittedReadModel(\n {\n domainScope: journal.domainScope,\n execSql: journal.execSql,\n sessionGeneration: journal.sessionGeneration,\n organizationId,\n userId: journal.scope.userId,\n },\n input.mutation.kind === \"group-create\"\n ? GROUP_CREATE_READ_MODEL_STAMPS\n : undefined,\n )\n : undefined;\n const options = lease?.heldCursor\n ? { ...input.options, readModelCursor: lease.heldCursor }\n : input.options;\n let delta: OrganizationReadModelDeltaResponse | undefined;\n try {\n const result = await submitJournaledPrincipalMutation({\n ...journal,\n mutation: input.mutation,\n submit: (saved) =>\n input.dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.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 (!input.validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n delta = committedReadModelDelta(\n input.committedReadModel?.(result.data),\n organizationId,\n );\n return { ok: true, data: result.data };\n } finally {\n lease?.settle(delta);\n }\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: JournalContext,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n const submit = <T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions | undefined,\n committedReadModel?: (response: T) => unknown,\n ) =>\n submitJournaled({\n api,\n committedReadModel,\n context,\n dispatch,\n mutation,\n options,\n organizationId,\n validator,\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 (response) => response.readModel,\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 (response) => response.readModel,\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"]}
@@ -3,7 +3,7 @@ import { createListenerSet } from "../../data/shared/listenerSet.js";
3
3
  import { runWithSecurityIncidentReporting, } from "../../data/shared/securityIncidents.js";
4
4
  import { unavailableExecSql } from "../../data/sqlite/sqlSchema.js";
5
5
  import { loadPinnedUserIdentity, } from "../../data/trustedUserIdentity/index.js";
6
- import { containerContentsOrganizationHost } from "../../workflows/organizations/containerContentsHost.js";
6
+ import { createContainerContentsOrganizationHost } from "../../workflows/organizations/containerContentsHost.js";
7
7
  import { PrincipalPolicyService } from "../../workflows/principals/principalPolicyService.js";
8
8
  import { createProvisionedStatePrimer, } from "../../workflows/registration/provisionedStatePrimer.js";
9
9
  import { getOrCreateOrganizationSyncPauses } from "../../workflows/sync/coordination.js";
@@ -13,9 +13,10 @@ import { createPrincipalMutationApiCustody, } from "./principalMutationApi.js";
13
13
  import { adoptSessionRootContainer } from "./rootContainerAdoption.js";
14
14
  import { createRuntimeIdentityResolution } from "./runtimeIdentityResolution.js";
15
15
  import { reuseIfShallowEqual } from "./runtimeInputReuse.js";
16
- function createRuntimeMutationApi(dependencies, readGeneration) {
16
+ function createRuntimeMutationApi(dependencies, readGeneration, readSessionGeneration) {
17
17
  return createPrincipalMutationApiCustody({
18
18
  api: dependencies.api,
19
+ readSessionGeneration,
19
20
  principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,
20
21
  readScope: () => {
21
22
  const { signingKeyPair, signingFingerprint } = dependencies.identity;
@@ -79,7 +80,7 @@ export function createRuntime(dependencies) {
79
80
  };
80
81
  },
81
82
  });
82
- const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, historyProtection.bind, createRuntimeMutationApi(dependencies, () => runtimeSubscription.mutationGeneration).bind);
83
+ const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, historyProtection.bind, createRuntimeMutationApi(dependencies, () => runtimeSubscription.mutationGeneration, () => runtimeSubscription.sessionGeneration).bind);
83
84
  return {
84
85
  identityTrustDomain: dependencies.identityTrustDomain,
85
86
  identityLinks: trustedUserIdentityService,
@@ -89,7 +90,7 @@ export function createRuntime(dependencies) {
89
90
  },
90
91
  adoptRootContainer: (input) => adoptSessionRootContainer(dependencies, input),
91
92
  deleteDocumentPlacements,
92
- containerContentsOrganizations: containerContentsOrganizationHost,
93
+ containerContentsOrganizations: createContainerContentsOrganizationHost(() => runtimeSubscription.sessionGeneration),
93
94
  boundUserId: (signingKeyFingerprint) => trustedUserIdentityService.boundUserId(signingKeyFingerprint),
94
95
  async pinLocalUserIdentity(userId, candidate) {
95
96
  await runWithSecurityIncidentReporting(dependencies.reportSecurityIncident, {
@@ -1 +1 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAI5H,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EACL,gCAAgC,GAEjC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAEL,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,iCAAiC,EAAE,MAAM,qDAAqD,CAAC;AACxG,OAAO,EAAE,sBAAsB,EAAE,MAAM,mDAAmD,CAAC;AAC3F,OAAO,EACL,4BAA4B,GAE7B,MAAM,qDAAqD,CAAC;AAS7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,mCAAmC,CAAC;AAGtF,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAK1E,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AA8E1D,SAAS,wBAAwB,CAC/B,YAAyC,EACzC,cAA4B;IAE5B,OAAO,iCAAiC,CAAC;QACvC,GAAG,EAAE,YAAY,CAAC,GAAG;QACrB,0BAA0B,EAAE,YAAY,CAAC,0BAA0B;QACnE,SAAS,EAAE,GAAG,EAAE;YACd,MAAM,EAAE,cAAc,EAAE,kBAAkB,EAAE,GAAG,YAAY,CAAC,QAAQ,CAAC;YACrE,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ACxD,CAAC;SACH,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,SAAS,CAAC,WAAW;YACnB,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,0BAA0B,EAAE,2BAA2B,EACvD,iBAAiB,EAAE,kBAAkB,EACrC,IAAI,EAAE,YAAY,EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport type { DocumentPlacementCleanup } from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport { createListenerSet } from \"../../data/shared/listenerSet\";\nimport {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n ContainerContentsOrganizationHost,\n ContainerContentsRootAdopter,\n} from \"../../workflows/container-contents\";\nimport { containerContentsOrganizationHost } from \"../../workflows/organizations/containerContentsHost\";\nimport { PrincipalPolicyService } from \"../../workflows/principals/principalPolicyService\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../workflows/sync/coordination\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { createRuntimeIdentityResolution } from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Bound to this snapshot's API client, executor, and history custody. */\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nexport interface InternalRuntime {\n /** Resolved once by the composition root; constant for the client's life. */\n readonly identityTrustDomain: string | null;\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly deleteDocumentPlacements: DocumentPlacementCleanup;\n readonly containerContentsOrganizations: ContainerContentsOrganizationHost;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\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\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n deleteDocumentPlacements,\n containerContentsOrganizations: containerContentsOrganizationHost,\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId, direction = \"push\") =>\n getOrCreateOrganizationSyncPauses(\n dependencies.getDomainScope(),\n ).holdsSync(organizationId) ||\n (direction === \"push\" &&\n (dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ??\n false)),\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n const apiClient = bindMutationApi();\n return {\n apiClient,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n // Binds this snapshot's lease now; work on an older snapshot keeps its own.\n principalPolicies: new PrincipalPolicyService({\n apiClient,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n }),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n principalPolicies: _principalPolicies,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAI5H,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EACL,gCAAgC,GAEjC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAEL,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAC9G,OAAO,EAAE,sBAAsB,EAAE,MAAM,mDAAmD,CAAC;AAC3F,OAAO,EACL,4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AC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport type { DocumentPlacementCleanup } from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport { createListenerSet } from \"../../data/shared/listenerSet\";\nimport {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n ContainerContentsOrganizationHost,\n ContainerContentsRootAdopter,\n} from \"../../workflows/container-contents\";\nimport { createContainerContentsOrganizationHost } from \"../../workflows/organizations/containerContentsHost\";\nimport { PrincipalPolicyService } from \"../../workflows/principals/principalPolicyService\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../workflows/sync/coordination\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { createRuntimeIdentityResolution } from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Bound to this snapshot's API client, executor, and history custody. */\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nexport interface InternalRuntime {\n /** Resolved once by the composition root; constant for the client's life. */\n readonly identityTrustDomain: string | null;\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly deleteDocumentPlacements: DocumentPlacementCleanup;\n readonly containerContentsOrganizations: ContainerContentsOrganizationHost;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n readSessionGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n readSessionGeneration,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n () => runtimeSubscription.sessionGeneration,\n ).bind,\n );\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n deleteDocumentPlacements,\n containerContentsOrganizations: createContainerContentsOrganizationHost(\n () => runtimeSubscription.sessionGeneration,\n ),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId, direction = \"push\") =>\n getOrCreateOrganizationSyncPauses(\n dependencies.getDomainScope(),\n ).holdsSync(organizationId) ||\n (direction === \"push\" &&\n (dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ??\n false)),\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n const apiClient = bindMutationApi();\n return {\n apiClient,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n // Binds this snapshot's lease now; work on an older snapshot keeps its own.\n principalPolicies: new PrincipalPolicyService({\n apiClient,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n }),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n principalPolicies: _principalPolicies,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
@@ -1,4 +1,6 @@
1
1
  export interface ContainerMutationRequestOptions {
2
2
  readonly expectedPaymentRequiredOrganizationId?: string | undefined;
3
+ /** A share only: the read-model cursor its sender holds. */
4
+ readonly readModelCursor?: string | undefined;
3
5
  readonly reportErrors?: boolean | undefined;
4
6
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mutationRequestOptions.js","sourceRoot":"","sources":["mutationRequestOptions.ts"],"names":[],"mappings":"","sourcesContent":["export interface ContainerMutationRequestOptions {\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly reportErrors?: boolean | undefined;\n}\n"]}
1
+ {"version":3,"file":"mutationRequestOptions.js","sourceRoot":"","sources":["mutationRequestOptions.ts"],"names":[],"mappings":"","sourcesContent":["export interface ContainerMutationRequestOptions {\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n /** A share only: the read-model cursor its sender holds. */\n readonly readModelCursor?: string | undefined;\n readonly reportErrors?: boolean | undefined;\n}\n"]}