@tearleads/client-sdk 0.1.230 → 0.1.231

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/data/principals/organizationPolicyRequest.d.ts +12 -0
  2. package/data/principals/organizationPolicyRequest.js +71 -0
  3. package/data/principals/organizationPolicyRequest.js.map +1 -0
  4. package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.d.ts +3 -3
  5. package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.js +3 -3
  6. package/data/principals/principalPolicyRequest.js.map +1 -0
  7. package/{workflows/principals/policyVerification.js → data/principals/principalPolicyVerification.js} +4 -4
  8. package/data/principals/principalPolicyVerification.js.map +1 -0
  9. package/package.json +1 -1
  10. package/workflows/organizations/groupMetadata/groupMetadataAccess.d.ts +1 -1
  11. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  12. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +1 -1
  13. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  14. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  15. package/workflows/organizations/groupNames/groupMembershipName.d.ts +1 -1
  16. package/workflows/organizations/groupNames/groupMembershipName.js +1 -1
  17. package/workflows/organizations/groupNames/groupMembershipName.js.map +1 -1
  18. package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
  19. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  20. package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
  21. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
  22. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  23. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  24. package/workflows/organizations/groupShare/currentShareGrantMutation.js +1 -1
  25. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
  26. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -1
  27. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
  28. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  29. package/workflows/organizations/groupShare/sharePrincipalPolicy.d.ts +1 -1
  30. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
  31. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  32. package/workflows/organizations/groupShare/shareWithGroup.d.ts +1 -1
  33. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  34. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  35. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  36. package/workflows/organizations/groups/groupCreation.js +1 -1
  37. package/workflows/organizations/groups/groupCreation.js.map +1 -1
  38. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  39. package/workflows/organizations/principalPolicy/index.d.ts +2 -2
  40. package/workflows/organizations/principalPolicy/index.js +1 -1
  41. package/workflows/organizations/principalPolicy/index.js.map +1 -1
  42. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  43. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  44. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  45. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  46. package/workflows/principals/externalAdminPolicy.js +1 -1
  47. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  48. package/workflows/principals/historyRecovery/principalHistoryPageAppend.js +1 -1
  49. package/workflows/principals/historyRecovery/principalHistoryPageAppend.js.map +1 -1
  50. package/workflows/principals/policyCache/index.js +1 -1
  51. package/workflows/principals/policyCache/index.js.map +1 -1
  52. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
  53. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  54. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
  55. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  56. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +1 -1
  57. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  58. package/workflows/registration/index.d.ts +2 -1
  59. package/workflows/registration/index.js +1 -1
  60. package/workflows/registration/index.js.map +1 -1
  61. package/workflows/registration/organizationProvisioning.d.ts +1 -12
  62. package/workflows/registration/organizationProvisioning.js +2 -70
  63. package/workflows/registration/organizationProvisioning.js.map +1 -1
  64. package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +0 -1
  65. package/workflows/principals/policyVerification.js.map +0 -1
@@ -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,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,kEAAkE,CAAC;AAQ1E,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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,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,gDAAgD,CAAC;QACjD,OAAO,EAAE;YACP,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE;YAC5D,YAAY;SACb;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { 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
+ {"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,kEAAkE,CAAC;AAY1E,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;AAC/F,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAErC,SAAS,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mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,gDAAgD,CAAC;QACjD,OAAO,EAAE;YACP,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE;YAC5D,YAAY;SACb;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type {\n buildInitialGroupPolicyRequest,\n GroupPolicyNameReader,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport type { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { assertGroupNameUniqueInDirectory } from \"../groupNames/groupNameUniqueness\";\nimport {\n acknowledgeGroupPolicyBundle,\n acknowledgeInitialGroupPolicy,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport { rewrapProjectionMemberEnvelopes } from \"../principalPolicy/principalPolicyRecipients\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nfunction organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\nexport function removeOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupId: string;\n}): OrganizationGroupHead[] {\n if (\n input.groupId === input.descriptor.adminGroupId ||\n input.groupId === input.descriptor.memberGroupId\n ) {\n throw new Error(\"Built-in groups cannot be removed from the directory\");\n }\n const groupHeads = input.descriptor.groupHeads.filter(\n (head) => head.principalId !== input.groupId,\n );\n if (groupHeads.length === input.descriptor.groupHeads.length) {\n throw new Error(\"Organization directory does not commit the deleted group\");\n }\n return normalizeOrganizationGroupHeads(groupHeads);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes,\n projection,\n state,\n };\n}\n\nexport async function commitCreatedGroupToDirectory(input: {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly name: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly apiClient: OrganizationPrincipalPolicyApi;\n readonly execSql: ExecSql;\n readonly externalAdminPolicy: NonNullable<\n Awaited<ReturnType<typeof loadOrganizationExternalAdminPolicy>>\n >;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly request: Awaited<ReturnType<typeof buildInitialGroupPolicyRequest>>;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<{\n readonly group: OrganizationGroupSummaryResponse;\n readonly head: ReferencedPrincipalHead;\n}> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Signed group names are unique per organization; refuse a collision before\n // anything reaches the server.\n await assertGroupNameUniqueInDirectory({\n apiClient: input.apiClient,\n descriptor: input.externalAdminPolicy.descriptor,\n execSql: input.execSql,\n externalAuthority: input.externalAdminPolicy.externalAuthority,\n name: input.name,\n readEncryptedName: input.readEncryptedName,\n organizationId: input.organizationId,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n const expectedHead = await groupPolicyMutationHead(\n input.request.initialGroupPolicy,\n );\n const adminProjection =\n input.externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: input.externalAdminPolicy.bundle,\n descriptor: input.externalAdminPolicy.descriptor,\n groupHeads: [\n ...input.externalAdminPolicy.descriptor.groupHeads,\n organizationGroupHead(expectedHead),\n ],\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...input.request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be created\");\n }\n const acknowledged = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request: input.request,\n response: stored.group,\n stateHash: expectedHead.stateHash,\n });\n const organization = await acknowledgeGroupPolicyBundle({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: await groupPolicyMutationHead(organizationRequest),\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [\n { bundle: acknowledged.bundle, policy: acknowledged.policy },\n organization,\n ],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { group: stored.group, head: expectedHead };\n}\n"]}
@@ -2,12 +2,12 @@ export { createOrganizationGroup } from "../groups/groupCreation.js";
2
2
  import type { ReferencedPrincipalHead, SigningKeyPair, VerifiedPrincipalPolicy } from "../../../internal/crypto/index.js";
