@tearleads/client-sdk 0.1.16 → 0.1.17

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 (128) hide show
  1. package/client/index.d.ts +1 -1
  2. package/client/index.js.map +1 -1
  3. package/client/organizations/currentPrincipalMutations.js +96 -0
  4. package/client/organizations/currentPrincipalMutations.js.map +1 -0
  5. package/client/organizations/index.d.ts +1 -1
  6. package/client/organizations/index.js +4 -3
  7. package/client/organizations/index.js.map +1 -1
  8. package/client/organizations/organizationGroupHistory.js +44 -0
  9. package/client/organizations/organizationGroupHistory.js.map +1 -0
  10. package/client/organizations/organizationGroupNameHydration.js +7 -1
  11. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  12. package/client/organizations/organizationGroupPresentation.d.ts +1 -0
  13. package/client/organizations/organizationGroupPresentation.js +16 -2
  14. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  15. package/client/organizations/organizationReadModels.d.ts +1 -1
  16. package/client/organizations/organizationReadModels.js +11 -1
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationsTypes.d.ts +8 -5
  19. package/client/organizations/organizationsTypes.js.map +1 -1
  20. package/client/organizations/principalContainerMutations.js +2 -0
  21. package/client/organizations/principalContainerMutations.js.map +1 -1
  22. package/client/organizations/principalMutations.d.ts +4 -308
  23. package/client/organizations/principalMutations.js +165 -87
  24. package/client/organizations/principalMutations.js.map +1 -1
  25. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +2 -2
  26. package/data/persistence/principalCurrentAcknowledgementPersistence.js +21 -14
  27. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  28. package/data/principals/currentPolicyReferenceResolver.js +2 -0
  29. package/data/principals/currentPolicyReferenceResolver.js.map +1 -0
  30. package/data/principals/principalHistoryScopeProtection.js +23 -0
  31. package/data/principals/principalHistoryScopeProtection.js.map +1 -0
  32. package/data/principals/principalPolicyAdminSigners.js.map +1 -1
  33. package/index.d.ts +1 -1
  34. package/index.js.map +1 -1
  35. package/internal/crypto/index.d.ts +1 -1
  36. package/internal/crypto/index.js +1 -1
  37. package/internal/crypto/index.js.map +1 -1
  38. package/internal/crypto/keying/index.d.ts +1 -0
  39. package/internal/crypto/keying/index.js +1 -0
  40. package/internal/crypto/keying/index.js.map +1 -1
  41. package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.d.ts +8 -0
  42. package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.js +46 -0
  43. package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.js.map +1 -0
  44. package/package.json +1 -1
  45. package/workflows/containers/child/carriedDescendantRekeys.js +9 -1
  46. package/workflows/containers/child/carriedDescendantRekeys.js.map +1 -1
  47. package/workflows/containers/child/replacementPrincipalPolicyReferences.js +19 -0
  48. package/workflows/containers/child/replacementPrincipalPolicyReferences.js.map +1 -0
  49. package/workflows/organizations/commitCurrentGroupPolicyMutation.js +72 -0
  50. package/workflows/organizations/commitCurrentGroupPolicyMutation.js.map +1 -0
  51. package/workflows/organizations/createCurrentOrganizationGroup.js +85 -0
  52. package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -0
  53. package/workflows/organizations/currentGroupMetadataAuthority.js +24 -3
  54. package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -1
  55. package/workflows/organizations/currentGroupMutationReferences.js +35 -0
  56. package/workflows/organizations/currentGroupMutationReferences.js.map +1 -0
  57. package/workflows/organizations/currentGroupPolicyMutationContext.js +79 -0
  58. package/workflows/organizations/currentGroupPolicyMutationContext.js.map +1 -0
  59. package/workflows/organizations/currentOrganizationGroupNames.js +5 -1
  60. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
  61. package/workflows/organizations/currentOrganizationMutationAuthority.js +16 -0
  62. package/workflows/organizations/currentOrganizationMutationAuthority.js.map +1 -0
  63. package/workflows/organizations/currentOrganizationMutationRetention.js +53 -0
  64. package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -0
  65. package/workflows/organizations/currentPrincipalMutationLease.js +38 -0
  66. package/workflows/organizations/currentPrincipalMutationLease.js.map +1 -0
  67. package/workflows/organizations/deleteCurrentOrganizationGroup.js +35 -0
  68. package/workflows/organizations/deleteCurrentOrganizationGroup.js.map +1 -0
  69. package/workflows/organizations/deleteOrganizationGroup.d.ts +1 -0
  70. package/workflows/organizations/deleteOrganizationGroup.js +10 -0
  71. package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
  72. package/workflows/organizations/groupCreation.d.ts +1 -0
  73. package/workflows/organizations/groupCreation.js +8 -0
  74. package/workflows/organizations/groupCreation.js.map +1 -1
  75. package/workflows/organizations/groupMembershipName.d.ts +1 -1
  76. package/workflows/organizations/groupMembershipName.js.map +1 -1
  77. package/workflows/organizations/groupMetadataRuntime.js +14 -9
  78. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  79. package/workflows/organizations/groupNameUniqueness.js +1 -1
  80. package/workflows/organizations/groupNameUniqueness.js.map +1 -1
  81. package/workflows/organizations/groupPolicyHistoryPage.js +31 -0
  82. package/workflows/organizations/groupPolicyHistoryPage.js.map +1 -0
  83. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -0
  84. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  85. package/workflows/organizations/groupPolicyMutationContext.d.ts +18 -0
  86. package/workflows/organizations/groupPolicyMutationContext.js +1 -1
  87. package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
  88. package/workflows/organizations/initialPrincipalCurrentPublication.js +83 -0
  89. package/workflows/organizations/initialPrincipalCurrentPublication.js.map +1 -0
  90. package/workflows/organizations/organizationGroupDirectory.js +6 -0
  91. package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
  92. package/workflows/organizations/organizationGroupNames.js.map +1 -1
  93. package/workflows/organizations/policyHistoryTypes.d.ts +2 -0
  94. package/workflows/organizations/policyHistoryTypes.js.map +1 -1
  95. package/workflows/organizations/principalContainerRematerialization.js +12 -2
  96. package/workflows/organizations/principalContainerRematerialization.js.map +1 -1
  97. package/workflows/organizations/principalContainerRematerializationPlanning.js +1 -0
  98. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
  99. package/workflows/organizations/principalContainerRematerializationTargets.js.map +1 -1
  100. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +2 -0
  101. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +5 -1
  102. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
  103. package/workflows/organizations/runtimeCurrentGroupMutation.js +85 -0
  104. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -0
  105. package/workflows/organizations/runtimeCurrentOrganizationMutation.js +48 -0
  106. package/workflows/organizations/runtimeCurrentOrganizationMutation.js.map +1 -0
  107. package/workflows/principals/loadRecoveredPrincipalHistoryPage.d.ts +11 -0
  108. package/workflows/principals/loadRecoveredPrincipalHistoryPage.js +120 -0
  109. package/workflows/principals/loadRecoveredPrincipalHistoryPage.js.map +1 -0
  110. package/workflows/principals/principalHistoryRecoveryReferences.js +8 -0
  111. package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -1
  112. package/workflows/principals/principalRecoveryDirectory.js +3 -8
  113. package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
  114. package/workflows/principals/principalRecoveryLocalPreference.js +3 -2
  115. package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -1
  116. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -1
  117. package/workflows/principals/recoverPrincipalHistoryPage.js +30 -0
  118. package/workflows/principals/recoverPrincipalHistoryPage.js.map +1 -0
  119. package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +2 -0
  120. package/workflows/principals/recoverPrincipalPolicyHistory.js +14 -2
  121. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  122. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +6 -0
  123. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +31 -19
  124. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  125. package/workflows/principals/runtimePolicyRecovery.js +25 -4
  126. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  127. package/workflows/principals/runtimePolicyWarmer.js +2 -2
  128. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
