@tearleads/client-sdk 0.1.230 → 0.1.231
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.
- package/data/principals/organizationPolicyRequest.d.ts +12 -0
- package/data/principals/organizationPolicyRequest.js +71 -0
- package/data/principals/organizationPolicyRequest.js.map +1 -0
- package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.d.ts +3 -3
- package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.js +3 -3
- package/data/principals/principalPolicyRequest.js.map +1 -0
- package/{workflows/principals/policyVerification.js → data/principals/principalPolicyVerification.js} +4 -4
- package/data/principals/principalPolicyVerification.js.map +1 -0
- package/package.json +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataAccess.d.ts +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/groupNames/groupMembershipName.d.ts +1 -1
- package/workflows/organizations/groupNames/groupMembershipName.js +1 -1
- package/workflows/organizations/groupNames/groupMembershipName.js.map +1 -1
- package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
- package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
- package/workflows/organizations/groupShare/currentShareGrantMutation.js +1 -1
- package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.d.ts +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/shareWithGroup.d.ts +1 -1
- package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/groupCreation.js +1 -1
- package/workflows/organizations/groups/groupCreation.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/principalPolicy/index.d.ts +2 -2
- package/workflows/organizations/principalPolicy/index.js +1 -1
- package/workflows/organizations/principalPolicy/index.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
- package/workflows/principals/externalAdminPolicy.js +1 -1
- package/workflows/principals/externalAdminPolicy.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryPageAppend.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryPageAppend.js.map +1 -1
- package/workflows/principals/policyCache/index.js +1 -1
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
- package/workflows/registration/index.d.ts +2 -1
- package/workflows/registration/index.js +1 -1
- package/workflows/registration/index.js.map +1 -1
- package/workflows/registration/organizationProvisioning.d.ts +1 -12
- package/workflows/registration/organizationProvisioning.js +2 -70
- package/workflows/registration/organizationProvisioning.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +0 -1
- package/workflows/principals/policyVerification.js.map +0 -1
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type ReferencedPrincipalHead, type SigningKeyPair } from "../../internal/crypto/index.js";
|
|
2
|
+
import type { RegistrationRequest } from "../../internal/validators/request/index.js";
|
|
3
|
+
export declare function buildInitialOrganizationPolicyRequest(input: {
|
|
4
|
+
identityTrustDomain: string;
|
|
5
|
+
adminGroupId: string;
|
|
6
|
+
groupHeads: readonly ReferencedPrincipalHead[];
|
|
7
|
+
encapsulationPublicKey: Uint8Array;
|
|
8
|
+
memberGroupId: string;
|
|
9
|
+
organizationId: string;
|
|
10
|
+
signingKeyPair: SigningKeyPair;
|
|
11
|
+
userId: string;
|
|
12
|
+
}): Promise<RegistrationRequest["initialOrganizationPolicy"]>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { bytesToBase64 } from "../../internal/encoding/index.js";
|
|
3
|
+
import { encodeOrganizationAuthorityDescriptor } from "../principalContracts/organizationAuthorityDescriptor.js";
|
|
4
|
+
import { createPrincipalProjectionMember } from "../principalContracts/principalIdentityCommitments.js";
|
|
5
|
+
export async function buildInitialOrganizationPolicyRequest(input) {
|
|
6
|
+
const organizationKem = generateKemSeedAndKeyPair();
|
|
7
|
+
const signerUserKeyFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
|
|
8
|
+
const userEncapsulationKeyFingerprint = await toFingerprint(input.encapsulationPublicKey);
|
|
9
|
+
const projection = [
|
|
10
|
+
await createPrincipalProjectionMember({
|
|
11
|
+
userId: input.userId,
|
|
12
|
+
identityTrustDomain: input.identityTrustDomain,
|
|
13
|
+
signingPublicKey: input.signingKeyPair.signingPublicKey,
|
|
14
|
+
encapsulationPublicKey: input.encapsulationPublicKey,
|
|
15
|
+
}, "admin"),
|
|
16
|
+
];
|
|
17
|
+
const payloadCiphertext = encodeOrganizationAuthorityDescriptor({
|
|
18
|
+
version: 2,
|
|
19
|
+
organizationId: input.organizationId,
|
|
20
|
+
adminGroupId: input.adminGroupId,
|
|
21
|
+
memberGroupId: input.memberGroupId,
|
|
22
|
+
groupHeads: input.groupHeads.map((head) => {
|
|
23
|
+
if (head.principalType !== "group") {
|
|
24
|
+
throw new Error("Organization directory can contain only group heads");
|
|
25
|
+
}
|
|
26
|
+
return { ...head, principalType: "group" };
|
|
27
|
+
}),
|
|
28
|
+
});
|
|
29
|
+
const [memberEnvelope] = await wrapDekForRecipients(organizationKem.secretKey, [input.encapsulationPublicKey]);
|
|
30
|
+
if (!memberEnvelope) {
|
|
31
|
+
throw new Error("Failed to wrap organization key for registering user");
|
|
32
|
+
}
|
|
33
|
+
const memberEnvelopes = [
|
|
34
|
+
{
|
|
35
|
+
userId: input.userId,
|
|
36
|
+
memberKeyFingerprint: userEncapsulationKeyFingerprint,
|
|
37
|
+
kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),
|
|
38
|
+
wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),
|
|
39
|
+
},
|
|
40
|
+
];
|
|
41
|
+
const state = await signPrincipalState(await buildPrincipalStateSigningInput({
|
|
42
|
+
principalType: "organization",
|
|
43
|
+
principalId: input.organizationId,
|
|
44
|
+
version: 1,
|
|
45
|
+
prevStateHash: null,
|
|
46
|
+
keyEpoch: 1,
|
|
47
|
+
encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
|
|
48
|
+
keyFingerprint: await toFingerprint(organizationKem.publicKey),
|
|
49
|
+
members: [{ userId: input.userId }],
|
|
50
|
+
memberEnvelopes,
|
|
51
|
+
projection,
|
|
52
|
+
grants: [],
|
|
53
|
+
payloadCiphertext,
|
|
54
|
+
externalAuthority: null,
|
|
55
|
+
signedAt: new Date().toISOString(),
|
|
56
|
+
signerUserId: input.userId,
|
|
57
|
+
signerUserKeyFingerprint,
|
|
58
|
+
}), input.signingKeyPair.signingPrivateKey);
|
|
59
|
+
return {
|
|
60
|
+
state,
|
|
61
|
+
encryptedPayload: {
|
|
62
|
+
cipherSuite: "aes-256-gcm",
|
|
63
|
+
ciphertext: payloadCiphertext,
|
|
64
|
+
ciphertextHash: state.payloadCiphertextHash,
|
|
65
|
+
},
|
|
66
|
+
projection,
|
|
67
|
+
grants: [],
|
|
68
|
+
memberEnvelopes,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
//# sourceMappingURL=organizationPolicyRequest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"organizationPolicyRequest.js","sourceRoot":"","sources":["organizationPolicyRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EAGzB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,qCAAqC,EAAE,MAAM,uDAAuD,CAAC;AAC9G,OAAO,EAAE,+BAA+B,EAAE,MAAM,oDAAoD,CAAC;AAErG,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAS3D;IACC,MAAM,eAAe,GAAG,yBAAyB,EAAE,CAAC;IACpD,MAAM,wBAAwB,GAAG,MAAM,aAAa,CAClD,KAAK,CAAC,cAAc,CAAC,gBAAgB,CACtC,CAAC;IACF,MAAM,+BAA+B,GAAG,MAAM,aAAa,CACzD,KAAK,CAAC,sBAAsB,CAC7B,CAAC;IACF,MAAM,UAAU,GAAG;QACjB,MAAM,+BAA+B,CACnC;YACE,MAAM,EAAE,KA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O,EAAE,CAAC;QACV,aAAa,EAAE,IAAI;QACnB,QAAQ,EAAE,CAAC;QACX,sBAAsB,EAAE,aAAa,CAAC,eAAe,CAAC,SAAS,CAAC;QAChE,cAAc,EAAE,MAAM,aAAa,CAAC,eAAe,CAAC,SAAS,CAAC;QAC9D,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;QACnC,eAAe;QACf,UAAU;QACV,MAAM,EAAE,EAAE;QACV,iBAAiB;QACjB,iBAAiB,EAAE,IAAI;QACvB,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,MAAM;QAC1B,wBAAwB;KACzB,CAAC,EACF,KAAK,CAAC,cAAc,CAAC,iBAAiB,CACvC,CAAC;IAEF,OAAO;QACL,KAAK;QACL,gBAAgB,EAAE;YAChB,WAAW,EAAE,aAAa;YAC1B,UAAU,EAAE,iBAAiB;YAC7B,cAAc,EAAE,KAAK,CAAC,qBAAqB;SAC5C;QACD,UAAU;QACV,MAAM,EAAE,EAAE;QACV,eAAe;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { RegistrationRequest } from \"@tearleads/validators/request\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../principalContracts/organizationAuthorityDescriptor\";\nimport { createPrincipalProjectionMember } from \"../principalContracts/principalIdentityCommitments\";\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n identityTrustDomain: string;\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n await createPrincipalProjectionMember(\n {\n userId: input.userId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.encapsulationPublicKey,\n },\n \"admin\",\n ),\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n"]}
|
package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.d.ts
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { type EncapsulationKeyPair, type GroupMetadataKey, type PrincipalContainerGrant, type PrincipalPolicyExternalAuthority, type SigningKeyPair } from "
|
|
2
|
-
import type { CreateOrganizationGroupRequest, PrincipalMemberEnvelopeRequest, PrincipalProjectionMemberRequest, PutPrincipalPolicyRequest } from "
|
|
3
|
-
import type { PrincipalPolicyBundleResponse } from "
|
|
1
|
+
import { type EncapsulationKeyPair, type GroupMetadataKey, type PrincipalContainerGrant, type PrincipalPolicyExternalAuthority, type SigningKeyPair } from "../../internal/crypto/index.js";
|
|
2
|
+
import type { CreateOrganizationGroupRequest, PrincipalMemberEnvelopeRequest, PrincipalProjectionMemberRequest, PutPrincipalPolicyRequest } from "../../internal/validators/request/index.js";
|
|
3
|
+
import type { PrincipalPolicyBundleResponse } from "../../internal/validators/response/index.js";
|
|
4
4
|
interface BuildInitialGroupPolicyInput {
|
|
5
5
|
readonly identityTrustDomain: string;
|
|
6
6
|
readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;
|
package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.js
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { buildPrincipalStateSigningInput, encodeBuiltinGroupMetadata, encryptGroupMetadata, generateKemSeedAndKeyPair, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, readGroupMetadata, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "
|
|
2
|
-
import { bytesToBase64 } from "
|
|
3
|
-
import { createPrincipalProjectionMember } from "
|
|
1
|
+
import { buildPrincipalStateSigningInput, encodeBuiltinGroupMetadata, encryptGroupMetadata, generateKemSeedAndKeyPair, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, readGroupMetadata, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { bytesToBase64 } from "../../internal/encoding/index.js";
|
|
3
|
+
import { createPrincipalProjectionMember } from "../principalContracts/principalIdentityCommitments.js";
|
|
4
4
|
function projectionToStateMembers(projection) {
|
|
5
5
|
return projection.map((member) => ({ userId: member.userId }));
|
|
6
6
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalPolicyRequest.js","sourceRoot":"","sources":["principalPolicyRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAE/B,0BAA0B,EAC1B,oBAAoB,EAEpB,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,EAGnC,iBAAiB,EAEjB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAQpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,oDAAoD,CAAC;AAmBrG,SAAS,wBAAwB,CAC/B,UAA2D;IAE3D,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AACjE,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,8BAA8B,CAAC,IAAY;IAClD,OAAO,uDAAuD,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC5E,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,OAAO,CACL,IAAI;SACD,SAAS,CAAC,MAAM,CAAC;SACjB,OAAO,CAAC,kDAAkD,EAAE,EAAE,CAAC;SAC/D,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,IAAI,EAAE;SACN,iBAAiB,CAAC,OAAO,CAAC;QAC3B,wEAAwE;QACxE,8DAA8D;SAC7D,SAAS,CAAC,MAAM,CAAC,CACrB,CAAC;AAC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AAW;YACjB,CAAC,CAAC,MAAM,oBAAoB,CAAC;gBACzB,GAAG,EAAE,KAAK,CAAC,WAAW;gBACtB,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,IAAI;aACL,CAAC;YACJ,CAAC,CAAC,CAAC,GAAG,EAAE;gBACJ,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;YACtE,CAAC,CAAC,EAAE,CAAC;IACX,MAAM,aAAa,GAAG,MAAM,wBAAwB,CAAC;QACnD,sBAAsB,EAAE,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC;QACzD,iBAAiB,EAAE,KAAK,CAAC,iBAAiB,IAAI,IAAI;QAClD,QAAQ,EAAE,CAAC;QACX,cAAc,EAAE,MAAM,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC;QACvD,MAAM,EAAE,KAAK,CAAC,MAAM,IAAI,EAAE;QAC1B,eAAe;QACf,iBAAiB;QACjB,WAAW,EAAE,KAAK,CAAC,OAAO;QAC1B,UAAU;QACV,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IAEH,OAAO;QACL,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,kBAAkB,EAAE,aAAa;KAClC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAQ1D;IACC,OAAO,8BAA8B,CAAC;QACpC,GAAG,KAAK;QACR,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,SAAS;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n encodeBuiltinGroupMetadata,\n encryptGroupMetadata,\n type GroupMetadataKey,\n generateKemSeedAndKeyPair,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type PrincipalContainerGrant,\n type PrincipalPolicyExternalAuthority,\n readGroupMetadata,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { createPrincipalProjectionMember } from \"../principalContracts/principalIdentityCommitments\";\n\ninterface BuildInitialGroupPolicyInput {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly externalAuthority?:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly includeSignerAsAdmin?: boolean;\n readonly name: string;\n readonly metadataKey?: GroupMetadataKey;\n readonly builtinRole?: \"admins\" | \"members\";\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}\n\nfunction projectionToStateMembers(\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n) {\n return projection.map((member) => ({ userId: member.userId }));\n}\n\n/**\n * Code points that must never appear in a group name: control and format\n * characters (bidi overrides, zero-width joiners, newlines), lone surrogates\n * (re-encoded as U+FFFD when signed, so the signed name would no longer match\n * the one sent to the server), and every other default-ignorable code point\n * (Hangul fillers, variation selectors), which render as nothing and would\n * let one name pass for another. A group name is an identifier here, so this\n * deliberately refuses ZWJ emoji sequences as well. One predicate serves the\n * signing-time and the share-time refusal so the two cannot drift.\n */\nfunction hasForbiddenGroupNameCharacter(name: string): boolean {\n return /[\\p{Cc}\\p{Cf}\\p{Cs}\\p{Default_Ignorable_Code_Point}]/u.test(name);\n}\n\n/**\n * The comparison key for a group display name: width- and compatibility-\n * normalized, stripped of control, format, and default-ignorable characters,\n * whitespace-collapsed, and case-folded. Two names that a user cannot tell\n * apart in a picker must compare equal, or a look-alike name would slip past\n * the share-time binding. Cross-script homoglyphs (Latin \"A\" against Greek\n * \"Α\") are not folded: that needs the UTS #39 confusables table, and both\n * names would still have to be signed groups the organization's own admins\n * created.\n */\nexport function canonicalGroupNameKey(name: string): string {\n return (\n name\n .normalize(\"NFKC\")\n .replace(/[\\p{Cc}\\p{Cf}\\p{Default_Ignorable_Code_Point}]/gu, \"\")\n .replace(/\\s+/gu, \" \")\n .trim()\n .toLocaleLowerCase(\"en-US\")\n // Case folding can leave the string un-normalized (U+0130 lowercases to\n // \"i\" plus a combining dot), so normalize once more after it.\n .normalize(\"NFKC\")\n );\n}\n\ntype GroupPolicyNameInput = Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentPayload\"\n>;\n\nexport type GroupPolicyNameReader = (\n bundle: GroupPolicyNameInput,\n) => Promise<string>;\n\n/** Read only after the policy and its organization-directory binding verify. */\nexport async function readGroupPolicyPayloadName(\n bundle: GroupPolicyNameInput,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<string> {\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (!readEncryptedName)\n throw new Error(\"Group metadata decryption context is unavailable\");\n return readEncryptedName(bundle);\n}\n\n/** One binding predicate for every operation selected by a read-model label. */\nexport async function groupPolicyNameMismatch(\n bundle: GroupPolicyNameInput,\n expectedGroupName: string,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<\"forbidden_characters\" | \"name_mismatch\" | null> {\n if (hasForbiddenGroupNameCharacter(expectedGroupName)) {\n return \"forbidden_characters\";\n }\n const signedName = await readGroupPolicyPayloadName(\n bundle,\n readEncryptedName,\n );\n if (hasForbiddenGroupNameCharacter(signedName)) return \"forbidden_characters\";\n return canonicalGroupNameKey(signedName) ===\n canonicalGroupNameKey(expectedGroupName)\n ? null\n : \"name_mismatch\";\n}\n\nexport async function signedGroupPolicyRequest(input: {\n readonly currentPolicy?: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly encapsulationPublicKey: string;\n readonly externalAuthority:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly grants: ReadonlyArray<PrincipalContainerGrant>;\n readonly memberEnvelopes: ReadonlyArray<PrincipalMemberEnvelopeRequest>;\n readonly payloadCiphertext: string;\n readonly principalId: string;\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly signedAt: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.projection);\n const grants = normalizePrincipalContainerGrants(input.grants);\n const payloadCiphertext = input.payloadCiphertext;\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"group\",\n principalId: input.principalId,\n version: input.currentPolicy\n ? input.currentPolicy.currentState.version + 1\n : 1,\n prevStateHash: input.currentPolicy?.currentState.stateHash ?? null,\n keyEpoch: input.keyEpoch,\n encapsulationPublicKey: input.encapsulationPublicKey,\n keyFingerprint: input.keyFingerprint,\n members: projectionToStateMembers(projection),\n memberEnvelopes: [...input.memberEnvelopes],\n projection,\n grants,\n payloadCiphertext,\n externalAuthority: input.externalAuthority,\n signedAt: input.signedAt,\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants,\n memberEnvelopes: [...input.memberEnvelopes],\n };\n}\n\nexport async function buildInitialGroupPolicyRequest(\n input: BuildInitialGroupPolicyInput,\n): Promise<CreateOrganizationGroupRequest> {\n const groupKem = generateKemSeedAndKeyPair();\n const withSigner = input.includeSignerAsAdmin ?? true;\n const projection = withSigner\n ? [\n await createPrincipalProjectionMember(\n {\n userId: input.signerUserId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.creatorEncapsulationKeyPair.publicKey,\n },\n \"admin\",\n ),\n ]\n : [];\n const memberEnvelopes: PrincipalMemberEnvelopeRequest[] = [];\n\n if (withSigner) {\n const creatorFingerprint = await toFingerprint(\n input.creatorEncapsulationKeyPair.publicKey,\n );\n const [creatorEnvelope] = await wrapDekForRecipients(groupKem.secretKey, [\n input.creatorEncapsulationKeyPair.publicKey,\n ]);\n\n if (!creatorEnvelope) {\n throw new Error(\"Failed to wrap group key for creator\");\n }\n\n memberEnvelopes.push({\n userId: input.signerUserId,\n memberKeyFingerprint: creatorFingerprint,\n kemCipherText: bytesToBase64(creatorEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(creatorEnvelope.wrappedKey),\n });\n }\n const name = input.name.trim();\n // A name is compared by canonical key but displayed raw, so an invisible\n // code point would let one signed name render as another. Refuse them\n // where the name is signed.\n if (name.length === 0 || hasForbiddenGroupNameCharacter(name)) {\n throw new Error(\n \"Group names must be non-empty and contain no control, format, or surrogate characters\",\n );\n }\n const payloadCiphertext = input.builtinRole\n ? encodeBuiltinGroupMetadata(input.builtinRole)\n : input.metadataKey\n ? await encryptGroupMetadata({\n key: input.metadataKey,\n groupId: input.groupId,\n name,\n })\n : (() => {\n throw new Error(\"Group metadata encryption context is unavailable\");\n })();\n const policyRequest = await signedGroupPolicyRequest({\n encapsulationPublicKey: bytesToBase64(groupKem.publicKey),\n externalAuthority: input.externalAuthority ?? null,\n keyEpoch: 1,\n keyFingerprint: await toFingerprint(groupKem.publicKey),\n grants: input.grants ?? [],\n memberEnvelopes,\n payloadCiphertext,\n principalId: input.groupId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n\n return {\n groupId: input.groupId,\n initialGroupPolicy: policyRequest,\n };\n}\n\n/**\n * Members at bootstrap holds the registering user alone.\n *\n * It used to also contain the Admins group as a nested member, so that admins\n * were implicitly members. Principals contain only users now, so an admin is an\n * ordinary Members entry — and bootstrap has exactly one user, who is that\n * admin.\n */\nexport async function buildInitialMemberGroupPolicyRequest(input: {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<CreateOrganizationGroupRequest> {\n return buildInitialGroupPolicyRequest({\n ...input,\n name: \"Members\",\n builtinRole: \"members\",\n });\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { computeUserIdentityBundleFingerprint, } from "../../internal/crypto/index.js";
|
|
2
|
-
import { assertProjectionVerificationCurrent } from "
|
|
3
|
-
import { publishVerifiedPolicyBundle, withUnauthenticatedPolicyIdentities, } from "
|
|
4
|
-
import { requireTrustedUserIdentityResolver, } from "
|
|
2
|
+
import { assertProjectionVerificationCurrent } from "../keyingProjectionVerification/types.js";
|
|
3
|
+
import { publishVerifiedPolicyBundle, withUnauthenticatedPolicyIdentities, } from "../principalContracts/principalIdentityCommitments.js";
|
|
4
|
+
import { requireTrustedUserIdentityResolver, } from "../trustedUserIdentity/index.js";
|
|
5
5
|
export function principalPolicyStates(bundle) {
|
|
6
6
|
return [
|
|
7
7
|
...bundle.previousStates.map((entry) => entry.state),
|
|
@@ -116,4 +116,4 @@ export function publishVerifiedCurrent(options, current, stillCurrent) {
|
|
|
116
116
|
assertCurrent: () => assertProjectionVerificationCurrent(stillCurrent),
|
|
117
117
|
});
|
|
118
118
|
}
|
|
119
|
-
//# sourceMappingURL=
|
|
119
|
+
//# sourceMappingURL=principalPolicyVerification.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,GAGrC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,kCAAkC,GAGnC,MAAM,wBAAwB,CAAC;AAMhC,MAAM,UAAU,qBAAqB,CACnC,MAGC;IAED,OAAO;QACL,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC;QACpD,MAAM,CAAC,YAAY;KACpB,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,KAGvB;IACC,OAAO,GAAG,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;AAC7D,CAAC;AAED,0EAA0E;AAC1E,MAAM,iBAAiB;IACA;IAArB,YAAqB,IAAiD;QAAjD,SAAI,GAAJ,IAAI,CAA6C;IAAG,CAAC;CAC3E;AAUD,KAAK,UAAU,iBAAiB,CAAC,KAGhC;IACC,MAAM,SAAS,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAEhE,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,iBAAiB,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IAED,IACE,SAAS,CAAC,qBAAqB,KAAK,KAAK,CAAC,KAAK,CAAC,wBAAwB,EACxE,CAAC;QACD,MAAM,IAAI,iBAAiB,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;IAED,OAAO;QACL,QAAQ,EAAE,SAAS;QACnB,SAAS,EAAE;YACT,MAAM,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B,CAAC,CAAC;YACxD,CAAC;YACD,OAAO;gBACL,gBAAgB,EAAE,KAAK,CAAC,IAAI,CAC1B,OAAO,CAAC,MAAM,EAAE,EAChB,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,SAAS,CAC7B;aACF,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,iBAAiB;YAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC;QACrE,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,8BAA8B,CAAC,KAS9C;IACC,MAAM,EAAE,YAAY,EAAE,GAAG,KAAK,CAAC;IAC/B,OAAO,2BAA2B,CAChC,KAAK,CAAC,MAAM,EACZ,kCAAkC,CAAC,KAAK,CAAC,0BAA0B,CAAC,EACpE,KAAK,CAAC,aAAa;QACjB,CAAC,YAAY;YACX,CAAC,CAAC,GAAG,EAAE,CAAC,mCAAmC,CAAC,YAAY,CAAC;YACzD,CAAC,CAAC,SAAS,CAAC,CACjB,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,sBAAsB,CACpC,OAA6E,EAC7E,OAGC,EACD,YAA2B;IAE3B,OAAO,8BAA8B,CAAC;QACpC,MAAM,EAAE,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE;QAC1C,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,aAAa,EAAE,GAAG,EAAE,CAAC,mCAAmC,CAAC,YAAY,CAAC;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computeUserIdentityBundleFingerprint,\n type PrincipalPolicySignerPublicKey,\n type PrincipalProjectionMember,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n publishVerifiedPolicyBundle,\n withUnauthenticatedPolicyIdentities,\n} from \"../principalContracts/principalIdentityCommitments\";\nimport {\n requireTrustedUserIdentityResolver,\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../trustedUserIdentity\";\n\nexport type PrincipalPolicySignerPublicKeyLoadErrorCode =\n | \"fingerprint-mismatch\"\n | \"not-found\";\n\nexport function principalPolicyStates(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\"\n >,\n): PrincipalPolicyBundleResponse[\"currentState\"][] {\n return [\n ...bundle.previousStates.map((entry) => entry.state),\n bundle.currentState,\n ];\n}\n\nfunction signerCacheKey(input: {\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n}): string {\n return `${input.signerUserId}:${input.signingFingerprint}`;\n}\n\n/** A signer refusal ends collection before any commitment is compared. */\nclass SignerLoadRefusal {\n constructor(readonly code: PrincipalPolicySignerPublicKeyLoadErrorCode) {}\n}\n\ninterface TrustedSigner {\n readonly identity: NonNullable<\n Awaited<ReturnType<StagedUserIdentityResolver>>\n >;\n readonly publicKey: PrincipalPolicySignerPublicKey;\n bundleFingerprint?: Promise<string>;\n}\n\nasync function loadTrustedSigner(input: {\n readonly resolve: StagedUserIdentityResolver;\n readonly state: PrincipalPolicyBundleResponse[\"currentState\"];\n}): Promise<TrustedSigner> {\n const signerKey = await input.resolve(input.state.signerUserId);\n\n if (!signerKey) {\n throw new SignerLoadRefusal(\"not-found\");\n }\n\n if (\n signerKey.signingKeyFingerprint !== input.state.signerUserKeyFingerprint\n ) {\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n\n return {\n identity: signerKey,\n publicKey: {\n userId: input.state.signerUserId,\n signingKeyFingerprint: input.state.signerUserKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n },\n };\n}\n\ntype SignedProjection = {\n readonly version: number;\n readonly stateHash: string;\n readonly projection: readonly PrincipalProjectionMember[];\n};\n\n/**\n * The signer's identity as its predecessor's signed projection committed it,\n * when the state links to that predecessor: an unlinked entry is left for the\n * chain verifier to refuse as disconnected.\n */\nfunction committedSignerBundle(\n state: PrincipalPolicyBundleResponse[\"currentState\"],\n predecessors: ReadonlyMap<number, SignedProjection>,\n): string | undefined {\n const predecessor = predecessors.get(state.version - 1);\n if (!predecessor || predecessor.stateHash !== state.prevStateHash)\n return undefined;\n return predecessor.projection.find(\n (member) => member.userId === state.signerUserId,\n )?.identityBundleFingerprint;\n}\n\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /**\n * A paged history's last accepted state, which authorizes the page's first\n * signer by user ID: that signer must be the identity it committed.\n */\n readonly predecessor?: SignedProjection | null;\n}): Promise<\n | { readonly signerPublicKeys: PrincipalPolicySignerPublicKey[] }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const states = principalPolicyStates(input.bundle);\n const predecessors = new Map<number, SignedProjection>(\n [\n ...(input.predecessor ? [input.predecessor] : []),\n ...input.bundle.previousStates.map((entry) => ({\n version: entry.state.version,\n stateHash: entry.state.stateHash,\n projection: entry.projection,\n })),\n ].map((entry) => [entry.version, entry]),\n );\n try {\n // Signatures are checked after collection: first-sight signers and\n // members are compared, but only a verified selection pins them.\n return await withUnauthenticatedPolicyIdentities(\n {\n signerUserIds: states.map((state) => state.signerUserId),\n projections: [\n ...input.bundle.previousStates.map((entry) => entry.projection),\n input.bundle.currentProjection,\n ],\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n },\n async (resolve) => {\n const signers = new Map<string, TrustedSigner>();\n for (const state of states) {\n const cacheKey = signerCacheKey({\n signerUserId: state.signerUserId,\n signingFingerprint: state.signerUserKeyFingerprint,\n });\n let signer = signers.get(cacheKey);\n if (!signer) {\n signer = await loadTrustedSigner({ resolve, state });\n signers.set(cacheKey, signer);\n }\n const committed = committedSignerBundle(state, predecessors);\n if (committed === undefined) continue;\n signer.bundleFingerprint ??= computeUserIdentityBundleFingerprint(\n signer.identity,\n );\n if ((await signer.bundleFingerprint) !== committed)\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n return {\n signerPublicKeys: Array.from(\n signers.values(),\n (signer) => signer.publicKey,\n ),\n };\n },\n );\n } catch (error) {\n if (error instanceof SignerLoadRefusal) return { error: error.code };\n throw error;\n }\n}\n\n/**\n * Pin the signers and members of a bundle the caller has just verified, so\n * the first sights signer collection staged become durable only now. Call it\n * after every successful verification of a collected bundle.\n */\nexport function publishVerifiedPrincipalPolicy(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly assertCurrent?: (() => void) | undefined;\n /** The operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n const { stillCurrent } = input;\n return publishVerifiedPolicyBundle(\n input.bundle,\n requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),\n input.assertCurrent ??\n (stillCurrent\n ? () => assertProjectionVerificationCurrent(stillCurrent)\n : undefined),\n );\n}\n\n/** Pin one recovery's just-verified current state, within its lifetime. */\nexport function publishVerifiedCurrent(\n options: { readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver },\n current: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n stillCurrent: () => boolean,\n): Promise<void> {\n return publishVerifiedPrincipalPolicy({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n assertCurrent: () => assertProjectionVerificationCurrent(stillCurrent),\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { type ContainerAccessManifestState, type GroupMetadataKey, type ReferencedPrincipalHead } from "../../../internal/crypto/index.js";
|
|
2
2
|
import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification/index.js";
|
|
4
|
+
import type { GroupPolicyNameReader } from "../../../data/principals/principalPolicyRequest.js";
|
|
4
5
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
5
|
-
import type { GroupPolicyNameReader } from "../principalPolicy/principalPolicyRequest.js";
|
|
6
6
|
export interface GroupMetadataAccessInput {
|
|
7
7
|
readonly apiClient: {
|
|
8
8
|
evictContainerWriterProjection(containerId: string): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupMetadataAccess.js","sourceRoot":"","sources":["groupMetadataAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EAGpB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAE1G,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AAKrF,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,cAAc,EAAE,MAAM,mEAAmE,CAAC;AAGnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAuB/D;;;;;;GAMG;AACH,MAAM,OAAO,4BAA6B,SAAQ,KAAK;IACrD,YAAY,OAAe,EAAE,KAAc;QACzC,KAAK,CAAC,SAAS,OAAO,+BAA+B,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAClE,IAAI,CAAC,IAAI,GAAG,8BAA8B,CAAC;IAC7C,CAAC;CACF;AAED,SAAS,mBAAmB,CAC1B,KAA+B,EAC/B,WAAmB;IAEnB,OAAO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AAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;YACzE,OAAO,OAAO,CAAC,OAAO,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n decryptGroupMetadata,\n type GroupMetadataKey,\n type ReferencedPrincipalHead,\n readGroupMetadata,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../data/documents/shared/containerKek\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { loadContainers } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { GroupPolicyNameReader } from \"../principalPolicy/principalPolicyRequest\";\nimport { withMetadataRootReload } from \"./groupMetadataErrors\";\n\nexport interface GroupMetadataAccessInput {\n readonly apiClient: {\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n };\n readonly verifyMetadataContainer: (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead | undefined,\n ) => Promise<void>;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly targetSecretKey: Uint8Array;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/**\n * A group's signed name does not open under the metadata key it cites, or opens\n * to an invalid name. Every reader holding that key gets the same result. The\n * API checks the citation but can never check the ciphertext, so a dishonest\n * admin can sign such a name; directory walks isolate the group instead of\n * failing every name in the organization.\n */\nexport class GroupMetadataUnreadableError extends Error {\n constructor(groupId: string, cause: unknown) {\n super(`Group ${groupId} metadata cannot be decrypted`, { cause });\n this.name = \"GroupMetadataUnreadableError\";\n }\n}\n\nfunction loadMetadataKeyring(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n return withMetadataRootReload(\n () => loadMetadataKeyringOnce(input, containerId),\n () => input.apiClient.evictContainerWriterProjection(containerId),\n );\n}\n\nasync function loadMetadataKeyringOnce(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n const projection =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!projection) return null;\n if (\n projection.containerId !== containerId ||\n projection.organizationId !== input.organizationId\n )\n throw new Error(\"Group metadata container is unavailable\");\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n if (\n state.organizationId !== input.organizationId ||\n state.systemSlot !== slot ||\n state.parentContainerId !== null\n )\n throw new Error(\n \"Group metadata requires the signed organization metadata container\",\n );\n await input.verifyMetadataContainer(\n state,\n projection.policyEvidence.organization?.head,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keys = await unwrapContainerKekPath({\n ...input,\n projection,\n secretKey: input.targetSecretKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keyMaterial = keys.get(target.kek.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata container key is unavailable\");\n return {\n current: {\n organizationId: input.organizationId,\n containerId,\n containerKeyEpochId: target.kek.containerKeyEpochId,\n keyMaterial,\n },\n keys,\n };\n}\n\n/** Uses the shared metadata container's authenticated keyring, including old epochs. */\nexport function createGroupMetadataAccess(input: GroupMetadataAccessInput) {\n const loads = new Map<\n string,\n Promise<{\n current: GroupMetadataKey;\n keys: ReadonlyMap<string, Uint8Array>;\n } | null>\n >();\n function loaded(containerId: string) {\n let pending = loads.get(containerId);\n if (!pending) {\n pending = loadMetadataKeyring(input, containerId);\n loads.set(containerId, pending);\n }\n return pending;\n }\n const readName: GroupPolicyNameReader = async (bundle) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (\n metadata.organizationId !== input.organizationId ||\n metadata.groupId !== bundle.currentState.principalId ||\n bundle.currentState.principalType !== \"group\"\n )\n throw new Error(\"Group metadata scope does not match its signed group\");\n const keyring = await loaded(metadata.containerId);\n const keyMaterial = keyring?.keys.get(metadata.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata historical key is unavailable\");\n try {\n return await decryptGroupMetadata({\n key: { ...metadata, keyMaterial },\n groupId: bundle.currentState.principalId,\n payload: bundle.currentPayload.ciphertext,\n });\n } catch (cause) {\n throw new GroupMetadataUnreadableError(\n bundle.currentState.principalId,\n cause,\n );\n }\n };\n return {\n readName,\n async loadEncryptionKey(): Promise<GroupMetadataKey> {\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n const containers = await loadContainers(input.execSql);\n const container = containers.find(\n (row) =>\n row.organizationId === input.organizationId &&\n row.systemSlot === slot,\n );\n if (!container)\n throw new Error(\n \"Organization metadata container has not been discovered\",\n );\n const keyring = await loaded(container.id);\n if (!keyring) throw new Error(\"Group metadata container is unavailable\");\n return keyring.current;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"groupMetadataAccess.js","sourceRoot":"","sources":["groupMetadataAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EAGpB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAE1G,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,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AAG,MAAM,6CAA6C,CAAC;gBAC/D,cAAc,EAAE,KAAK,CAAC,cAAc;aACrC,CAAC,CAAC;YACH,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACvD,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAC/B,CAAC,GAAG,EAAE,EAAE,CACN,GAAG,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;gBAC3C,GAAG,CAAC,UAAU,KAAK,IAAI,CAC1B,CAAC;YACF,IAAI,CAAC,SAAS;gBACZ,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;YACJ,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YAC3C,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;YACzE,OAAO,OAAO,CAAC,OAAO,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n decryptGroupMetadata,\n type GroupMetadataKey,\n type ReferencedPrincipalHead,\n readGroupMetadata,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../data/documents/shared/containerKek\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { loadContainers } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport type { GroupPolicyNameReader } from \"../../../data/principals/principalPolicyRequest\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { withMetadataRootReload } from \"./groupMetadataErrors\";\n\nexport interface GroupMetadataAccessInput {\n readonly apiClient: {\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n };\n readonly verifyMetadataContainer: (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead | undefined,\n ) => Promise<void>;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly targetSecretKey: Uint8Array;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/**\n * A group's signed name does not open under the metadata key it cites, or opens\n * to an invalid name. Every reader holding that key gets the same result. The\n * API checks the citation but can never check the ciphertext, so a dishonest\n * admin can sign such a name; directory walks isolate the group instead of\n * failing every name in the organization.\n */\nexport class GroupMetadataUnreadableError extends Error {\n constructor(groupId: string, cause: unknown) {\n super(`Group ${groupId} metadata cannot be decrypted`, { cause });\n this.name = \"GroupMetadataUnreadableError\";\n }\n}\n\nfunction loadMetadataKeyring(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n return withMetadataRootReload(\n () => loadMetadataKeyringOnce(input, containerId),\n () => input.apiClient.evictContainerWriterProjection(containerId),\n );\n}\n\nasync function loadMetadataKeyringOnce(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n const projection =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!projection) return null;\n if (\n projection.containerId !== containerId ||\n projection.organizationId !== input.organizationId\n )\n throw new Error(\"Group metadata container is unavailable\");\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n if (\n state.organizationId !== input.organizationId ||\n state.systemSlot !== slot ||\n state.parentContainerId !== null\n )\n throw new Error(\n \"Group metadata requires the signed organization metadata container\",\n );\n await input.verifyMetadataContainer(\n state,\n projection.policyEvidence.organization?.head,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keys = await unwrapContainerKekPath({\n ...input,\n projection,\n secretKey: input.targetSecretKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keyMaterial = keys.get(target.kek.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata container key is unavailable\");\n return {\n current: {\n organizationId: input.organizationId,\n containerId,\n containerKeyEpochId: target.kek.containerKeyEpochId,\n keyMaterial,\n },\n keys,\n };\n}\n\n/** Uses the shared metadata container's authenticated keyring, including old epochs. */\nexport function createGroupMetadataAccess(input: GroupMetadataAccessInput) {\n const loads = new Map<\n string,\n Promise<{\n current: GroupMetadataKey;\n keys: ReadonlyMap<string, Uint8Array>;\n } | null>\n >();\n function loaded(containerId: string) {\n let pending = loads.get(containerId);\n if (!pending) {\n pending = loadMetadataKeyring(input, containerId);\n loads.set(containerId, pending);\n }\n return pending;\n }\n const readName: GroupPolicyNameReader = async (bundle) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (\n metadata.organizationId !== input.organizationId ||\n metadata.groupId !== bundle.currentState.principalId ||\n bundle.currentState.principalType !== \"group\"\n )\n throw new Error(\"Group metadata scope does not match its signed group\");\n const keyring = await loaded(metadata.containerId);\n const keyMaterial = keyring?.keys.get(metadata.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata historical key is unavailable\");\n try {\n return await decryptGroupMetadata({\n key: { ...metadata, keyMaterial },\n groupId: bundle.currentState.principalId,\n payload: bundle.currentPayload.ciphertext,\n });\n } catch (cause) {\n throw new GroupMetadataUnreadableError(\n bundle.currentState.principalId,\n cause,\n );\n }\n };\n return {\n readName,\n async loadEncryptionKey(): Promise<GroupMetadataKey> {\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n const containers = await loadContainers(input.execSql);\n const container = containers.find(\n (row) =>\n row.organizationId === input.organizationId &&\n row.systemSlot === slot,\n );\n if (!container)\n throw new Error(\n \"Organization metadata container has not been discovered\",\n );\n const keyring = await loaded(container.id);\n if (!keyring) throw new Error(\"Group metadata container is unavailable\");\n return keyring.current;\n },\n };\n}\n"]}
|
|
@@ -25,7 +25,7 @@ export declare function createRuntimeGroupMetadataAccess(runtime: GroupMetadataR
|
|
|
25
25
|
readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;
|
|
26
26
|
readonly recoveryBatch: object;
|
|
27
27
|
}): {
|
|
28
|
-
readName: import("
|
|
28
|
+
readName: import("../../../data/principals/principalPolicyRequest.js").GroupPolicyNameReader;
|
|
29
29
|
loadEncryptionKey(): Promise<import("../../../internal/crypto/index.js").GroupMetadataKey>;
|
|
30
30
|
};
|
|
31
31
|
export {};
|
|
@@ -2,10 +2,10 @@ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
4
|
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
5
|
+
import { readGroupPolicyPayloadName, } from "../../../data/principals/principalPolicyRequest.js";
|
|
5
6
|
import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
|
|
6
7
|
import { GroupMetadataUnreadableError } from "../groupMetadata/groupMetadataAccess.js";
|
|
7
8
|
import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
|
|
8
|
-
import { readGroupPolicyPayloadName, } from "../principalPolicy/principalPolicyRequest.js";
|
|
9
9
|
/** Names consume verified current artifacts; paged recovery retains their separate evidence. */
|
|
10
10
|
export async function hydrateCurrentOrganizationGroupNames(input) {
|
|
11
11
|
const authority = await loadCurrentOrganizationAuthority(input);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currentOrganizationGroupNames.js","sourceRoot":"","sources":["currentOrganizationGroupNames.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;
|
|
1
|
+
{"version":3,"file":"currentOrganizationGroupNames.js","sourceRoot":"","sources":["currentOrganizationGroupNames.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAC1H,OAAO,EAEL,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AAEzD,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AAcnF,gGAAgG;AAChG,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAAY;IAEZ,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAChE,MAAM,SAAS,GAAG;QAChB,GAAG,KAAK;QACR,iBAAiB,EACf,KAAK,CAAC,uBAAuB,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,iBAAiB;KACxE,CAAC;IACF,MAAM,KAAK,GAA2D,EAAE,CAAC;IACzE,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACrC,MAAM,SAAS,GAAsB,CAAC,SA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AA8D,CAC/D,EACD;YACE,cAAc,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,YAAY,CAAC,SAAS,EAAE;YAC7D,QAAQ,EAAE,OAAO,CAAC,YAAY,CAAC,WAAW;YAC1C,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,wBAAwB;YACnC,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CACF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport {\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport type { OrganizationDirectoryAndGroups } from \"../readModel\";\n\ntype Input = Parameters<typeof loadCurrentOrganizationAuthority>[0] & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly createCurrentNameReader?:\n | ((\n authority: Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>,\n ) => GroupPolicyNameReader)\n | undefined;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n};\n\n/** Names consume verified current artifacts; paged recovery retains their separate evidence. */\nexport async function hydrateCurrentOrganizationGroupNames(\n input: Input,\n): Promise<OrganizationDirectoryAndGroups> {\n const authority = await loadCurrentOrganizationAuthority(input);\n const nameInput = {\n ...input,\n readEncryptedName:\n input.createCurrentNameReader?.(authority) ?? input.readEncryptedName,\n };\n const names: { groupId: string; name: string; stateHash: string }[] = [];\n const unreadable = new Set<string>();\n const lifetimes: (() => boolean)[] = [authority.stillCurrent];\n for (const group of input.directory.groups) {\n const head = authority.descriptor.groupHeads.find(\n (head) => head.principalId === group.groupId,\n );\n if (!head || head.stateHash !== group.currentState?.stateHash)\n throw new Error(\"Group listing does not match the signed directory\");\n const verified = await authority.readGroup(group.groupId);\n lifetimes.push(verified.stillCurrent);\n assertGroupMetadataBinding(verified.current, authority.descriptor);\n const name = await readCurrentGroupName(nameInput, verified.current);\n if (name === null) unreadable.add(group.groupId);\n else\n names.push({ groupId: group.groupId, name, stateHash: head.stateHash });\n }\n const stillCurrent = () =>\n input.stillCurrent() && lifetimes.every((current) => current());\n assertProjectionVerificationCurrent(stillCurrent);\n // Match the authority admission performed by the full-bundle path. Group\n // name reads alone do not move group checkpoints.\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent,\n });\n await new OrganizationReadModelRepository(\n input.execSql,\n ).saveOrganizationGroupDisplayNames({\n organizationId: input.organizationId,\n names,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const byId = new Map(names.map((entry) => [entry.groupId, entry.name]));\n return {\n ...input.directory,\n groups: input.directory.groups.map((group) => ({\n ...group,\n name: byId.get(group.groupId) ?? \"\",\n nameUnreadable: unreadable.has(group.groupId),\n })),\n };\n}\n\nasync function readCurrentGroupName(\n input: Input,\n current: Parameters<GroupPolicyNameReader>[0],\n) {\n try {\n return await readGroupPolicyPayloadName(current, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: current.currentState.stateHash },\n objectId: current.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
2
|
import type { PrincipalPolicyBundleResponse } from "../../../internal/validators/response/index.js";
|
|
3
|
-
import { type GroupPolicyNameReader } from "
|
|
3
|
+
import { type GroupPolicyNameReader } from "../../../data/principals/principalPolicyRequest.js";
|
|
4
4
|
export declare class GroupMembershipNameMismatchError extends KeyingVerificationError {
|
|
5
5
|
constructor(reason: "forbidden_characters" | "name_mismatch");
|
|
6
6
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { groupPolicyNameMismatch, } from "
|
|
2
|
+
import { groupPolicyNameMismatch, } from "../../../data/principals/principalPolicyRequest.js";
|
|
3
3
|
export class GroupMembershipNameMismatchError extends KeyingVerificationError {
|
|
4
4
|
constructor(reason) {
|
|
5
5
|
super("object_mismatch", reason === "forbidden_characters"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupMembershipName.js","sourceRoot":"","sources":["groupMembershipName.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAEL,uBAAuB,GACxB,MAAM,
|
|
1
|
+
{"version":3,"file":"groupMembershipName.js","sourceRoot":"","sources":["groupMembershipName.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAEL,uBAAuB,GACxB,MAAM,iDAAiD,CAAC;AAEzD,MAAM,OAAO,gCAAiC,SAAQ,uBAAuB;IAC3E,YAAY,MAAgD;QAC1D,KAAK,CACH,iBAAiB,EACjB,MAAM,KAAK,sBAAsB;YAC/B,CAAC,CAAC,uEAAuE;YACzE,CAAC,CAAC,8DAA8D,CACnE,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,kCAAkC,CAAC;IACjD,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,cAGC,EACD,iBAAyB,EACzB,iBAAyC;IAEzC,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAC5C,cAAc,EACd,iBAAiB,EACjB,iBAAiB,CAClB,CAAC;IACF,IAAI,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,gCAAgC,CAAC,QAAQ,CAAC,CAAC;IACvD,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../../data/principals/principalPolicyRequest\";\n\nexport class GroupMembershipNameMismatchError extends KeyingVerificationError {\n constructor(reason: \"forbidden_characters\" | \"name_mismatch\") {\n super(\n \"object_mismatch\",\n reason === \"forbidden_characters\"\n ? \"Group membership name contains forbidden control or format characters\"\n : \"Group membership name does not match the signed group policy\",\n );\n this.name = \"GroupMembershipNameMismatchError\";\n }\n}\n\n/** Check the selected label only after verifying the signed policy bundle. */\nexport async function assertGroupMembershipName(\n verifiedBundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentPayload\"\n >,\n expectedGroupName: string,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<void> {\n const mismatch = await groupPolicyNameMismatch(\n verifiedBundle,\n expectedGroupName,\n readEncryptedName,\n );\n if (mismatch) {\n throw new GroupMembershipNameMismatchError(mismatch);\n }\n}\n"]}
|
|
@@ -4,10 +4,10 @@ import { KeyingCheckpointRepository } from "../../../data/persistence/keyingChec
|
|
|
4
4
|
import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
5
5
|
import { principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
6
6
|
import { principalPolicyReferenceFromBundle, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
|
|
7
|
-
import {
|
|
7
|
+
import { canonicalGroupNameKey, readGroupPolicyPayloadName, } from "../../../data/principals/principalPolicyRequest.js";
|
|
8
|
+
import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../../../data/principals/principalPolicyVerification.js";
|
|
8
9
|
import { GroupMetadataUnreadableError } from "../groupMetadata/groupMetadataAccess.js";
|
|
9
10
|
import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
|
|
10
|
-
import { canonicalGroupNameKey, readGroupPolicyPayloadName, } from "../principalPolicy/principalPolicyRequest.js";
|
|
11
11
|
/**
|
|
12
12
|
* Loads one directory group at its committed head: from the local retained
|
|
13
13
|
* bundles when they already hold that head, and from the API otherwise.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupNameUniqueness.js","sourceRoot":"","sources":["groupNameUniqueness.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EACL,kCAAkC,EAClC,yDAAyD,GAC1D,MAAM,8DAA8D,CAAC;AAKtE,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EACL,qBAAqB,EAErB,0BAA0B,GAC3B,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IACxE,MAAM,UAAU,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC5C,IAAI,SAAS,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IACjD,MAAM,eAAe,GAAG,KAAK,EAC3B,IAAwB,EACS,EAAE;QACnC,MAAM,KAAK,GAAG,MAAM,oBAAoB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACtD,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE,CAC9B,IAAI,+BAA+B,CACjC,KAAK,CAAC,OAAO,CACd,CAAC,mCAAmC,CAAC;YACpC,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,SAAS,EAAE,UAAU;SACtB,CAAC,CACH,CAAC;QACF,MAAM,SAAS,CAAC;QAChB,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,kBAAkB,CACrC,KAAK,CAAC,UAAU,CAAC,UAAU,EAC3B,0BAA0B,EAC1B,eAAe,CAChB,CAAC;IACF,4EAA4E;IAC5E,2EAA2E;IAC3E,+CAA+C;IAC/C,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../../principals/policyVerification\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport {\n canonicalGroupNameKey,\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../principalPolicy/principalPolicyRequest\";\n\nexport interface DirectoryGroupWalkInput {\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly apiClient: CurrentPrincipalPolicyReader;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The walk's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ntype DirectoryGroupHead = OrganizationAuthorityDescriptor[\"groupHeads\"][number];\n\ninterface VerifiedDirectoryGroup {\n readonly bundle: PrincipalPolicyBundleResponse;\n /** Null when the signed name does not decrypt for any member. */\n readonly name: string | null;\n readonly nameKey: string | null;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/**\n * Loads one directory group at its committed head: from the local retained\n * bundles when they already hold that head, and from the API otherwise.\n */\nasync function loadDirectoryGroupBundle(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n) {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", head.principalId);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(head, localCheckpoint);\n const bundle =\n cached ??\n (await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n head.principalId,\n ));\n if (!bundle) {\n throw new Error(\n `Organization directory group ${head.principalId} could not be loaded`,\n );\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n head,\n )\n ) {\n // Head drift is reachable by a concurrent admin mutation, so it is a\n // plain error to retry on, not an incident (as in the share path). The\n // typed errors stay for signature and projection failures.\n throw new Error(\n \"Organization directory group policy does not match the signed organization directory\",\n );\n }\n return { bundle, localCheckpoint };\n}\n\n/**\n * A bundle served from local retention was verified when it was retained, and\n * is verified again here on purpose: the re-check costs local CPU only, and it\n * keeps the name a group vouches for independent of what any earlier caller\n * trusted at retention time.\n */\nexport async function verifyDirectoryGroup(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n): Promise<VerifiedDirectoryGroup> {\n const { bundle, localCheckpoint } = await loadDirectoryGroupBundle(\n input,\n head,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(\n `Organization directory group signer key could not be loaded (${signerPublicKeys.error})`,\n );\n }\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: head,\n loadExternalAuthority: async () => input.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Organization directory group verification failed\",\n );\n }\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n assertGroupMetadataBinding(bundle, input.descriptor);\n const name = await readDirectoryGroupName(input, bundle);\n return {\n bundle,\n name,\n nameKey: name === null ? null : canonicalGroupNameKey(name),\n policy: verified.value,\n };\n}\n\n/**\n * A verified group whose name no member can open has no name to select by. The\n * walk isolates it rather than failing every name in the organization, but it\n * still records the incident: only a dishonest admin signs such a name.\n */\nexport async function readDirectoryGroupName(\n input: Pick<\n DirectoryGroupWalkInput,\n \"readEncryptedName\" | \"reportSecurityIncident\" | \"organizationId\"\n >,\n bundle: Parameters<typeof readGroupPolicyPayloadName>[0],\n): Promise<string | null> {\n try {\n return await readGroupPolicyPayloadName(bundle, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: bundle.currentState.stateHash },\n objectId: bundle.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n\n/**\n * Signed group names are the only authenticated label a member can choose a\n * group by, and the API does not make them unique within an organization. So\n * uniqueness is enforced here, where a name enters: before an admin signs a\n * new group, every group committed in the signed organization directory\n * (the reserved Admins and Members groups included) is loaded, verified\n * against its directory head, and its committed name compared by canonical\n * key. A share then needs only the target's verified name. A compromised\n * server cannot mint a signed group, so it cannot create the duplicate this\n * check refuses.\n *\n * The walk is fail-closed: one group that cannot be loaded or verified blocks\n * the creation, since an unverifiable group could carry any name. A verified\n * group whose name does not decrypt is skipped: no member can open that name,\n * so it cannot collide with one. It runs the\n * loads in parallel and retains every verified bundle, so a later creation\n * finds unchanged groups locally and fetches only those whose head moved.\n */\nconst DIRECTORY_WALK_CONCURRENCY = 4;\n\n/** Runs `work` over `items` with at most `limit` in flight, keeping order. */\nasync function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n limit: number,\n work: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = [];\n let next = 0;\n const worker = async () => {\n for (;;) {\n const index = next++;\n const item = items[index];\n if (index >= items.length || item === undefined) return;\n results[index] = await work(item);\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(limit, items.length) }, worker),\n );\n return results;\n}\n\nexport async function assertGroupNameUniqueInDirectory(\n input: DirectoryGroupWalkInput & { readonly name: string },\n): Promise<void> {\n const nameKey = canonicalGroupNameKey(input.name);\n // Each verified bundle is retained as soon as it verifies, so a failure\n // later in the walk (or a taken name) still leaves the cache warm for the\n // retry. Retention runs in a transaction on the shared connection, so the\n // writes are chained one after another while the loads stay concurrent.\n const retainedAt = new Date().toISOString();\n let retention: Promise<void> = Promise.resolve();\n const verifyAndRetain = async (\n head: DirectoryGroupHead,\n ): Promise<VerifiedDirectoryGroup> => {\n const group = await verifyDirectoryGroup(input, head);\n retention = retention.then(() =>\n new PrincipalPolicyBundleRepository(\n input.execSql,\n ).retainVerifiedPrincipalPolicyBundle({\n bundle: group.bundle,\n organizationId: input.organizationId,\n policy: group.policy,\n updatedAt: retainedAt,\n }),\n );\n await retention;\n return group;\n };\n const groups = await mapWithConcurrency(\n input.descriptor.groupHeads,\n DIRECTORY_WALK_CONCURRENCY,\n verifyAndRetain,\n );\n // A taken name is user input to correct, not evidence of tampering, so this\n // is a plain error: group creation runs under security-incident reporting,\n // which records every KeyingVerificationError.\n if (groups.some((group) => group.nameKey === nameKey)) {\n throw new Error(\n \"Another signed group in this organization already carries this name\",\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"groupNameUniqueness.js","sourceRoot":"","sources":["groupNameUniqueness.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;A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IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n canonicalGroupNameKey,\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\n\nexport interface DirectoryGroupWalkInput {\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly apiClient: CurrentPrincipalPolicyReader;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The walk's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ntype DirectoryGroupHead = OrganizationAuthorityDescriptor[\"groupHeads\"][number];\n\ninterface VerifiedDirectoryGroup {\n readonly bundle: PrincipalPolicyBundleResponse;\n /** Null when the signed name does not decrypt for any member. */\n readonly name: string | null;\n readonly nameKey: string | null;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/**\n * Loads one directory group at its committed head: from the local retained\n * bundles when they already hold that head, and from the API otherwise.\n */\nasync function loadDirectoryGroupBundle(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n) {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", head.principalId);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(head, localCheckpoint);\n const bundle =\n cached ??\n (await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n head.principalId,\n ));\n if (!bundle) {\n throw new Error(\n `Organization directory group ${head.principalId} could not be loaded`,\n );\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n head,\n )\n ) {\n // Head drift is reachable by a concurrent admin mutation, so it is a\n // plain error to retry on, not an incident (as in the share path). The\n // typed errors stay for signature and projection failures.\n throw new Error(\n \"Organization directory group policy does not match the signed organization directory\",\n );\n }\n return { bundle, localCheckpoint };\n}\n\n/**\n * A bundle served from local retention was verified when it was retained, and\n * is verified again here on purpose: the re-check costs local CPU only, and it\n * keeps the name a group vouches for independent of what any earlier caller\n * trusted at retention time.\n */\nexport async function verifyDirectoryGroup(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n): Promise<VerifiedDirectoryGroup> {\n const { bundle, localCheckpoint } = await loadDirectoryGroupBundle(\n input,\n head,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(\n `Organization directory group signer key could not be loaded (${signerPublicKeys.error})`,\n );\n }\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: head,\n loadExternalAuthority: async () => input.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Organization directory group verification failed\",\n );\n }\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n assertGroupMetadataBinding(bundle, input.descriptor);\n const name = await readDirectoryGroupName(input, bundle);\n return {\n bundle,\n name,\n nameKey: name === null ? null : canonicalGroupNameKey(name),\n policy: verified.value,\n };\n}\n\n/**\n * A verified group whose name no member can open has no name to select by. The\n * walk isolates it rather than failing every name in the organization, but it\n * still records the incident: only a dishonest admin signs such a name.\n */\nexport async function readDirectoryGroupName(\n input: Pick<\n DirectoryGroupWalkInput,\n \"readEncryptedName\" | \"reportSecurityIncident\" | \"organizationId\"\n >,\n bundle: Parameters<typeof readGroupPolicyPayloadName>[0],\n): Promise<string | null> {\n try {\n return await readGroupPolicyPayloadName(bundle, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: bundle.currentState.stateHash },\n objectId: bundle.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n\n/**\n * Signed group names are the only authenticated label a member can choose a\n * group by, and the API does not make them unique within an organization. So\n * uniqueness is enforced here, where a name enters: before an admin signs a\n * new group, every group committed in the signed organization directory\n * (the reserved Admins and Members groups included) is loaded, verified\n * against its directory head, and its committed name compared by canonical\n * key. A share then needs only the target's verified name. A compromised\n * server cannot mint a signed group, so it cannot create the duplicate this\n * check refuses.\n *\n * The walk is fail-closed: one group that cannot be loaded or verified blocks\n * the creation, since an unverifiable group could carry any name. A verified\n * group whose name does not decrypt is skipped: no member can open that name,\n * so it cannot collide with one. It runs the\n * loads in parallel and retains every verified bundle, so a later creation\n * finds unchanged groups locally and fetches only those whose head moved.\n */\nconst DIRECTORY_WALK_CONCURRENCY = 4;\n\n/** Runs `work` over `items` with at most `limit` in flight, keeping order. */\nasync function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n limit: number,\n work: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = [];\n let next = 0;\n const worker = async () => {\n for (;;) {\n const index = next++;\n const item = items[index];\n if (index >= items.length || item === undefined) return;\n results[index] = await work(item);\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(limit, items.length) }, worker),\n );\n return results;\n}\n\nexport async function assertGroupNameUniqueInDirectory(\n input: DirectoryGroupWalkInput & { readonly name: string },\n): Promise<void> {\n const nameKey = canonicalGroupNameKey(input.name);\n // Each verified bundle is retained as soon as it verifies, so a failure\n // later in the walk (or a taken name) still leaves the cache warm for the\n // retry. Retention runs in a transaction on the shared connection, so the\n // writes are chained one after another while the loads stay concurrent.\n const retainedAt = new Date().toISOString();\n let retention: Promise<void> = Promise.resolve();\n const verifyAndRetain = async (\n head: DirectoryGroupHead,\n ): Promise<VerifiedDirectoryGroup> => {\n const group = await verifyDirectoryGroup(input, head);\n retention = retention.then(() =>\n new PrincipalPolicyBundleRepository(\n input.execSql,\n ).retainVerifiedPrincipalPolicyBundle({\n bundle: group.bundle,\n organizationId: input.organizationId,\n policy: group.policy,\n updatedAt: retainedAt,\n }),\n );\n await retention;\n return group;\n };\n const groups = await mapWithConcurrency(\n input.descriptor.groupHeads,\n DIRECTORY_WALK_CONCURRENCY,\n verifyAndRetain,\n );\n // A taken name is user input to correct, not evidence of tampering, so this\n // is a plain error: group creation runs under security-incident reporting,\n // which records every KeyingVerificationError.\n if (groups.some((group) => group.nameKey === nameKey)) {\n throw new Error(\n \"Another signed group in this organization already carries this name\",\n );\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 { signedGroupPolicyRequest } from "../../../data/principals/principalPolicyRequest.js";
|
|
5
6
|
import { rewrapProjectionMemberEnvelopes, toRecipientEntries, } from "../principalPolicy/principalPolicyRecipients.js";
|
|
6
|
-
import { signedGroupPolicyRequest } from "../principalPolicy/principalPolicyRequest.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;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAChH,OAAO,EAAE,8BAA8B,EAAE,MAAM,iDAAiD,CAAC;AAGjG,OAAO,EACL,+BAA+B,EAC/B,kBAAkB,GACn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,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 type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { TrustedUserIdentity } from \"../../../data/trustedUserIdentity\";\nimport {\n rewrapProjectionMemberEnvelopes,\n toRecipientEntries,\n} from \"../principalPolicy/principalPolicyRecipients\";\nimport { signedGroupPolicyRequest } from \"../principalPolicy/principalPolicyRequest\";\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
|
+
{"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,mBAA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AAQ;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 { 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.signingKeyPair,\n });\n });\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { verifyPrincipalPolicyBundle, } from "../../../internal/crypto/index.js"
|
|
|
2
2
|
import { throwKeyingVerificationErrorWithContext } from "../../../data/keyingProjectionVerification/error.js";
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
4
|
import { verifyPrincipalPolicyBundleWithExternalOrganizationAdmins } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
|
|
5
|
-
import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "
|
|
5
|
+
import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../../../data/principals/principalPolicyVerification.js";
|
|
6
6
|
function signerPublicKeyLoadErrorMessage(code) {
|
|
7
7
|
switch (code) {
|
|
8
8
|
case "fingerprint-mismatch":
|