@tearleads/client-sdk 0.1.199 → 0.1.201

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +2 -2
  2. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  3. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
  4. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  5. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +6 -7
  6. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  7. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js +4 -16
  8. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -1
  9. package/data/persistence/principalMutationJournalPersistence.d.ts +20 -13
  10. package/data/persistence/principalMutationJournalPersistence.js +54 -43
  11. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  12. package/data/persistence/principalPolicy/heldPrincipalState.js +2 -11
  13. package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
  14. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +14 -65
  15. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
  16. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +180 -0
  17. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -0
  18. package/data/persistence/principalPolicy/principalPolicyPersistence.js +6 -62
  19. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
  20. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +11 -12
  21. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
  22. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +24 -40
  23. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -1
  24. package/data/principals/organizationGroupRoles.js +2 -2
  25. package/data/principals/organizationGroupRoles.js.map +1 -1
  26. package/data/principals/principalPolicyCrypto.js +2 -2
  27. package/data/principals/principalPolicyCrypto.js.map +1 -1
  28. package/package.json +1 -1
  29. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
  30. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  31. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -5
  32. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  33. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  34. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  35. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +4 -11
  36. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  37. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +7 -9
  38. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  39. package/workflows/organizations/groupShare/shareWithGroup.js +2 -2
  40. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  41. package/workflows/organizations/groups/deleteOrganizationGroup.js +2 -4
  42. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  43. package/workflows/organizations/groups/organizationGroupDirectory.js +2 -4
  44. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  45. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js +5 -7
  46. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js.map +1 -1
  47. package/workflows/organizations/principalMutations/principalMutationJournalSession.js +4 -6
  48. package/workflows/organizations/principalMutations/principalMutationJournalSession.js.map +1 -1
  49. package/workflows/organizations/readModel/localReadModelDetails.js +3 -3
  50. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  51. package/workflows/principals/externalAdminPolicy.js +2 -4
  52. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  53. package/workflows/principals/policyCache/index.js +3 -5
  54. package/workflows/principals/policyCache/index.js.map +1 -1
  55. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +3 -2
  56. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  57. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
  58. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  59. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
  60. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  61. package/workflows/registration/registrationPrincipalPolicyPersistence.js +2 -4
  62. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  63. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
  64. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, normalizePrincipalProjectionMembers, signPrincipalState, toFingerprint, } from "../../../internal/crypto/index.js";
2
2
  import { bytesToBase64 } from "../../../internal/encoding/index.js";
3
3
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
- import { persistLocallyAcknowledgedPrincipalPolicyBundles } from "../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js";
4
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
5
  import { encodeOrganizationAuthorityDescriptor, normalizeOrganizationGroupHeads, } from "../../../data/principals/organizationAuthorityDescriptor.js";
6
6
  import { assertGroupNameUniqueInDirectory } from "../groupNames/groupNameUniqueness.js";
7
7
  import { acknowledgeGroupPolicyBundle, acknowledgeInitialGroupPolicy, } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
@@ -131,14 +131,12 @@ export async function commitCreatedGroupToDirectory(input) {
131
131
  request: organizationRequest,
132
132
  response: stored.organizationPolicy,
133
133
  });