@@ -1,7 +1,12 @@
1
1
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
2
2
  import { addOrganizationGroupUser, createOrganizationGroup, deleteOrganizationGroup, removeOrganizationGroupUser, revokeOrganizationContainerGrant, rotateOrganizationGroupForAccessSetShrink, } from "../../workflows/organizations/index.js";
3
+ import { createCurrentOrganizationGroup } from "../../workflows/organizations/createCurrentOrganizationGroup.js";
4
+ import { createSelectedCurrentGroupMetadataContainerVerifier } from "../../workflows/organizations/currentGroupMetadataAuthority.js";
5
+ import { deleteCurrentOrganizationGroup } from "../../workflows/organizations/deleteCurrentOrganizationGroup.js";
3
6
  import { createRuntimeGroupMetadataAccess } from "../../workflows/organizations/groupMetadataRuntime.js";
7
+ import { createRuntimeCurrentOrganizationMutation } from "../../workflows/organizations/runtimeCurrentOrganizationMutation.js";
4
8
  import { createRuntimePrincipalPolicyWarmer } from "../../workflows/principals/runtimePolicyWarmer.js";
9
+ import { createCurrentPrincipalMutation } from "./currentPrincipalMutations.js";
5
10
  import { syncOrganizationMetadataProfile } from "./organizationMetadataProfileSync.js";
6
11
  import { preparePrincipalContainerMutations } from "./principalContainerMutations.js";
7
12
  function requireSigningContext(runtime) {
@@ -33,30 +38,44 @@ export async function addUserToOrganizationGroup(input) {
33
38
  organizationId: signingContext.organizationId,
34
39
  }, async () => {
35
40
  let memberGroupId = null;
36
- const bundle = await addOrganizationGroupUser({
37
- apiClient: input.runtime.apiClient,
38
- beforePolicyCommit: (_head, authority) => {
39
- memberGroupId = authority.memberGroupId;
40
- },
41
- currentUserSecretKey: requireEncapsulationKeyPair(input.runtime)
42
- .secretKey,
43
- execSql: input.runtime.infra.execSql,
44
- expectedGroupName: input.expectedGroupName,
45
- readEncryptedName: createRuntimeGroupMetadataAccess(input.runtime, signingContext.organizationId, input.stillCurrent).readName,
46
- groupId: input.groupId,
47
- prepareContainerMutations: ({ currentPolicy, nextPolicy }) => preparePrincipalContainerMutations({
48
- currentPolicy,
49
- groupId: input.groupId,
50
- nextPolicy,
51
- organizationId: signingContext.organizationId,
52
- runtime: input.runtime,
53
- stillCurrent: input.stillCurrent,
54
- }),
55
- reportSecurityIncident: input.runtime.util.reportSecurityIncident,
56
- resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
57
- targetUserId: input.targetUserId,
41
+ const mutateCurrent = createCurrentPrincipalMutation({
58
42
  ...signingContext,
43
+ runtime: input.runtime,
44
+ stillCurrent: input.stillCurrent,
59
45
  });
46
+ const current = mutateCurrent
47
+ ? await mutateCurrent(input.groupId, {
48
+ kind: "add",
49
+ expectedGroupName: input.expectedGroupName,
50
+ targetUserId: input.targetUserId,
51
+ })
52
+ : undefined;
53
+ memberGroupId = current?.memberGroupId ?? null;
54
+ const bundle = current?.response ??
55
+ (await addOrganizationGroupUser({
56
+ apiClient: input.runtime.apiClient,
57
+ beforePolicyCommit: (_head, authority) => {
58
+ memberGroupId = authority.memberGroupId;
59
+ },
60
+ currentUserSecretKey: requireEncapsulationKeyPair(input.runtime)
61
+ .secretKey,
62
+ execSql: input.runtime.infra.execSql,
63
+ expectedGroupName: input.expectedGroupName,
64
+ readEncryptedName: createRuntimeGroupMetadataAccess(input.runtime, signingContext.organizationId, input.stillCurrent).readName,
65
+ groupId: input.groupId,
66
+ prepareContainerMutations: ({ currentPolicy, nextPolicy }) => preparePrincipalContainerMutations({
67
+ currentPolicy,
68
+ groupId: input.groupId,
69
+ nextPolicy,
70
+ organizationId: signingContext.organizationId,
71
+ runtime: input.runtime,
72
+ stillCurrent: input.stillCurrent,
73
+ }),
74
+ reportSecurityIncident: input.runtime.util.reportSecurityIncident,
75
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
76
+ targetUserId: input.targetUserId,
77
+ ...signingContext,
78
+ }));
60
79
  if (input.groupId === memberGroupId) {
61
80
  await syncOrganizationMetadataProfile({
62
81
  containerContents: input.containerContents,
@@ -75,16 +94,37 @@ export function createGroupForOrganization(input) {
75
94
  objectKind: "principal",
76
95
  operation: "group.create",
77
96
  organizationId: signingContext.organizationId,
78
- }, () => createOrganizationGroup({
79
- apiClient: input.runtime.apiClient,
80
- creatorEncapsulationKeyPair: requireEncapsulationKeyPair(input.runtime),
81
- execSql: input.runtime.infra.execSql,
82
- name: input.name,
83
- metadataAccess: createRuntimeGroupMetadataAccess(input.runtime, signingContext.organizationId),
84
- reportSecurityIncident: input.runtime.util.reportSecurityIncident,
85
- resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
86
- ...signingContext,
87
- }));
97
+ }, () => {
98
+ const creatorEncapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);
99
+ const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);
100
+ if (mutate)
101
+ return mutate({ ...signingContext, stillCurrent: input.stillCurrent }, (context) => createCurrentOrganizationGroup({
102
+ ...signingContext,
103
+ context,
104
+ apiClient: input.runtime.apiClient,
105
+ creatorEncapsulationKeyPair,
106
+ execSql: input.runtime.infra.execSql,
107
+ name: input.name,
108
+ metadataAccess: createRuntimeGroupMetadataAccess(input.runtime, signingContext.organizationId, context.stillCurrent, createSelectedCurrentGroupMetadataContainerVerifier({
109
+ authority: context,
110
+ organizationId: signingContext.organizationId,
111
+ stillCurrent: context.stillCurrent,
112
+ })),
113
+ reportSecurityIncident: input.runtime.util.reportSecurityIncident,
114
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
115
+ }));
116
+ return createOrganizationGroup({
117
+ stillCurrent: input.stillCurrent,
118
+ apiClient: input.runtime.apiClient,
119
+ creatorEncapsulationKeyPair,
120
+ execSql: input.runtime.infra.execSql,
121
+ name: input.name,
122
+ metadataAccess: createRuntimeGroupMetadataAccess(input.runtime, signingContext.organizationId, input.stillCurrent),
123
+ reportSecurityIncident: input.runtime.util.reportSecurityIncident,
124
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
125
+ ...signingContext,
126
+ });
127
+ });
88
128
  }
89
129
  export function deleteGroupForOrganization(input) {
90
130
  const signingContext = requireSigningContext(input.runtime);
@@ -93,13 +133,25 @@ export function deleteGroupForOrganization(input) {
93
133
  objectKind: "principal",
94
134
  operation: "group.delete",
95
135
  organizationId: signingContext.organizationId,
96
- }, () => deleteOrganizationGroup({
97
- apiClient: input.runtime.apiClient,
98
- execSql: input.runtime.infra.execSql,
99
- groupId: input.groupId,
100
- resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
101
- ...signingContext,
102
- }));
136
+ }, () => {
137
+ const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);
138
+ if (mutate)
139
+ return mutate({ ...signingContext, stillCurrent: input.stillCurrent }, (context) => deleteCurrentOrganizationGroup({
140
+ ...signingContext,
141
+ context,
142
+ groupId: input.groupId,
143
+ apiClient: input.runtime.apiClient,
144
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
145
+ }));
146
+ return deleteOrganizationGroup({
147
+ stillCurrent: input.stillCurrent,
148
+ apiClient: input.runtime.apiClient,
149
+ execSql: input.runtime.infra.execSql,
150
+ groupId: input.groupId,
151
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
152
+ ...signingContext,
153
+ });
154
+ });
103
155
  }