3
3
  import type { ContainerMutationRequest } from "../../../internal/validators/request/index.js";
4
4
  import type { ContainerMutationResponse, PrincipalPolicyBundleResponse } from "../../../internal/validators/response/index.js";
5
+ import type { GroupPolicyNameReader } from "../../../data/principals/principalPolicyRequest.js";
6
+ import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest } from "../../../data/principals/principalPolicyRequest.js";
5
7
  import type { SecurityIncidentReporter } from "../../../data/shared/securityIncidents.js";
6
8
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
7
9
  import type { TrustedUserIdentityResolver } from "../../../data/trustedUserIdentity/index.js";
8
10
  import { type AcknowledgedGroupPolicyBundle, type PrincipalPolicyReadWriteApi } from "../groupPolicy/groupPolicyMutationContext.js";
9
- import type { GroupPolicyNameReader } from "./principalPolicyRequest.js";
10
- import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest } from "./principalPolicyRequest.js";
11
11
  export { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };
12
12
  interface PreparedGroupContainerMutations {
13
13
  readonly retiredContainerIds: readonly string[];
@@ -1,4 +1,5 @@
1
1
  export { createOrganizationGroup } from "../groups/groupCreation.js";
2
+ import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, } from "../../../data/principals/principalPolicyRequest.js";
2
3
  import { assertGroupMembershipName } from "../groupNames/groupMembershipName.js";
3
4
  import { prepareAuthoredGroupPolicy } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
4
5
  import { cacheGroupPolicy, commitGroupPolicyMutation, loadGroupPolicyMutationContext, } from "../groupPolicy/groupPolicyMutationContext.js";
@@ -6,7 +7,6 @@ import { groupPolicyMutationHead } from "../groupPolicy/groupPolicyMutationHead.
6
7
  import { buildAddGroupUserPolicyRequest, buildGroupAccessSetShrinkPolicyRequest, buildRemoveGroupUserPolicyRequest, buildSetGroupContainerGrantPolicyRequest, } from "../groupPolicy/groupPolicyRequests.js";
7
8
  import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "../groups/organizationGroupDirectory.js";
8
9
  import { projectionUserIds, resolveRequiredUserIdentities, } from "../trustedOrganizationUsers.js";
9
- import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, } from "./principalPolicyRequest.js";
10
10
  export { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };
11
11
  function createPolicyMutationCommitGuard(assertCanCommit) {
12
12
  if (!assertCanCommit)
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAmBlE,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,mDAAmD,CAAC;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QAChB,YAAY;QACZ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;IACH,OAAO,iCAAiC,CAAC;QACvC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,aAAa,EAAE,aAAa,CAAC,aAAa;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,iBAAiB,EAAE,aAAa,CAAC,iBAAiB;QAClD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;QAC1D,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,aAAa;QACb,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;KAC7D,CAAC,CAAC;AACL,CAAC","sourcesContent":["export { createOrganizationGroup } from \"../groups/groupCreation\";\n\nimport type {\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMembershipName } from \"../groupNames/groupMembershipName\";\nimport { prepareAuthoredGroupPolicy } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport {\n type AcknowledgedGroupPolicyBundle,\n cacheGroupPolicy,\n commitGroupPolicyMutation,\n loadGroupPolicyMutationContext,\n type PrincipalPolicyReadWriteApi,\n} from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n buildSetGroupContainerGrantPolicyRequest,\n} from \"../groupPolicy/groupPolicyRequests\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../groups/organizationGroupDirectory\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport type { GroupPolicyNameReader } from \"./principalPolicyRequest\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"./principalPolicyRequest\";\n\nexport { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };\n\ninterface PreparedGroupContainerMutations {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /** Sign the descendant rekeys a refused commit named; see `carry` there. */\n readonly carry?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly requests: readonly ContainerMutationRequest[];\n}\n\ntype PrepareGroupContainerMutations = (input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly nextPolicy: VerifiedPrincipalPolicy;\n}) => Promise<\n readonly ContainerMutationRequest[] | PreparedGroupContainerMutations\n>;\n\ninterface CommitAndCacheGroupPolicyMutationInput {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly beforePolicyCommit?:\n | ((head: ReferencedPrincipalHead) => void)\n | undefined;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly policyContext: Awaited<\n ReturnType<typeof loadGroupPolicyMutationContext>\n >;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nfunction createPolicyMutationCommitGuard(\n assertCanCommit: (() => void) | undefined,\n): (() => boolean) | undefined {\n if (!assertCanCommit) return undefined;\n return () => {\n assertCanCommit();\n return true;\n };\n}\n\n/**\n * Plan the container mutations the policy change rematerializes and place their\n * requests on the policy request. A bare request list has nothing to\n * acknowledge or carry; a prepared batch does both.\n */\nasync function prepareGroupContainerMutations(\n input: CommitAndCacheGroupPolicyMutationInput,\n expectedHead: ReferencedPrincipalHead,\n): Promise<Partial<PreparedGroupContainerMutations> | null> {\n if (!input.prepareContainerMutations) return null;\n const prepared = await input.prepareContainerMutations({\n currentPolicy: input.currentPolicy,\n nextPolicy: await prepareAuthoredGroupPolicy({\n currentPolicy: input.currentPolicy,\n expectedHead,\n request: input.request,\n }),\n });\n if (\"requests\" in prepared) {\n input.request.containerMutations = [...prepared.requests];\n return prepared;\n }\n input.request.containerMutations = [...prepared];\n return {};\n}\n\nasync function commitAndCacheGroupPolicyMutation(\n input: CommitAndCacheGroupPolicyMutationInput,\n): Promise<AcknowledgedGroupPolicyBundle> {\n const stillCurrent = createPolicyMutationCommitGuard(input.assertCanCommit);\n const expectedHead = await groupPolicyMutationHead(input.request);\n input.beforePolicyCommit?.(expectedHead);\n const containerMutations = await prepareGroupContainerMutations(\n input,\n expectedHead,\n );\n const nextAdminProjection = input.policyContext.isOrganizationAdminsGroup\n ? input.request.projection\n : input.policyContext.adminPolicyBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(nextAdminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection: nextAdminProjection,\n adminUsers,\n currentPolicy: input.policyContext.organizationPolicyBundle,\n descriptor: input.policyContext.organizationDescriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: input.policyContext.organizationDescriptor,\n nextHead: expectedHead,\n }),\n signerUserId: input.policyContext.signerUserId,\n signingFingerprint: input.policyContext.signingFingerprint,\n signingKeyPair: input.policyContext.signingKeyPair,\n });\n input.assertCanCommit?.();\n const acknowledgedBundle = await commitGroupPolicyMutation({\n apiClient: input.apiClient,\n carryDescendantRekeys: containerMutations?.carry,\n retiredContainerIds: () => containerMutations?.retiredContainerIds ?? [],\n currentPolicy: input.currentPolicy,\n execSql: input.execSql,\n expectedHead,\n groupId: input.groupId,\n organizationId: input.organizationId,\n organizationPolicy: input.policyContext.organizationPolicyBundle,\n organizationRequest,\n request: input.request,\n stillCurrent,\n });\n input.assertCanCommit?.();\n if (containerMutations?.acknowledge) {\n await containerMutations.acknowledge(\n acknowledgedBundle.containerMutations,\n stillCurrent,\n );\n }\n input.assertCanCommit?.();\n await input.afterPolicyCommitBeforeCache?.();\n input.assertCanCommit?.();\n await cacheGroupPolicy({\n acknowledgedMemberEnvelopes: acknowledgedBundle.currentMemberEnvelopes,\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedCurrentHead: expectedHead,\n externalAuthority: input.externalAuthority,\n groupId: input.groupId,\n localPolicyCheckpoint: {\n principalId: expectedHead.principalId,\n principalType: expectedHead.principalType,\n stateHash: expectedHead.stateHash,\n version: expectedHead.version,\n },\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n input.assertCanCommit?.();\n return acknowledgedBundle;\n}\n\nexport async function addOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentUserSecretKey: Uint8Array;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly targetUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const identities = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [\n ...projectionUserIds(policyContext.currentPolicy.currentProjection),\n input.targetUserId,\n ],\n });\n const targetUser = identities.find(\n (identity) => identity.userId === input.targetUserId,\n );\n if (!targetUser) {\n throw new Error(\n `User identity could not be loaded for ${input.targetUserId}`,\n );\n }\n const request = await buildAddGroupUserPolicyRequest({\n ...policyContext,\n currentUserSecretKey: input.currentUserSecretKey,\n currentUsers: identities.filter(\n (identity) => identity.userId !== input.targetUserId,\n ),\n reportSecurityIncident: input.reportSecurityIncident,\n targetUser,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\nexport async function removeOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly removedUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const removedKey = input.removedUserId;\n const projection = policyContext.currentPolicy.currentProjection.filter(\n (member) => member.userId !== removedKey,\n );\n if (\n projection.length === policyContext.currentPolicy.currentProjection.length\n ) {\n throw new Error(\"User is not a group member\");\n }\n const remainingUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(projection),\n });\n const request = await buildRemoveGroupUserPolicyRequest({\n ...policyContext,\n remainingUsers,\n removedUserId: input.removedUserId,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * Adds or changes one container in the group's signed complete grant set and\n * commits every resulting container rematerialization in the same request.\n */\nexport async function setOrganizationGroupContainerGrant(input: {\n readonly accessLevel: \"admin\" | \"read\" | \"write\";\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly containerId: string;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...policyContext,\n accessLevel: input.accessLevel,\n containerId: input.containerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n assertCanCommit: input.assertCanCommit,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * A group losing a container grant rotates its own key in the same request as\n * that container revoke and the rekeys of all remaining grants. This prevents\n * a later member from using the group's still-current key to open a retained\n * wrap from before the revoke.\n */\nexport async function rotateOrganizationGroupForAccessSetShrink(input: {\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly revokedContainerId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const currentUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(policyContext.currentPolicy.currentProjection),\n });\n const request = await buildGroupAccessSetShrinkPolicyRequest({\n ...policyContext,\n currentUsers,\n revokedContainerId: input.revokedContainerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAiBlE,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AAIzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,mDAAmD,CAAC;AAC/F,OAAO,EAEL,gBAAgB,EAChB,yBAAyB,EACzB,8BAA8B,GAE/B,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EACL,8BAA8B,EAC9B,sCAAsC,EACtC,iCAAiC,EACjC,wCAAwC,GACzC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,EACjB,6BA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AAK,CAAC,0BAA0B;KAC7D,CAAC,CAAC;AACL,CAAC","sourcesContent":["export { createOrganizationGroup } from \"../groups/groupCreation\";\n\nimport type {\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { GroupPolicyNameReader } from \"../../../data/principals/principalPolicyRequest\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../../../data/principals/principalPolicyRequest\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMembershipName } from \"../groupNames/groupMembershipName\";\nimport { prepareAuthoredGroupPolicy } from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport {\n type AcknowledgedGroupPolicyBundle,\n cacheGroupPolicy,\n commitGroupPolicyMutation,\n loadGroupPolicyMutationContext,\n type PrincipalPolicyReadWriteApi,\n} from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n buildSetGroupContainerGrantPolicyRequest,\n} from \"../groupPolicy/groupPolicyRequests\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../groups/organizationGroupDirectory\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nexport { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };\n\ninterface PreparedGroupContainerMutations {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /** Sign the descendant rekeys a refused commit named; see `carry` there. */\n readonly carry?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly requests: readonly ContainerMutationRequest[];\n}\n\ntype PrepareGroupContainerMutations = (input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly nextPolicy: VerifiedPrincipalPolicy;\n}) => Promise<\n readonly ContainerMutationRequest[] | PreparedGroupContainerMutations\n>;\n\ninterface CommitAndCacheGroupPolicyMutationInput {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly beforePolicyCommit?:\n | ((head: ReferencedPrincipalHead) => void)\n | undefined;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly policyContext: Awaited<\n ReturnType<typeof loadGroupPolicyMutationContext>\n >;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nfunction createPolicyMutationCommitGuard(\n assertCanCommit: (() => void) | undefined,\n): (() => boolean) | undefined {\n if (!assertCanCommit) return undefined;\n return () => {\n assertCanCommit();\n return true;\n };\n}\n\n/**\n * Plan the container mutations the policy change rematerializes and place their\n * requests on the policy request. A bare request list has nothing to\n * acknowledge or carry; a prepared batch does both.\n */\nasync function prepareGroupContainerMutations(\n input: CommitAndCacheGroupPolicyMutationInput,\n expectedHead: ReferencedPrincipalHead,\n): Promise<Partial<PreparedGroupContainerMutations> | null> {\n if (!input.prepareContainerMutations) return null;\n const prepared = await input.prepareContainerMutations({\n currentPolicy: input.currentPolicy,\n nextPolicy: await prepareAuthoredGroupPolicy({\n currentPolicy: input.currentPolicy,\n expectedHead,\n request: input.request,\n }),\n });\n if (\"requests\" in prepared) {\n input.request.containerMutations = [...prepared.requests];\n return prepared;\n }\n input.request.containerMutations = [...prepared];\n return {};\n}\n\nasync function commitAndCacheGroupPolicyMutation(\n input: CommitAndCacheGroupPolicyMutationInput,\n): Promise<AcknowledgedGroupPolicyBundle> {\n const stillCurrent = createPolicyMutationCommitGuard(input.assertCanCommit);\n const expectedHead = await groupPolicyMutationHead(input.request);\n input.beforePolicyCommit?.(expectedHead);\n const containerMutations = await prepareGroupContainerMutations(\n input,\n expectedHead,\n );\n const nextAdminProjection = input.policyContext.isOrganizationAdminsGroup\n ? input.request.projection\n : input.policyContext.adminPolicyBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(nextAdminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection: nextAdminProjection,\n adminUsers,\n currentPolicy: input.policyContext.organizationPolicyBundle,\n descriptor: input.policyContext.organizationDescriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: input.policyContext.organizationDescriptor,\n nextHead: expectedHead,\n }),\n signerUserId: input.policyContext.signerUserId,\n signingFingerprint: input.policyContext.signingFingerprint,\n signingKeyPair: input.policyContext.signingKeyPair,\n });\n input.assertCanCommit?.();\n const acknowledgedBundle = await commitGroupPolicyMutation({\n apiClient: input.apiClient,\n carryDescendantRekeys: containerMutations?.carry,\n retiredContainerIds: () => containerMutations?.retiredContainerIds ?? [],\n currentPolicy: input.currentPolicy,\n execSql: input.execSql,\n expectedHead,\n groupId: input.groupId,\n organizationId: input.organizationId,\n organizationPolicy: input.policyContext.organizationPolicyBundle,\n organizationRequest,\n request: input.request,\n stillCurrent,\n });\n input.assertCanCommit?.();\n if (containerMutations?.acknowledge) {\n await containerMutations.acknowledge(\n acknowledgedBundle.containerMutations,\n stillCurrent,\n );\n }\n input.assertCanCommit?.();\n await input.afterPolicyCommitBeforeCache?.();\n input.assertCanCommit?.();\n await cacheGroupPolicy({\n acknowledgedMemberEnvelopes: acknowledgedBundle.currentMemberEnvelopes,\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedCurrentHead: expectedHead,\n externalAuthority: input.externalAuthority,\n groupId: input.groupId,\n localPolicyCheckpoint: {\n principalId: expectedHead.principalId,\n principalType: expectedHead.principalType,\n stateHash: expectedHead.stateHash,\n version: expectedHead.version,\n },\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n input.assertCanCommit?.();\n return acknowledgedBundle;\n}\n\nexport async function addOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentUserSecretKey: Uint8Array;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly targetUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const identities = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [\n ...projectionUserIds(policyContext.currentPolicy.currentProjection),\n input.targetUserId,\n ],\n });\n const targetUser = identities.find(\n (identity) => identity.userId === input.targetUserId,\n );\n if (!targetUser) {\n throw new Error(\n `User identity could not be loaded for ${input.targetUserId}`,\n );\n }\n const request = await buildAddGroupUserPolicyRequest({\n ...policyContext,\n currentUserSecretKey: input.currentUserSecretKey,\n currentUsers: identities.filter(\n (identity) => identity.userId !== input.targetUserId,\n ),\n reportSecurityIncident: input.reportSecurityIncident,\n targetUser,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\nexport async function removeOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly removedUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const removedKey = input.removedUserId;\n const projection = policyContext.currentPolicy.currentProjection.filter(\n (member) => member.userId !== removedKey,\n );\n if (\n projection.length === policyContext.currentPolicy.currentProjection.length\n ) {\n throw new Error(\"User is not a group member\");\n }\n const remainingUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(projection),\n });\n const request = await buildRemoveGroupUserPolicyRequest({\n ...policyContext,\n remainingUsers,\n removedUserId: input.removedUserId,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * Adds or changes one container in the group's signed complete grant set and\n * commits every resulting container rematerialization in the same request.\n */\nexport async function setOrganizationGroupContainerGrant(input: {\n readonly accessLevel: \"admin\" | \"read\" | \"write\";\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly containerId: string;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...policyContext,\n accessLevel: input.accessLevel,\n containerId: input.containerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n assertCanCommit: input.assertCanCommit,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * A group losing a container grant rotates its own key in the same request as\n * that container revoke and the rekeys of all remaining grants. This prevents\n * a later member from using the group's still-current key to open a retained\n * wrap from before the revoke.\n */\nexport async function rotateOrganizationGroupForAccessSetShrink(input: {\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly revokedContainerId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<AcknowledgedGroupPolicyBundle> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const currentUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(policyContext.currentPolicy.currentProjection),\n });\n const request = await buildGroupAccessSetShrinkPolicyRequest({\n ...policyContext,\n currentUsers,\n revokedContainerId: input.revokedContainerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n"]}
@@ -4,8 +4,8 @@ import { PrincipalAcknowledgementChangedError, } from "../../../data/persistence
4
4
  import { preparePrincipalHistoryEvidencePage } from "../../../data/persistence/principalHistory/principalHistoryEvidencePersistence.js";