134
- await persistLocallyAcknowledgedPrincipalPolicyBundles({
134
+ await new PrincipalPolicyBundleRepository(input.execSql).persistLocallyAcknowledgedPrincipalPolicyBundles({
135
135
  entries: [
136
136
  { bundle: acknowledged.bundle, policy: acknowledged.policy },
137
137
  organization,
138
138
  ],
139
- execSql: input.execSql,
140
139
  organizationId: input.organizationId,
141
- updatedAt: new Date().toISOString(),
142
140
  stillCurrent: input.stillCurrent,
143
141
  });
144
142
  assertProjectionVerificationCurrent(input.stillCurrent);
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupDirectory.js","sourceRoot":"","sources":["organizationGroupDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,mCAAmC,EAGnC,kBAAkB,EAClB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AASpD,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,gDAAgD,EAAE,MAAM,yFAAyF,CAAC;AAC3J,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,0DAA0D,CAAC;AAQlE,OAAO,EAAE,gCAAgC,EAAE,MAAM,mCAAmC,CAAC;AACrF,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,mDAAmD,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,+BAA+B,EAAE,MAAM,8CAA8C,CAAC;AAK/F,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAErC,SAAS,qBAAqB,CAC5B,IAA6B;IAE7B,IAAI,IAAI,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,EA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AE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE;YAC5D,YAAY;SACb;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { persistLocallyAcknowledgedPrincipalPolicyBundles } from \"../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport type { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { assertGroupNameUniqueInDirectory } from \"../groupNames/groupNameUniqueness\";\nimport {\n acknowledgeGroupPolicyBundle,\n acknowledgeInitialGroupPolicy,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport { rewrapProjectionMemberEnvelopes } from \"../principalPolicy/principalPolicyRecipients\";\nimport type {\n buildInitialGroupPolicyRequest,\n GroupPolicyNameReader,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nfunction organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\nexport function removeOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupId: string;\n}): OrganizationGroupHead[] {\n if (\n input.groupId === input.descriptor.adminGroupId ||\n input.groupId === input.descriptor.memberGroupId\n ) {\n throw new Error(\"Built-in groups cannot be removed from the directory\");\n }\n const groupHeads = input.descriptor.groupHeads.filter(\n (head) => head.principalId !== input.groupId,\n );\n if (groupHeads.length === input.descriptor.groupHeads.length) {\n throw new Error(\"Organization directory does not commit the deleted group\");\n }\n return normalizeOrganizationGroupHeads(groupHeads);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes,\n projection,\n state,\n };\n}\n\nexport async function commitCreatedGroupToDirectory(input: {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly name: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly apiClient: OrganizationPrincipalPolicyApi;\n readonly execSql: ExecSql;\n readonly externalAdminPolicy: NonNullable<\n Awaited<ReturnType<typeof loadOrganizationExternalAdminPolicy>>\n >;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly request: Awaited<ReturnType<typeof buildInitialGroupPolicyRequest>>;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<{\n readonly group: OrganizationGroupSummaryResponse;\n readonly head: ReferencedPrincipalHead;\n}> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Signed group names are unique per organization; refuse a collision before\n // anything reaches the server.\n await assertGroupNameUniqueInDirectory({\n apiClient: input.apiClient,\n descriptor: input.externalAdminPolicy.descriptor,\n execSql: input.execSql,\n externalAuthority: input.externalAdminPolicy.externalAuthority,\n name: input.name,\n readEncryptedName: input.readEncryptedName,\n organizationId: input.organizationId,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n const expectedHead = await groupPolicyMutationHead(\n input.request.initialGroupPolicy,\n );\n const adminProjection =\n input.externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: input.externalAdminPolicy.bundle,\n descriptor: input.externalAdminPolicy.descriptor,\n groupHeads: [\n ...input.externalAdminPolicy.descriptor.groupHeads,\n organizationGroupHead(expectedHead),\n ],\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...input.request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be created\");\n }\n const acknowledged = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request: input.request,\n response: stored.group,\n stateHash: expectedHead.stateHash,\n });\n const organization = await acknowledgeGroupPolicyBundle({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: await groupPolicyMutationHead(organizationRequest),\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [\n { bundle: acknowledged.bundle, policy: acknowledged.policy },\n organization,\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { group: stored.group, head: expectedHead };\n}\n"]}
1
+ {"version":3,"file":"organizationGroupDirectory.js","sourceRoot":"","sources":["organizationGroupDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,mCAAmC,EAGnC,kBAAkB,EAClB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AASpD,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,0DAA0D,CAAC;AAQlE,OAAO,EAAE,gCAAgC,EAAE,MAAM,mCAAmC,CAAC;AACrF,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,mDAAmD,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,+BAA+B,EAAE,MAAM,8CAA8C,CAAC;AAK/F,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAErC,SAAS,qBAAqB,CAC5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B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,gDAAgD,CAAC;QACjD,OAAO,EAAE;YACP,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE;YAC5D,YAAY;SACb;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport type { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { assertGroupNameUniqueInDirectory } from \"../groupNames/groupNameUniqueness\";\nimport {\n acknowledgeGroupPolicyBundle,\n acknowledgeInitialGroupPolicy,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport { rewrapProjectionMemberEnvelopes } from \"../principalPolicy/principalPolicyRecipients\";\nimport type {\n buildInitialGroupPolicyRequest,\n GroupPolicyNameReader,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nfunction organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\nexport function removeOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupId: string;\n}): OrganizationGroupHead[] {\n if (\n input.groupId === input.descriptor.adminGroupId ||\n input.groupId === input.descriptor.memberGroupId\n ) {\n throw new Error(\"Built-in groups cannot be removed from the directory\");\n }\n const groupHeads = input.descriptor.groupHeads.filter(\n (head) => head.principalId !== input.groupId,\n );\n if (groupHeads.length === input.descriptor.groupHeads.length) {\n throw new Error(\"Organization directory does not commit the deleted group\");\n }\n return normalizeOrganizationGroupHeads(groupHeads);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes,\n projection,\n state,\n };\n}\n\nexport async function commitCreatedGroupToDirectory(input: {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly name: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly apiClient: OrganizationPrincipalPolicyApi;\n readonly execSql: ExecSql;\n readonly externalAdminPolicy: NonNullable<\n Awaited<ReturnType<typeof loadOrganizationExternalAdminPolicy>>\n >;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly request: Awaited<ReturnType<typeof buildInitialGroupPolicyRequest>>;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<{\n readonly group: OrganizationGroupSummaryResponse;\n readonly head: ReferencedPrincipalHead;\n}> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Signed group names are unique per organization; refuse a collision before\n // anything reaches the server.\n await assertGroupNameUniqueInDirectory({\n apiClient: input.apiClient,\n descriptor: input.externalAdminPolicy.descriptor,\n execSql: input.execSql,\n externalAuthority: input.externalAdminPolicy.externalAuthority,\n name: input.name,\n readEncryptedName: input.readEncryptedName,\n organizationId: input.organizationId,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n const expectedHead = await groupPolicyMutationHead(\n input.request.initialGroupPolicy,\n );\n const adminProjection =\n input.externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: input.externalAdminPolicy.bundle,\n descriptor: input.externalAdminPolicy.descriptor,\n groupHeads: [\n ...input.externalAdminPolicy.descriptor.groupHeads,\n organizationGroupHead(expectedHead),\n ],\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...input.request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be created\");\n }\n const acknowledged = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request: input.request,\n response: stored.group,\n stateHash: expectedHead.stateHash,\n });\n const organization = await acknowledgeGroupPolicyBundle({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: await groupPolicyMutationHead(organizationRequest),\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [\n { bundle: acknowledged.bundle, policy: acknowledged.policy },\n organization,\n ],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { group: stored.group, head: expectedHead };\n}\n"]}
@@ -1,13 +1,13 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { canonicalKeyingJsonString } from "../../../data/keying/canonicalJson.js";
3
3
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
- import { clearPrincipalMutationJournal, loadPrincipalMutationJournal, } from "../../../data/persistence/principalMutationJournalPersistence.js";
4
+ import { PrincipalMutationJournalRepository } from "../../../data/persistence/principalMutationJournalPersistence.js";
5
5
  import { openPrincipalMutation, principalMutationJournalScopeId, } from "../../../data/principals/principalMutationJournal.js";
6
6
  import { principalMutationJournalRecordId, UnreadablePrincipalMutationError, } from "../../../data/principals/principalMutationJournalRecord.js";
7
7
  import { getOrCreatePrincipalPolicyCoordinator } from "../../../data/principals/principalPolicyCoordinator.js";
