@tearleads/client-sdk 0.1.233 → 0.1.234

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 (20) hide show
  1. package/data/principals/organizationGroupDirectoryRequest.js +64 -0
  2. package/data/principals/organizationGroupDirectoryRequest.js.map +1 -0
  3. package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRecipients.js +3 -3
  4. package/data/principals/principalPolicyRecipients.js.map +1 -0
  5. package/package.json +1 -1
  6. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +1 -1
  7. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  8. package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
  9. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
  10. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  11. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  12. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js +2 -1
  13. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js.map +1 -1
  14. package/workflows/organizations/groups/deleteOrganizationGroup.js +2 -1
  15. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  16. package/workflows/organizations/groups/organizationGroupDirectory.js +2 -63
  17. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  18. package/workflows/organizations/principalPolicy/index.js +1 -1
  19. package/workflows/organizations/principalPolicy/index.js.map +1 -1
  20. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +0 -1
@@ -0,0 +1,64 @@
1
+ import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, normalizePrincipalProjectionMembers, signPrincipalState, toFingerprint, } from "../../internal/crypto/index.js";
2
+ import { bytesToBase64 } from "../../internal/encoding/index.js";
3
+ import { encodeOrganizationAuthorityDescriptor, normalizeOrganizationGroupHeads, } from "../principalContracts/organizationAuthorityDescriptor.js";
4
+ import { rewrapProjectionMemberEnvelopes } from "./principalPolicyRecipients.js";
5
+ export function organizationGroupHead(head) {
6
+ if (head.principalType !== "group") {
7
+ throw new Error("Organization directory can contain only group heads");
8
+ }
9
+ return { ...head, principalType: "group" };
10
+ }
11
+ export function replaceOrganizationGroupHead(input) {
12
+ const nextHead = organizationGroupHead(input.nextHead);
13
+ return normalizeOrganizationGroupHeads([
14
+ ...input.descriptor.groupHeads.filter((head) => head.principalId !== nextHead.principalId),
15
+ nextHead,
16
+ ]);
17
+ }
18
+ export async function buildOrganizationGroupDirectoryPolicyRequest(input) {
19
+ const projection = normalizePrincipalProjectionMembers(input.adminProjection);
20
+ if (projection.length === 0 ||
21
+ projection.some((member) => member.role !== "admin")) {
22
+ throw new Error("Organization policy must mirror the Admins projection");
23
+ }
24
+ const organizationKem = generateKemSeedAndKeyPair();
25
+ const memberEnvelopes = await rewrapProjectionMemberEnvelopes({
26
+ projection,
27
+ secretKey: organizationKem.secretKey,
28
+ users: input.adminUsers,
29
+ });
30
+ const payloadCiphertext = encodeOrganizationAuthorityDescriptor({
31
+ ...input.descriptor,
32
+ groupHeads: input.groupHeads,
33
+ });
34
+ const state = await signPrincipalState(await buildPrincipalStateSigningInput({
35
+ principalType: "organization",
36
+ principalId: input.descriptor.organizationId,
37
+ version: input.currentPolicy.currentState.version + 1,
38
+ prevStateHash: input.currentPolicy.currentState.stateHash,
39
+ keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,
40
+ encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
41
+ keyFingerprint: await toFingerprint(organizationKem.publicKey),
42
+ members: projection.map((member) => ({ userId: member.userId })),
43
+ memberEnvelopes,
44
+ projection,
45
+ grants: [],
46
+ payloadCiphertext,
47
+ externalAuthority: null,
48
+ signedAt: new Date().toISOString(),
49
+ signerUserId: input.signerUserId,
50
+ signerUserKeyFingerprint: input.signingFingerprint,
51
+ }), input.signingKeyPair.signingPrivateKey);
52
+ return {
53
+ encryptedPayload: {
54
+ cipherSuite: "aes-256-gcm",
55
+ ciphertext: payloadCiphertext,
56
+ ciphertextHash: state.payloadCiphertextHash,
57
+ },
58
+ grants: [],
59
+ memberEnvelopes,
60
+ projection,
61
+ state,
62
+ };
63
+ }
64
+ //# sourceMappingURL=organizationGroupDirectoryRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"organizationGroupDirectoryRequest.js","sourceRoot":"","sources":["organizationGroupDirectoryRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,mCAAmC,EAGnC,kBAAkB,EAClB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,uDAAuD,CAAC;AAE/D,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAE9E,MAAM,UAAU,qBAAqB,CACnC,IAA6B;IAE7B,IAAI,IAAI,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,EAAE,GAAG,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAG5C;IACC,MAAM,QAAQ,GAAG,qBAAqB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACvD,OAAO,+BAA+B,CAAC;QACrC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,MAAM,CACnC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CACpD;QACD,QAAQ;KACT,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAAC,KASlE;IACC,MAAM,UAAU,GAAG,mCAAmC,CAAC,KAAK,CAAC,eAAe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AQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,wBAAwB,EAAE,KAAK,CAAC,kBAAkB;KACnD,CAAC,EACF,KAAK,CAAC,cAAc,CAAC,iBAAiB,CACvC,CAAC;IAEF,OAAO;QACL,gBAAgB,EAAE;YAChB,WAAW,EAAE,aAAa;YAC1B,UAAU,EAAE,iBAAiB;YAC7B,cAAc,EAAE,KAAK,CAAC,qBAAqB;SAC5C;QACD,MAAM,EAAE,EAAE;QACV,eAAe;QACf,UAAU;QACV,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../principalContracts/organizationAuthorityDescriptor\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\nimport { rewrapProjectionMemberEnvelopes } from \"./principalPolicyRecipients\";\n\nexport function organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes,\n projection,\n state,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { wrapDekForRecipients } from "../../../internal/crypto/index.js";
2
- import { base64ToBytes, bytesToBase64 } from "../../../internal/encoding/index.js";
3
- import { assertPrincipalIdentityCommitments } from "../../../data/principalContracts/principalIdentityCommitments.js";
1
+ import { wrapDekForRecipients } from "../../internal/crypto/index.js";
2
+ import { base64ToBytes, bytesToBase64 } from "../../internal/encoding/index.js";
3
+ import { assertPrincipalIdentityCommitments } from "../principalContracts/principalIdentityCommitments.js";
4
4
  function toPrincipalMemberEnvelopeRequest(input) {
5
5
  return {
6
6
  userId: input.userId,
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyRecipients.js","sourceRoot":"","sources":["principalPolicyRecipients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMnE,OAAO,EAAE,kCAAkC,EAAE,MAAM,oDAAoD,CAAC;AAQxG,SAAS,gCAAgC,CAAC,KAOzC;IACC,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,oBAAoB,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc;QACnD,aAAa,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC1D,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC;KACrD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,SAAyD;IAEzD,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QAClC,cAAc,EAAE,QAAQ,CAAC,oBAAoB;QAC7C,aAAa,EAAE,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC;QACpD,UAAU,EAAE,aAAa,CAAC,QAAQ,CAAC,UAAU,CAAC;KAC/C,CAAC,CAAC,CAAC;AACN,CAAC;AAED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MAAM,oBAAoB,CAClD,KAAK,CAAC,SAAS,EACf,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAChE,CAAC;IAEF,OAAO,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,CAC/C,gCAAgC,CAAC;QAC/B,QAAQ;QACR,MAAM,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,IAAI,EAAE;KACxC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { wrapDekForRecipients } from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalMemberEnvelopeResponse } from \"@tearleads/validators/response\";\nimport { assertPrincipalIdentityCommitments } from \"../principalContracts/principalIdentityCommitments\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\n\ntype PrincipalRekeyRecipient = {\n readonly encapsulationPublicKey: Uint8Array;\n readonly userId: string;\n};\n\nfunction toPrincipalMemberEnvelopeRequest(input: {\n readonly envelope: {\n readonly keyFingerprint: string;\n readonly kemCipherText: Uint8Array;\n readonly wrappedKey: Uint8Array;\n };\n readonly userId: string;\n}): PrincipalMemberEnvelopeRequest {\n return {\n userId: input.userId,\n memberKeyFingerprint: input.envelope.keyFingerprint,\n kemCipherText: bytesToBase64(input.envelope.kemCipherText),\n wrappedKey: bytesToBase64(input.envelope.wrappedKey),\n };\n}\n\nexport function toRecipientEntries(\n envelopes: ReadonlyArray<PrincipalMemberEnvelopeResponse>,\n) {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.memberKeyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\n/** Every projected member is a user, so there is no group recipient branch. */\nfunction toRekeyRecipientEntries(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): PrincipalRekeyRecipient[] {\n const usersById = new Map(input.users.map((user) => [user.userId, user]));\n\n return input.projection.map((member) => {\n const user = usersById.get(member.userId);\n if (!user) {\n throw new Error(`Missing recipient key for user ${member.userId}`);\n }\n\n return {\n encapsulationPublicKey: user.encapsulationPublicKey,\n userId: user.userId,\n };\n });\n}\n\nexport async function rewrapProjectionMemberEnvelopes(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly secretKey: Uint8Array;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): Promise<PrincipalMemberEnvelopeRequest[]> {\n const users = new Map(input.users.map((user) => [user.userId, user]));\n await assertPrincipalIdentityCommitments({\n authenticated: false,\n projections: [input.projection],\n resolveTrustedUserIdentity: async (userId) => users.get(userId) ?? null,\n });\n const recipients = toRekeyRecipientEntries(input);\n if (recipients.length === 0) {\n return [];\n }\n const wrappedRecipients = await wrapDekForRecipients(\n input.secretKey,\n recipients.map((recipient) => recipient.encapsulationPublicKey),\n );\n\n return wrappedRecipients.map((envelope, index) =>\n toPrincipalMemberEnvelopeRequest({\n envelope,\n userId: recipients[index]?.userId ?? \"\",\n }),\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.233",
3
+ "version": "0.1.234",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,5 +1,5 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
- import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "../groups/organizationGroupDirectory.js";
2
+ import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "../../../data/principals/organizationGroupDirectoryRequest.js";
3
3
  import { assertAuthoredPrincipalMutationReceipt } from "../principalMutations/principalMutationReceipt.js";
4
4
  import { projectionUserIds, resolveRequiredUserIdentities, } from "../trustedOrganizationUsers.js";
5
5
  import { prepareAuthoredGroupPolicy } from "./groupPolicyMutationAcknowledgement.js";
@@ -1 +1 @@
1
- {"version":3,"file":"commitCurrentGroupPolicyMutation.js","sourceRoot":"","sources":["commitCurrentGroupPolicyMutation.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAMvG,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,sCAAsC,EAAE,MAAM,gDAAgD,CAAC;AAExG,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAEL,uBAAuB,GACxB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAsBpE,sFAAsF;AACtF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,6BAA6B,CAAC;QACnD,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,OAAO,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC;KAC9B,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IACnE,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM;QACzB,CAAC,CAAC,MAAM,aAAa,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC;QA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icyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type {\n PreparedPrincipalContainerRematerializationBatch,\n PrincipalRematerializationPredecessor,\n} from \"../../containers/rematerialization\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../groups/organizationGroupDirectory\";\nimport { assertAuthoredPrincipalMutationReceipt } from \"../principalMutations/principalMutationReceipt\";\nimport type { RuntimeCurrentGroupMutationContext } from \"../principalMutations/runtimeCurrentGroupMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport { prepareAuthoredGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n type PrincipalPolicyReadWriteApi,\n submitGroupPolicyCommit,\n} from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\n\ninterface GroupPolicyChange {\n readonly context: RuntimeCurrentGroupMutationContext;\n readonly request: PutPrincipalPolicyRequest;\n readonly prepareContainerMutations: (\n nextPolicy: VerifiedPrincipalPolicyCurrent,\n preceding?: PrincipalRematerializationPredecessor | undefined,\n ) => Promise<PreparedPrincipalContainerRematerializationBatch>;\n}\n\ninterface CommitInput extends GroupPolicyChange {\n readonly member?: GroupPolicyChange | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** Commit and retain the group, optional roster enrollment and directory together. */\nexport async function commitCurrentGroupPolicyMutation(\n input: CommitInput,\n): Promise<PrincipalPolicyMutationResponse> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const [signer] = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [input.signerUserId],\n });\n if (!signer) throw new Error(\"Group policy signer is unavailable\");\n const member = input.member\n ? await prepareChange(input.member, signer)\n : null;\n const { expectedHead, prepared } = await prepareChange(\n input,\n signer,\n member?.preceding,\n );\n const organizationRequest = await prepareDirectory(\n input,\n expectedHead,\n member?.expectedHead,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n const response = await submitGroupPolicyCommit({\n apiClient: input.apiClient,\n groupId: input.groupId,\n organizationId: input.organizationId,\n request: input.request,\n organizationRequest,\n memberRequest: input.member?.request,\n // A compound retry must rebuild both batches' shared speculative heads.\n // Refuse the whole transaction if a damaged-key repair needs extra rekeys;\n // ordinary adds preserve key epochs and need no descendant carry retry.\n carryDescendantRekeys: member ? undefined : prepared.carry,\n refreshContainerMutations: member\n ? undefined\n : prepared.refreshAfterConflict,\n stillCurrent: context.stillCurrent,\n });\n if (!response) throw new Error(\"Group policy update failed\");\n assertProjectionVerificationCurrent(context.stillCurrent);\n await assertAuthoredPrincipalMutationReceipt(\n {\n groupPolicy: input.request,\n organizationPolicy: organizationRequest,\n ...(input.member ? { memberPolicy: input.member.request } : {}),\n },\n response,\n );\n await context.retainAcknowledged({\n additionalGroups:\n input.member && response.memberPolicy\n ? [\n {\n ...input.member.context.groupRetention,\n request: input.member.request,\n response: response.memberPolicy,\n retiredContainerIds: member?.prepared.retiredContainerIds,\n },\n ]\n : [],\n request: input.request,\n organizationRequest,\n response,\n retiredContainerIds: prepared.retiredContainerIds,\n });\n if (member && response.memberPolicy) {\n await member.prepared.acknowledge(\n response.memberPolicy.containerMutations,\n context.stillCurrent,\n );\n }\n await prepared.acknowledge(\n response.groupPolicy.containerMutations,\n context.stillCurrent,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n return response.groupPolicy;\n}\n\nasync function prepareChange(\n change: GroupPolicyChange,\n signer: Awaited<ReturnType<typeof resolveRequiredUserIdentities>>[number],\n preceding?: PrincipalRematerializationPredecessor,\n) {\n const expectedHead = await groupPolicyMutationHead(change.request);\n const nextPolicy = await prepareAuthoredGroupPolicy({\n verifiedCurrentPolicy: change.context.verifiedCurrentPolicy,\n expectedHead,\n request: change.request,\n signerPublicKeys: [signer],\n externalAuthority: change.context.externalAuthority,\n localPolicyCheckpoint: change.context.localPolicyCheckpoint,\n stillCurrent: change.context.stillCurrent,\n });\n const authored = [\n ...(preceding?.authored ?? []),\n {\n organizationId: change.context.organizationDescriptor.organizationId,\n policy: nextPolicy,\n dependencies: [\n change.context.organizationCurrent.policy,\n change.context.adminCurrent.policy,\n ],\n stillCurrent: change.context.stillCurrent,\n },\n ];\n // A level the batch plans under its own rotation cites this successor\n // before the transaction commits, so the batch resolves it as authored,\n // exactly as the next group in a compound transaction does (#2646).\n const prepared = await change.prepareContainerMutations(nextPolicy, {\n policies: preceding?.policies ?? [],\n projections: preceding?.projections ?? [],\n knownContainerKeks: preceding?.knownContainerKeks ?? new Map(),\n authored,\n });\n change.request.containerMutations = [...prepared.requests];\n return {\n expectedHead,\n prepared,\n preceding: prepared.preceding\n ? { ...prepared.preceding, authored }\n : undefined,\n };\n}\n\nasync function prepareDirectory(\n input: CommitInput,\n expectedHead: Awaited<ReturnType<typeof groupPolicyMutationHead>>,\n memberHead: Awaited<ReturnType<typeof groupPolicyMutationHead>> | undefined,\n) {\n const { context } = input;\n if (\n input.member &&\n (input.member.context.currentPolicy.currentState.principalId !==\n context.memberGroupId ||\n input.member.context.organizationCurrent.current.currentState\n .stateHash !==\n context.organizationCurrent.current.currentState.stateHash)\n )\n throw new Error(\n \"Roster and group changes must share the same organization policy\",\n );\n let groupHeads = replaceOrganizationGroupHead({\n descriptor: context.organizationDescriptor,\n nextHead: expectedHead,\n });\n if (memberHead)\n groupHeads = replaceOrganizationGroupHead({\n descriptor: { ...context.organizationDescriptor, groupHeads },\n nextHead: memberHead,\n });\n const adminProjection = context.isOrganizationAdminsGroup\n ? input.request.projection\n : context.adminCurrent.current.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n return buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: context.organizationCurrent.current,\n descriptor: context.organizationDescriptor,\n groupHeads,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n"]}
1
+ {"version":3,"file":"commitCurrentGroupPolicyMutation.js","sourceRoot":"","sources":["commitCurrentGroupPolicyMutation.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,4DAA4D,CAAC;AAMpE,OAAO,EAAE,sCAAsC,EAAE,MAAM,gDAAgD,CAAC;AAExG,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAEL,uBAAuB,GACxB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAsBpE,sFAAsF;AACtF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,6BAA6B,CAAC;QACnD,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,OAAO,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC;KAC9B,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,MAAM,I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AY;QAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n SigningKeyPair,\n VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type {\n PreparedPrincipalContainerRematerializationBatch,\n PrincipalRematerializationPredecessor,\n} from \"../../containers/rematerialization\";\nimport { assertAuthoredPrincipalMutationReceipt } from \"../principalMutations/principalMutationReceipt\";\nimport type { RuntimeCurrentGroupMutationContext } from \"../principalMutations/runtimeCurrentGroupMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport { prepareAuthoredGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n type PrincipalPolicyReadWriteApi,\n submitGroupPolicyCommit,\n} from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\n\ninterface GroupPolicyChange {\n readonly context: RuntimeCurrentGroupMutationContext;\n readonly request: PutPrincipalPolicyRequest;\n readonly prepareContainerMutations: (\n nextPolicy: VerifiedPrincipalPolicyCurrent,\n preceding?: PrincipalRematerializationPredecessor | undefined,\n ) => Promise<PreparedPrincipalContainerRematerializationBatch>;\n}\n\ninterface CommitInput extends GroupPolicyChange {\n readonly member?: GroupPolicyChange | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** Commit and retain the group, optional roster enrollment and directory together. */\nexport async function commitCurrentGroupPolicyMutation(\n input: CommitInput,\n): Promise<PrincipalPolicyMutationResponse> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const [signer] = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [input.signerUserId],\n });\n if (!signer) throw new Error(\"Group policy signer is unavailable\");\n const member = input.member\n ? await prepareChange(input.member, signer)\n : null;\n const { expectedHead, prepared } = await prepareChange(\n input,\n signer,\n member?.preceding,\n );\n const organizationRequest = await prepareDirectory(\n input,\n expectedHead,\n member?.expectedHead,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n const response = await submitGroupPolicyCommit({\n apiClient: input.apiClient,\n groupId: input.groupId,\n organizationId: input.organizationId,\n request: input.request,\n organizationRequest,\n memberRequest: input.member?.request,\n // A compound retry must rebuild both batches' shared speculative heads.\n // Refuse the whole transaction if a damaged-key repair needs extra rekeys;\n // ordinary adds preserve key epochs and need no descendant carry retry.\n carryDescendantRekeys: member ? undefined : prepared.carry,\n refreshContainerMutations: member\n ? undefined\n : prepared.refreshAfterConflict,\n stillCurrent: context.stillCurrent,\n });\n if (!response) throw new Error(\"Group policy update failed\");\n assertProjectionVerificationCurrent(context.stillCurrent);\n await assertAuthoredPrincipalMutationReceipt(\n {\n groupPolicy: input.request,\n organizationPolicy: organizationRequest,\n ...(input.member ? { memberPolicy: input.member.request } : {}),\n },\n response,\n );\n await context.retainAcknowledged({\n additionalGroups:\n input.member && response.memberPolicy\n ? [\n {\n ...input.member.context.groupRetention,\n request: input.member.request,\n response: response.memberPolicy,\n retiredContainerIds: member?.prepared.retiredContainerIds,\n },\n ]\n : [],\n request: input.request,\n organizationRequest,\n response,\n retiredContainerIds: prepared.retiredContainerIds,\n });\n if (member && response.memberPolicy) {\n await member.prepared.acknowledge(\n response.memberPolicy.containerMutations,\n context.stillCurrent,\n );\n }\n await prepared.acknowledge(\n response.groupPolicy.containerMutations,\n context.stillCurrent,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n return response.groupPolicy;\n}\n\nasync function prepareChange(\n change: GroupPolicyChange,\n signer: Awaited<ReturnType<typeof resolveRequiredUserIdentities>>[number],\n preceding?: PrincipalRematerializationPredecessor,\n) {\n const expectedHead = await groupPolicyMutationHead(change.request);\n const nextPolicy = await prepareAuthoredGroupPolicy({\n verifiedCurrentPolicy: change.context.verifiedCurrentPolicy,\n expectedHead,\n request: change.request,\n signerPublicKeys: [signer],\n externalAuthority: change.context.externalAuthority,\n localPolicyCheckpoint: change.context.localPolicyCheckpoint,\n stillCurrent: change.context.stillCurrent,\n });\n const authored = [\n ...(preceding?.authored ?? []),\n {\n organizationId: change.context.organizationDescriptor.organizationId,\n policy: nextPolicy,\n dependencies: [\n change.context.organizationCurrent.policy,\n change.context.adminCurrent.policy,\n ],\n stillCurrent: change.context.stillCurrent,\n },\n ];\n // A level the batch plans under its own rotation cites this successor\n // before the transaction commits, so the batch resolves it as authored,\n // exactly as the next group in a compound transaction does (#2646).\n const prepared = await change.prepareContainerMutations(nextPolicy, {\n policies: preceding?.policies ?? [],\n projections: preceding?.projections ?? [],\n knownContainerKeks: preceding?.knownContainerKeks ?? new Map(),\n authored,\n });\n change.request.containerMutations = [...prepared.requests];\n return {\n expectedHead,\n prepared,\n preceding: prepared.preceding\n ? { ...prepared.preceding, authored }\n : undefined,\n };\n}\n\nasync function prepareDirectory(\n input: CommitInput,\n expectedHead: Awaited<ReturnType<typeof groupPolicyMutationHead>>,\n memberHead: Awaited<ReturnType<typeof groupPolicyMutationHead>> | undefined,\n) {\n const { context } = input;\n if (\n input.member &&\n (input.member.context.currentPolicy.currentState.principalId !==\n context.memberGroupId ||\n input.member.context.organizationCurrent.current.currentState\n .stateHash !==\n context.organizationCurrent.current.currentState.stateHash)\n )\n throw new Error(\n \"Roster and group changes must share the same organization policy\",\n );\n let groupHeads = replaceOrganizationGroupHead({\n descriptor: context.organizationDescriptor,\n nextHead: expectedHead,\n });\n if (memberHead)\n groupHeads = replaceOrganizationGroupHead({\n descriptor: { ...context.organizationDescriptor, groupHeads },\n nextHead: memberHead,\n });\n const adminProjection = context.isOrganizationAdminsGroup\n ? input.request.projection\n : context.adminCurrent.current.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n return buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: context.organizationCurrent.current,\n descriptor: context.organizationDescriptor,\n groupHeads,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n"]}
@@ -2,8 +2,8 @@ import { generateKemSeedAndKeyPair, KeyingVerificationError, toFingerprint, unwr
2
2
  import { bytesToBase64 } from "../../../internal/encoding/index.js";
3
3
  import { createPrincipalProjectionMember } from "../../../data/principalContracts/principalIdentityCommitments.js";
4
4
  import { principalSecretKeyMatchesState } from "../../../data/principals/principalKeyValidation.js";
5
+ import { rewrapProjectionMemberEnvelopes, toRecipientEntries, } from "../../../data/principals/principalPolicyRecipients.js";
5
6
  import { signedGroupPolicyRequest } from "../../../data/principals/principalPolicyRequest.js";
6
- import { rewrapProjectionMemberEnvelopes, toRecipientEntries, } from "../principalPolicy/principalPolicyRecipients.js";
7
7
  import { isDirectGroupAdmin } from "./groupMutationAuthorization.js";
8
8
  import { withVerifiedGroupMutation, } from "./groupPolicyMutationEvidence.js";
9
9
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"groupPolicyRequests.js","sourceRoot":"","sources":["groupPolicyRequests.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EAEvB,aAAa,EACb,SAAS,EACT,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3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Ac,EAAE,KAAK,CAAC,aAAa,CAAC,YAAY,CAAC,cAAc;YAC/D,MAAM;YACN,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,sBAAsB,CAAC,SAAS;YACrE,iBAAiB,EAAE,KAAK,CAAC,aAAa,CAAC,cAAc,CAAC,UAAU;YAChE,WAAW,EAAE,KAAK,CAAC,aAAa,CAAC,YAAY,CAAC,WAAW;YACzD,UAAU,EAAE,KAAK,CAAC,aAAa,CAAC,iBAAiB;YACjD,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YAClC,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n generateKemSeedAndKeyPair,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n toFingerprint,\n unwrapDek,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalContainerGrantRequest,\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport { createPrincipalProjectionMember } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport { principalSecretKeyMatchesState } from \"../../../data/principals/principalKeyValidation\";\nimport { signedGroupPolicyRequest } from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { TrustedUserIdentity } from \"../../../data/trustedUserIdentity\";\nimport {\n rewrapProjectionMemberEnvelopes,\n toRecipientEntries,\n} from \"../principalPolicy/principalPolicyRecipients\";\nimport { isDirectGroupAdmin } from \"./groupMutationAuthorization\";\nimport {\n type BuildGroupMembershipMutationInput,\n withVerifiedGroupMutation,\n} from \"./groupPolicyMutationEvidence\";\n\ntype BuildAddGroupUserPolicyInput = BuildGroupMembershipMutationInput & {\n readonly currentUsers: ReadonlyArray<TrustedUserIdentity>;\n readonly currentUserSecretKey: Uint8Array;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly targetUser: TrustedUserIdentity;\n};\n\n/**\n * The signed policy commits both the group's public key and the member\n * envelopes that are supposed to wrap its secret. An envelope that unwraps to\n * a different secret means a prior admin (or the server) published a policy\n * whose envelopes do not match its signed key. Rotating repairs the group, but\n * the mismatch is evidence and is recorded before the repair proceeds.\n */\nasync function reportPrincipalEnvelopeMismatch(\n input: BuildAddGroupUserPolicyInput,\n): Promise<void> {\n const state = input.currentPolicy.currentState;\n await input.reportSecurityIncident?.(\n new KeyingVerificationError(\n \"object_mismatch\",\n \"Group member envelope does not unwrap the signed principal key\",\n ),\n {\n evidenceHashes: {\n principalKeyFingerprint: state.keyFingerprint,\n principalStateHash: state.stateHash,\n },\n objectId: state.principalId,\n objectKind: \"principal\",\n operation: \"group.policy.envelope_mismatch\",\n },\n );\n}\n\nfunction hasAdmin(\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n): boolean {\n return projection.some((member) => member.role === \"admin\");\n}\n\nfunction requireExternalAuthority(\n authority: PrincipalPolicyExternalAuthority | undefined,\n): PrincipalPolicyExternalAuthority {\n if (!authority) {\n throw new Error(\"External principal authority could not be verified\");\n }\n return authority;\n}\n\nasync function buildRotatedKeyGroupPolicyRequest(\n input: BuildGroupMembershipMutationInput,\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n users: ReadonlyArray<TrustedUserIdentity>,\n grants = input.currentPolicy.currentGrants,\n): Promise<PutPrincipalPolicyRequest> {\n const groupKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: groupKem.secretKey,\n users,\n });\n return signedGroupPolicyRequest({\n currentPolicy: input.currentPolicy,\n encapsulationPublicKey: bytesToBase64(groupKem.publicKey),\n externalAuthority: isDirectGroupAdmin(\n input.currentPolicy,\n input.signerUserId,\n )\n ? null\n : requireExternalAuthority(input.externalAuthority).currentHead,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n keyFingerprint: await toFingerprint(groupKem.publicKey),\n grants,\n memberEnvelopes,\n payloadCiphertext: input.currentPolicy.currentPayload.ciphertext,\n principalId: input.currentPolicy.currentState.principalId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n\nasync function buildDirectAdminAddGroupUserPolicyRequest(\n input: BuildAddGroupUserPolicyInput,\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n targetKey: string,\n): Promise<PutPrincipalPolicyRequest> {\n const groupSecretKey = await unwrapDek(\n toRecipientEntries(input.currentPolicy.currentMemberEnvelopes.envelopes),\n input.currentUserSecretKey,\n );\n if (\n !(await principalSecretKeyMatchesState(\n groupSecretKey,\n input.currentPolicy.currentState,\n ))\n ) {\n await reportPrincipalEnvelopeMismatch(input);\n return buildRotatedKeyGroupPolicyRequest(input, projection, [\n ...input.currentUsers,\n input.targetUser,\n ]);\n }\n const [targetEnvelope] = await wrapDekForRecipients(groupSecretKey, [\n input.targetUser.encapsulationPublicKey,\n ]);\n\n if (!targetEnvelope) {\n throw new Error(\"Failed to wrap group key for target user\");\n }\n\n const memberEnvelopes = [\n ...input.currentPolicy.currentMemberEnvelopes.envelopes.filter(\n (envelope) => envelope.userId !== targetKey,\n ),\n {\n userId: input.targetUser.userId,\n memberKeyFingerprint: input.targetUser.encapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(targetEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(targetEnvelope.wrappedKey),\n },\n ];\n return signedGroupPolicyRequest({\n currentPolicy: input.currentPolicy,\n encapsulationPublicKey:\n input.currentPolicy.currentState.encapsulationPublicKey,\n externalAuthority: null,\n keyEpoch: input.currentPolicy.currentState.keyEpoch,\n keyFingerprint: input.currentPolicy.currentState.keyFingerprint,\n grants: input.currentPolicy.currentGrants,\n memberEnvelopes,\n payloadCiphertext: input.currentPolicy.currentPayload.ciphertext,\n principalId: input.currentPolicy.currentState.principalId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n\nexport async function buildAddGroupUserPolicyRequest(\n input: BuildAddGroupUserPolicyInput,\n): Promise<PutPrincipalPolicyRequest> {\n input = {\n ...input,\n currentUsers: structuredClone(input.currentUsers),\n currentUserSecretKey: input.currentUserSecretKey.slice(),\n targetUser: structuredClone(input.targetUser),\n };\n try {\n return await withVerifiedGroupMutation(input, async (input) => {\n const targetKey = input.targetUser.userId;\n const currentProjection = input.currentPolicy.currentProjection;\n if (currentProjection.some((member) => member.userId === targetKey)) {\n throw new Error(\"User is already a group member\");\n }\n\n const projection = [\n ...currentProjection,\n await createPrincipalProjectionMember(\n input.targetUser,\n input.isOrganizationAdminsGroup ? \"admin\" : \"member\",\n ),\n ];\n\n return isDirectGroupAdmin(input.currentPolicy, input.signerUserId)\n ? buildDirectAdminAddGroupUserPolicyRequest(\n input,\n projection,\n targetKey,\n )\n : buildRotatedKeyGroupPolicyRequest(input, projection, [\n ...input.currentUsers,\n input.targetUser,\n ]);\n });\n } finally {\n input.currentUserSecretKey.fill(0);\n }\n}\n\nexport async function buildRemoveGroupUserPolicyRequest(\n input: BuildGroupMembershipMutationInput & {\n readonly remainingUsers: ReadonlyArray<TrustedUserIdentity>;\n readonly removedUserId: string;\n },\n): Promise<PutPrincipalPolicyRequest> {\n input = { ...input, remainingUsers: structuredClone(input.remainingUsers) };\n return withVerifiedGroupMutation(input, async (input) => {\n const key = input.removedUserId;\n const projection = input.currentPolicy.currentProjection.filter(\n (member) => member.userId !== key,\n );\n\n if (projection.length === input.currentPolicy.currentProjection.length) {\n throw new Error(\"User is not a group member\");\n }\n\n if (\n hasAdmin(input.currentPolicy.currentProjection) &&\n !hasAdmin(projection)\n ) {\n throw new Error(\"Cannot remove the last group admin\");\n }\n\n return buildRotatedKeyGroupPolicyRequest(\n input,\n projection,\n input.remainingUsers,\n );\n });\n}\n\nexport async function buildGroupAccessSetShrinkPolicyRequest(\n input: BuildGroupMembershipMutationInput & {\n readonly currentUsers: ReadonlyArray<TrustedUserIdentity>;\n readonly revokedContainerId: string;\n },\n): Promise<PutPrincipalPolicyRequest> {\n input = { ...input, currentUsers: structuredClone(input.currentUsers) };\n return withVerifiedGroupMutation(input, async (input) => {\n return buildRotatedKeyGroupPolicyRequest(\n input,\n [...input.currentPolicy.currentProjection],\n input.currentUsers,\n input.currentPolicy.currentGrants.filter(\n (grant) => grant.containerId !== input.revokedContainerId,\n ),\n );\n });\n}\n\n/** Signs a complete successor grant projection without rotating group key material. */\nexport async function buildSetGroupContainerGrantPolicyRequest(\n input: BuildGroupMembershipMutationInput & {\n readonly accessLevel: PrincipalContainerGrantRequest[\"accessLevel\"];\n readonly containerId: string;\n },\n): Promise<PutPrincipalPolicyRequest> {\n return withVerifiedGroupMutation(input, async (input) => {\n const grants = [\n ...input.currentPolicy.currentGrants.filter(\n (grant) => grant.containerId !== input.containerId,\n ),\n { accessLevel: input.accessLevel, containerId: input.containerId },\n ];\n return signedGroupPolicyRequest({\n currentPolicy: input.currentPolicy,\n encapsulationPublicKey:\n input.currentPolicy.currentState.encapsulationPublicKey,\n externalAuthority: isDirectGroupAdmin(\n input.currentPolicy,\n input.signerUserId,\n )\n ? null\n : requireExternalAuthority(input.externalAuthority).currentHead,\n keyEpoch: input.currentPolicy.currentState.keyEpoch,\n keyFingerprint: input.currentPolicy.currentState.keyFingerprint,\n grants,\n memberEnvelopes: input.currentPolicy.currentMemberEnvelopes.envelopes,\n payloadCiphertext: input.currentPolicy.currentPayload.ciphertext,\n principalId: input.currentPolicy.currentState.principalId,\n projection: input.currentPolicy.currentProjection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKey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CAAC,aAAa,EACnB,KAAK,CAAC,YAAY,CACnB;gBACC,CAAC,CAAC,IAAI;gBACN,CAAC,CAAC,wBAAwB,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,WAAW;YACjE,QAAQ,EAAE,KAAK,CAAC,aAAa,CAAC,YAAY,CAAC,QAAQ;YACnD,cAAc,EAAE,KAAK,CAAC,aAAa,CAAC,YAAY,CAAC,cAAc;YAC/D,MAAM;YACN,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,sBAAsB,CAAC,SAAS;YACrE,iBAAiB,EAAE,KAAK,CAAC,aAAa,CAAC,cAAc,CAAC,UAAU;YAChE,WAAW,EAAE,KAAK,CAAC,aAAa,CAAC,YAAY,CAAC,WAAW;YACzD,UAAU,EAAE,KAAK,CAAC,aAAa,CAAC,iBAAiB;YACjD,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YAClC,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n generateKemSeedAndKeyPair,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n toFingerprint,\n unwrapDek,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalContainerGrantRequest,\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport { createPrincipalProjectionMember } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport { principalSecretKeyMatchesState } from \"../../../data/principals/principalKeyValidation\";\nimport {\n rewrapProjectionMemberEnvelopes,\n toRecipientEntries,\n} from \"../../../data/principals/principalPolicyRecipients\";\nimport { signedGroupPolicyRequest } from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { TrustedUserIdentity } from \"../../../data/trustedUserIdentity\";\nimport { isDirectGroupAdmin } from \"./groupMutationAuthorization\";\nimport {\n type BuildGroupMembershipMutationInput,\n withVerifiedGroupMutation,\n} from \"./groupPolicyMutationEvidence\";\n\ntype BuildAddGroupUserPolicyInput = BuildGroupMembershipMutationInput & {\n readonly currentUsers: ReadonlyArray<TrustedUserIdentity>;\n readonly currentUserSecretKey: Uint8Array;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly targetUser: TrustedUserIdentity;\n};\n\n/**\n * The signed policy commits both the group's public key and the member\n * envelopes that are supposed to wrap its secret. An envelope that unwraps to\n * a different secret means a prior admin (or the server) published a policy\n * whose envelopes do not match its signed key. Rotating repairs the group, but\n * the mismatch is evidence and is recorded before the repair proceeds.\n */\nasync function reportPrincipalEnvelopeMismatch(\n input: BuildAddGroupUserPolicyInput,\n): Promise<void> {\n const state = input.currentPolicy.currentState;\n await input.reportSecurityIncident?.(\n new KeyingVerificationError(\n \"object_mismatch\",\n \"Group member envelope does not unwrap the signed principal key\",\n ),\n {\n evidenceHashes: {\n principalKeyFingerprint: state.keyFingerprint,\n principalStateHash: state.stateHash,\n },\n objectId: state.principalId,\n objectKind: \"principal\",\n operation: \"group.policy.envelope_mismatch\",\n },\n );\n}\n\nfunction hasAdmin(\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n): boolean {\n return projection.some((member) => member.role === \"admin\");\n}\n\nfunction requireExternalAuthority(\n authority: PrincipalPolicyExternalAuthority | undefined,\n): PrincipalPolicyExternalAuthority {\n if (!authority) {\n throw new Error(\"External principal authority could not be verified\");\n }\n return authority;\n}\n\nasync function buildRotatedKeyGroupPolicyRequest(\n input: BuildGroupMembershipMutationInput,\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n users: ReadonlyArray<TrustedUserIdentity>,\n grants = input.currentPolicy.currentGrants,\n): Promise<PutPrincipalPolicyRequest> {\n const groupKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: groupKem.secretKey,\n users,\n });\n return signedGroupPolicyRequest({\n currentPolicy: input.currentPolicy,\n encapsulationPublicKey: bytesToBase64(groupKem.publicKey),\n externalAuthority: isDirectGroupAdmin(\n input.currentPolicy,\n input.signerUserId,\n )\n ? null\n : requireExternalAuthority(input.externalAuthority).currentHead,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n keyFingerprint: await toFingerprint(groupKem.publicKey),\n grants,\n memberEnvelopes,\n payloadCiphertext: input.currentPolicy.currentPayload.ciphertext,\n principalId: input.currentPolicy.currentState.principalId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n\nasync function buildDirectAdminAddGroupUserPolicyRequest(\n input: BuildAddGroupUserPolicyInput,\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n targetKey: string,\n): Promise<PutPrincipalPolicyRequest> {\n const groupSecretKey = await unwrapDek(\n toRecipientEntries(input.currentPolicy.currentMemberEnvelopes.envelopes),\n input.currentUserSecretKey,\n );\n if (\n !(await principalSecretKeyMatchesState(\n groupSecretKey,\n input.currentPolicy.currentState,\n ))\n ) {\n await reportPrincipalEnvelopeMismatch(input);\n return buildRotatedKeyGroupPolicyRequest(input, projection, [\n ...input.currentUsers,\n input.targetUser,\n ]);\n }\n const [targetEnvelope] = await wrapDekForRecipients(groupSecretKey, [\n input.targetUser.encapsulationPublicKey,\n ]);\n\n if (!targetEnvelope) {\n throw new Error(\"Failed to wrap group key for target user\");\n }\n\n const memberEnvelopes = [\n ...input.currentPolicy.currentMemberEnvelopes.envelopes.filter(\n (envelope) => envelope.userId !== targetKey,\n ),\n {\n userId: input.targetUser.userId,\n memberKeyFingerprint: input.targetUser.encapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(targetEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(targetEnvelope.wrappedKey),\n },\n ];\n return signedGroupPolicyRequest({\n currentPolicy: input.currentPolicy,\n encapsulationPublicKey:\n input.currentPolicy.currentState.encapsulationPublicKey,\n externalAuthority: null,\n keyEpoch: input.currentPolicy.currentState.keyEpoch,\n keyFingerprint: input.currentPolicy.currentState.keyFingerprint,\n grants: input.currentPolicy.currentGrants,\n memberEnvelopes,\n payloadCiphertext: input.currentPolicy.currentPayload.ciphertext,\n principalId: input.currentPolicy.currentState.principalId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n\nexport async function buildAddGroupUserPolicyRequest(\n input: BuildAddGroupUserPolicyInput,\n): Promise<PutPrincipalPolicyRequest> {\n input = {\n ...input,\n currentUsers: structuredClone(input.currentUsers),\n currentUserSecretKey: input.currentUserSecretKey.slice(),\n targetUser: structuredClone(input.targetUser),\n };\n try {\n return await withVerifiedGroupMutation(input, async (input) => {\n const targetKey = input.targetUser.userId;\n const currentProjection = input.currentPolicy.currentProjection;\n if (currentProjection.some((member) => member.userId === targetKey)) {\n throw new Error(\"User is already a group member\");\n }\n\n const projection = [\n ...currentProjection,\n await createPrincipalProjectionMember(\n input.targetUser,\n input.isOrganizationAdminsGroup ? \"admin\" : \"member\",\n ),\n ];\n\n return isDirectGroupAdmin(input.currentPolicy, input.signerUserId)\n ? buildDirectAdminAddGroupUserPolicyRequest(\n input,\n projection,\n targetKey,\n )\n : buildRotatedKeyGroupPolicyRequest(input, projection, [\n ...input.currentUsers,\n input.targetUser,\n ]);\n });\n } finally {\n input.currentUserSecretKey.fill(0);\n }\n}\n\nexport async function buildRemoveGroupUserPolicyRequest(\n input: BuildGroupMembershipMutationInput & {\n readonly remainingUsers: ReadonlyArray<TrustedUserIdentity>;\n readonly removedUserId: string;\n },\n): Promise<PutPrincipalPolicyRequest> {\n input = { ...input, remainingUsers: structuredClone(input.remainingUsers) };\n return withVerifiedGroupMutation(input, async (input) => {\n const key = input.removedUserId;\n const projection = input.currentPolicy.currentProjection.filter(\n (member) => member.userId !== key,\n );\n\n if (projection.length === input.currentPolicy.currentProjection.length) {\n throw new Error(\"User is not a group member\");\n }\n\n if (\n hasAdmin(input.currentPolicy.currentProjection) &&\n !hasAdmin(projection)\n ) {\n throw new Error(\"Cannot remove the last group admin\");\n }\n\n return buildRotatedKeyGroupPolicyRequest(\n input,\n projection,\n input.remainingUsers,\n );\n });\n}\n\nexport async function buildGroupAccessSetShrinkPolicyRequest(\n input: BuildGroupMembershipMutationInput & {\n readonly currentUsers: ReadonlyArray<TrustedUserIdentity>;\n readonly revokedContainerId: string;\n },\n): Promise<PutPrincipalPolicyRequest> {\n input = { ...input, currentUsers: structuredClone(input.currentUsers) };\n return withVerifiedGroupMutation(input, async (input) => {\n return buildRotatedKeyGroupPolicyRequest(\n input,\n [...input.currentPolicy.currentProjection],\n input.currentUsers,\n input.currentPolicy.currentGrants.filter(\n (grant) => grant.containerId !== input.revokedContainerId,\n ),\n );\n });\n}\n\n/** Signs a complete successor grant projection without rotating group key material. */\nexport async function buildSetGroupContainerGrantPolicyRequest(\n input: BuildGroupMembershipMutationInput & {\n readonly accessLevel: PrincipalContainerGrantRequest[\"accessLevel\"];\n readonly containerId: string;\n },\n): Promise<PutPrincipalPolicyRequest> {\n return withVerifiedGroupMutation(input, async (input) => {\n const grants = [\n ...input.currentPolicy.currentGrants.filter(\n (grant) => grant.containerId !== input.containerId,\n ),\n { accessLevel: input.accessLevel, containerId: input.containerId },\n ];\n return signedGroupPolicyRequest({\n currentPolicy: input.currentPolicy,\n encapsulationPublicKey:\n input.currentPolicy.currentState.encapsulationPublicKey,\n externalAuthority: isDirectGroupAdmin(\n input.currentPolicy,\n input.signerUserId,\n )\n ? null\n : requireExternalAuthority(input.externalAuthority).currentHead,\n keyEpoch: input.currentPolicy.currentState.keyEpoch,\n keyFingerprint: input.currentPolicy.currentState.keyFingerprint,\n grants,\n memberEnvelopes: input.currentPolicy.currentMemberEnvelopes.envelopes,\n payloadCiphertext: input.currentPolicy.currentPayload.ciphertext,\n principalId: input.currentPolicy.currentState.principalId,\n projection: input.currentPolicy.currentProjection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n });\n}\n"]}
@@ -1,13 +1,13 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
2
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
3
  import { principalPolicyReferenceFromBundle } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
4
+ import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "../../../data/principals/organizationGroupDirectoryRequest.js";
4
5
  import { buildInitialGroupPolicyRequest, canonicalGroupNameKey, } from "../../../data/principals/principalPolicyRequest.js";
5
6
  import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
6
7
  import { readDirectoryGroupName } from "../groupNames/groupNameUniqueness.js";
7
8
  import { acknowledgeInitialGroupPolicy } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
8
9
  import { groupPolicyMutationHead } from "../groupPolicy/groupPolicyMutationHead.js";
9
10
  import { projectionUserIds, resolveRequiredUserIdentities, } from "../trustedOrganizationUsers.js";
10
- import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "./organizationGroupDirectory.js";
11
11
  /** Create from bounded current evidence and publish its genuine genesis with the directory. */
12
12
  export async function createCurrentOrganizationGroup(input) {
13
13
  const { context } = input;
@@ -1 +1 @@
1
- {"version":3,"file":"createCurrentOrganizationGroup.js","sourceRoot":"","sources":["createCurrentOrganizationGroup.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AAC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AA0B,EAAE,KAAK,CAAC,0BAA0B;YAC5D,OAAO,EAAE,iBAAiB,CAAC,eAAe,CAAC;SAC5C,CAAC;KACH,CAAC,CAAC;IACL,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,uBAAuB,CAC1D,KAAK,CAAC,cAAc,EACpB,EAAE,GAAG,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,CACxD,CAAC;IACF,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAC3D,2EAA2E;IAC3E,mEAAmE;IACnE,MAAM,6BAA6B,CAAC;QAClC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,OAAO;QACP,QAAQ,EAAE,MAAM,CAAC,KAAK;QACtB,SAAS,EAAE,IAAI,CAAC,SAAS;KAC1B,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,kBAAkB,CAAC;QAC/B,OAAO,EAAE,OAAO,CAAC,kBAAkB;QACnC,QAAQ,EAAE;YACR,IAAI;YACJ,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,SAAS;YACjC,kBAAkB,EAAE,EAAE;SACvB;QACD,mBAAmB;QACnB,oBAAoB,EAAE,MAAM,CAAC,kBAAkB;KAChD,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,OAAO,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC;AAC7E,CAAC","sourcesContent":["import type { EncapsulationKeyPair, SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n buildInitialGroupPolicyRequest,\n canonicalGroupNameKey,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { createGroupMetadataAccess } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { readDirectoryGroupName } from \"../groupNames/groupNameUniqueness\";\nimport { acknowledgeInitialGroupPolicy } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport type { CurrentOrganizationMutationContext } from \"../principalMutations/runtimeCurrentOrganizationMutation\";\nimport type { OrganizationGroupSummary } from \"../readModel\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\n\n/** Create from bounded current evidence and publish its genuine genesis with the directory. */\nexport async function createCurrentOrganizationGroup(input: {\n readonly apiClient: Pick<\n OrganizationPrincipalPolicyApi,\n \"createOrganizationGroup\"\n >;\n readonly context: CurrentOrganizationMutationContext;\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly execSql: ExecSql;\n readonly metadataAccess: ReturnType<typeof createGroupMetadataAccess>;\n readonly name: string;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<OrganizationGroupSummary> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const nameKey = canonicalGroupNameKey(input.name);\n // Each current recovery is queued by organization. Retain verified heads one\n // at a time so the walk stays bounded without collecting full group histories.\n for (const head of context.descriptor.groupHeads) {\n const group = await context.readGroup(head.principalId);\n const stillCurrent = () => context.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, context.descriptor);\n const name = await readDirectoryGroupName(\n { ...input, readEncryptedName: input.metadataAccess.readName },\n group.current,\n );\n // Remember independently verified heads even if uniqueness or dispatch\n // later fails; these are observed policies, never speculative successors.\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n organizationId: input.organizationId,\n access: [],\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n if (name !== null && canonicalGroupNameKey(name) === nameKey)\n throw new Error(\n \"Another signed group in this organization already carries this name\",\n );\n }\n const request = await buildInitialGroupPolicyRequest({\n ...input,\n groupId: crypto.randomUUID(),\n includeSignerAsAdmin: false,\n externalAuthority: {\n ...principalPolicyReferenceFromBundle(context.admins.current),\n principalType: \"group\",\n },\n metadataKey: await input.metadataAccess.loadEncryptionKey(),\n });\n const head = await groupPolicyMutationHead(request.initialGroupPolicy);\n const adminProjection = context.admins.policy.projection;\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n ...input,\n currentPolicy: context.directory.current,\n descriptor: context.descriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: context.descriptor,\n nextHead: head,\n }),\n adminProjection,\n adminUsers: await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n }),\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n if (!stored) throw new Error(\"Group could not be created\");\n // Genesis really has one signed state. Its acknowledgement is the summary;\n // the retained current is rebuilt from the exact authored request.\n await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request,\n response: stored.group,\n stateHash: head.stateHash,\n });\n await context.retainCreatedGroup({\n request: request.initialGroupPolicy,\n response: {\n head,\n createdAt: stored.group.createdAt,\n containerMutations: [],\n },\n organizationRequest,\n organizationResponse: stored.organizationPolicy,\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n return { ...stored.group, name: input.name.trim(), nameUnreadable: false };\n}\n"]}
1
+ {"version":3,"file":"createCurrentOrganizationGroup.js","sourceRoot":"","sources":["createCurrentOrganizationGroup.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,4DAA4D,CAAC;AACpE,OAAO,EACL,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,iDAAiD,CAAC;AAKzD,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAC3E,OAAO,EAAE,6BAA6B,EAAE,MAAM,mDAAmD,CAAC;AAElG,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AAGjF,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAErC,+FAA+F;AAC/F,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAiBpD;IACC,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC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ACH,MAAM,OAAO,CAAC,kBAAkB,CAAC;QAC/B,OAAO,EAAE,OAAO,CAAC,kBAAkB;QACnC,QAAQ,EAAE;YACR,IAAI;YACJ,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,SAAS;YACjC,kBAAkB,EAAE,EAAE;SACvB;QACD,mBAAmB;QACnB,oBAAoB,EAAE,MAAM,CAAC,kBAAkB;KAChD,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,OAAO,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC;AAC7E,CAAC","sourcesContent":["import type { EncapsulationKeyPair, SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport {\n buildInitialGroupPolicyRequest,\n canonicalGroupNameKey,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { createGroupMetadataAccess } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { readDirectoryGroupName } from \"../groupNames/groupNameUniqueness\";\nimport { acknowledgeInitialGroupPolicy } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport type { CurrentOrganizationMutationContext } from \"../principalMutations/runtimeCurrentOrganizationMutation\";\nimport type { OrganizationGroupSummary } from \"../readModel\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\n/** Create from bounded current evidence and publish its genuine genesis with the directory. */\nexport async function createCurrentOrganizationGroup(input: {\n readonly apiClient: Pick<\n OrganizationPrincipalPolicyApi,\n \"createOrganizationGroup\"\n >;\n readonly context: CurrentOrganizationMutationContext;\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly execSql: ExecSql;\n readonly metadataAccess: ReturnType<typeof createGroupMetadataAccess>;\n readonly name: string;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<OrganizationGroupSummary> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const nameKey = canonicalGroupNameKey(input.name);\n // Each current recovery is queued by organization. Retain verified heads one\n // at a time so the walk stays bounded without collecting full group histories.\n for (const head of context.descriptor.groupHeads) {\n const group = await context.readGroup(head.principalId);\n const stillCurrent = () => context.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, context.descriptor);\n const name = await readDirectoryGroupName(\n { ...input, readEncryptedName: input.metadataAccess.readName },\n group.current,\n );\n // Remember independently verified heads even if uniqueness or dispatch\n // later fails; these are observed policies, never speculative successors.\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n organizationId: input.organizationId,\n access: [],\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n if (name !== null && canonicalGroupNameKey(name) === nameKey)\n throw new Error(\n \"Another signed group in this organization already carries this name\",\n );\n }\n const request = await buildInitialGroupPolicyRequest({\n ...input,\n groupId: crypto.randomUUID(),\n includeSignerAsAdmin: false,\n externalAuthority: {\n ...principalPolicyReferenceFromBundle(context.admins.current),\n principalType: \"group\",\n },\n metadataKey: await input.metadataAccess.loadEncryptionKey(),\n });\n const head = await groupPolicyMutationHead(request.initialGroupPolicy);\n const adminProjection = context.admins.policy.projection;\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n ...input,\n currentPolicy: context.directory.current,\n descriptor: context.descriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: context.descriptor,\n nextHead: head,\n }),\n adminProjection,\n adminUsers: await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n }),\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n if (!stored) throw new Error(\"Group could not be created\");\n // Genesis really has one signed state. Its acknowledgement is the summary;\n // the retained current is rebuilt from the exact authored request.\n await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request,\n response: stored.group,\n stateHash: head.stateHash,\n });\n await context.retainCreatedGroup({\n request: request.initialGroupPolicy,\n response: {\n head,\n createdAt: stored.group.createdAt,\n containerMutations: [],\n },\n organizationRequest,\n organizationResponse: stored.organizationPolicy,\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n return { ...stored.group, name: input.name.trim(), nameUnreadable: false };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
+ import { buildOrganizationGroupDirectoryPolicyRequest } from "../../../data/principals/organizationGroupDirectoryRequest.js";
2
3
  import { projectionUserIds, resolveRequiredUserIdentities, } from "../trustedOrganizationUsers.js";
3
- import { buildOrganizationGroupDirectoryPolicyRequest, removeOrganizationGroupHead, } from "./organizationGroupDirectory.js";
4
+ import { removeOrganizationGroupHead } from "./organizationGroupDirectory.js";
4
5
  /** Delete against a verified directory without loading the removed group's history. */
5
6
  export async function deleteCurrentOrganizationGroup(input) {
6
7
  const { context } = input;
@@ -1 +1 @@
1
- {"version":3,"file":"deleteCurrentOrganizationGroup.js","sourceRoot":"","sources":["deleteCurrentOrganizationGroup.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAGvG,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,4CAA4C,EAC5C,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAEtC,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAYpD;IACC,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC;IACzD,MAAM,OAAO,GAAG,MAAM,4CAA4C,CAAC;QACjE,GAAG,KAAK;QACR,eAAe;QACf,UAAU,EAAE,MAAM,6BAA6B,CAAC;YAC9C,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;YAC5D,OAAO,EAAE,iBAAiB,CAAC,eAAe,CAAC;SAC5C,CAAC;QACF,aAAa,EAAE,OAAO,CAAC,SAAS,CAAC,OAAO;QACxC,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,UAAU,EAAE,2BAA2B,CAAC;YACtC,UAAU,EAAE,OAAO,CAAC,UAAU;YAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC;KACH,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,uBAAuB,CAC1D,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,OAAO,EACb,EAAE,kBAAkB,EAAE,OAAO,EAAE,CAChC,CAAC;IACF,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAC3D,IACE,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC9C,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO;QAEhC,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,MAAM,OAAO,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,CAAC,kBAAkB,CAAC,CAAC;IAClE,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentOrganizationMutationContext } from \"../principalMutations/runtimeCurrentOrganizationMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport type { deleteOrganizationGroup } from \"./deleteOrganizationGroup\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n removeOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\n\n/** Delete against a verified directory without loading the removed group's history. */\nexport async function deleteCurrentOrganizationGroup(input: {\n readonly apiClient: Pick<\n Parameters<typeof deleteOrganizationGroup>[0][\"apiClient\"],\n \"deleteOrganizationGroup\"\n >;\n readonly context: CurrentOrganizationMutationContext;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}) {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const adminProjection = context.admins.policy.projection;\n const request = await buildOrganizationGroupDirectoryPolicyRequest({\n ...input,\n adminProjection,\n adminUsers: await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n }),\n currentPolicy: context.directory.current,\n descriptor: context.descriptor,\n groupHeads: removeOrganizationGroupHead({\n descriptor: context.descriptor,\n groupId: input.groupId,\n }),\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n const stored = await input.apiClient.deleteOrganizationGroup(\n input.organizationId,\n input.groupId,\n { organizationPolicy: request },\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n if (!stored) throw new Error(\"Group could not be deleted\");\n if (\n stored.organizationId !== input.organizationId ||\n stored.groupId !== input.groupId\n )\n throw new Error(\"Group deletion response target mismatch\");\n await context.retainDirectory(request, stored.organizationPolicy);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return stored;\n}\n"]}
1
+ {"version":3,"file":"deleteCurrentOrganizationGroup.js","sourceRoot":"","sources":["deleteCurrentOrganizationGroup.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4CAA4C,EAAE,MAAM,4DAA4D,CAAC;AAG1H,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAE3E,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAYpD;IACC,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC;IACzD,MAAM,OAAO,GAAG,MAAM,4CAA4C,CAAC;QACjE,GAAG,KAAK;QACR,eAAe;QACf,UAAU,EAAE,MAAM,6BAA6B,CAAC;YAC9C,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;YAC5D,OAAO,EAAE,iBAAiB,CAAC,eAAe,CAAC;SAC5C,CAAC;QACF,aAAa,EAAE,OAAO,CAAC,SAAS,CAAC,OAAO;QACxC,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,UAAU,EAAE,2BAA2B,CAAC;YACtC,UAAU,EAAE,OAAO,CAAC,UAAU;YAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC;KACH,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,uBAAuB,CAC1D,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,OAAO,EACb,EAAE,kBAAkB,EAAE,OAAO,EAAE,CAChC,CAAC;IACF,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAC3D,IACE,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC9C,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO;QAEhC,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,MAAM,OAAO,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,CAAC,kBAAkB,CAAC,CAAC;IAClE,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildOrganizationGroupDirectoryPolicyRequest } from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentOrganizationMutationContext } from \"../principalMutations/runtimeCurrentOrganizationMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport type { deleteOrganizationGroup } from \"./deleteOrganizationGroup\";\nimport { removeOrganizationGroupHead } from \"./organizationGroupDirectory\";\n\n/** Delete against a verified directory without loading the removed group's history. */\nexport async function deleteCurrentOrganizationGroup(input: {\n readonly apiClient: Pick<\n Parameters<typeof deleteOrganizationGroup>[0][\"apiClient\"],\n \"deleteOrganizationGroup\"\n >;\n readonly context: CurrentOrganizationMutationContext;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}) {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const adminProjection = context.admins.policy.projection;\n const request = await buildOrganizationGroupDirectoryPolicyRequest({\n ...input,\n adminProjection,\n adminUsers: await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n }),\n currentPolicy: context.directory.current,\n descriptor: context.descriptor,\n groupHeads: removeOrganizationGroupHead({\n descriptor: context.descriptor,\n groupId: input.groupId,\n }),\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n const stored = await input.apiClient.deleteOrganizationGroup(\n input.organizationId,\n input.groupId,\n { organizationPolicy: request },\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n if (!stored) throw new Error(\"Group could not be deleted\");\n if (\n stored.organizationId !== input.organizationId ||\n stored.groupId !== input.groupId\n )\n throw new Error(\"Group deletion response target mismatch\");\n await context.retainDirectory(request, stored.organizationPolicy);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return stored;\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
2
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
3
+ import { buildOrganizationGroupDirectoryPolicyRequest } from "../../../data/principals/organizationGroupDirectoryRequest.js";
3
4
  import { loadOrganizationExternalAdminPolicy } from "../../principals/externalAdminPolicy.js";
4
5
  import { acknowledgeGroupPolicyBundle } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
5
6
  import { groupPolicyMutationHead } from "../groupPolicy/groupPolicyMutationHead.js";
6
7
  import { projectionUserIds, resolveRequiredUserIdentities, } from "../trustedOrganizationUsers.js";
7
- import { buildOrganizationGroupDirectoryPolicyRequest, removeOrganizationGroupHead, } from "./organizationGroupDirectory.js";
8
+ import { removeOrganizationGroupHead } from "./organizationGroupDirectory.js";
8
9
  export async function deleteOrganizationGroup(input) {
9
10
  const stillCurrent = input.stillCurrent;
10
11
  assertProjectionVerificationCurrent(stillCurrent);
@@ -1 +1 @@
1
- {"version":3,"file":"deleteOrganizationGroup.js","sourceRoot":"","sources":["deleteOrganizationGroup.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAG5H,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AAEjG,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,4CAA4C,EAC5C,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAEtC,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAgB7C;IACC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IACxC,mCAAmC,CAAC,YAAY,CAAC,CAAC;I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,CAAC,SAAS,CAAC,uBAAuB,CAC1D,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,OAAO,EACb,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,CAC5C,CAAC;IACF,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAChD,CAAC;IACD,IACE,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC9C,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,EAChC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,4BAA4B,CAAC;QACtD,aAAa,EAAE,mBAAmB,CAAC,MAAM;QACzC,YAAY,EAAE,MAAM,uBAAuB,CAAC,mBAAmB,CAAC;QAChE,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,gDAAgD,CAAC;QACjD,OAAO,EAAE,CAAC,YAAY,CAAC;QACvB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY;KACb,CAAC,CAAC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { DeleteOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport type { DeleteOrganizationGroupResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { acknowledgeGroupPolicyBundle } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n removeOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\n\nexport async function deleteOrganizationGroup(input: {\n readonly apiClient: PrincipalPolicyReadApi & {\n deleteOrganizationGroup: (\n organizationId: string,\n groupId: string,\n request: DeleteOrganizationGroupRequest,\n ) => Promise<DeleteOrganizationGroupResponse | null>;\n };\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<DeleteOrganizationGroupResponse> {\n const stillCurrent = input.stillCurrent;\n assertProjectionVerificationCurrent(stillCurrent);\n await input.apiClient.recoverPendingPrincipalMutation?.(input.organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n const externalAdminPolicy = await loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.apiClient,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (!externalAdminPolicy?.signerUserIds.includes(input.signerUserId)) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const adminProjection = externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: externalAdminPolicy.bundle,\n descriptor: externalAdminPolicy.descriptor,\n groupHeads: removeOrganizationGroupHead({\n descriptor: externalAdminPolicy.descriptor,\n groupId: input.groupId,\n }),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const stored = await input.apiClient.deleteOrganizationGroup(\n input.organizationId,\n input.groupId,\n { organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be deleted\");\n }\n if (\n stored.organizationId !== input.organizationId ||\n stored.groupId !== input.groupId\n ) {\n throw new Error(\"Group deletion response target mismatch\");\n }\n const organization = await acknowledgeGroupPolicyBundle({\n currentPolicy: externalAdminPolicy.bundle,\n expectedHead: await groupPolicyMutationHead(organizationRequest),\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [organization],\n organizationId: input.organizationId,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return stored;\n}\n"]}
1
+ {"version":3,"file":"deleteOrganizationGroup.js","sourceRoot":"","sources":["deleteOrganizationGroup.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,4CAA4C,EAAE,MAAM,4DAA4D,CAAC;AAG1H,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AAEjG,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EACL,iBAAiB,EACjB,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K,CAAC,OAAO;SACvB,CAAC;QACF,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IACL,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,uBAAuB,CAC1D,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,OAAO,EACb,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,CAC5C,CAAC;IACF,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAChD,CAAC;IACD,IACE,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC9C,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,EAChC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,4BAA4B,CAAC;QACtD,aAAa,EAAE,mBAAmB,CAAC,MAAM;QACzC,YAAY,EAAE,MAAM,uBAAuB,CAAC,mBAAmB,CAAC;QAChE,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,gDAAgD,CAAC;QACjD,OAAO,EAAE,CAAC,YAAY,CAAC;QACvB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY;KACb,CAAC,CAAC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { DeleteOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport type { DeleteOrganizationGroupResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { buildOrganizationGroupDirectoryPolicyRequest } from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { acknowledgeGroupPolicyBundle } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport { removeOrganizationGroupHead } from \"./organizationGroupDirectory\";\n\nexport async function deleteOrganizationGroup(input: {\n readonly apiClient: PrincipalPolicyReadApi & {\n deleteOrganizationGroup: (\n organizationId: string,\n groupId: string,\n request: DeleteOrganizationGroupRequest,\n ) => Promise<DeleteOrganizationGroupResponse | null>;\n };\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<DeleteOrganizationGroupResponse> {\n const stillCurrent = input.stillCurrent;\n assertProjectionVerificationCurrent(stillCurrent);\n await input.apiClient.recoverPendingPrincipalMutation?.(input.organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n const externalAdminPolicy = await loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.apiClient,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (!externalAdminPolicy?.signerUserIds.includes(input.signerUserId)) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const adminProjection = externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: externalAdminPolicy.bundle,\n descriptor: externalAdminPolicy.descriptor,\n groupHeads: removeOrganizationGroupHead({\n descriptor: externalAdminPolicy.descriptor,\n groupId: input.groupId,\n }),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const stored = await input.apiClient.deleteOrganizationGroup(\n input.organizationId,\n input.groupId,\n { organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be deleted\");\n }\n if (\n stored.organizationId !== input.organizationId ||\n stored.groupId !== input.groupId\n ) {\n throw new Error(\"Group deletion response target mismatch\");\n }\n const organization = await acknowledgeGroupPolicyBundle({\n currentPolicy: externalAdminPolicy.bundle,\n expectedHead: await groupPolicyMutationHead(organizationRequest),\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [organization],\n organizationId: input.organizationId,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return stored;\n}\n"]}
@@ -1,26 +1,11 @@
1
- import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, normalizePrincipalProjectionMembers, signPrincipalState, toFingerprint, } from "../../../internal/crypto/index.js";
2
- import { bytesToBase64 } from "../../../internal/encoding/index.js";
3
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
2
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
- import { encodeOrganizationAuthorityDescriptor, normalizeOrganizationGroupHeads, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
3
+ import { normalizeOrganizationGroupHeads, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
4
+ import { buildOrganizationGroupDirectoryPolicyRequest, organizationGroupHead, } from "../../../data/principals/organizationGroupDirectoryRequest.js";
6
5
  import { assertGroupNameUniqueInDirectory } from "../groupNames/groupNameUniqueness.js";
7
6
  import { acknowledgeGroupPolicyBundle, acknowledgeInitialGroupPolicy, } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
8
7
  import { groupPolicyMutationHead } from "../groupPolicy/groupPolicyMutationHead.js";
9
- import { rewrapProjectionMemberEnvelopes } from "../principalPolicy/principalPolicyRecipients.js";
10
8
  import { projectionUserIds, resolveRequiredUserIdentities, } from "../trustedOrganizationUsers.js";
11
- function organizationGroupHead(head) {
12
- if (head.principalType !== "group") {
13
- throw new Error("Organization directory can contain only group heads");
14
- }
15
- return { ...head, principalType: "group" };
16
- }
17
- export function replaceOrganizationGroupHead(input) {
18
- const nextHead = organizationGroupHead(input.nextHead);
19
- return normalizeOrganizationGroupHeads([
20
- ...input.descriptor.groupHeads.filter((head) => head.principalId !== nextHead.principalId),
21
- nextHead,
22
- ]);
23
- }
24
9
  export function removeOrganizationGroupHead(input) {
25
10
  if (input.groupId === input.descriptor.adminGroupId ||
26
11
  input.groupId === input.descriptor.memberGroupId) {
@@ -32,52 +17,6 @@ export function removeOrganizationGroupHead(input) {
32
17
  }
33
18
  return normalizeOrganizationGroupHeads(groupHeads);
34
19
  }
35
- export async function buildOrganizationGroupDirectoryPolicyRequest(input) {
36
- const projection = normalizePrincipalProjectionMembers(input.adminProjection);
37
- if (projection.length === 0 ||
38
- projection.some((member) => member.role !== "admin")) {
39
- throw new Error("Organization policy must mirror the Admins projection");
40
- }
41
- const organizationKem = generateKemSeedAndKeyPair();
42
- const memberEnvelopes = await rewrapProjectionMemberEnvelopes({
43
- projection,
44
- secretKey: organizationKem.secretKey,
45
- users: input.adminUsers,
46
- });
47
- const payloadCiphertext = encodeOrganizationAuthorityDescriptor({
48
- ...input.descriptor,
49
- groupHeads: input.groupHeads,
50
- });
51
- const state = await signPrincipalState(await buildPrincipalStateSigningInput({
52
- principalType: "organization",
53
- principalId: input.descriptor.organizationId,
54
- version: input.currentPolicy.currentState.version + 1,
55
- prevStateHash: input.currentPolicy.currentState.stateHash,
56
- keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,
57
- encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
58
- keyFingerprint: await toFingerprint(organizationKem.publicKey),
59
- members: projection.map((member) => ({ userId: member.userId })),
60
- memberEnvelopes,
61
- projection,
62
- grants: [],
63
- payloadCiphertext,
64
- externalAuthority: null,
65
- signedAt: new Date().toISOString(),
66
- signerUserId: input.signerUserId,
67
- signerUserKeyFingerprint: input.signingFingerprint,
68
- }), input.signingKeyPair.signingPrivateKey);
69
- return {
70
- encryptedPayload: {
71
- cipherSuite: "aes-256-gcm",
72
- ciphertext: payloadCiphertext,
73
- ciphertextHash: state.payloadCiphertextHash,
74
- },
75
- grants: [],
76
- memberEnvelopes,
77
- projection,
78
- state,
79
- };
80
- }
81
20
  export async function commitCreatedGroupToDirectory(input) {
82
21
  assertProjectionVerificationCurrent(input.stillCurrent);
83
22
  // Signed group names are unique per organization; refuse a collision before
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupDirectory.js","sourceRoot":"","sources":["organizationGroupDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,mCAAmC,EAGnC,kBAAkB,EAClB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AASpD,OAAO,EAAE,mC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AAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,6BAA6B,CAAC;QACvD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,MAAM,CAAC,KAAK;QACtB,SAAS,EAAE,YAAY,CAAC,SAAS;KAClC,CAAC,CAAC;IACH,MAAM,YAAY,GAAG,MAAM,4BAA4B,CAAC;QACtD,aAAa,EAAE,KAAK,CAAC,mBAAmB,CAAC,MAAM;QAC/C,YAAY,EAAE,MAAM,uBAAuB,CAAC,mBAAmB,CAAC;QAChE,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,gDAAgD,CAAC;QACjD,OAAO,EAAE;YACP,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE;YAC5D,YAAY;SACb;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type {\n buildInitialGroupPolicyRequest,\n GroupPolicyNameReader,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport type { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { assertGroupNameUniqueInDirectory } from \"../groupNames/groupNameUniqueness\";\nimport {\n acknowledgeGroupPolicyBundle,\n acknowledgeInitialGroupPolicy,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport { rewrapProjectionMemberEnvelopes } from \"../principalPolicy/principalPolicyRecipients\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nfunction organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\nexport function removeOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupId: string;\n}): OrganizationGroupHead[] {\n if (\n input.groupId === input.descriptor.adminGroupId ||\n input.groupId === input.descriptor.memberGroupId\n ) {\n throw new Error(\"Built-in groups cannot be removed from the directory\");\n }\n const groupHeads = input.descriptor.groupHeads.filter(\n (head) => head.principalId !== input.groupId,\n );\n if (groupHeads.length === input.descriptor.groupHeads.length) {\n throw new Error(\"Organization directory does not commit the deleted group\");\n }\n return normalizeOrganizationGroupHeads(groupHeads);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes,\n projection,\n state,\n };\n}\n\nexport async function commitCreatedGroupToDirectory(input: {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly name: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly apiClient: OrganizationPrincipalPolicyApi;\n readonly execSql: ExecSql;\n readonly externalAdminPolicy: NonNullable<\n Awaited<ReturnType<typeof loadOrganizationExternalAdminPolicy>>\n >;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly request: Awaited<ReturnType<typeof buildInitialGroupPolicyRequest>>;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<{\n readonly group: OrganizationGroupSummaryResponse;\n readonly head: ReferencedPrincipalHead;\n}> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Signed group names are unique per organization; refuse a collision before\n // anything reaches the server.\n await assertGroupNameUniqueInDirectory({\n apiClient: input.apiClient,\n descriptor: input.externalAdminPolicy.descriptor,\n execSql: input.execSql,\n externalAuthority: input.externalAdminPolicy.externalAuthority,\n name: input.name,\n readEncryptedName: input.readEncryptedName,\n organizationId: input.organizationId,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n const expectedHead = await groupPolicyMutationHead(\n input.request.initialGroupPolicy,\n );\n const adminProjection =\n input.externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: input.externalAdminPolicy.bundle,\n descriptor: input.externalAdminPolicy.descriptor,\n groupHeads: [\n ...input.externalAdminPolicy.descriptor.groupHeads,\n organizationGroupHead(expectedHead),\n ],\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...input.request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be created\");\n }\n const acknowledged = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request: input.request,\n response: stored.group,\n stateHash: expectedHead.stateHash,\n });\n const organization = await acknowledgeGroupPolicyBundle({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: await groupPolicyMutationHead(organizationRequest),\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [\n { bundle: acknowledged.bundle, policy: acknowledged.policy },\n organization,\n ],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { group: stored.group, head: expectedHead };\n}\n"]}
1
+ {"version":3,"file":"organizationGroupDirectory.js","sourceRoot":"","sources":["organizationGroupDirectory.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAA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O,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,CAC9D,CAAC;IACF,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,6BAA6B,CAAC;QACvD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,MAAM,CAAC,KAAK;QACtB,SAAS,EAAE,YAAY,CAAC,SAAS;KAClC,CAAC,CAAC;IACH,MAAM,YAAY,GAAG,MAAM,4BAA4B,CAAC;QACtD,aAAa,EAAE,KAAK,CAAC,mBAAmB,CAAC,MAAM;QAC/C,YAAY,EAAE,MAAM,uBAAuB,CAAC,mBAAmB,CAAC;QAChE,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,gDAAgD,CAAC;QACjD,OAAO,EAAE;YACP,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE;YAC5D,YAAY;SACb;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type { OrganizationGroupSummaryResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n organizationGroupHead,\n} from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport type {\n buildInitialGroupPolicyRequest,\n GroupPolicyNameReader,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { assertGroupNameUniqueInDirectory } from \"../groupNames/groupNameUniqueness\";\nimport {\n acknowledgeGroupPolicyBundle,\n acknowledgeInitialGroupPolicy,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nexport function removeOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupId: string;\n}): OrganizationGroupHead[] {\n if (\n input.groupId === input.descriptor.adminGroupId ||\n input.groupId === input.descriptor.memberGroupId\n ) {\n throw new Error(\"Built-in groups cannot be removed from the directory\");\n }\n const groupHeads = input.descriptor.groupHeads.filter(\n (head) => head.principalId !== input.groupId,\n );\n if (groupHeads.length === input.descriptor.groupHeads.length) {\n throw new Error(\"Organization directory does not commit the deleted group\");\n }\n return normalizeOrganizationGroupHeads(groupHeads);\n}\n\nexport async function commitCreatedGroupToDirectory(input: {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly name: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly apiClient: OrganizationPrincipalPolicyApi;\n readonly execSql: ExecSql;\n readonly externalAdminPolicy: NonNullable<\n Awaited<ReturnType<typeof loadOrganizationExternalAdminPolicy>>\n >;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly request: Awaited<ReturnType<typeof buildInitialGroupPolicyRequest>>;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<{\n readonly group: OrganizationGroupSummaryResponse;\n readonly head: ReferencedPrincipalHead;\n}> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Signed group names are unique per organization; refuse a collision before\n // anything reaches the server.\n await assertGroupNameUniqueInDirectory({\n apiClient: input.apiClient,\n descriptor: input.externalAdminPolicy.descriptor,\n execSql: input.execSql,\n externalAuthority: input.externalAdminPolicy.externalAuthority,\n name: input.name,\n readEncryptedName: input.readEncryptedName,\n organizationId: input.organizationId,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n const expectedHead = await groupPolicyMutationHead(\n input.request.initialGroupPolicy,\n );\n const adminProjection =\n input.externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: input.externalAdminPolicy.bundle,\n descriptor: input.externalAdminPolicy.descriptor,\n groupHeads: [\n ...input.externalAdminPolicy.descriptor.groupHeads,\n organizationGroupHead(expectedHead),\n ],\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...input.request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be created\");\n }\n const acknowledged = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request: input.request,\n response: stored.group,\n stateHash: expectedHead.stateHash,\n });\n const organization = await acknowledgeGroupPolicyBundle({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: await groupPolicyMutationHead(organizationRequest),\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [\n { bundle: acknowledged.bundle, policy: acknowledged.policy },\n organization,\n ],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { group: stored.group, head: expectedHead };\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  export { createOrganizationGroup } from "../groups/groupCreation.js";
2
+ import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "../../../data/principals/organizationGroupDirectoryRequest.js";
2
3
  import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, } from "../../../data/principals/principalPolicyRequest.js";
3
4
  import { assertGroupMembershipName } from "../groupNames/groupMembershipName.js";
4
5
  import { prepareAuthoredGroupPolicy } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
5
6
  import { cacheGroupPolicy, commitGroupPolicyMutation, loadGroupPolicyMutationContext, } from "../groupPolicy/groupPolicyMutationContext.js";
6
7
  import { groupPolicyMutationHead } from "../groupPolicy/groupPolicyMutationHead.js";
7
8
  import { buildAddGroupUserPolicyRequest, buildGroupAccessSetShrinkPolicyRequest, buildRemoveGroupUserPolicyRequest, buildSetGroupContainerGrantPolicyRequest, } from "../groupPolicy/groupPolicyRequests.js";
8
- import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "../groups/organizationGroupDirectory.js";
9
9
  import { projectionUserIds, resolveRequiredUserIdentities, } from "../trustedOrganizationUsers.js";
10
10
  export { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };
11
11
  function createPolicyMutationCommitGuard(assertCanCommit) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAiBlE,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AAIzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,mDAAmD,CAAC;AAC/F,OAAO,EAEL,gBAAgB,EAChB,yBAAyB,EACzB,8BAA8B,GAE/B,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EACL,8BAA8B,EAC9B,sCAAsC,EACtC,iCAAiC,EACjC,wCAAwC,GACzC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,8BAA8B,EAAE,oCAAoC,EAAE,CAAC;AA8ChF,SAAS,+BAA+B,CACtC,eAAyC;IAEzC,IAAI,CAAC,eAAe;QAAE,OAAO,SAAS,CAAC;IACvC,OAAO,GAAG,EAAE;QACV,eAAe,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,8BAA8B,CAC3C,KAA6C,EAC7C,YAAqC;IAErC,IAAI,CAAC,KAAK,CAAC,yBAAyB;QAAE,OAAO,IAAI,CA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K,CAAC,cAAc;QACpC,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IACH,MAAM,YAAY,GAAG,MAAM,6BAA6B,CAAC;QACvD,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,OAAO,EAAE,iBAAiB,CAAC,aAAa,CAAC,aAAa,CAAC,iBAAiB,CAAC;KAC1E,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,MAAM,sCAAsC,CAAC;QAC3D,GAAG,aAAa;QAChB,YAAY;QACZ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;IACH,OAAO,iCAAiC,CAAC;QACvC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,aAAa,EAAE,aAAa,CAAC,aAAa;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,iBAAiB,EAAE,aAAa,CAAC,iBAAiB;QAClD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;QAC1D,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,aAAa;QACb,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;KAC7D,CAAC,CAAC;AACL,CAAC","sourcesContent":["export { createOrganizationGroup } from \"../groups/groupCreation\";\n\nimport type {\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { GroupPolicyNameReader } from \"../../../data/principals/principalPolicyRequest\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMembershipName } from \"../groupNames/groupMembershipName\";\nimport { prepareAuthoredGroupPolicy } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport {\n type AcknowledgedGroupPolicyBundle,\n cacheGroupPolicy,\n commitGroupPolicyMutation,\n loadGroupPolicyMutationContext,\n type PrincipalPolicyReadWriteApi,\n} from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n buildSetGroupContainerGrantPolicyRequest,\n} from \"../groupPolicy/groupPolicyRequests\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../groups/organizationGroupDirectory\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nexport { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };\n\ninterface PreparedGroupContainerMutations {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /** Sign the descendant rekeys a refused commit named; see `carry` there. */\n readonly carry?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly requests: readonly ContainerMutationRequest[];\n}\n\ntype PrepareGroupContainerMutations = (input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly nextPolicy: VerifiedPrincipalPolicy;\n}) => Promise<\n readonly ContainerMutationRequest[] | PreparedGroupContainerMutations\n>;\n\ninterface CommitAndCacheGroupPolicyMutationInput {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly beforePolicyCommit?:\n | ((head: ReferencedPrincipalHead) => void)\n | undefined;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly policyContext: Awaited<\n ReturnType<typeof loadGroupPolicyMutationContext>\n >;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nfunction createPolicyMutationCommitGuard(\n assertCanCommit: (() => void) | undefined,\n): (() => boolean) | undefined {\n if (!assertCanCommit) return undefined;\n return () => {\n assertCanCommit();\n return true;\n };\n}\n\n/**\n * Plan the container mutations the policy change rematerializes and place their\n * requests on the policy request. A bare request list has nothing to\n * acknowledge or carry; a prepared batch does both.\n */\nasync function prepareGroupContainerMutations(\n input: CommitAndCacheGroupPolicyMutationInput,\n expectedHead: ReferencedPrincipalHead,\n): Promise<Partial<PreparedGroupContainerMutations> | null> {\n if (!input.prepareContainerMutations) return null;\n const prepared = await input.prepareContainerMutations({\n currentPolicy: input.currentPolicy,\n nextPolicy: await prepareAuthoredGroupPolicy({\n currentPolicy: input.currentPolicy,\n expectedHead,\n request: input.request,\n }),\n });\n if (\"requests\" in prepared) {\n input.request.containerMutations = [...prepared.requests];\n return prepared;\n }\n input.request.containerMutations = [...prepared];\n return {};\n}\n\nasync function commitAndCacheGroupPolicyMutation(\n input: CommitAndCacheGroupPolicyMutationInput,\n): Promise<AcknowledgedGroupPolicyBundle> {\n const stillCurrent = createPolicyMutationCommitGuard(input.assertCanCommit);\n const expectedHead = await groupPolicyMutationHead(input.request);\n input.beforePolicyCommit?.(expectedHead);\n const containerMutations = await prepareGroupContainerMutations(\n input,\n expectedHead,\n );\n const nextAdminProjection = input.policyContext.isOrganizationAdminsGroup\n ? input.request.projection\n : input.policyContext.adminPolicyBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(nextAdminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection: nextAdminProjection,\n adminUsers,\n currentPolicy: input.policyContext.organizationPolicyBundle,\n descriptor: input.policyContext.organizationDescriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: input.policyContext.organizationDescriptor,\n nextHead: expectedHead,\n }),\n signerUserId: input.policyContext.signerUserId,\n signingFingerprint: input.policyContext.signingFingerprint,\n signingKeyPair: input.policyContext.signingKeyPair,\n });\n input.assertCanCommit?.();\n const acknowledgedBundle = await commitGroupPolicyMutation({\n apiClient: input.apiClient,\n carryDescendantRekeys: containerMutations?.carry,\n retiredContainerIds: () => containerMutations?.retiredContainerIds ?? [],\n currentPolicy: input.currentPolicy,\n execSql: input.execSql,\n expectedHead,\n groupId: input.groupId,\n organizationId: input.organizationId,\n organizationPolicy: input.policyContext.organizationPolicyBundle,\n organizationRequest,\n request: input.request,\n stillCurrent,\n });\n input.assertCanCommit?.();\n if (containerMutations?.acknowledge) {\n await containerMutations.acknowledge(\n acknowledgedBundle.containerMutations,\n stillCurrent,\n );\n }\n input.assertCanCommit?.();\n await input.afterPolicyCommitBeforeCache?.();\n input.assertCanCommit?.();\n await cacheGroupPolicy({\n acknowledgedMemberEnvelopes: acknowledgedBundle.currentMemberEnvelopes,\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedCurrentHead: expectedHead,\n externalAuthority: input.externalAuthority,\n groupId: input.groupId,\n localPolicyCheckpoint: {\n principalId: expectedHead.principalId,\n principalType: expectedHead.principalType,\n stateHash: expectedHead.stateHash,\n version: expectedHead.version,\n },\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n input.assertCanCommit?.();\n return acknowledgedBundle;\n}\n\nexport async function addOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentUserSecretKey: Uint8Array;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly targetUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const identities = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [\n ...projectionUserIds(policyContext.currentPolicy.currentProjection),\n input.targetUserId,\n ],\n });\n const targetUser = identities.find(\n (identity) => identity.userId === input.targetUserId,\n );\n if (!targetUser) {\n throw new Error(\n `User identity could not be loaded for ${input.targetUserId}`,\n );\n }\n const request = await buildAddGroupUserPolicyRequest({\n ...policyContext,\n currentUserSecretKey: input.currentUserSecretKey,\n currentUsers: identities.filter(\n (identity) => identity.userId !== input.targetUserId,\n ),\n reportSecurityIncident: input.reportSecurityIncident,\n targetUser,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\nexport async function removeOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly removedUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const removedKey = input.removedUserId;\n const projection = policyContext.currentPolicy.currentProjection.filter(\n (member) => member.userId !== removedKey,\n );\n if (\n projection.length === policyContext.currentPolicy.currentProjection.length\n ) {\n throw new Error(\"User is not a group member\");\n }\n const remainingUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(projection),\n });\n const request = await buildRemoveGroupUserPolicyRequest({\n ...policyContext,\n remainingUsers,\n removedUserId: input.removedUserId,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * Adds or changes one container in the group's signed complete grant set and\n * commits every resulting container rematerialization in the same request.\n */\nexport async function setOrganizationGroupContainerGrant(input: {\n readonly accessLevel: \"admin\" | \"read\" | \"write\";\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly containerId: string;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...policyContext,\n accessLevel: input.accessLevel,\n containerId: input.containerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n assertCanCommit: input.assertCanCommit,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * A group losing a container grant rotates its own key in the same request as\n * that container revoke and the rekeys of all remaining grants. This prevents\n * a later member from using the group's still-current key to open a retained\n * wrap from before the revoke.\n */\nexport async function rotateOrganizationGroupForAccessSetShrink(input: {\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly revokedContainerId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const currentUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(policyContext.currentPolicy.currentProjection),\n });\n const request = await buildGroupAccessSetShrinkPolicyRequest({\n ...policyContext,\n currentUsers,\n revokedContainerId: input.revokedContainerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAgBlE,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,4DAA4D,CAAC;AA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AM,sCAAsC,CAAC;QAC3D,GAAG,aAAa;QAChB,YAAY;QACZ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;IACH,OAAO,iCAAiC,CAAC;QACvC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,aAAa,EAAE,aAAa,CAAC,aAAa;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,iBAAiB,EAAE,aAAa,CAAC,iBAAiB;QAClD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;QAC1D,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,aAAa;QACb,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;KAC7D,CAAC,CAAC;AACL,CAAC","sourcesContent":["export { createOrganizationGroup } from \"../groups/groupCreation\";\n\nimport type {\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport type { GroupPolicyNameReader } from \"../../../data/principals/principalPolicyRequest\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMembershipName } from \"../groupNames/groupMembershipName\";\nimport { prepareAuthoredGroupPolicy } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport {\n type AcknowledgedGroupPolicyBundle,\n cacheGroupPolicy,\n commitGroupPolicyMutation,\n loadGroupPolicyMutationContext,\n type PrincipalPolicyReadWriteApi,\n} from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n buildSetGroupContainerGrantPolicyRequest,\n} from \"../groupPolicy/groupPolicyRequests\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nexport { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };\n\ninterface PreparedGroupContainerMutations {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /** Sign the descendant rekeys a refused commit named; see `carry` there. */\n readonly carry?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly requests: readonly ContainerMutationRequest[];\n}\n\ntype PrepareGroupContainerMutations = (input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly nextPolicy: VerifiedPrincipalPolicy;\n}) => Promise<\n readonly ContainerMutationRequest[] | PreparedGroupContainerMutations\n>;\n\ninterface CommitAndCacheGroupPolicyMutationInput {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly beforePolicyCommit?:\n | ((head: ReferencedPrincipalHead) => void)\n | undefined;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly policyContext: Awaited<\n ReturnType<typeof loadGroupPolicyMutationContext>\n >;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nfunction createPolicyMutationCommitGuard(\n assertCanCommit: (() => void) | undefined,\n): (() => boolean) | undefined {\n if (!assertCanCommit) return undefined;\n return () => {\n assertCanCommit();\n return true;\n };\n}\n\n/**\n * Plan the container mutations the policy change rematerializes and place their\n * requests on the policy request. A bare request list has nothing to\n * acknowledge or carry; a prepared batch does both.\n */\nasync function prepareGroupContainerMutations(\n input: CommitAndCacheGroupPolicyMutationInput,\n expectedHead: ReferencedPrincipalHead,\n): Promise<Partial<PreparedGroupContainerMutations> | null> {\n if (!input.prepareContainerMutations) return null;\n const prepared = await input.prepareContainerMutations({\n currentPolicy: input.currentPolicy,\n nextPolicy: await prepareAuthoredGroupPolicy({\n currentPolicy: input.currentPolicy,\n expectedHead,\n request: input.request,\n }),\n });\n if (\"requests\" in prepared) {\n input.request.containerMutations = [...prepared.requests];\n return prepared;\n }\n input.request.containerMutations = [...prepared];\n return {};\n}\n\nasync function commitAndCacheGroupPolicyMutation(\n input: CommitAndCacheGroupPolicyMutationInput,\n): Promise<AcknowledgedGroupPolicyBundle> {\n const stillCurrent = createPolicyMutationCommitGuard(input.assertCanCommit);\n const expectedHead = await groupPolicyMutationHead(input.request);\n input.beforePolicyCommit?.(expectedHead);\n const containerMutations = await prepareGroupContainerMutations(\n input,\n expectedHead,\n );\n const nextAdminProjection = input.policyContext.isOrganizationAdminsGroup\n ? input.request.projection\n : input.policyContext.adminPolicyBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(nextAdminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection: nextAdminProjection,\n adminUsers,\n currentPolicy: input.policyContext.organizationPolicyBundle,\n descriptor: input.policyContext.organizationDescriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: input.policyContext.organizationDescriptor,\n nextHead: expectedHead,\n }),\n signerUserId: input.policyContext.signerUserId,\n signingFingerprint: input.policyContext.signingFingerprint,\n signingKeyPair: input.policyContext.signingKeyPair,\n });\n input.assertCanCommit?.();\n const acknowledgedBundle = await commitGroupPolicyMutation({\n apiClient: input.apiClient,\n carryDescendantRekeys: containerMutations?.carry,\n retiredContainerIds: () => containerMutations?.retiredContainerIds ?? [],\n currentPolicy: input.currentPolicy,\n execSql: input.execSql,\n expectedHead,\n groupId: input.groupId,\n organizationId: input.organizationId,\n organizationPolicy: input.policyContext.organizationPolicyBundle,\n organizationRequest,\n request: input.request,\n stillCurrent,\n });\n input.assertCanCommit?.();\n if (containerMutations?.acknowledge) {\n await containerMutations.acknowledge(\n acknowledgedBundle.containerMutations,\n stillCurrent,\n );\n }\n input.assertCanCommit?.();\n await input.afterPolicyCommitBeforeCache?.();\n input.assertCanCommit?.();\n await cacheGroupPolicy({\n acknowledgedMemberEnvelopes: acknowledgedBundle.currentMemberEnvelopes,\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedCurrentHead: expectedHead,\n externalAuthority: input.externalAuthority,\n groupId: input.groupId,\n localPolicyCheckpoint: {\n principalId: expectedHead.principalId,\n principalType: expectedHead.principalType,\n stateHash: expectedHead.stateHash,\n version: expectedHead.version,\n },\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n input.assertCanCommit?.();\n return acknowledgedBundle;\n}\n\nexport async function addOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentUserSecretKey: Uint8Array;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly targetUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const identities = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [\n ...projectionUserIds(policyContext.currentPolicy.currentProjection),\n input.targetUserId,\n ],\n });\n const targetUser = identities.find(\n (identity) => identity.userId === input.targetUserId,\n );\n if (!targetUser) {\n throw new Error(\n `User identity could not be loaded for ${input.targetUserId}`,\n );\n }\n const request = await buildAddGroupUserPolicyRequest({\n ...policyContext,\n currentUserSecretKey: input.currentUserSecretKey,\n currentUsers: identities.filter(\n (identity) => identity.userId !== input.targetUserId,\n ),\n reportSecurityIncident: input.reportSecurityIncident,\n targetUser,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\nexport async function removeOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly removedUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const removedKey = input.removedUserId;\n const projection = policyContext.currentPolicy.currentProjection.filter(\n (member) => member.userId !== removedKey,\n );\n if (\n projection.length === policyContext.currentPolicy.currentProjection.length\n ) {\n throw new Error(\"User is not a group member\");\n }\n const remainingUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(projection),\n });\n const request = await buildRemoveGroupUserPolicyRequest({\n ...policyContext,\n remainingUsers,\n removedUserId: input.removedUserId,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * Adds or changes one container in the group's signed complete grant set and\n * commits every resulting container rematerialization in the same request.\n */\nexport async function setOrganizationGroupContainerGrant(input: {\n readonly accessLevel: \"admin\" | \"read\" | \"write\";\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly containerId: string;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...policyContext,\n accessLevel: input.accessLevel,\n containerId: input.containerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n assertCanCommit: input.assertCanCommit,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * A group losing a container grant rotates its own key in the same request as\n * that container revoke and the rekeys of all remaining grants. This prevents\n * a later member from using the group's still-current key to open a retained\n * wrap from before the revoke.\n */\nexport async function rotateOrganizationGroupForAccessSetShrink(input: {\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly revokedContainerId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const currentUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(policyContext.currentPolicy.currentProjection),\n });\n const request = await buildGroupAccessSetShrinkPolicyRequest({\n ...policyContext,\n currentUsers,\n revokedContainerId: input.revokedContainerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyRecipients.js","sourceRoot":"","sources":["principalPolicyRecipients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMnE,OAAO,EAAE,kCAAkC,EAAE,MAAM,+DAA+D,CAAC;AAQnH,SAAS,gCAAgC,CAAC,KAOzC;IACC,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,oBAAoB,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc;QACnD,aAAa,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC1D,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC;KACrD,CAAC;AACJ,CAAC;AAED,MA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;QAC/B,0BAA0B,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI;KACxE,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;IAClD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,iBAAiB,GAAG,MAAM,oBAAoB,CAClD,KAAK,CAAC,SAAS,EACf,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAChE,CAAC;IAEF,OAAO,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,CAC/C,gCAAgC,CAAC;QAC/B,QAAQ;QACR,MAAM,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,IAAI,EAAE;KACxC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { wrapDekForRecipients } from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalMemberEnvelopeResponse } from \"@tearleads/validators/response\";\nimport { assertPrincipalIdentityCommitments } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport type { TrustedUserIdentity } from \"../../../data/trustedUserIdentity\";\n\ntype PrincipalRekeyRecipient = {\n readonly encapsulationPublicKey: Uint8Array;\n readonly userId: string;\n};\n\nfunction toPrincipalMemberEnvelopeRequest(input: {\n readonly envelope: {\n readonly keyFingerprint: string;\n readonly kemCipherText: Uint8Array;\n readonly wrappedKey: Uint8Array;\n };\n readonly userId: string;\n}): PrincipalMemberEnvelopeRequest {\n return {\n userId: input.userId,\n memberKeyFingerprint: input.envelope.keyFingerprint,\n kemCipherText: bytesToBase64(input.envelope.kemCipherText),\n wrappedKey: bytesToBase64(input.envelope.wrappedKey),\n };\n}\n\nexport function toRecipientEntries(\n envelopes: ReadonlyArray<PrincipalMemberEnvelopeResponse>,\n) {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.memberKeyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\n/** Every projected member is a user, so there is no group recipient branch. */\nfunction toRekeyRecipientEntries(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): PrincipalRekeyRecipient[] {\n const usersById = new Map(input.users.map((user) => [user.userId, user]));\n\n return input.projection.map((member) => {\n const user = usersById.get(member.userId);\n if (!user) {\n throw new Error(`Missing recipient key for user ${member.userId}`);\n }\n\n return {\n encapsulationPublicKey: user.encapsulationPublicKey,\n userId: user.userId,\n };\n });\n}\n\nexport async function rewrapProjectionMemberEnvelopes(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly secretKey: Uint8Array;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): Promise<PrincipalMemberEnvelopeRequest[]> {\n const users = new Map(input.users.map((user) => [user.userId, user]));\n await assertPrincipalIdentityCommitments({\n authenticated: false,\n projections: [input.projection],\n resolveTrustedUserIdentity: async (userId) => users.get(userId) ?? null,\n });\n const recipients = toRekeyRecipientEntries(input);\n if (recipients.length === 0) {\n return [];\n }\n const wrappedRecipients = await wrapDekForRecipients(\n input.secretKey,\n recipients.map((recipient) => recipient.encapsulationPublicKey),\n );\n\n return wrappedRecipients.map((envelope, index) =>\n toPrincipalMemberEnvelopeRequest({\n envelope,\n userId: recipients[index]?.userId ?? \"\",\n }),\n );\n}\n"]}