5
5
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
6
6
  import { ownPrincipalHistoryProtection } from "../../../data/principals/principalHistoryProtection.js";
7
+ import { collectPrincipalPolicySignerPublicKeys, publishVerifiedCurrent, } from "../../../data/principals/principalPolicyVerification.js";
7
8
  import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "../historyRecovery/principalHistoryRecoveryVerification.js";
8
- import { collectPrincipalPolicySignerPublicKeys, publishVerifiedCurrent, } from "../policyVerification.js";
9
9
  import { restoreAcknowledgedPrincipalPredecessor, } from "./acknowledgedPrincipalPredecessor.js";
10
10
  import { prepareInitialGroupCurrentPublication } from "./initialPrincipalCurrentPublication.js";
11
11
  import { sealPrincipalCurrentPublication, sealPrincipalCurrentStage, } from "./principalCurrentPublicationSeal.js";
@@ -1 +1 @@
1
- {"version":3,"file":"acknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["acknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAGL,oCAAoC,GACrC,MAAM,sEAAsE,CAAC;AAC9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH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I,CAAC;oBAEZ,MAAM,KAAK,CAAC;YAChB,CAAC;QACH,CAAC;QACD,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n PrincipalAcknowledgementChangedError,\n} from \"../../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../historyRecovery/principalHistoryRecoveryVerification\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedCurrent,\n} from \"../policyVerification\";\nimport {\n type AcknowledgedPrincipalPredecessor,\n restoreAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { reconcileAcknowledgedPrincipalCurrent } from \"./reconcileAcknowledgedPrincipalCurrent\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Capture before submitting the mutation; null only for a new group. */\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n current: PrincipalPolicyPageCurrent,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const stillCurrent = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n const {\n scopeId,\n saved,\n artifacts,\n verifier,\n previous,\n predecessorIndexRootHash,\n } = await restoreAcknowledgedPrincipalPredecessor(options, predecessor);\n const expectedHead = await checks.authoredHead(request);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const policy = await checks.acknowledgeSuccessor({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: current.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent,\n });\n await publishVerifiedCurrent(options, current, stillCurrent);\n const entry = {\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n current,\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n predecessorIndexRootHash,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** The acknowledged currents of one mutation, recorded together. */\nexport interface AcknowledgedPrincipalCurrentBatch {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\nasync function reconcilePublications(\n entries: readonly {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n }[],\n publications: readonly AcknowledgedPrincipalCurrentPublication[],\n) {\n const reconciled = [];\n for (const [index, publication] of publications.entries()) {\n const entry = entries[index];\n if (!entry) throw new Error(\"Missing acknowledgement entry\");\n reconciled.push(\n await reconcileAcknowledgedPrincipalCurrent(entry.options, publication),\n );\n }\n return reconciled;\n}\n\ninterface OwnedAcknowledgementEntry {\n readonly initialGroup: boolean;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n}\n\n/** Rebuild each acknowledged current from its owned request, then prepare it. */\nasync function preparePublications(\n entries: readonly OwnedAcknowledgementEntry[],\n checks: PrincipalAcknowledgementChecks,\n) {\n const currents: PrincipalPolicyPageCurrent[] = [];\n for (const entry of entries)\n currents.push(\n await checks.acknowledgedCurrent({\n request: entry.request,\n response: entry.response,\n }),\n );\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const [index, entry] of entries.entries()) {\n const current = currents[index];\n if (!current) throw new Error(\"Missing acknowledgement entry\");\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(\n entry.options,\n entry.request,\n current,\n entry.predecessor,\n checks,\n ),\n );\n }\n return { currents, publications };\n}\n\n/**\n * Extend authenticated local progress and retain exact acknowledged artifacts\n * atomically with pins, once `checks` accept each acknowledgement.\n */\nexport async function recordAcknowledgedPrincipalCurrents(\n input: AcknowledgedPrincipalCurrentBatch & {\n readonly checks: PrincipalAcknowledgementChecks;\n },\n): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const checks = input.checks;\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: OwnedAcknowledgementEntry[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n // Own every entry and protection key before the first await, so a caller\n // mutating a later receipt cannot change what this batch checks.\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n predecessor: structuredClone(entry.predecessor),\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const { currents, publications } = await preparePublications(\n entries,\n checks,\n );\n checks.assertDirectoryBindings(organizationId, currents);\n for (let attempt = 0; ; attempt += 1) {\n const reconciled = await reconcilePublications(entries, publications);\n try {\n await new PrincipalHistoryRepository(\n execSql,\n ).persistAcknowledgedPrincipalCurrents({\n organizationId,\n entries: reconciled,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n break;\n } catch (error) {\n if (\n !(error instanceof PrincipalAcknowledgementChangedError) ||\n attempt >= 7\n )\n throw error;\n }\n }\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
1
+ {"version":3,"file":"acknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["acknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAGL,oCAAoC,GACrC,MAAM,sEAAsE,CAAC;AAC9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EACL,sCAAsC,EACtC,sBAAsB,GACvB,MAAM,sDAAsD,CAAC;AAG9D,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAEL,uCAAuC,GACxC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAE7F,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,GAC1B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE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KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n PrincipalAcknowledgementChangedError,\n} from \"../../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedCurrent,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../historyRecovery/principalHistoryRecoveryVerification\";\nimport {\n type AcknowledgedPrincipalPredecessor,\n restoreAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { reconcileAcknowledgedPrincipalCurrent } from \"./reconcileAcknowledgedPrincipalCurrent\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Capture before submitting the mutation; null only for a new group. */\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n current: PrincipalPolicyPageCurrent,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const stillCurrent = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n const {\n scopeId,\n saved,\n artifacts,\n verifier,\n previous,\n predecessorIndexRootHash,\n } = await restoreAcknowledgedPrincipalPredecessor(options, predecessor);\n const expectedHead = await checks.authoredHead(request);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const policy = await checks.acknowledgeSuccessor({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: current.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent,\n });\n await publishVerifiedCurrent(options, current, stillCurrent);\n const entry = {\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n current,\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n predecessorIndexRootHash,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** The acknowledged currents of one mutation, recorded together. */\nexport interface AcknowledgedPrincipalCurrentBatch {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\nasync function reconcilePublications(\n entries: readonly {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n }[],\n publications: readonly AcknowledgedPrincipalCurrentPublication[],\n) {\n const reconciled = [];\n for (const [index, publication] of publications.entries()) {\n const entry = entries[index];\n if (!entry) throw new Error(\"Missing acknowledgement entry\");\n reconciled.push(\n await reconcileAcknowledgedPrincipalCurrent(entry.options, publication),\n );\n }\n return reconciled;\n}\n\ninterface OwnedAcknowledgementEntry {\n readonly initialGroup: boolean;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n}\n\n/** Rebuild each acknowledged current from its owned request, then prepare it. */\nasync function preparePublications(\n entries: readonly OwnedAcknowledgementEntry[],\n checks: PrincipalAcknowledgementChecks,\n) {\n const currents: PrincipalPolicyPageCurrent[] = [];\n for (const entry of entries)\n currents.push(\n await checks.acknowledgedCurrent({\n request: entry.request,\n response: entry.response,\n }),\n );\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const [index, entry] of entries.entries()) {\n const current = currents[index];\n if (!current) throw new Error(\"Missing acknowledgement entry\");\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(\n entry.options,\n entry.request,\n current,\n entry.predecessor,\n checks,\n ),\n );\n }\n return { currents, publications };\n}\n\n/**\n * Extend authenticated local progress and retain exact acknowledged artifacts\n * atomically with pins, once `checks` accept each acknowledgement.\n */\nexport async function recordAcknowledgedPrincipalCurrents(\n input: AcknowledgedPrincipalCurrentBatch & {\n readonly checks: PrincipalAcknowledgementChecks;\n },\n): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const checks = input.checks;\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: OwnedAcknowledgementEntry[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n // Own every entry and protection key before the first await, so a caller\n // mutating a later receipt cannot change what this batch checks.\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n predecessor: structuredClone(entry.predecessor),\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const { currents, publications } = await preparePublications(\n entries,\n checks,\n );\n checks.assertDirectoryBindings(organizationId, currents);\n for (let attempt = 0; ; attempt += 1) {\n const reconciled = await reconcilePublications(entries, publications);\n try {\n await new PrincipalHistoryRepository(\n execSql,\n ).persistAcknowledgedPrincipalCurrents({\n organizationId,\n entries: reconciled,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n break;\n } catch (error) {\n if (\n !(error instanceof PrincipalAcknowledgementChangedError) ||\n attempt >= 7\n )\n throw error;\n }\n }\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
@@ -3,8 +3,8 @@ import { assertProjectionVerificationCurrent } from "../../../data/keyingProject
3
3
  import { preparePrincipalHistoryEvidencePage } from "../../../data/persistence/principalHistory/principalHistoryEvidencePersistence.js";