8
8
  async function loadAuthenticatedMutation(input) {
9
9
  assertProjectionVerificationCurrent(input.stillCurrent);
10
- const row = await loadPrincipalMutationJournal(input.execSql, await principalMutationJournalScopeId(input.scope));
10
+ const row = await new PrincipalMutationJournalRepository(input.execSql).loadPrincipalMutationJournal(await principalMutationJournalScopeId(input.scope));
11
11
  assertProjectionVerificationCurrent(input.stillCurrent);
12
12
  if (!row)
13
13
  return null;
@@ -37,7 +37,7 @@ export async function discardUnreadableJournaledPrincipalMutation(input) {
37
37
  const expected = input.recordId;
38
38
  return getOrCreatePrincipalPolicyCoordinator(input.execSql).runJournalOperation(input.scope, async () => {
39
39
  assertProjectionVerificationCurrent(input.stillCurrent);
40
- const row = await loadPrincipalMutationJournal(input.execSql, await principalMutationJournalScopeId(input.scope));
40
+ const row = await new PrincipalMutationJournalRepository(input.execSql).loadPrincipalMutationJournal(await principalMutationJournalScopeId(input.scope));
41
41
  assertProjectionVerificationCurrent(input.stillCurrent);
42
42
  if (!row)
43
43
  return false;
@@ -58,8 +58,7 @@ export async function discardUnreadableJournaledPrincipalMutation(input) {
58
58
  }
59
59
  if (!unreadable)
60
60
  throw new Error("Readable principal mutations require ordinary abandonment");
61
- const removed = await clearPrincipalMutationJournal({
62
- execSql: input.execSql,
61
+ const removed = await new PrincipalMutationJournalRepository(input.execSql).clearPrincipalMutationJournal({
63
62
  row,
64
63
  stillCurrent: input.stillCurrent,
65
64
  });
@@ -90,8 +89,7 @@ export async function abandonJournaledPrincipalMutation(input) {
90
89
  if (canonicalKeyingJsonString(saved.mutation, "saved authored mutation") !==
91
90
  expected)
92
91
  throw new Error("The pending principal mutation changed after inspection");
93
- const removed = await clearPrincipalMutationJournal({
94
- execSql: input.execSql,
92
+ const removed = await new PrincipalMutationJournalRepository(input.execSql).clearPrincipalMutationJournal({
95
93
  row: saved.row,
96
94
  stillCurrent: input.stillCurrent,
97
95
  });
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationJournalManagement.js","sourceRoot":"","sources":["principalMutationJournalManagement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EAAE,mCAAmC,EAAE,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C;YAClD,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,GAAG,EAAE,KAAK,CAAC,GAAG;YACd,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,IAAI,CAAC,OAAO;YACV,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;QACJ,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n clearPrincipalMutationJournal,\n loadPrincipalMutationJournal,\n} from \"../../../data/persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n openPrincipalMutation,\n principalMutationJournalScopeId,\n} from \"../../../data/principals/principalMutationJournal\";\nimport {\n principalMutationJournalRecordId,\n UnreadablePrincipalMutationError,\n} from \"../../../data/principals/principalMutationJournalRecord\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../../data/principals/principalPolicyCoordinator\";\nimport type { PrincipalMutationJournalContext } from \"./principalMutationJournalSession\";\n\nexport interface PrincipalMutationRecoveryApi {\n readonly readPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<AuthoredPrincipalMutation | null>;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly abandonPendingPrincipalMutation: (\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n acknowledgeUnknownOutcome: true,\n ) => Promise<boolean>;\n readonly discardUnreadablePrincipalMutation: (\n organizationId: string,\n recordId: string,\n acknowledgeUnknownOutcome: true,\n ) => Promise<boolean>;\n}\n\ntype JournalIdentity = Pick<\n PrincipalMutationJournalContext,\n \"execSql\" | \"scope\" | \"signingKeyPair\" | \"stillCurrent\"\n>;\n\nasync function loadAuthenticatedMutation(input: JournalIdentity) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await loadPrincipalMutationJournal(\n input.execSql,\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return null;\n let mutation: AuthoredPrincipalMutation;\n try {\n mutation = await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n } catch (error) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!(error instanceof KeyingVerificationError)) throw error;\n const recordId = await principalMutationJournalRecordId(row);\n assertProjectionVerificationCurrent(input.stillCurrent);\n throw new UnreadablePrincipalMutationError(\n recordId,\n error.code === \"invalid_shape\" ? \"format\" : \"authentication\",\n );\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { row, mutation };\n}\n\n/** Discard only the inspected unreadable bytes; never parse them for submission. */\nexport async function discardUnreadableJournaledPrincipalMutation(\n input: JournalIdentity & {\n readonly recordId: string;\n readonly acknowledgeUnknownOutcome: true;\n },\n): Promise<boolean> {\n if (input.acknowledgeUnknownOutcome !== true)\n throw new Error(\n \"Discarding unreadable work requires acknowledging its unknown outcome\",\n );\n const expected = input.recordId;\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await loadPrincipalMutationJournal(\n input.execSql,\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return false;\n if ((await principalMutationJournalRecordId(row)) !== expected)\n throw new Error(\n \"The unreadable principal mutation changed after inspection\",\n );\n let unreadable = false;\n try {\n await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n } catch (error) {\n if (!(error instanceof KeyingVerificationError)) throw error;\n unreadable = true;\n }\n if (!unreadable)\n throw new Error(\n \"Readable principal mutations require ordinary abandonment\",\n );\n const removed = await clearPrincipalMutationJournal({\n execSql: input.execSql,\n row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!removed)\n throw new Error(\n \"The unreadable principal mutation changed during discard\",\n );\n return true;\n });\n}\n\n/** Inspect authenticated authored work without retrying it or changing checkpoints. */\nexport async function readJournaledPrincipalMutation(\n input: JournalIdentity,\n): Promise<AuthoredPrincipalMutation | null> {\n // Inspection may observe an owned dispatch; all mutations still use the lane.\n return (await loadAuthenticatedMutation(input))?.mutation ?? null;\n}\n\n/**\n * An explicit host/user choice to stop retries, not a claim that the write failed.\n * The exact inspected request must still own the lane; ordinary recovery never\n * calls this. Future authoring must still verify the latest policy state.\n */\nexport async function abandonJournaledPrincipalMutation(\n input: JournalIdentity & {\n readonly mutation: AuthoredPrincipalMutation;\n readonly acknowledgeUnknownOutcome: true;\n },\n): Promise<boolean> {\n if (input.acknowledgeUnknownOutcome !== true)\n throw new Error(\n \"Abandoning authored work requires acknowledging its unknown outcome\",\n );\n const expected = canonicalKeyingJsonString(\n JSON.parse(JSON.stringify(input.mutation)),\n \"inspected authored mutation\",\n );\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n const saved = await loadAuthenticatedMutation(input);\n if (!saved) return false;\n if (\n canonicalKeyingJsonString(saved.mutation, \"saved authored mutation\") !==\n expected\n )\n throw new Error(\n \"The pending principal mutation changed after inspection\",\n );\n const removed = await clearPrincipalMutationJournal({\n execSql: input.execSql,\n row: saved.row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!removed)\n throw new Error(\n \"The pending principal mutation changed during abandonment\",\n );\n return true;\n });\n}\n"]}
1
+ {"version":3,"file":"principalMutationJournalManagement.js","sourceRoot":"","sources":["principalMutationJournalManagement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,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B,CAAC;YACpE,QAAQ;YAER,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;QACJ,MAAM,OAAO,GAAG,MAAM,IAAI,kCAAkC,CAC1D,KAAK,CAAC,OAAO,CACd,CAAC,6BAA6B,CAAC;YAC9B,GAAG,EAAE,KAAK,CAAC,GAAG;YACd,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,IAAI,CAAC,OAAO;YACV,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;QACJ,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalMutationJournalRepository } from \"../../../data/persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n openPrincipalMutation,\n principalMutationJournalScopeId,\n} from \"../../../data/principals/principalMutationJournal\";\nimport {\n principalMutationJournalRecordId,\n UnreadablePrincipalMutationError,\n} from \"../../../data/principals/principalMutationJournalRecord\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../../data/principals/principalPolicyCoordinator\";\nimport type { PrincipalMutationJournalContext } from \"./principalMutationJournalSession\";\n\nexport interface PrincipalMutationRecoveryApi {\n readonly readPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<AuthoredPrincipalMutation | null>;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly abandonPendingPrincipalMutation: (\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n acknowledgeUnknownOutcome: true,\n ) => Promise<boolean>;\n readonly discardUnreadablePrincipalMutation: (\n organizationId: string,\n recordId: string,\n acknowledgeUnknownOutcome: true,\n ) => Promise<boolean>;\n}\n\ntype JournalIdentity = Pick<\n PrincipalMutationJournalContext,\n \"execSql\" | \"scope\" | \"signingKeyPair\" | \"stillCurrent\"\n>;\n\nasync function loadAuthenticatedMutation(input: JournalIdentity) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await new PrincipalMutationJournalRepository(\n input.execSql,\n ).loadPrincipalMutationJournal(\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return null;\n let mutation: AuthoredPrincipalMutation;\n try {\n mutation = await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n } catch (error) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!(error instanceof KeyingVerificationError)) throw error;\n const recordId = await principalMutationJournalRecordId(row);\n assertProjectionVerificationCurrent(input.stillCurrent);\n throw new UnreadablePrincipalMutationError(\n recordId,\n error.code === \"invalid_shape\" ? \"format\" : \"authentication\",\n );\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { row, mutation };\n}\n\n/** Discard only the inspected unreadable bytes; never parse them for submission. */\nexport async function discardUnreadableJournaledPrincipalMutation(\n input: JournalIdentity & {\n readonly recordId: string;\n readonly acknowledgeUnknownOutcome: true;\n },\n): Promise<boolean> {\n if (input.acknowledgeUnknownOutcome !== true)\n throw new Error(\n \"Discarding unreadable work requires acknowledging its unknown outcome\",\n );\n const expected = input.recordId;\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await new PrincipalMutationJournalRepository(\n input.execSql,\n ).loadPrincipalMutationJournal(\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return false;\n if ((await principalMutationJournalRecordId(row)) !== expected)\n throw new Error(\n \"The unreadable principal mutation changed after inspection\",\n );\n let unreadable = false;\n try {\n await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n } catch (error) {\n if (!(error instanceof KeyingVerificationError)) throw error;\n unreadable = true;\n }\n if (!unreadable)\n throw new Error(\n \"Readable principal mutations require ordinary abandonment\",\n );\n const removed = await new PrincipalMutationJournalRepository(\n input.execSql,\n ).clearPrincipalMutationJournal({\n row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!removed)\n throw new Error(\n \"The unreadable principal mutation changed during discard\",\n );\n return true;\n });\n}\n\n/** Inspect authenticated authored work without retrying it or changing checkpoints. */\nexport async function readJournaledPrincipalMutation(\n input: JournalIdentity,\n): Promise<AuthoredPrincipalMutation | null> {\n // Inspection may observe an owned dispatch; all mutations still use the lane.\n return (await loadAuthenticatedMutation(input))?.mutation ?? null;\n}\n\n/**\n * An explicit host/user choice to stop retries, not a claim that the write failed.\n * The exact inspected request must still own the lane; ordinary recovery never\n * calls this. Future authoring must still verify the latest policy state.\n */\nexport async function abandonJournaledPrincipalMutation(\n input: JournalIdentity & {\n readonly mutation: AuthoredPrincipalMutation;\n readonly acknowledgeUnknownOutcome: true;\n },\n): Promise<boolean> {\n if (input.acknowledgeUnknownOutcome !== true)\n throw new Error(\n \"Abandoning authored work requires acknowledging its unknown outcome\",\n );\n const expected = canonicalKeyingJsonString(\n JSON.parse(JSON.stringify(input.mutation)),\n \"inspected authored mutation\",\n );\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n const saved = await loadAuthenticatedMutation(input);\n if (!saved) return false;\n if (\n canonicalKeyingJsonString(saved.mutation, \"saved authored mutation\") !==\n expected\n )\n throw new Error(\n \"The pending principal mutation changed after inspection\",\n );\n const removed = await new PrincipalMutationJournalRepository(\n input.execSql,\n ).clearPrincipalMutationJournal({\n row: saved.row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!removed)\n throw new Error(\n \"The pending principal mutation changed during abandonment\",\n );\n return true;\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
- import { claimPrincipalMutationJournal, clearPrincipalMutationJournal, loadPrincipalMutationJournal, } from "../../../data/persistence/principalMutationJournalPersistence.js";
2
+ import { PrincipalMutationJournalRepository, } from "../../../data/persistence/principalMutationJournalPersistence.js";
3
3
  import { openPrincipalMutation, principalMutationJournalScopeId, sealPrincipalMutation, } from "../../../data/principals/principalMutationJournal.js";
4
4
  import { getOrCreatePrincipalPolicyCoordinator } from "../../../data/principals/principalPolicyCoordinator.js";
5
5
  import { assertAuthoredPrincipalOperationReceipt, } from "./principalOperationReceipt.js";
@@ -47,8 +47,7 @@ async function submitSavedMutation(input, row, recovering) {
47
47
  // an earlier disconnected attempt committed. Preserve the original intent.
48
48
  throw new PrincipalMutationOutcomeUnknownError();
49
49
  }
50
- await clearPrincipalMutationJournal({
51
- execSql: input.execSql,
50
+ await new PrincipalMutationJournalRepository(input.execSql).clearPrincipalMutationJournal({
52
51
  row,
53
52
  stillCurrent: input.stillCurrent,
54
53
  });
@@ -60,8 +59,7 @@ export async function submitJournaledPrincipalMutation(input) {
60
59
  return getOrCreatePrincipalPolicyCoordinator(input.execSql).runJournalOperation(input.scope, async () => {
61
60
  assertProjectionVerificationCurrent(input.stillCurrent);
62
61
  const row = await sealPrincipalMutation(input);
63
- await claimPrincipalMutationJournal({
64
- execSql: input.execSql,
62
+ await new PrincipalMutationJournalRepository(input.execSql).claimPrincipalMutationJournal({
65
63
  row,
66
64
  stillCurrent: input.stillCurrent,
67
65
  });
@@ -72,7 +70,7 @@ export async function submitJournaledPrincipalMutation(input) {
72
70
  export async function recoverJournaledPrincipalMutation(input) {
73
71
  return getOrCreatePrincipalPolicyCoordinator(input.execSql).runJournalOperation(input.scope, async () => {
74
72
  assertProjectionVerificationCurrent(input.stillCurrent);
75
- const row = await loadPrincipalMutationJournal(input.execSql, await principalMutationJournalScopeId(input.scope));
73
+ const row = await new PrincipalMutationJournalRepository(input.execSql).loadPrincipalMutationJournal(await principalMutationJournalScopeId(input.scope));
76
74
  assertProjectionVerificationCurrent(input.stillCurrent);
77
75
  if (!row)
78
76
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationJournalSession.js","sourceRoot":"","sources":["principalMutationJournalSession.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,EAC7B,4BAA4B,GAE7B,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAEL,qBAAqB,EAErB,+BAA+B,EAC/B,qBAAqB,GACtB,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,qCAAqC,EAAE,MAAM,qDAAqD,CAAC;AAE5G,OAAO,EACL,uCAAuC,GAExC,MAAM,6BAA6B,CAAC;AAcrC,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D,YAAY,OAAsB;QAChC,KAAK,CACH,wHAAwH,EACxH,OAAO,CACR,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,SAAS,mBAAmB,CAAC,MAAsB;IACjD,IAAI,MAAM,CAAC,EAAE;QAAE,OAAO,KAAK,CAAC;IAC5B,8EAA8E;IAC9E,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,IAAI,CAAC;IAC7C,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IACzC,OAAO,CACL,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;QACtD,CAAC,MAAM,CAAC,MAAM,KAAK,GAAG;YACpB,MAAM,CAAC,IAAI,KAAK,2CAA2C,CAAC,CAC/D,CAAC;AACJ,CAAC;AAED,KAA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ourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n claimPrincipalMutationJournal,\n clearPrincipalMutationJournal,\n loadPrincipalMutationJournal,\n type PrincipalMutationJournalRow,\n} from \"../../../data/persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n openPrincipalMutation,\n type PrincipalMutationJournalScope,\n principalMutationJournalScopeId,\n sealPrincipalMutation,\n} from \"../../../data/principals/principalMutationJournal\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../../data/principals/principalPolicyCoordinator\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertAuthoredPrincipalOperationReceipt,\n type PrincipalMutationResponse,\n} from \"./principalOperationReceipt\";\n\ntype MutationResult = RequestResult<PrincipalMutationResponse>;\n\nexport interface PrincipalMutationJournalContext {\n readonly execSql: ExecSql;\n readonly scope: PrincipalMutationJournalScope;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent: () => boolean;\n readonly submit: (\n mutation: AuthoredPrincipalMutation,\n ) => Promise<MutationResult>;\n}\n\nexport class PrincipalMutationOutcomeUnknownError extends Error {\n constructor(options?: ErrorOptions) {\n super(\n \"A saved policy request may have committed; resolve its outcome or explicitly abandon its retry before another mutation\",\n options,\n );\n this.name = \"PrincipalMutationOutcomeUnknownError\";\n }\n}\n\nfunction knownInitialRefusal(result: MutationResult): boolean {\n if (result.ok) return false;\n // ApiClient separates pre-dispatch cancellation from an uncertain sent write.\n if (result.kind === \"cancelled\") return true;\n if (result.kind !== \"http\") return false;\n return (\n [400, 401, 402, 403, 409].includes(result.status ?? 0) ||\n (result.status === 503 &&\n result.code === \"principal_history_preparation_unavailable\")\n );\n}\n\nasync function submitSavedMutation(\n input: PrincipalMutationJournalContext,\n row: PrincipalMutationJournalRow,\n recovering: boolean,\n): Promise<{ mutation: AuthoredPrincipalMutation; result: MutationResult }> {\n const mutation = await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Keep the authenticated copy for acknowledgement checks even if a transport\n // mutates its argument while preparing or retrying the HTTP request.\n let result: MutationResult;\n try {\n result = await input.submit(structuredClone(mutation));\n } catch (cause) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n throw new PrincipalMutationOutcomeUnknownError({ cause });\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (result.ok) {\n await assertAuthoredPrincipalOperationReceipt(mutation, result.data);\n } else if (recovering || !knownInitialRefusal(result)) {\n // A refusal today (including loss of admin access) cannot establish whether\n // an earlier disconnected attempt committed. Preserve the original intent.\n throw new PrincipalMutationOutcomeUnknownError();\n }\n await clearPrincipalMutationJournal({\n execSql: input.execSql,\n row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { mutation, result };\n}\n\n/** No HTTP begins until the exact authored request is durably claimed. */\nexport async function submitJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext & {\n readonly mutation: AuthoredPrincipalMutation;\n },\n): Promise<MutationResult> {\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await sealPrincipalMutation(input);\n await claimPrincipalMutationJournal({\n execSql: input.execSql,\n row,\n stillCurrent: input.stillCurrent,\n });\n return (await submitSavedMutation(input, row, false)).result;\n });\n}\n\n/** Retry only authenticated saved bytes, never an application mutation callback. */\nexport async function recoverJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext,\n): Promise<{\n readonly mutation: AuthoredPrincipalMutation;\n readonly response: PrincipalMutationResponse;\n} | null> {\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await loadPrincipalMutationJournal(\n input.execSql,\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return null;\n const { mutation, result } = await submitSavedMutation(input, row, true);\n if (!result.ok) throw new PrincipalMutationOutcomeUnknownError();\n return { mutation, response: result.data };\n });\n}\n"]}
1
+ {"version":3,"file":"principalMutationJournalSession.js","sourceRoot":"","sources":["principalMutationJournalSession.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,kCAAkC,GAEnC,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAEL,qBAAqB,EAErB,+BAA+B,EAC/B,qBAAqB,GACtB,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,qCAAqC,EAAE,MAAM,qDAAqD,CAAC;AAE5G,OAAO,EACL,uCAAuC,GAExC,MAAM,6BAA6B,CAAC;AAcrC,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D,YAAY,OAAsB;QAChC,KAAK,CACH,wHAAwH,EACxH,OAAO,CACR,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,SAAS,mBAAmB,CAAC,MAAsB;IACjD,IAAI,MAAM,CAAC,EAAE;QAAE,OAAO,KAAK,CAAC;IAC5B,8EAA8E;IAC9E,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,IAAI,CAAC;IAC7C,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IACzC,OAAO,CACL,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;QACtD,CAAC,MAAM,CAAC,MAAM,KAAK,GAAG;YACpB,MAAM,CAAC,IAAI,KAAK,2CAA2C,CAAC,CAC/D,CAAC;AACJ,CAAC;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AAM,CAAC,IAAI,EAAE,CAAC;IAC7C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n PrincipalMutationJournalRepository,\n type PrincipalMutationJournalRow,\n} from \"../../../data/persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n openPrincipalMutation,\n type PrincipalMutationJournalScope,\n principalMutationJournalScopeId,\n sealPrincipalMutation,\n} from \"../../../data/principals/principalMutationJournal\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../../data/principals/principalPolicyCoordinator\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertAuthoredPrincipalOperationReceipt,\n type PrincipalMutationResponse,\n} from \"./principalOperationReceipt\";\n\ntype MutationResult = RequestResult<PrincipalMutationResponse>;\n\nexport interface PrincipalMutationJournalContext {\n readonly execSql: ExecSql;\n readonly scope: PrincipalMutationJournalScope;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent: () => boolean;\n readonly submit: (\n mutation: AuthoredPrincipalMutation,\n ) => Promise<MutationResult>;\n}\n\nexport class PrincipalMutationOutcomeUnknownError extends Error {\n constructor(options?: ErrorOptions) {\n super(\n \"A saved policy request may have committed; resolve its outcome or explicitly abandon its retry before another mutation\",\n options,\n );\n this.name = \"PrincipalMutationOutcomeUnknownError\";\n }\n}\n\nfunction knownInitialRefusal(result: MutationResult): boolean {\n if (result.ok) return false;\n // ApiClient separates pre-dispatch cancellation from an uncertain sent write.\n if (result.kind === \"cancelled\") return true;\n if (result.kind !== \"http\") return false;\n return (\n [400, 401, 402, 403, 409].includes(result.status ?? 0) ||\n (result.status === 503 &&\n result.code === \"principal_history_preparation_unavailable\")\n );\n}\n\nasync function submitSavedMutation(\n input: PrincipalMutationJournalContext,\n row: PrincipalMutationJournalRow,\n recovering: boolean,\n): Promise<{ mutation: AuthoredPrincipalMutation; result: MutationResult }> {\n const mutation = await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Keep the authenticated copy for acknowledgement checks even if a transport\n // mutates its argument while preparing or retrying the HTTP request.\n let result: MutationResult;\n try {\n result = await input.submit(structuredClone(mutation));\n } catch (cause) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n throw new PrincipalMutationOutcomeUnknownError({ cause });\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (result.ok) {\n await assertAuthoredPrincipalOperationReceipt(mutation, result.data);\n } else if (recovering || !knownInitialRefusal(result)) {\n // A refusal today (including loss of admin access) cannot establish whether\n // an earlier disconnected attempt committed. Preserve the original intent.\n throw new PrincipalMutationOutcomeUnknownError();\n }\n await new PrincipalMutationJournalRepository(\n input.execSql,\n ).clearPrincipalMutationJournal({\n row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { mutation, result };\n}\n\n/** No HTTP begins until the exact authored request is durably claimed. */\nexport async function submitJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext & {\n readonly mutation: AuthoredPrincipalMutation;\n },\n): Promise<MutationResult> {\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await sealPrincipalMutation(input);\n await new PrincipalMutationJournalRepository(\n input.execSql,\n ).claimPrincipalMutationJournal({\n row,\n stillCurrent: input.stillCurrent,\n });\n return (await submitSavedMutation(input, row, false)).result;\n });\n}\n\n/** Retry only authenticated saved bytes, never an application mutation callback. */\nexport async function recoverJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext,\n): Promise<{\n readonly mutation: AuthoredPrincipalMutation;\n readonly response: PrincipalMutationResponse;\n} | null> {\n return getOrCreatePrincipalPolicyCoordinator(\n input.execSql,\n ).runJournalOperation(input.scope, async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await new PrincipalMutationJournalRepository(\n input.execSql,\n ).loadPrincipalMutationJournal(\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return null;\n const { mutation, result } = await submitSavedMutation(input, row, true);\n if (!result.ok) throw new PrincipalMutationOutcomeUnknownError();\n return { mutation, response: result.data };\n });\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { loadContainerDisplayNamesByIds } from "../../../data/persistence/container-contents/containerPersistence.js";
2
2
  import { loadOrganizationGroupDisplayNames } from "../../../data/persistence/organizations/organizationGroupNamePersistence.js";
3
3
  import { loadOrganizationReadModelProjection } from "../../../data/persistence/organizations/organizationReadModelPersistence.js";
4
- import { loadPrincipalPolicyBundle } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
4
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
5
  import { loadVerifiedOrganizationGroupRoles } from "../../../data/principals/organizationGroupRoles.js";
6
6
  import { buildOrganizationGroupPolicyHistory, buildOrganizationPolicyHistory, } from "../policyHistory/policyHistoryReadModel.js";
7
7
  import { runOrganizationPresentationRead } from "./organizationPresentationAccessState.js";
@@ -97,7 +97,7 @@ export async function loadLocalOrganizationGroupPolicyHistory(input) {
97
97
  if (!projectedHead) {
98
98
  return null;
99
99
  }
100
- const bundle = await loadPrincipalPolicyBundle(input.execSql, "group", input.groupId);
100
+ const bundle = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("group", input.groupId);
101
101
  return policyBundleMatchesProjectedHead(bundle, projectedHead)
102
102
  ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)
103
103
  : null;
@@ -125,7 +125,7 @@ export async function loadLocalOrganizationPolicyHistory(input) {
125
125
  if (!projectedHead) {
126
126
  return null;
127
127
  }
128
- const bundle = await loadPrincipalPolicyBundle(input.execSql, "organization", input.organizationId);
128
+ const bundle = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
129
129
  return policyBundleMatchesProjectedHead(bundle, projectedHead)
130
130
  ? buildOrganizationPolicyHistory(bundle)
131
131
  : null;
@@ -1 +1 @@
1
- {"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAAE,MAAM,0EAA0E,CAAC;AAC/H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sEAAsE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAgB,EAChB,MAAqD,EACrD,cAAsB;IAEtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CACxD,OAAO,EACP,cAAc,CACf,CAAC;IACF,MAAM,UAAU,GAAG,MAAM,kCAAkC,CACzD,OAAO,EACP,cAAc,CACf,CAAC;IACF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC/C,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK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c,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACzD,MAAM,cAAc,GAAG,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CACpD,CAAC,KAAK,EAAE,EAAE,CACR,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CAAC;YAClE,CAAC,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CACpE,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,YAAY,CAC/B,KAAK,CAAC,OAAO,EACb,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,OAAO;YACL,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,IAAI;YACJ,MAAM;YACN,MAAM,EAAE;gBACN,YAAY,EAAE,MAAM,CAAC,MAAM,CACzB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CACnE;gBACD,WAAW,EAAE,MAAM,CAAC,MAAM,CACxB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAClE;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.groupId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
1
+ {"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAAE,MAAM,0EAA0E,CAAC;AAC/H,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAgB,EAChB,MAAqD,EACrD,cAAsB;IAEtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CAC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,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"group\", input.groupId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, verifyPrincipalPolicyBundle, } from "../../internal/crypto/index.js";
2
2
  import { KeyingCheckpointRepository } from "../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
- import { persistVerifiedPrincipalPolicyBundlesAtomically } from "../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js";
3
+ import { PrincipalPolicyBundleRepository } from "../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
4
4
  import { parseOrganizationAuthorityDescriptor, previousStatesIncludeHead, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../data/principals/organizationAuthorityDescriptor.js";
5
5
  import { organizationAdminExternalAuthority, organizationAdminSignerUserIds, principalPolicyReferenceFromBundle, verifyOrganizationAdminPolicy, } from "../../data/principals/principalPolicyAdminSigners.js";
6
6
  import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "./policyVerification.js";
@@ -150,12 +150,10 @@ async function loadExternalAdminPolicyOnce(input, organizationId, mayRefetchDire
150
150
  policy,
151
151
  signerUserIds: organizationAdminSignerUserIds(admin.policy),
152
152
  };
153
- await persistVerifiedPrincipalPolicyBundlesAtomically({
153
+ await new PrincipalPolicyBundleRepository(input.execSql).persistVerifiedPrincipalPolicyBundlesAtomically({
154
154
  entries: externalAdminPolicyPersistenceEntries(verified),
155
- execSql: input.execSql,
156
155
  organizationId,
157
156
  stillCurrent: input.stillCurrent,
158
- updatedAt: new Date().toISOString(),
159
157
  });
160
158
  return verified;
161
159
  }
@@ -1 +1 @@
1
- {"version":3,"file":"externalAdminPolicy.js","sourceRoot":"","sources":["externalAdminPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,+CAA+C,EAAE,MAAM,iFAAiF,CAAC;AAClJ,OAAO,EAEL,oCAAoC,EACpC,yBAAyB,EACzB,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,kCAAkC,EAClC,6BAA6B,GAC9B,MAAM,mDAAmD,CAAC;AAI3D,OAAO,EACL,sCAAsC,EAEtC,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAc9B,MAAM,UAAU,qCAAqC,CACnD,SAAsC;IAKtC,OAAO;QACL,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE;QACtD,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE;KACjE,CAAC;AACJ,CAAC;AAED,SAAS,uBAAuB,CAAC,MAA+B;IAC9D,IACE,CAAC,MAAM,CAAC,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AAC;QACxD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc;QACd,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAA+B;IAE/B,MAAM,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IACjC,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC;YACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,kBAAkB,CAAC;gBAAE,MAAM,KAAK,CAAC;YACxD,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { persistVerifiedPrincipalPolicyBundlesAtomically } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n previousStatesIncludeHead,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n organizationAdminSignerUserIds,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n} from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"./currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n publishVerifiedPrincipalPolicy,\n} from \"./policyVerification\";\n\nexport interface VerifiedExternalAdminPolicy {\n readonly adminBundle: PrincipalPolicyBundleResponse;\n readonly adminGroupId: string;\n readonly adminPolicy: VerifiedPrincipalPolicy;\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly memberGroupId: string;\n readonly policy: VerifiedPrincipalPolicy;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly signerUserIds: readonly string[];\n}\n\nexport function externalAdminPolicyPersistenceEntries(\n authority: VerifiedExternalAdminPolicy,\n): ReadonlyArray<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n return [\n { bundle: authority.bundle, policy: authority.policy },\n { bundle: authority.adminBundle, policy: authority.adminPolicy },\n ];\n}\n\nfunction assertAdminsPolicyShape(policy: VerifiedPrincipalPolicy): void {\n if (\n (policy.history ?? [{ projection: policy.projection }]).some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\n/**\n * A signer the caller cannot resolve is a cache miss, but a resolved signer\n * whose trusted key differs from the one the policy signed with is a\n * verification failure, as on every other policy path (#2365 finding 23).\n */\nfunction signerKeyLoadFailure(\n error: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): null {\n if (error === \"fingerprint-mismatch\") {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"external admin policy signer key fingerprint mismatch\",\n );\n }\n return null;\n}\n\nasync function verifyOrganizationPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | null> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle: input.bundle,\n localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await publishVerifiedPrincipalPolicy(input);\n return verified.value;\n}\n\nfunction parseScopedAuthorityDescriptor(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n): OrganizationAuthorityDescriptor {\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization authority descriptor is invalid\",\n );\n }\n if (descriptor.organizationId !== organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n return descriptor;\n}\n\n/**\n * The organization and its Admins group are separate reads, so an honest\n * Admins commit between them serves a chain that extends the head the\n * directory cites: a stale directory, not tampering (#2365 finding 22). The\n * claim is checked before any signer is trusted, so it is unverified and buys\n * only one organization refetch; a disagreement after that is an incident.\n */\nclass AdminsHeadAdvanced extends Error {}\n\nasync function loadVerifiedAdminsPolicy(input: {\n readonly adminGroupId: string;\n readonly expectedHead: ReturnType<typeof requireOrganizationGroupHead>;\n readonly mayRefetchDirectory: boolean;\n readonly execSql: ExecSql;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n} | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"group\",\n input.adminGroupId,\n );\n if (!bundle) {\n return null;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedHead,\n )\n ) {\n if (\n input.mayRefetchDirectory &&\n previousStatesIncludeHead(bundle, input.expectedHead)\n ) {\n throw new AdminsHeadAdvanced();\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"reserved Admins policy does not match the signed organization directory\",\n );\n }\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyPrincipalPolicyBundle({\n bundle,\n expectedReference: input.expectedHead,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n if (\n verified.value.principalType !== \"group\" ||\n verified.value.principalId !== input.adminGroupId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"reserved Admins policy target does not match\",\n );\n }\n assertAdminsPolicyShape(verified.value);\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return { bundle, policy: verified.value };\n}\n\ninterface ExternalAdminPolicyInput {\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly execSql: ExecSql;\n readonly organizationId: string | null | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function loadExternalAdminPolicyOnce(\n input: ExternalAdminPolicyInput,\n organizationId: string,\n mayRefetchDirectory: boolean,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n organizationId,\n );\n if (!bundle) {\n return null;\n }\n const policy = await verifyOrganizationPolicy({\n bundle,\n execSql: input.execSql,\n organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!policy) {\n return null;\n }\n const descriptor = parseScopedAuthorityDescriptor(bundle, organizationId);\n const admin = await loadVerifiedAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n mayRefetchDirectory,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n execSql: input.execSql,\n currentPolicyReader: input.currentPolicyReader,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!admin) {\n return null;\n }\n\n const verified: VerifiedExternalAdminPolicy = {\n adminBundle: admin.bundle,\n adminGroupId: descriptor.adminGroupId,\n adminPolicy: admin.policy,\n bundle,\n descriptor,\n externalAuthority: organizationAdminExternalAuthority(admin.policy),\n memberGroupId: descriptor.memberGroupId,\n policy,\n signerUserIds: organizationAdminSignerUserIds(admin.policy),\n };\n await persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: externalAdminPolicyPersistenceEntries(verified),\n execSql: input.execSql,\n organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: new Date().toISOString(),\n });\n return verified;\n}\n\nexport async function loadOrganizationExternalAdminPolicy(\n input: ExternalAdminPolicyInput,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const { organizationId } = input;\n if (!organizationId) {\n return null;\n }\n try {\n try {\n return await loadExternalAdminPolicyOnce(input, organizationId, true);\n } catch (error) {\n if (!(error instanceof AdminsHeadAdvanced)) throw error;\n return await loadExternalAdminPolicyOnce(input, organizationId, false);\n }\n } catch (error) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n"]}
1
+ {"version":3,"file":"externalAdminPolicy.js","sourceRoot":"","sources":["externalAdminPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AACzH,OAAO,EAEL,oCAAoC,EACpC,yBAAyB,EACzB,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,kCAAkC,EAClC,6BAA6B,GAC9B,MAAM,mDAAmD,CAAC;AAI3D,OAAO,EACL,sCAAsC,EAEtC,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAc9B,MAAM,UAAU,qCAAqC,CACnD,SAAsC;IAKtC,OAAO;QACL,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE;QACtD,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE;KACjE,CAAC;AACJ,CAAC;AAED,SAAS,uBAAuB,CAAC,MAA+B;IAC9D,IACE,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,CA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Y,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAA+B;IAE/B,MAAM,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IACjC,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC;YACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,kBAAkB,CAAC;gBAAE,MAAM,KAAK,CAAC;YACxD,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n previousStatesIncludeHead,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n organizationAdminSignerUserIds,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n} from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"./currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n publishVerifiedPrincipalPolicy,\n} from \"./policyVerification\";\n\nexport interface VerifiedExternalAdminPolicy {\n readonly adminBundle: PrincipalPolicyBundleResponse;\n readonly adminGroupId: string;\n readonly adminPolicy: VerifiedPrincipalPolicy;\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly memberGroupId: string;\n readonly policy: VerifiedPrincipalPolicy;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly signerUserIds: readonly string[];\n}\n\nexport function externalAdminPolicyPersistenceEntries(\n authority: VerifiedExternalAdminPolicy,\n): ReadonlyArray<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n return [\n { bundle: authority.bundle, policy: authority.policy },\n { bundle: authority.adminBundle, policy: authority.adminPolicy },\n ];\n}\n\nfunction assertAdminsPolicyShape(policy: VerifiedPrincipalPolicy): void {\n if (\n (policy.history ?? [{ projection: policy.projection }]).some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\n/**\n * A signer the caller cannot resolve is a cache miss, but a resolved signer\n * whose trusted key differs from the one the policy signed with is a\n * verification failure, as on every other policy path (#2365 finding 23).\n */\nfunction signerKeyLoadFailure(\n error: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): null {\n if (error === \"fingerprint-mismatch\") {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"external admin policy signer key fingerprint mismatch\",\n );\n }\n return null;\n}\n\nasync function verifyOrganizationPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | null> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle: input.bundle,\n localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await publishVerifiedPrincipalPolicy(input);\n return verified.value;\n}\n\nfunction parseScopedAuthorityDescriptor(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n): OrganizationAuthorityDescriptor {\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization authority descriptor is invalid\",\n );\n }\n if (descriptor.organizationId !== organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n return descriptor;\n}\n\n/**\n * The organization and its Admins group are separate reads, so an honest\n * Admins commit between them serves a chain that extends the head the\n * directory cites: a stale directory, not tampering (#2365 finding 22). The\n * claim is checked before any signer is trusted, so it is unverified and buys\n * only one organization refetch; a disagreement after that is an incident.\n */\nclass AdminsHeadAdvanced extends Error {}\n\nasync function loadVerifiedAdminsPolicy(input: {\n readonly adminGroupId: string;\n readonly expectedHead: ReturnType<typeof requireOrganizationGroupHead>;\n readonly mayRefetchDirectory: boolean;\n readonly execSql: ExecSql;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n} | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"group\",\n input.adminGroupId,\n );\n if (!bundle) {\n return null;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedHead,\n )\n ) {\n if (\n input.mayRefetchDirectory &&\n previousStatesIncludeHead(bundle, input.expectedHead)\n ) {\n throw new AdminsHeadAdvanced();\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"reserved Admins policy does not match the signed organization directory\",\n );\n }\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyPrincipalPolicyBundle({\n bundle,\n expectedReference: input.expectedHead,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n if (\n verified.value.principalType !== \"group\" ||\n verified.value.principalId !== input.adminGroupId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"reserved Admins policy target does not match\",\n );\n }\n assertAdminsPolicyShape(verified.value);\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return { bundle, policy: verified.value };\n}\n\ninterface ExternalAdminPolicyInput {\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly execSql: ExecSql;\n readonly organizationId: string | null | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function loadExternalAdminPolicyOnce(\n input: ExternalAdminPolicyInput,\n organizationId: string,\n mayRefetchDirectory: boolean,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n organizationId,\n );\n if (!bundle) {\n return null;\n }\n const policy = await verifyOrganizationPolicy({\n bundle,\n execSql: input.execSql,\n organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!policy) {\n return null;\n }\n const descriptor = parseScopedAuthorityDescriptor(bundle, organizationId);\n const admin = await loadVerifiedAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n mayRefetchDirectory,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n execSql: input.execSql,\n currentPolicyReader: input.currentPolicyReader,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!admin) {\n return null;\n }\n\n const verified: VerifiedExternalAdminPolicy = {\n adminBundle: admin.bundle,\n adminGroupId: descriptor.adminGroupId,\n adminPolicy: admin.policy,\n bundle,\n descriptor,\n externalAuthority: organizationAdminExternalAuthority(admin.policy),\n memberGroupId: descriptor.memberGroupId,\n policy,\n signerUserIds: organizationAdminSignerUserIds(admin.policy),\n };\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: externalAdminPolicyPersistenceEntries(verified),\n organizationId,\n stillCurrent: input.stillCurrent,\n });\n return verified;\n}\n\nexport async function loadOrganizationExternalAdminPolicy(\n input: ExternalAdminPolicyInput,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const { organizationId } = input;\n if (!organizationId) {\n return null;\n }\n try {\n try {\n return await loadExternalAdminPolicyOnce(input, organizationId, true);\n } catch (error) {\n if (!(error instanceof AdminsHeadAdvanced)) throw error;\n return await loadExternalAdminPolicyOnce(input, organizationId, false);\n }\n } catch (error) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n"]}
@@ -2,8 +2,7 @@ import { isProjectionVerificationCancelledError } from "../../../data/keyingProj
2
2
  import { reportAndRethrowKeyingVerificationError, rethrowKeyingVerificationError, } from "../../../data/keyingProjectionVerification/error.js";
3
3
  import { dedupeReferencedPrincipalStates } from "../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js";
4
4
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
5
- import { ensurePrincipalPolicyTables } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
6
- import { loadPrincipalPolicyBundleForReference } from "../../../data/persistence/principalPolicy/principalPolicyReferencePersistence.js";
5
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
7
6
  import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
8
7
  import { errorMessage } from "../../../data/shared/errorMessage.js";
9
8
  import { externalAdminPolicyPersistenceEntries, loadOrganizationExternalAdminPolicy, } from "../externalAdminPolicy.js";
@@ -55,7 +54,6 @@ async function persistScopedPolicy(input) {
55
54
  ],
56
55
  execSql: input.execSql,
57
56
  organizationId: input.organizationId,
58
- updatedAt: new Date().toISOString(),
59
57
  stillCurrent: input.stillCurrent,
60
58
  });
61
59
  return [...externalEntries.map(({ policy }) => policy), validation.policy];
@@ -66,7 +64,7 @@ async function cacheReferencedPrincipalPolicy(execSql, reader, reference, resolv
66
64
  // must escape rather than being hidden by a canonical network retry.
67
65
  const cachedBundle = fresh
68
66
  ? null
69
- : await loadPrincipalPolicyBundleForReference(execSql, reference, localCheckpoint);
67
+ : await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);
70
68
  let bundle = cachedBundle ??
71
69
  (await reader.getCurrentPrincipalPolicy(reference.principalType, reference.principalId));
72
70
  if (!bundle) {
@@ -161,7 +159,7 @@ async function runPrincipalPolicyCache(input) {
161
159
  return [];
162
160
  }
163
161
  try {
164
- await ensurePrincipalPolicyTables(input.execSql);
162
+ await new PrincipalPolicyBundleRepository(input.execSql).ensurePrincipalPolicyTables();
165
163
  const uniqueItems = input.dedupe(input.items);
166
164
  const loadDirectory = createPolicyDirectoryLoader(input);
167
165
  let externalAdminPolicy = null;