104
156
  export async function removeUserFromOrganizationGroup(input) {
105
157
  const signingContext = requireSigningContext(input.runtime);
@@ -110,27 +162,41 @@ export async function removeUserFromOrganizationGroup(input) {
110
162
  organizationId: signingContext.organizationId,
111
163
  }, async () => {
112
164
  let memberGroupId = null;
113
- const bundle = await removeOrganizationGroupUser({
114
- apiClient: input.runtime.apiClient,
115
- beforePolicyCommit: (_head, authority) => {
116
- memberGroupId = authority.memberGroupId;
117
- },
118
- execSql: input.runtime.infra.execSql,
119
- expectedGroupName: input.expectedGroupName,
120
- readEncryptedName: createRuntimeGroupMetadataAccess(input.runtime, signingContext.organizationId, input.stillCurrent).readName,
121
- groupId: input.groupId,
122
- prepareContainerMutations: ({ currentPolicy, nextPolicy }) => preparePrincipalContainerMutations({
123
- currentPolicy,
124
- groupId: input.groupId,
125
- nextPolicy,
126
- organizationId: signingContext.organizationId,
127
- runtime: input.runtime,
128
- stillCurrent: input.stillCurrent,
129
- }),
130
- removedUserId: input.removedUserId,
131
- resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
165
+ const mutateCurrent = createCurrentPrincipalMutation({
132
166
  ...signingContext,
167
+ runtime: input.runtime,
168
+ stillCurrent: input.stillCurrent,
133
169
  });
170
+ const current = mutateCurrent
171
+ ? await mutateCurrent(input.groupId, {
172
+ kind: "remove",
173
+ expectedGroupName: input.expectedGroupName,
174
+ removedUserId: input.removedUserId,
175
+ })
176
+ : undefined;
177
+ memberGroupId = current?.memberGroupId ?? null;
178
+ const bundle = current?.response ??
179
+ (await removeOrganizationGroupUser({
180
+ apiClient: input.runtime.apiClient,
181
+ beforePolicyCommit: (_head, authority) => {
182
+ memberGroupId = authority.memberGroupId;
183
+ },
184
+ execSql: input.runtime.infra.execSql,
185
+ expectedGroupName: input.expectedGroupName,
186
+ readEncryptedName: createRuntimeGroupMetadataAccess(input.runtime, signingContext.organizationId, input.stillCurrent).readName,
187
+ groupId: input.groupId,
188
+ prepareContainerMutations: ({ currentPolicy, nextPolicy }) => preparePrincipalContainerMutations({
189
+ currentPolicy,
190
+ groupId: input.groupId,
191
+ nextPolicy,
192
+ organizationId: signingContext.organizationId,
193
+ runtime: input.runtime,
194
+ stillCurrent: input.stillCurrent,
195
+ }),
196
+ removedUserId: input.removedUserId,
197
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
198
+ ...signingContext,
199
+ }));
134
200
  if (input.groupId === memberGroupId) {
135
201
  await syncOrganizationMetadataProfile({
136
202
  containerContents: input.containerContents,
@@ -154,39 +220,51 @@ export async function revokeOrganizationGrant(input) {
154
220
  operation: "principal.grant.revoke",
155
221
  organizationId: signingContext.organizationId,
156
222
  }, async () => {
157
- const response = input.subjectType === "group"
158
- ? await rotateOrganizationGroupForAccessSetShrink({
159
- apiClient: input.runtime.apiClient,
160
- execSql: input.runtime.infra.execSql,
161
- groupId: input.subjectId,
223
+ const mutateCurrent = createCurrentPrincipalMutation({
224
+ ...signingContext,
225
+ runtime: input.runtime,
226
+ stillCurrent: input.stillCurrent,
227
+ });
228
+ const current = input.subjectType === "group" && mutateCurrent
229
+ ? await mutateCurrent(input.subjectId, {
230
+ kind: "revoke",
162
231
  revokedContainerId: input.containerId,
163
- prepareContainerMutations: ({ currentPolicy, nextPolicy }) => preparePrincipalContainerMutations({
164
- currentPolicy,
232
+ })
233
+ : undefined;
234
+ const response = current?.response ??
235
+ (input.subjectType === "group"
236
+ ? await rotateOrganizationGroupForAccessSetShrink({
237
+ apiClient: input.runtime.apiClient,
238
+ execSql: input.runtime.infra.execSql,
165
239
  groupId: input.subjectId,
166
- nextPolicy,
167
- organizationId: signingContext.organizationId,
168
240
  revokedContainerId: input.containerId,
169
- runtime: input.runtime,
241
+ prepareContainerMutations: ({ currentPolicy, nextPolicy }) => preparePrincipalContainerMutations({
242
+ currentPolicy,
243
+ groupId: input.subjectId,
244
+ nextPolicy,
245
+ organizationId: signingContext.organizationId,
246
+ revokedContainerId: input.containerId,
247
+ runtime: input.runtime,
248
+ stillCurrent: input.stillCurrent,
249
+ }),
250
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
251
+ ...signingContext,
252
+ })
253
+ : await revokeOrganizationContainerGrant({
170
254
  stillCurrent: input.stillCurrent,
171
- }),
172
- resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
173
- ...signingContext,
174
- })
175
- : await revokeOrganizationContainerGrant({
176
- stillCurrent: input.stillCurrent,
177
- reportSecurityIncident: input.runtime.util.reportSecurityIncident,
178
- apiClient: input.runtime.apiClient,
179
- containerId: input.containerId,
180
- encapsulationKeyPair,
181
- execSql: input.runtime.infra.execSql,
182
- revokedSubject: {
183
- subjectId: input.subjectId,
184
- subjectType: input.subjectType,
185
- },
186
- resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
187
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
188
- ...signingContext,
189
- });
255
+ reportSecurityIncident: input.runtime.util.reportSecurityIncident,
256
+ apiClient: input.runtime.apiClient,
257
+ containerId: input.containerId,
258
+ encapsulationKeyPair,
259
+ execSql: input.runtime.infra.execSql,
260
+ revokedSubject: {
261
+ subjectId: input.subjectId,
262
+ subjectType: input.subjectType,
263
+ },
264
+ resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
265
+ warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
266
+ ...signingContext,
267
+ }));
190
268
  await input.readModelCoordinator.reconcileAfterMutation(signingContext.organizationId);
191
269
  return response;
192
270
  });
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutations.js","sourceRoot":"","sources":["principalMutations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,gCAAgC,EAChC,yCAAyC,GAC1C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,gCAAgC,EAAE,MAAM,oDAAoD,CAAC;AACtG,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AAGpG,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAEpF,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AAgCnF,SAAS,qBAAqB,CAC5B,OAAqC;IAErC,IACE,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc;QAC5B,CAAC,OAA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AC;IAClB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerGrantSubjectType } from \"@tearleads/crypto\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n addOrganizationGroupUser,\n createOrganizationGroup,\n deleteOrganizationGroup,\n removeOrganizationGroupUser,\n revokeOrganizationContainerGrant,\n rotateOrganizationGroupForAccessSetShrink,\n} from \"../../workflows/organizations\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadataRuntime\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../workflows/principals/runtimePolicyWarmer\";\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../workflowRuntime\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport { preparePrincipalContainerMutations } from \"./principalContainerMutations\";\n\nexport interface OrganizationGrantRef {\n containerId: string;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface OrganizationGroupUserMutationInput {\n groupId: string;\n expectedGroupName: string;\n}\n\nexport interface AddOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n targetUserId: string;\n}\n\nexport interface RemoveOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n removedUserId: string;\n}\n\ninterface OrganizationSigningContext {\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\nfunction requireSigningContext(\n runtime: InternalWorkflowRuntimeInput,\n): OrganizationSigningContext {\n if (\n !runtime.auth.organizationId ||\n !runtime.auth.userId ||\n !runtime.crypto.signingFingerprint ||\n !runtime.crypto.signingKeyPair\n ) {\n throw new Error(\"Organization signing context is unavailable\");\n }\n\n return {\n organizationId: runtime.auth.organizationId,\n signerUserId: runtime.auth.userId,\n signingFingerprint: runtime.crypto.signingFingerprint,\n signingKeyPair: runtime.crypto.signingKeyPair,\n };\n}\n\nfunction requireEncapsulationKeyPair(\n runtime: InternalWorkflowRuntimeInput,\n): NonNullable<InternalWorkflowRuntimeInput[\"crypto\"][\"encapsulationKeyPair\"]> {\n if (!runtime.crypto.encapsulationKeyPair) {\n throw new Error(\"Organization encryption context is unavailable\");\n }\n\n return runtime.crypto.encapsulationKeyPair;\n}\n\ninterface PrincipalMutationRuntime {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime & AddOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.add\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n let memberGroupId: string | null = null;\n const bundle = await addOrganizationGroupUser({\n apiClient: input.runtime.apiClient,\n beforePolicyCommit: (_head, authority) => {\n memberGroupId = authority.memberGroupId;\n },\n currentUserSecretKey: requireEncapsulationKeyPair(input.runtime)\n .secretKey,\n execSql: input.runtime.infra.execSql,\n expectedGroupName: input.expectedGroupName,\n readEncryptedName: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n input.stillCurrent,\n ).readName,\n groupId: input.groupId,\n prepareContainerMutations: ({ currentPolicy, nextPolicy }) =>\n preparePrincipalContainerMutations({\n currentPolicy,\n groupId: input.groupId,\n nextPolicy,\n organizationId: signingContext.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n }),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n targetUserId: input.targetUserId,\n ...signingContext,\n });\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport function createGroupForOrganization(input: {\n readonly name: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: signingContext.organizationId,\n objectKind: \"principal\",\n operation: \"group.create\",\n organizationId: signingContext.organizationId,\n },\n () =>\n createOrganizationGroup({\n apiClient: input.runtime.apiClient,\n creatorEncapsulationKeyPair: requireEncapsulationKeyPair(input.runtime),\n execSql: input.runtime.infra.execSql,\n name: input.name,\n metadataAccess: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n }),\n );\n}\n\nexport function deleteGroupForOrganization(input: {\n readonly groupId: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.delete\",\n organizationId: signingContext.organizationId,\n },\n () =>\n deleteOrganizationGroup({\n apiClient: input.runtime.apiClient,\n execSql: input.runtime.infra.execSql,\n groupId: input.groupId,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n }),\n );\n}\n\nexport async function removeUserFromOrganizationGroup(\n input: PrincipalMutationRuntime & RemoveOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.remove\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n let memberGroupId: string | null = null;\n const bundle = await removeOrganizationGroupUser({\n apiClient: input.runtime.apiClient,\n beforePolicyCommit: (_head, authority) => {\n memberGroupId = authority.memberGroupId;\n },\n execSql: input.runtime.infra.execSql,\n expectedGroupName: input.expectedGroupName,\n readEncryptedName: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n input.stillCurrent,\n ).readName,\n groupId: input.groupId,\n prepareContainerMutations: ({ currentPolicy, nextPolicy }) =>\n preparePrincipalContainerMutations({\n currentPolicy,\n groupId: input.groupId,\n nextPolicy,\n organizationId: signingContext.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n }),\n removedUserId: input.removedUserId,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n });\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input.runtime);\n const encapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);\n if (input.runtime.infra.dbStatus !== \"ready\") {\n throw new Error(\"Organization local database is unavailable\");\n }\n\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.subjectId,\n objectKind: \"principal\",\n operation: \"principal.grant.revoke\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const response =\n input.subjectType === \"group\"\n ? await rotateOrganizationGroupForAccessSetShrink({\n apiClient: input.runtime.apiClient,\n execSql: input.runtime.infra.execSql,\n groupId: input.subjectId,\n revokedContainerId: input.containerId,\n prepareContainerMutations: ({ currentPolicy, nextPolicy }) =>\n preparePrincipalContainerMutations({\n currentPolicy,\n groupId: input.subjectId,\n nextPolicy,\n organizationId: signingContext.organizationId,\n revokedContainerId: input.containerId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n }),\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n })\n : await revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient: input.runtime.apiClient,\n containerId: input.containerId,\n encapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(input.runtime),\n ...signingContext,\n });\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,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,gCAAgC,EAChC,yCAAyC,GAC1C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,8BAA8B,EAAE,MAAM,8DAA8D,CAAC;AAC9G,OAAO,EAAE,mDAAmD,EAAE,MAAM,6DAA6D,CAAC;AAClI,OAAO,EAAE,8BAA8B,EAAE,MAAM,8DAA8D,CAAC;AAC9G,OAAO,EAAE,gCAAgC,EAAE,MAAM,oDAAoD,CAAC;AACtG,OAAO,EAAE,wCAAwC,EAAE,MAAM,kEAAkE,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AAGpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAEpF,OAAO,EAAE,kCAAkC,EAAE,MAAM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B,oBAAoB;oBACpB,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;oBACpC,cAAc,EAAE;wBACd,SAAS,EAAE,KAAK,CAAC,SAAS;wBAC1B,WAAW,EAAE,KAAK,CAAC,WAAW;qBAC/B;oBACD,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;oBAC1C,+BAA+B,EAC7B,kCAAkC,CAAC,KAAK,CAAC,OAAO,CAAC;oBACnD,GAAG,cAAc;iBAClB,CAAC,CAAC,CAAC;QACV,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 { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n addOrganizationGroupUser,\n createOrganizationGroup,\n deleteOrganizationGroup,\n removeOrganizationGroupUser,\n revokeOrganizationContainerGrant,\n rotateOrganizationGroupForAccessSetShrink,\n} from \"../../workflows/organizations\";\nimport { createCurrentOrganizationGroup } from \"../../workflows/organizations/createCurrentOrganizationGroup\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../workflows/organizations/currentGroupMetadataAuthority\";\nimport { deleteCurrentOrganizationGroup } from \"../../workflows/organizations/deleteCurrentOrganizationGroup\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadataRuntime\";\nimport { createRuntimeCurrentOrganizationMutation } from \"../../workflows/organizations/runtimeCurrentOrganizationMutation\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../workflows/principals/runtimePolicyWarmer\";\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../workflowRuntime\";\nimport { createCurrentPrincipalMutation } from \"./currentPrincipalMutations\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport { preparePrincipalContainerMutations } from \"./principalContainerMutations\";\n\nexport interface OrganizationGrantRef {\n containerId: string;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface OrganizationGroupUserMutationInput {\n groupId: string;\n expectedGroupName: string;\n}\n\nexport interface AddOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n targetUserId: string;\n}\n\nexport interface RemoveOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n removedUserId: string;\n}\n\ninterface OrganizationSigningContext {\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\nfunction requireSigningContext(\n runtime: InternalWorkflowRuntimeInput,\n): OrganizationSigningContext {\n if (\n !runtime.auth.organizationId ||\n !runtime.auth.userId ||\n !runtime.crypto.signingFingerprint ||\n !runtime.crypto.signingKeyPair\n ) {\n throw new Error(\"Organization signing context is unavailable\");\n }\n\n return {\n organizationId: runtime.auth.organizationId,\n signerUserId: runtime.auth.userId,\n signingFingerprint: runtime.crypto.signingFingerprint,\n signingKeyPair: runtime.crypto.signingKeyPair,\n };\n}\n\nfunction requireEncapsulationKeyPair(\n runtime: InternalWorkflowRuntimeInput,\n): NonNullable<InternalWorkflowRuntimeInput[\"crypto\"][\"encapsulationKeyPair\"]> {\n if (!runtime.crypto.encapsulationKeyPair) {\n throw new Error(\"Organization encryption context is unavailable\");\n }\n\n return runtime.crypto.encapsulationKeyPair;\n}\n\ninterface PrincipalMutationRuntime {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime & AddOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.add\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n let memberGroupId: string | null = null;\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n const current = mutateCurrent\n ? await mutateCurrent(input.groupId, {\n kind: \"add\",\n expectedGroupName: input.expectedGroupName,\n targetUserId: input.targetUserId,\n })\n : undefined;\n memberGroupId = current?.memberGroupId ?? null;\n const bundle =\n current?.response ??\n (await addOrganizationGroupUser({\n apiClient: input.runtime.apiClient,\n beforePolicyCommit: (_head, authority) => {\n memberGroupId = authority.memberGroupId;\n },\n currentUserSecretKey: requireEncapsulationKeyPair(input.runtime)\n .secretKey,\n execSql: input.runtime.infra.execSql,\n expectedGroupName: input.expectedGroupName,\n readEncryptedName: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n input.stillCurrent,\n ).readName,\n groupId: input.groupId,\n prepareContainerMutations: ({ currentPolicy, nextPolicy }) =>\n preparePrincipalContainerMutations({\n currentPolicy,\n groupId: input.groupId,\n nextPolicy,\n organizationId: signingContext.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n }),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n targetUserId: input.targetUserId,\n ...signingContext,\n }));\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport function createGroupForOrganization(input: {\n readonly name: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: signingContext.organizationId,\n objectKind: \"principal\",\n operation: \"group.create\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const creatorEncapsulationKeyPair = requireEncapsulationKeyPair(\n input.runtime,\n );\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (mutate)\n 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 return createOrganizationGroup({\n stillCurrent: input.stillCurrent,\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 input.stillCurrent,\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n });\n },\n );\n}\n\nexport function deleteGroupForOrganization(input: {\n readonly groupId: string;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n}) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.delete\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (mutate)\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n deleteCurrentOrganizationGroup({\n ...signingContext,\n context,\n groupId: input.groupId,\n apiClient: input.runtime.apiClient,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n return deleteOrganizationGroup({\n stillCurrent: input.stillCurrent,\n apiClient: input.runtime.apiClient,\n execSql: input.runtime.infra.execSql,\n groupId: input.groupId,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n });\n },\n );\n}\n\nexport async function removeUserFromOrganizationGroup(\n input: PrincipalMutationRuntime & RemoveOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input.runtime);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.remove\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n let memberGroupId: string | null = null;\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n const current = mutateCurrent\n ? await mutateCurrent(input.groupId, {\n kind: \"remove\",\n expectedGroupName: input.expectedGroupName,\n removedUserId: input.removedUserId,\n })\n : undefined;\n memberGroupId = current?.memberGroupId ?? null;\n const bundle =\n current?.response ??\n (await removeOrganizationGroupUser({\n apiClient: input.runtime.apiClient,\n beforePolicyCommit: (_head, authority) => {\n memberGroupId = authority.memberGroupId;\n },\n execSql: input.runtime.infra.execSql,\n expectedGroupName: input.expectedGroupName,\n readEncryptedName: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n input.stillCurrent,\n ).readName,\n groupId: input.groupId,\n prepareContainerMutations: ({ currentPolicy, nextPolicy }) =>\n preparePrincipalContainerMutations({\n currentPolicy,\n groupId: input.groupId,\n nextPolicy,\n organizationId: signingContext.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n }),\n removedUserId: input.removedUserId,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n }));\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return bundle;\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input.runtime);\n const encapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);\n if (input.runtime.infra.dbStatus !== \"ready\") {\n throw new Error(\"Organization local database is unavailable\");\n }\n\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.subjectId,\n objectKind: \"principal\",\n operation: \"principal.grant.revoke\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n const current =\n input.subjectType === \"group\" && mutateCurrent\n ? await mutateCurrent(input.subjectId, {\n kind: \"revoke\",\n revokedContainerId: input.containerId,\n })\n : undefined;\n const response =\n current?.response ??\n (input.subjectType === \"group\"\n ? await rotateOrganizationGroupForAccessSetShrink({\n apiClient: input.runtime.apiClient,\n execSql: input.runtime.infra.execSql,\n groupId: input.subjectId,\n revokedContainerId: input.containerId,\n prepareContainerMutations: ({ currentPolicy, nextPolicy }) =>\n preparePrincipalContainerMutations({\n currentPolicy,\n groupId: input.subjectId,\n nextPolicy,\n organizationId: signingContext.organizationId,\n revokedContainerId: input.containerId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n }),\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n ...signingContext,\n })\n : await revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient: input.runtime.apiClient,\n containerId: input.containerId,\n encapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(input.runtime),\n ...signingContext,\n }));\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return response;\n },\n );\n}\n"]}
@@ -7,9 +7,9 @@ import type { PrincipalHistoryStage } from "./principalHistoryStagePersistence.j
7
7
  export interface AcknowledgedPrincipalCurrentPublication {
8
8
  readonly policy: VerifiedPrincipalPolicyCurrent;
9
9
  readonly prefix: PrincipalHistoryPrefix;
10
- readonly previousPrefixProgress: string;
10
+ readonly previousPrefixProgress: string | null;
11
11
  readonly stage: PrincipalHistoryStage;
12
- readonly predecessorStage: PrincipalHistoryStage;
12
+ readonly predecessorStage: PrincipalHistoryStage | null;
13
13
  readonly evidence: PrincipalHistoryEvidencePage;
14
14
  }
15
15
  export interface AcknowledgedPrincipalCurrentRetirement {
@@ -18,9 +18,14 @@ function assertPublicationScope(entries, organizationId) {
18
18
  seen.add(key);
19
19
  if (entry.prefix.organizationId !== organizationId ||
20
20
  entry.stage.organizationId !== organizationId ||
21
- entry.predecessorStage.organizationId !== organizationId ||
22
- !entry.predecessorStage.complete ||
23
- entry.predecessorStage.afterVersion !== entry.policy.version - 2 ||
21
+ (entry.predecessorStage
22
+ ? entry.predecessorStage.organizationId !== organizationId ||
23
+ !entry.predecessorStage.complete ||
24
+ entry.predecessorStage.afterVersion !== entry.policy.version - 2
25
+ : entry.policy.principalType !== "group" ||
26
+ entry.policy.version !== 1 ||
27
+ entry.policy.state.prevStateHash !== null ||
28
+ entry.previousPrefixProgress !== null) ||
24
29
  entry.evidence.organizationId !== organizationId ||
25
30
  entry.prefix.scopeId !== entry.evidence.scopeId ||
26
31
  entry.prefix.version !== entry.policy.version ||
@@ -37,14 +42,15 @@ async function validatePublication(tx, entry) {
37
42
  currentState: entry.policy.state,
38
43
  localCheckpoint: checkpoint,
39
44
  });
40
- if (!checkpoint || entry.policy.version > checkpoint.version + 1)
45
+ if ((!checkpoint && entry.policy.version !== 1) ||
46
+ (checkpoint && entry.policy.version > checkpoint.version + 1))
41
47
  throw new KeyingVerificationError("stale_predecessor", "Acknowledged current policy must directly extend its durable checkpoint");
42
48
  const [prefix] = await tx
43
49
  .select()
44
50
  .from(principalHistoryPrefixes)
45
51
  .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))
46
52
  .limit(1);
47
- if (prefix?.progress !== entry.previousPrefixProgress)
53
+ if ((prefix?.progress ?? null) !== entry.previousPrefixProgress)
48
54
  throw new KeyingVerificationError("stale_predecessor", "Authenticated principal prefix changed before acknowledgement");
49
55
  }
50
56
  /** Store current artifacts and resumable progress in the same transaction as their pins. */
@@ -74,15 +80,16 @@ export async function persistAcknowledgedPrincipalCurrents(input) {
74
80
  await writePrincipalHistoryEvidencePage(tx, entry.evidence);
75
81
  // A prefix-only predecessor must keep its encrypted key envelopes
76
82
  // before its reusable slot is replaced by the acknowledged successor.
77
- await tx
78
- .insert(principalHistoryStages)
79
- .values(entry.predecessorStage)
80
- .onConflictDoUpdate({
81
- target: principalHistoryStages.id,
82
- set: entry.predecessorStage,
83
- setWhere: eq(principalHistoryStages.complete, false),
84
- })
85
- .run();
83
+ if (entry.predecessorStage)
84
+ await tx
85
+ .insert(principalHistoryStages)
86
+ .values(entry.predecessorStage)
87
+ .onConflictDoUpdate({
88
+ target: principalHistoryStages.id,
89
+ set: entry.predecessorStage,
90
+ setWhere: eq(principalHistoryStages.complete, false),
91
+ })
92
+ .run();
86
93
  // A fully authenticated publication supersedes an in-flight stage for
87
94
  // this exact head. Its other writer fails its progress CAS and resumes.
88
95
  await tx
@@ -1 +1 @@
1
- {"version":3,"file":"principalCurrentAcknowledgementPersistence.js","sourceRoot":"","sources":["principalCurrentAcknowledgementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAE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EACvB,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,cAAc,CACf,CAAC;QACJ,CAAC;IACH,CAAC,EACD,YAAY,EACZ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport { principalHistoryPrefixes } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { storePrincipalGrantRetirements } from \"./principalGrantRetirementPersistence\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"./principalHistoryPrefixPersistence\";\nimport type { PrincipalHistoryStage } from \"./principalHistoryStagePersistence\";\n\n/** Owned output of authenticated prefix extension and exact receipt verification. */\nexport interface AcknowledgedPrincipalCurrentPublication {\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly prefix: PrincipalHistoryPrefix;\n readonly previousPrefixProgress: string;\n readonly stage: PrincipalHistoryStage;\n readonly predecessorStage: PrincipalHistoryStage;\n readonly evidence: PrincipalHistoryEvidencePage;\n}\n\nexport interface AcknowledgedPrincipalCurrentRetirement {\n readonly principalId: string;\n readonly principalType: VerifiedPrincipalPolicyCurrent[\"principalType\"];\n readonly containerIds: readonly string[];\n}\n\nfunction assertPublicationScope(\n entries: readonly AcknowledgedPrincipalCurrentPublication[],\n organizationId: string,\n) {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key))\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Acknowledged current batch repeats a principal\",\n );\n seen.add(key);\n if (\n entry.prefix.organizationId !== organizationId ||\n entry.stage.organizationId !== organizationId ||\n entry.predecessorStage.organizationId !== organizationId ||\n !entry.predecessorStage.complete ||\n entry.predecessorStage.afterVersion !== entry.policy.version - 2 ||\n entry.evidence.organizationId !== organizationId ||\n entry.prefix.scopeId !== entry.evidence.scopeId ||\n entry.prefix.version !== entry.policy.version ||\n entry.stage.afterVersion !== entry.policy.version - 1 ||\n !entry.stage.complete ||\n entry.stage.currentJson !== entry.prefix.currentJson\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged current publication is outside its scope\",\n );\n }\n}\n\nasync function validatePublication(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(\n tx,\n entry.policy,\n );\n verifyPrincipalPolicyCheckpoint({\n chain: entry.policy.retainedHistory,\n currentState: entry.policy.state,\n localCheckpoint: checkpoint,\n });\n if (!checkpoint || entry.policy.version > checkpoint.version + 1)\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledged current policy must directly extend its durable checkpoint\",\n );\n const [prefix] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))\n .limit(1);\n if (prefix?.progress !== entry.previousPrefixProgress)\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Authenticated principal prefix changed before acknowledgement\",\n );\n}\n\n/** Store current artifacts and resumable progress in the same transaction as their pins. */\nexport async function persistAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentPublication[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const entries = structuredClone(input.entries);\n const retirements = structuredClone(input.retirements ?? []);\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n assertPublicationScope(entries, organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const stored = await runtime.guardedTransaction(\n async (tx) => {\n for (const entry of entries) await validatePublication(tx, entry);\n for (const retirement of retirements) {\n const policy = entries.find(\n (entry) =>\n entry.policy.principalId === retirement.principalId &&\n entry.policy.principalType === retirement.principalType,\n )?.policy;\n if (!policy)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged principal\",\n );\n await storePrincipalGrantRetirements(\n tx,\n { ...retirement, policy, organizationId },\n entries.map((entry) => entry.policy),\n organizationId,\n );\n }\n for (const entry of entries) {\n await writePrincipalHistoryEvidencePage(tx, entry.evidence);\n // A prefix-only predecessor must keep its encrypted key envelopes\n // before its reusable slot is replaced by the acknowledged successor.\n await tx\n .insert(principalHistoryStages)\n .values(entry.predecessorStage)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: entry.predecessorStage,\n setWhere: eq(principalHistoryStages.complete, false),\n })\n .run();\n // A fully authenticated publication supersedes an in-flight stage for\n // this exact head. Its other writer fails its progress CAS and resumes.\n await tx\n .insert(principalHistoryStages)\n .values(entry.stage)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: entry.stage,\n })\n .run();\n await tx\n .insert(principalHistoryPrefixes)\n .values(entry.prefix)\n .onConflictDoUpdate({\n target: principalHistoryPrefixes.scopeId,\n set: entry.prefix,\n })\n .run();\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n entry.policy.checkpoint,\n new Date().toISOString(),\n organizationId,\n );\n }\n },\n stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => stored.committed);\n}\n"]}
1
+ {"version":3,"file":"principalCurrentAcknowledgementPersistence.js","sourceRoot":"","sources":["principalCurrentAcknowledgementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAC/E,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,mCAAmC,EACnC,kBAAkB,EAClB,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAoB/C,SAAS,sBAAsB,CAC7B,OAA2D,EAC3D,cAAsB;IAEtB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YACf,MAAM,IAAI,u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CAAC;oBAClB,MAAM,EAAE,sBAAsB,CAAC,EAAE;oBACjC,GAAG,EAAE,KAAK,CAAC,gBAAgB;oBAC3B,QAAQ,EAAE,EAAE,CAAC,sBAAsB,CAAC,QAAQ,EAAE,KAAK,CAAC;iBACrD,CAAC;qBACD,GAAG,EAAE,CAAC;YACX,sEAAsE;YACtE,wEAAwE;YACxE,MAAM,EAAE;iBACL,MAAM,CAAC,sBAAsB,CAAC;iBAC9B,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC;iBACnB,kBAAkB,CAAC;gBAClB,MAAM,EAAE,sBAAsB,CAAC,EAAE;gBACjC,GAAG,EAAE,KAAK,CAAC,KAAK;aACjB,CAAC;iBACD,GAAG,EAAE,CAAC;YACT,MAAM,EAAE;iBACL,MAAM,CAAC,wBAAwB,CAAC;iBAChC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC;iBACpB,kBAAkB,CAAC;gBAClB,MAAM,EAAE,wBAAwB,CAAC,OAAO;gBACxC,GAAG,EAAE,KAAK,CAAC,MAAM;aAClB,CAAC;iBACD,GAAG,EAAE,CAAC;YACT,MAAM,4CAA4C,CAChD,EAAE,EACF,KAAK,CAAC,MAAM,CAAC,UAAU,EACvB,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,cAAc,CACf,CAAC;QACJ,CAAC;IACH,CAAC,EACD,YAAY,EACZ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport { principalHistoryPrefixes } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { storePrincipalGrantRetirements } from \"./principalGrantRetirementPersistence\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"./principalHistoryPrefixPersistence\";\nimport type { PrincipalHistoryStage } from \"./principalHistoryStagePersistence\";\n\n/** Owned output of authenticated prefix extension and exact receipt verification. */\nexport interface AcknowledgedPrincipalCurrentPublication {\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly prefix: PrincipalHistoryPrefix;\n readonly previousPrefixProgress: string | null;\n readonly stage: PrincipalHistoryStage;\n readonly predecessorStage: PrincipalHistoryStage | null;\n readonly evidence: PrincipalHistoryEvidencePage;\n}\n\nexport interface AcknowledgedPrincipalCurrentRetirement {\n readonly principalId: string;\n readonly principalType: VerifiedPrincipalPolicyCurrent[\"principalType\"];\n readonly containerIds: readonly string[];\n}\n\nfunction assertPublicationScope(\n entries: readonly AcknowledgedPrincipalCurrentPublication[],\n organizationId: string,\n) {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key))\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Acknowledged current batch repeats a principal\",\n );\n seen.add(key);\n if (\n entry.prefix.organizationId !== organizationId ||\n entry.stage.organizationId !== organizationId ||\n (entry.predecessorStage\n ? entry.predecessorStage.organizationId !== organizationId ||\n !entry.predecessorStage.complete ||\n entry.predecessorStage.afterVersion !== entry.policy.version - 2\n : entry.policy.principalType !== \"group\" ||\n entry.policy.version !== 1 ||\n entry.policy.state.prevStateHash !== null ||\n entry.previousPrefixProgress !== null) ||\n entry.evidence.organizationId !== organizationId ||\n entry.prefix.scopeId !== entry.evidence.scopeId ||\n entry.prefix.version !== entry.policy.version ||\n entry.stage.afterVersion !== entry.policy.version - 1 ||\n !entry.stage.complete ||\n entry.stage.currentJson !== entry.prefix.currentJson\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged current publication is outside its scope\",\n );\n }\n}\n\nasync function validatePublication(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(\n tx,\n entry.policy,\n );\n verifyPrincipalPolicyCheckpoint({\n chain: entry.policy.retainedHistory,\n currentState: entry.policy.state,\n localCheckpoint: checkpoint,\n });\n if (\n (!checkpoint && entry.policy.version !== 1) ||\n (checkpoint && entry.policy.version > checkpoint.version + 1)\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledged current policy must directly extend its durable checkpoint\",\n );\n const [prefix] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))\n .limit(1);\n if ((prefix?.progress ?? null) !== entry.previousPrefixProgress)\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Authenticated principal prefix changed before acknowledgement\",\n );\n}\n\n/** Store current artifacts and resumable progress in the same transaction as their pins. */\nexport async function persistAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentPublication[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const entries = structuredClone(input.entries);\n const retirements = structuredClone(input.retirements ?? []);\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n assertPublicationScope(entries, organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const stored = await runtime.guardedTransaction(\n async (tx) => {\n for (const entry of entries) await validatePublication(tx, entry);\n for (const retirement of retirements) {\n const policy = entries.find(\n (entry) =>\n entry.policy.principalId === retirement.principalId &&\n entry.policy.principalType === retirement.principalType,\n )?.policy;\n if (!policy)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged principal\",\n );\n await storePrincipalGrantRetirements(\n tx,\n { ...retirement, policy, organizationId },\n entries.map((entry) => entry.policy),\n organizationId,\n );\n }\n for (const entry of entries) {\n await writePrincipalHistoryEvidencePage(tx, entry.evidence);\n // A prefix-only predecessor must keep its encrypted key envelopes\n // before its reusable slot is replaced by the acknowledged successor.\n if (entry.predecessorStage)\n await tx\n .insert(principalHistoryStages)\n .values(entry.predecessorStage)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: entry.predecessorStage,\n setWhere: eq(principalHistoryStages.complete, false),\n })\n .run();\n // A fully authenticated publication supersedes an in-flight stage for\n // this exact head. Its other writer fails its progress CAS and resumes.\n await tx\n .insert(principalHistoryStages)\n .values(entry.stage)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: entry.stage,\n })\n .run();\n await tx\n .insert(principalHistoryPrefixes)\n .values(entry.prefix)\n .onConflictDoUpdate({\n target: principalHistoryPrefixes.scopeId,\n set: entry.prefix,\n })\n .run();\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n entry.policy.checkpoint,\n new Date().toISOString(),\n organizationId,\n );\n }\n },\n stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => stored.committed);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=currentPolicyReferenceResolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"currentPolicyReferenceResolver.js","sourceRoot":"","sources":["currentPolicyReferenceResolver.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\n\n/** Privately authenticated historical citations selected for one authored head. */\nexport type CurrentPolicyReferenceResolver = (\n current: VerifiedPrincipalPolicyCurrent,\n references: readonly ReferencedPrincipalHead[],\n) => Promise<VerifiedPrincipalPolicyCurrent>;\n"]}
@@ -0,0 +1,23 @@
1
+ import { serializeKeyingCanonicalJson, } from "../../internal/crypto/index.js";
2
+ /** Stable authenticated scopes shared by paged recovery and acknowledged extension. */
3
+ export function directoryHistoryProtection(protection) {
4
+ return {
5
+ localKey: protection.localKey,
6
+ context: serializeKeyingCanonicalJson([
7
+ "tearleads.sdk.principal-history.directory.v1",
8
+ protection.context,
9
+ ]),
10
+ };
11
+ }
12
+ export function scopedGroupHistoryProtection(protection, organizationId, adminGroupId) {
13
+ return {
14
+ localKey: protection.localKey,
15
+ context: serializeKeyingCanonicalJson([
16
+ "tearleads.sdk.principal-history.scoped-group.v1",
17
+ protection.context,
18
+ organizationId,
19
+ adminGroupId,
20
+ ]),
21
+ };
22
+ }
23
+ //# sourceMappingURL=principalHistoryScopeProtection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalHistoryScopeProtection.js","sourceRoot":"","sources":["principalHistoryScopeProtection.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,uFAAuF;AACvF,MAAM,UAAU,0BAA0B,CACxC,UAAiD;IAEjD,OAAO;QACL,QAAQ,EAAE,UAAU,CAAC,QAAQ;QAC7B,OAAO,EAAE,4BAA4B,CAAC;YACpC,8CAA8C;YAC9C,UAAU,CAAC,OAAO;SACnB,CAAC;KACH,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,UAAiD,EACjD,cAAsB,EACtB,YAAoB;IAEpB,OAAO;QACL,QAAQ,EAAE,UAAU,CAAC,QAAQ;QAC7B,OAAO,EAAE,4BAA4B,CAAC;YACpC,iDAAiD;YACjD,UAAU,CAAC,OAAO;YAClB,cAAc;YACd,YAAY;SACb,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalPolicyHistoryProgressOptions,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\n\n/** Stable authenticated scopes shared by paged recovery and acknowledged extension. */\nexport function directoryHistoryProtection(\n protection: PrincipalPolicyHistoryProgressOptions,\n) {\n return {\n localKey: protection.localKey,\n context: serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.directory.v1\",\n protection.context,\n ]),\n };\n}\n\nexport function scopedGroupHistoryProtection(\n protection: PrincipalPolicyHistoryProgressOptions,\n organizationId: string,\n adminGroupId: string,\n) {\n return {\n localKey: protection.localKey,\n context: serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.scoped-group.v1\",\n protection.context,\n organizationId,\n adminGroupId,\n ]),\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyAdminSigners.js","sourceRoot":"","sources":["principalPolicyAdminSigners.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAOvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAG3B,MAAM,UAAU,kCAAkC,CAChD,MAAqC;IAErC,OAAO;QACL,aAAa,EAAE,MAAM,CAAC,YAAY,CAAC,aAAa;QAChD,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;QAC5C,OAAO,EAAE,MAAM,CAAC,YAAY,CAAC,OAAO;QACpC,QAAQ,EAAE,MAAM,CAAC,YAAY,CAAC,QAAQ;QACtC,SAAS,EAAE,MAAM,CAAC,YAAY,CAAC,SAAS;QACxC,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC,cAAc;KACnD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,MAA+B;IAE/B,O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ationError,\n type KeyingVerificationResult,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\n\nexport function principalPolicyReferenceFromBundle(\n bundle: PrincipalPolicyBundleResponse,\n): ReferencedPrincipalHead {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n keyFingerprint: bundle.currentState.keyFingerprint,\n };\n}\n\nexport function organizationAdminSignerUserIds(\n policy: VerifiedPrincipalPolicy,\n): string[] {\n return [\n ...new Set(\n policy.projection\n .filter((member) => member.role === \"admin\")\n .map((member) => member.userId),\n ),\n ].sort();\n}\n\nexport function organizationAdminExternalAuthority(\n policy: VerifiedPrincipalPolicy,\n): PrincipalPolicyExternalAuthority {\n const history = policy.history ?? [\n {\n state: policy.state,\n projection: policy.projection,\n grants: policy.grants,\n },\n ];\n const toHead = (state: (typeof history)[number][\"state\"]) => ({\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n });\n return {\n currentHead: toHead(policy.state),\n states: history.map((entry) => ({\n head: toHead(entry.state),\n projection: entry.projection,\n })),\n };\n}\n\nexport async function verifyOrganizationAdminPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly localCheckpoint?: PrincipalPolicyCheckpoint | null | undefined;\n readonly organizationId: string;\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n}): Promise<KeyingVerificationResult<VerifiedPrincipalPolicy>> {\n if (\n input.bundle.currentState.principalType !== \"organization\" ||\n input.bundle.currentState.principalId !== input.organizationId\n ) {\n return {\n ok: false,\n error: new KeyingVerificationError(\n \"object_mismatch\",\n \"organization policy does not match the expected organization\",\n ),\n };\n }\n\n return verifyPrincipalPolicyBundle({\n bundle: input.bundle,\n expectedReference: principalPolicyReferenceFromBundle(input.bundle),\n localCheckpoint: input.localCheckpoint ?? null,\n signerPublicKeys: input.signerPublicKeys,\n });\n}\n\nexport async function verifyPrincipalPolicyBundleWithExternalOrganizationAdmins(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly expectedReference: ReferencedPrincipalHead;\n readonly loadExternalAuthority: () => Promise<PrincipalPolicyExternalAuthority | null>;\n readonly localCheckpoint?: PrincipalPolicyCheckpoint | null | undefined;\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n}): Promise<KeyingVerificationResult<VerifiedPrincipalPolicy>> {\n const verified = await verifyPrincipalPolicyBundle({\n bundle: input.bundle,\n expectedReference: input.expectedReference,\n localCheckpoint: input.localCheckpoint ?? null,\n signerPublicKeys: input.signerPublicKeys,\n });\n if (verified.ok || verified.error.code !== \"unauthorized\") {\n return verified;\n }\n\n const externalAuthority = await input.loadExternalAuthority();\n if (!externalAuthority) {\n return verified;\n }\n\n const verifiedWithExternalAdmins = await verifyPrincipalPolicyBundle({\n bundle: input.bundle,\n externalAuthority,\n expectedReference: input.expectedReference,\n localCheckpoint: input.localCheckpoint ?? null,\n signerPublicKeys: input.signerPublicKeys,\n });\n\n return verifiedWithExternalAdmins;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyAdminSigners.js","sourceRoot":"","sources":["principalPolicyAdminSigners.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAOvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAG3B,MAAM,UAAU,kCAAkC,CAChD,MAA2D;IAE3D,OAAO;QACL,aAAa,EAAE,MAAM,CAAC,YAAY,CAAC,aAAa;QAChD,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;QAC5C,OAAO,EAAE,MAAM,CAAC,YAA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,MAAM;QACpB,iBAAiB;QACjB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,eAAe,EAAE,KAAK,CAAC,eAAe,IAAI,IAAI;QAC9C,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC,CAAC;IAEH,OAAO,0BAA0B,CAAC;AACpC,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type KeyingVerificationResult,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\n\nexport function principalPolicyReferenceFromBundle(\n bundle: Pick<PrincipalPolicyBundleResponse, \"currentState\">,\n): ReferencedPrincipalHead {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n keyFingerprint: bundle.currentState.keyFingerprint,\n };\n}\n\nexport function organizationAdminSignerUserIds(\n policy: Pick<VerifiedPrincipalPolicy, \"projection\">,\n): string[] {\n return [\n ...new Set(\n policy.projection\n .filter((member) => member.role === \"admin\")\n .map((member) => member.userId),\n ),\n ].sort();\n}\n\nexport function organizationAdminExternalAuthority(\n policy: VerifiedPrincipalPolicy,\n): PrincipalPolicyExternalAuthority {\n const history = policy.history ?? [\n {\n state: policy.state,\n projection: policy.projection,\n grants: policy.grants,\n },\n ];\n const toHead = (state: (typeof history)[number][\"state\"]) => ({\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n });\n return {\n currentHead: toHead(policy.state),\n states: history.map((entry) => ({\n head: toHead(entry.state),\n projection: entry.projection,\n })),\n };\n}\n\nexport async function verifyOrganizationAdminPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly localCheckpoint?: PrincipalPolicyCheckpoint | null | undefined;\n readonly organizationId: string;\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n}): Promise<KeyingVerificationResult<VerifiedPrincipalPolicy>> {\n if (\n input.bundle.currentState.principalType !== \"organization\" ||\n input.bundle.currentState.principalId !== input.organizationId\n ) {\n return {\n ok: false,\n error: new KeyingVerificationError(\n \"object_mismatch\",\n \"organization policy does not match the expected organization\",\n ),\n };\n }\n\n return verifyPrincipalPolicyBundle({\n bundle: input.bundle,\n expectedReference: principalPolicyReferenceFromBundle(input.bundle),\n localCheckpoint: input.localCheckpoint ?? null,\n signerPublicKeys: input.signerPublicKeys,\n });\n}\n\nexport async function verifyPrincipalPolicyBundleWithExternalOrganizationAdmins(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly expectedReference: ReferencedPrincipalHead;\n readonly loadExternalAuthority: () => Promise<PrincipalPolicyExternalAuthority | null>;\n readonly localCheckpoint?: PrincipalPolicyCheckpoint | null | undefined;\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n}): Promise<KeyingVerificationResult<VerifiedPrincipalPolicy>> {\n const verified = await verifyPrincipalPolicyBundle({\n bundle: input.bundle,\n expectedReference: input.expectedReference,\n localCheckpoint: input.localCheckpoint ?? null,\n signerPublicKeys: input.signerPublicKeys,\n });\n if (verified.ok || verified.error.code !== \"unauthorized\") {\n return verified;\n }\n\n const externalAuthority = await input.loadExternalAuthority();\n if (!externalAuthority) {\n return verified;\n }\n\n const verifiedWithExternalAdmins = await verifyPrincipalPolicyBundle({\n bundle: input.bundle,\n externalAuthority,\n expectedReference: input.expectedReference,\n localCheckpoint: input.localCheckpoint ?? null,\n signerPublicKeys: input.signerPublicKeys,\n });\n\n return verifiedWithExternalAdmins;\n}\n"]}