4
4
  import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
5
5
  import { principalHistoryEvidenceScopeId } from "../../../data/principals/principalHistoryPrefixProtection.js";
6
+ import { collectPrincipalPolicySignerPublicKeys, publishVerifiedCurrent, } from "../../../data/principals/principalPolicyVerification.js";
6
7
  import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "../historyRecovery/principalHistoryRecoveryVerification.js";
7
- import { collectPrincipalPolicySignerPublicKeys, publishVerifiedCurrent, } from "../policyVerification.js";
8
8
  import { sealPrincipalCurrentPublication } from "./principalCurrentPublicationSeal.js";
9
9
  /** Verify a newly authored group from genesis before its atomic directory publication. */
10
10
  export async function prepareInitialGroupCurrentPublication(input, request, current, predecessor, checks) {
@@ -1 +1 @@
1
- {"version":3,"file":"initialPrincipalCurrentPublication.js","sourceRoot":"","sources":["initialPrincipalCurrentPublication.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2DAA2D,CAAC;AAE5G,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,sCAAsC,EACtC,sBAAs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A+B,CAAC;QACpD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,OAAO,CAAC,UAAU;KAC/B,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,+BAA+B,CAClD,OAAO,EACP,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,OAAO,CACR,CAAC;IACF,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO;QACL,GAAG,MAAM;QACT,MAAM,EAAE,MAAM,CAAC,KAAK;QACpB,gBAAgB,EAAE,IAAI;QACtB,wBAAwB,EAAE,IAAI;QAC9B,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO,EAAE,CAAC,KAAK,CAAC;YAChB,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { AcknowledgedPrincipalCurrentPublication } from \"../../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../historyRecovery/principalHistoryRecoveryVerification\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedCurrent,\n} from \"../policyVerification\";\nimport type { AcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport { sealPrincipalCurrentPublication } from \"./principalCurrentPublicationSeal\";\n\n/** Verify a newly authored group from genesis before its atomic directory publication. */\nexport async function prepareInitialGroupCurrentPublication(\n input: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n current: PrincipalPolicyPageCurrent,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n const expectedHead = await checks.authoredHead(request);\n if (\n predecessor !== null ||\n request.state.principalType !== \"group\" ||\n request.state.version !== 1 ||\n request.state.prevStateHash !== null ||\n !principalHeadMatchesReference(expectedHead, input.expectedHead)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Initial group publication must begin at its exact genesis\",\n );\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Initial group signer could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const verifier = createPrincipalPolicyHistoryVerifier({\n principalType: \"group\",\n principalId: expectedHead.principalId,\n });\n const entry = {\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(input, [entry]);\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const history = verifier.finish(expectedHead);\n if (!history.ok) throw history.error;\n const policy = await verifyPrincipalPolicyCurrent({\n current,\n history: history.value,\n });\n if (!policy.ok) throw policy.error;\n await publishVerifiedCurrent(input, current, stillCurrent);\n const options = {\n ...input,\n protection: {\n ...input.protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: expectedHead,\n protection: options.protection,\n });\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n current,\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n ...sealed,\n policy: policy.value,\n predecessorStage: null,\n predecessorIndexRootHash: null,\n previousPrefixProgress: null,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: input.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"initialPrincipalCurrentPublication.js","sourceRoot":"","sources":["initialPrincipalCurrentPublication.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2DAA2D,CAAC;AAC5G,OAAO,EACL,sCAAsC,EACtC,sBAAsB,GACvB,MAAM,sDAAsD,CAAC;AAE9D,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AAGjE,OAAO,EAAE,+BAA+B,EAAE,MAAM,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Y;QAClB,UAAU,EAAE,OAAO,CAAC,UAAU;KAC/B,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,+BAA+B,CAClD,OAAO,EACP,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,OAAO,CACR,CAAC;IACF,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO;QACL,GAAG,MAAM;QACT,MAAM,EAAE,MAAM,CAAC,KAAK;QACpB,gBAAgB,EAAE,IAAI;QACtB,wBAAwB,EAAE,IAAI;QAC9B,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO,EAAE,CAAC,KAAK,CAAC;YAChB,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { AcknowledgedPrincipalCurrentPublication } from \"../../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedCurrent,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../historyRecovery/principalHistoryRecoveryVerification\";\nimport type { AcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport { sealPrincipalCurrentPublication } from \"./principalCurrentPublicationSeal\";\n\n/** Verify a newly authored group from genesis before its atomic directory publication. */\nexport async function prepareInitialGroupCurrentPublication(\n input: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n current: PrincipalPolicyPageCurrent,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n const expectedHead = await checks.authoredHead(request);\n if (\n predecessor !== null ||\n request.state.principalType !== \"group\" ||\n request.state.version !== 1 ||\n request.state.prevStateHash !== null ||\n !principalHeadMatchesReference(expectedHead, input.expectedHead)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Initial group publication must begin at its exact genesis\",\n );\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Initial group signer could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const verifier = createPrincipalPolicyHistoryVerifier({\n principalType: \"group\",\n principalId: expectedHead.principalId,\n });\n const entry = {\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(input, [entry]);\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const history = verifier.finish(expectedHead);\n if (!history.ok) throw history.error;\n const policy = await verifyPrincipalPolicyCurrent({\n current,\n history: history.value,\n });\n if (!policy.ok) throw policy.error;\n await publishVerifiedCurrent(input, current, stillCurrent);\n const options = {\n ...input,\n protection: {\n ...input.protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: expectedHead,\n protection: options.protection,\n });\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n current,\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n ...sealed,\n policy: policy.value,\n predecessorStage: null,\n predecessorIndexRootHash: null,\n previousPrefixProgress: null,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: input.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n"]}
@@ -3,7 +3,7 @@ import { KeyingCheckpointRepository } from "../../data/persistence/keyingCheckpo
3
3
  import { PrincipalPolicyBundleRepository } from "../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
4
4
  import { parseOrganizationAuthorityDescriptor, previousStatesIncludeHead, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../data/principalContracts/organizationAuthorityDescriptor.js";
5
5
  import { organizationAdminExternalAuthority, organizationAdminSignerUserIds, principalPolicyReferenceFromBundle, verifyOrganizationAdminPolicy, } from "../../data/principalContracts/principalPolicyAdminSigners.js";
6
- import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "./policyVerification.js";
6
+ import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../../data/principals/principalPolicyVerification.js";
7
7
  export function externalAdminPolicyPersistenceEntries(authority) {
8
8
  return [
9
9
  { bundle: authority.bundle, policy: authority.policy },
@@ -1 +1 @@
1
- {"version":3,"file":"externalAdmin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AC;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/principalContracts/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n organizationAdminSignerUserIds,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n} from \"../../data/principalContracts/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"]}
1
+ {"version":3,"file":"externalAdminPolicy.js","sourceRoot":"","sources":["externalAdminPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OA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,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/principalContracts/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n organizationAdminSignerUserIds,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n} from \"../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n publishVerifiedPrincipalPolicy,\n} from \"../../data/principals/principalPolicyVerification\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"./currentPrincipalPolicyReader\";\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"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
- import { collectPrincipalPolicySignerPublicKeys } from "../policyVerification.js";
2
+ import { collectPrincipalPolicySignerPublicKeys } from "../../../data/principals/principalPolicyVerification.js";
3
3
  /**
4
4
  * Verify one fetched page's entries onto the stage's chain. The page's first
5
5
  * signer is authorized only by user ID against the last accepted state, so
@@ -1 +1 @@
1
- {"version":3,"file":"principalHistoryPageAppend.js","sourceRoot":"","sources":["principalHistoryPageAppend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,sCAAsC,EAAE,MAAM,uBAAuB,CAAC;AAI/E;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAO/C;IACC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IACnC,MAAM,WAAW,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,2BAA2B,EAAE,CAAC;IACvE,MAAM,IAAI,GAAG,MAAM,sCAAsC,CAAC;QACxD,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW;QACX,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;KAC/D,CAAC,CAAC;IACH,IAAI,OAAO,IAAI,IAAI;QACjB,MAAM,IAAI,uBAAuB,CAC/B,IAAI,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,iBAAiB,EACrE,8DAA8D,CAC/D,CAAC;IACJ,MAAM,iBAAiB,GAAG,MAAM,OAAO,CAAC,qBAAqB,EAAE,CAC7D,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAC5B,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CACzD,CACF,CAAC;IACF,OAAO,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC;QACjC,OAAO;QACP,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACpD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../policyVerification\";\nimport type { PrincipalHistoryRecoveryStage } from \"./principalHistoryRecoveryStage\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\n/**\n * Verify one fetched page's entries onto the stage's chain. The page's first\n * signer is authorized only by user ID against the last accepted state, so\n * it must resolve to the identity that state's signed projection committed.\n * Nothing is pinned here: a page is not yet proven to reach the expected\n * head. The verifier records its signers, published once the chain does.\n */\nexport async function appendVerifiedHistoryPage(input: {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly stage: PrincipalHistoryRecoveryStage;\n readonly bundle: Parameters<\n typeof collectPrincipalPolicySignerPublicKeys\n >[0][\"bundle\"];\n readonly entries: PrincipalPolicyPageResponse[\"previousStates\"];\n}) {\n const { options, entries } = input;\n const predecessor = input.stage.verifier.getLatestAcceptedProjection();\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n predecessor,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n ),\n );\n return input.stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n}\n"]}
1
+ {"version":3,"file":"principalHistoryPageAppend.js","sourceRoot":"","sources":["principalHistoryPageAppend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,sCAAsC,EAAE,MAAM,sDAAsD,CAAC;AAI9G;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAO/C;IACC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IACnC,MAAM,WAAW,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,2BAA2B,EAAE,CAAC;IACvE,MAAM,IAAI,GAAG,MAAM,sCAAsC,CAAC;QACxD,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW;QACX,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;KAC/D,CAAC,CAAC;IACH,IAAI,OAAO,IAAI,IAAI;QACjB,MAAM,IAAI,uBAAuB,CAC/B,IAAI,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,iBAAiB,EACrE,8DAA8D,CAC/D,CAAC;IACJ,MAAM,iBAAiB,GAAG,MAAM,OAAO,CAAC,qBAAqB,EAAE,CAC7D,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAC5B,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CACzD,CACF,CAAC;IACF,OAAO,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC;QACjC,OAAO;QACP,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACpD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../../../data/principals/principalPolicyVerification\";\nimport type { PrincipalHistoryRecoveryStage } from \"./principalHistoryRecoveryStage\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\n/**\n * Verify one fetched page's entries onto the stage's chain. The page's first\n * signer is authorized only by user ID against the last accepted state, so\n * it must resolve to the identity that state's signed projection committed.\n * Nothing is pinned here: a page is not yet proven to reach the expected\n * head. The verifier records its signers, published once the chain does.\n */\nexport async function appendVerifiedHistoryPage(input: {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly stage: PrincipalHistoryRecoveryStage;\n readonly bundle: Parameters<\n typeof collectPrincipalPolicySignerPublicKeys\n >[0][\"bundle\"];\n readonly entries: PrincipalPolicyPageResponse[\"previousStates\"];\n}) {\n const { options, entries } = input;\n const predecessor = input.stage.verifier.getLatestAcceptedProjection();\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n predecessor,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n ),\n );\n return input.stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n}\n"]}
@@ -4,10 +4,10 @@ import { dedupeReferencedPrincipalStates } from "../../../data/keyingProjectionV
4
4
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
5
5
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
6
  import { principalPolicyReferenceFromBundle } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
7
+ import { publishVerifiedPrincipalPolicy } from "../../../data/principals/principalPolicyVerification.js";
7
8
  import { errorMessage } from "../../../data/shared/errorMessage.js";
8
9
  import { reportAndRethrowKeyingVerificationError, } from "../../../data/shared/securityIncidents.js";
9
10
  import { externalAdminPolicyPersistenceEntries, loadOrganizationExternalAdminPolicy, } from "../externalAdminPolicy.js";
10
- import { publishVerifiedPrincipalPolicy } from "../policyVerification.js";
11
11
  import { persistPrincipalPolicyCacheEntries, retryPrincipalPolicyCacheAdvance, } from "./principalPolicyCacheAdvance.js";
12
12
  import { scopeReferencedPolicyForCache } from "./principalPolicyCacheScope.js";
13
13
  import { validatePrincipalPolicyBundleForCache } from "./principalPolicyCacheValidation.js";