@tearleads/client-sdk 0.1.199 → 0.1.200

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 (57) hide show
  1. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +2 -2
  2. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  3. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
  4. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  5. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +6 -7
  6. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  7. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js +4 -16
  8. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -1
  9. package/data/persistence/principalPolicy/heldPrincipalState.js +2 -11
  10. package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
  11. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +14 -65
  12. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
  13. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +180 -0
  14. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -0
  15. package/data/persistence/principalPolicy/principalPolicyPersistence.js +6 -62
  16. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
  17. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +11 -12
  18. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
  19. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +24 -40
  20. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -1
  21. package/data/principals/organizationGroupRoles.js +2 -2
  22. package/data/principals/organizationGroupRoles.js.map +1 -1
  23. package/data/principals/principalPolicyCrypto.js +2 -2
  24. package/data/principals/principalPolicyCrypto.js.map +1 -1
  25. package/package.json +1 -1
  26. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
  27. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  28. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -5
  29. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  30. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  31. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  32. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +4 -11
  33. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  34. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +7 -9
  35. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  36. package/workflows/organizations/groupShare/shareWithGroup.js +2 -2
  37. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  38. package/workflows/organizations/groups/deleteOrganizationGroup.js +2 -4
  39. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  40. package/workflows/organizations/groups/organizationGroupDirectory.js +2 -4
  41. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  42. package/workflows/organizations/readModel/localReadModelDetails.js +3 -3
  43. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  44. package/workflows/principals/externalAdminPolicy.js +2 -4
  45. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  46. package/workflows/principals/policyCache/index.js +3 -5
  47. package/workflows/principals/policyCache/index.js.map +1 -1
  48. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +3 -2
  49. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  50. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
  51. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  52. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
  53. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  54. package/workflows/registration/registrationPrincipalPolicyPersistence.js +2 -4
  55. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  56. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
  57. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAAE,MAAM,0EAA0E,CAAC;AAC/H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sEAAsE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAgB,EAChB,MAAqD,EACrD,cAAsB;IAEtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CACxD,OAAO,EACP,cAAc,CACf,CAAC;IACF,MAAM,UAAU,GAAG,MAAM,kCAAkC,CACzD,OAAO,EACP,cAAc,CACf,CAAC;IAC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C,CAAC;aAC/C,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACzD,MAAM,cAAc,GAAG,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CACpD,CAAC,KAAK,EAAE,EAAE,CACR,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CAAC;YAClE,CAAC,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CACpE,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,YAAY,CAC/B,KAAK,CAAC,OAAO,EACb,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,OAAO;YACL,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,IAAI;YACJ,MAAM;YACN,MAAM,EAAE;gBACN,YAAY,EAAE,MAAM,CAAC,MAAM,CACzB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CACnE;gBACD,WAAW,EAAE,MAAM,CAAC,MAAM,CACxB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAClE;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.groupId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
1
+ {"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAAE,MAAM,0EAA0E,CAAC;AAC/H,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAgB,EAChB,MAAqD,EACrD,cAAsB;IAEtB,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AC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"group\", input.groupId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, verifyPrincipalPolicyBundle, } from "../../internal/crypto/index.js";
2
2
  import { KeyingCheckpointRepository } from "../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
- import { persistVerifiedPrincipalPolicyBundlesAtomically } from "../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js";
3
+ import { PrincipalPolicyBundleRepository } from "../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
4
4
  import { parseOrganizationAuthorityDescriptor, previousStatesIncludeHead, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../data/principals/organizationAuthorityDescriptor.js";
5
5
  import { organizationAdminExternalAuthority, organizationAdminSignerUserIds, principalPolicyReferenceFromBundle, verifyOrganizationAdminPolicy, } from "../../data/principals/principalPolicyAdminSigners.js";
6
6
  import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "./policyVerification.js";
@@ -150,12 +150,10 @@ async function loadExternalAdminPolicyOnce(input, organizationId, mayRefetchDire
150
150
  policy,
151
151
  signerUserIds: organizationAdminSignerUserIds(admin.policy),
152
152
  };
153
- await persistVerifiedPrincipalPolicyBundlesAtomically({
153
+ await new PrincipalPolicyBundleRepository(input.execSql).persistVerifiedPrincipalPolicyBundlesAtomically({
154
154
  entries: externalAdminPolicyPersistenceEntries(verified),
155
- execSql: input.execSql,
156
155
  organizationId,
157
156
  stillCurrent: input.stillCurrent,
158
- updatedAt: new Date().toISOString(),
159
157
  });
160
158
  return verified;
161
159
  }
@@ -1 +1 @@
1
- {"version":3,"file":"externalAdminPolicy.js","sourceRoot":"","sources":["externalAdminPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,+CAA+C,EAAE,MAAM,iFAAiF,CAAC;AAClJ,OAAO,EAEL,oCAAoC,EACpC,yBAAyB,EACzB,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,kCAAkC,EAClC,6BAA6B,GAC9B,MAAM,mDAAmD,CAAC;AAI3D,OAAO,EACL,sCAAsC,EAEtC,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAc9B,MAAM,UAAU,qCAAqC,CACnD,SAAsC;IAKtC,OAAO;QACL,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE;QACtD,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,E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MAAM,CAAC;KAC5D,CAAC;IACF,MAAM,+CAA+C,CAAC;QACpD,OAAO,EAAE,qCAAqC,CAAC,QAAQ,CAAC;QACxD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc;QACd,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAA+B;IAE/B,MAAM,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IACjC,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC;YACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,kBAAkB,CAAC;gBAAE,MAAM,KAAK,CAAC;YACxD,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { persistVerifiedPrincipalPolicyBundlesAtomically } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n previousStatesIncludeHead,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n organizationAdminSignerUserIds,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n} from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"./currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n publishVerifiedPrincipalPolicy,\n} from \"./policyVerification\";\n\nexport interface VerifiedExternalAdminPolicy {\n readonly adminBundle: PrincipalPolicyBundleResponse;\n readonly adminGroupId: string;\n readonly adminPolicy: VerifiedPrincipalPolicy;\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly memberGroupId: string;\n readonly policy: VerifiedPrincipalPolicy;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly signerUserIds: readonly string[];\n}\n\nexport function externalAdminPolicyPersistenceEntries(\n authority: VerifiedExternalAdminPolicy,\n): ReadonlyArray<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n return [\n { bundle: authority.bundle, policy: authority.policy },\n { bundle: authority.adminBundle, policy: authority.adminPolicy },\n ];\n}\n\nfunction assertAdminsPolicyShape(policy: VerifiedPrincipalPolicy): void {\n if (\n (policy.history ?? [{ projection: policy.projection }]).some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\n/**\n * A signer the caller cannot resolve is a cache miss, but a resolved signer\n * whose trusted key differs from the one the policy signed with is a\n * verification failure, as on every other policy path (#2365 finding 23).\n */\nfunction signerKeyLoadFailure(\n error: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): null {\n if (error === \"fingerprint-mismatch\") {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"external admin policy signer key fingerprint mismatch\",\n );\n }\n return null;\n}\n\nasync function verifyOrganizationPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | null> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle: input.bundle,\n localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await publishVerifiedPrincipalPolicy(input);\n return verified.value;\n}\n\nfunction parseScopedAuthorityDescriptor(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n): OrganizationAuthorityDescriptor {\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization authority descriptor is invalid\",\n );\n }\n if (descriptor.organizationId !== organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n return descriptor;\n}\n\n/**\n * The organization and its Admins group are separate reads, so an honest\n * Admins commit between them serves a chain that extends the head the\n * directory cites: a stale directory, not tampering (#2365 finding 22). The\n * claim is checked before any signer is trusted, so it is unverified and buys\n * only one organization refetch; a disagreement after that is an incident.\n */\nclass AdminsHeadAdvanced extends Error {}\n\nasync function loadVerifiedAdminsPolicy(input: {\n readonly adminGroupId: string;\n readonly expectedHead: ReturnType<typeof requireOrganizationGroupHead>;\n readonly mayRefetchDirectory: boolean;\n readonly execSql: ExecSql;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n} | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"group\",\n input.adminGroupId,\n );\n if (!bundle) {\n return null;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedHead,\n )\n ) {\n if (\n input.mayRefetchDirectory &&\n previousStatesIncludeHead(bundle, input.expectedHead)\n ) {\n throw new AdminsHeadAdvanced();\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"reserved Admins policy does not match the signed organization directory\",\n );\n }\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyPrincipalPolicyBundle({\n bundle,\n expectedReference: input.expectedHead,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n if (\n verified.value.principalType !== \"group\" ||\n verified.value.principalId !== input.adminGroupId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"reserved Admins policy target does not match\",\n );\n }\n assertAdminsPolicyShape(verified.value);\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return { bundle, policy: verified.value };\n}\n\ninterface ExternalAdminPolicyInput {\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly execSql: ExecSql;\n readonly organizationId: string | null | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function loadExternalAdminPolicyOnce(\n input: ExternalAdminPolicyInput,\n organizationId: string,\n mayRefetchDirectory: boolean,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n organizationId,\n );\n if (!bundle) {\n return null;\n }\n const policy = await verifyOrganizationPolicy({\n bundle,\n execSql: input.execSql,\n organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!policy) {\n return null;\n }\n const descriptor = parseScopedAuthorityDescriptor(bundle, organizationId);\n const admin = await loadVerifiedAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n mayRefetchDirectory,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n execSql: input.execSql,\n currentPolicyReader: input.currentPolicyReader,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!admin) {\n return null;\n }\n\n const verified: VerifiedExternalAdminPolicy = {\n adminBundle: admin.bundle,\n adminGroupId: descriptor.adminGroupId,\n adminPolicy: admin.policy,\n bundle,\n descriptor,\n externalAuthority: organizationAdminExternalAuthority(admin.policy),\n memberGroupId: descriptor.memberGroupId,\n policy,\n signerUserIds: organizationAdminSignerUserIds(admin.policy),\n };\n await persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: externalAdminPolicyPersistenceEntries(verified),\n execSql: input.execSql,\n organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: new Date().toISOString(),\n });\n return verified;\n}\n\nexport async function loadOrganizationExternalAdminPolicy(\n input: ExternalAdminPolicyInput,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const { organizationId } = input;\n if (!organizationId) {\n return null;\n }\n try {\n try {\n return await loadExternalAdminPolicyOnce(input, organizationId, true);\n } catch (error) {\n if (!(error instanceof AdminsHeadAdvanced)) throw error;\n return await loadExternalAdminPolicyOnce(input, organizationId, false);\n }\n } catch (error) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n"]}
1
+ {"version":3,"file":"externalAdminPolicy.js","sourceRoot":"","sources":["externalAdminPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AACzH,OAAO,EAEL,oCAAoC,EACpC,yBAAyB,EACzB,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,kCAAkC,EAClC,6BAA6B,GAC9B,MAAM,mDAAmD,CAAC;AAI3D,OAAO,EACL,sCAAsC,EAEtC,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAc9B,MAAM,UAAU,qCAAqC,CACnD,SAAsC;IAKtC,OAAO;QACL,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE;QACtD,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE;KACjE,CAAC;AACJ,CAAC;AAED,SAAS,uBAAuB,CAAC,MAA+B;IAC9D,IACE,C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CACd,CAAC,+CAA+C,CAAC;QAChD,OAAO,EAAE,qCAAqC,CAAC,QAAQ,CAAC;QACxD,cAAc;QACd,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAA+B;IAE/B,MAAM,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IACjC,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC;YACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,kBAAkB,CAAC;gBAAE,MAAM,KAAK,CAAC;YACxD,OAAO,MAAM,2BAA2B,CAAC,KAAK,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n previousStatesIncludeHead,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n organizationAdminSignerUserIds,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n} from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"./currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n publishVerifiedPrincipalPolicy,\n} from \"./policyVerification\";\n\nexport interface VerifiedExternalAdminPolicy {\n readonly adminBundle: PrincipalPolicyBundleResponse;\n readonly adminGroupId: string;\n readonly adminPolicy: VerifiedPrincipalPolicy;\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly memberGroupId: string;\n readonly policy: VerifiedPrincipalPolicy;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly signerUserIds: readonly string[];\n}\n\nexport function externalAdminPolicyPersistenceEntries(\n authority: VerifiedExternalAdminPolicy,\n): ReadonlyArray<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n return [\n { bundle: authority.bundle, policy: authority.policy },\n { bundle: authority.adminBundle, policy: authority.adminPolicy },\n ];\n}\n\nfunction assertAdminsPolicyShape(policy: VerifiedPrincipalPolicy): void {\n if (\n (policy.history ?? [{ projection: policy.projection }]).some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\n/**\n * A signer the caller cannot resolve is a cache miss, but a resolved signer\n * whose trusted key differs from the one the policy signed with is a\n * verification failure, as on every other policy path (#2365 finding 23).\n */\nfunction signerKeyLoadFailure(\n error: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): null {\n if (error === \"fingerprint-mismatch\") {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"external admin policy signer key fingerprint mismatch\",\n );\n }\n return null;\n}\n\nasync function verifyOrganizationPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | null> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle: input.bundle,\n localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await publishVerifiedPrincipalPolicy(input);\n return verified.value;\n}\n\nfunction parseScopedAuthorityDescriptor(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n): OrganizationAuthorityDescriptor {\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization authority descriptor is invalid\",\n );\n }\n if (descriptor.organizationId !== organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n return descriptor;\n}\n\n/**\n * The organization and its Admins group are separate reads, so an honest\n * Admins commit between them serves a chain that extends the head the\n * directory cites: a stale directory, not tampering (#2365 finding 22). The\n * claim is checked before any signer is trusted, so it is unverified and buys\n * only one organization refetch; a disagreement after that is an incident.\n */\nclass AdminsHeadAdvanced extends Error {}\n\nasync function loadVerifiedAdminsPolicy(input: {\n readonly adminGroupId: string;\n readonly expectedHead: ReturnType<typeof requireOrganizationGroupHead>;\n readonly mayRefetchDirectory: boolean;\n readonly execSql: ExecSql;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n} | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"group\",\n input.adminGroupId,\n );\n if (!bundle) {\n return null;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedHead,\n )\n ) {\n if (\n input.mayRefetchDirectory &&\n previousStatesIncludeHead(bundle, input.expectedHead)\n ) {\n throw new AdminsHeadAdvanced();\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"reserved Admins policy does not match the signed organization directory\",\n );\n }\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return signerKeyLoadFailure(signerPublicKeys.error);\n }\n const verified = await verifyPrincipalPolicyBundle({\n bundle,\n expectedReference: input.expectedHead,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n if (\n verified.value.principalType !== \"group\" ||\n verified.value.principalId !== input.adminGroupId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"reserved Admins policy target does not match\",\n );\n }\n assertAdminsPolicyShape(verified.value);\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return { bundle, policy: verified.value };\n}\n\ninterface ExternalAdminPolicyInput {\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly execSql: ExecSql;\n readonly organizationId: string | null | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function loadExternalAdminPolicyOnce(\n input: ExternalAdminPolicyInput,\n organizationId: string,\n mayRefetchDirectory: boolean,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const bundle = await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n organizationId,\n );\n if (!bundle) {\n return null;\n }\n const policy = await verifyOrganizationPolicy({\n bundle,\n execSql: input.execSql,\n organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!policy) {\n return null;\n }\n const descriptor = parseScopedAuthorityDescriptor(bundle, organizationId);\n const admin = await loadVerifiedAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n mayRefetchDirectory,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n execSql: input.execSql,\n currentPolicyReader: input.currentPolicyReader,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!admin) {\n return null;\n }\n\n const verified: VerifiedExternalAdminPolicy = {\n adminBundle: admin.bundle,\n adminGroupId: descriptor.adminGroupId,\n adminPolicy: admin.policy,\n bundle,\n descriptor,\n externalAuthority: organizationAdminExternalAuthority(admin.policy),\n memberGroupId: descriptor.memberGroupId,\n policy,\n signerUserIds: organizationAdminSignerUserIds(admin.policy),\n };\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: externalAdminPolicyPersistenceEntries(verified),\n organizationId,\n stillCurrent: input.stillCurrent,\n });\n return verified;\n}\n\nexport async function loadOrganizationExternalAdminPolicy(\n input: ExternalAdminPolicyInput,\n): Promise<VerifiedExternalAdminPolicy | null> {\n const { organizationId } = input;\n if (!organizationId) {\n return null;\n }\n try {\n try {\n return await loadExternalAdminPolicyOnce(input, organizationId, true);\n } catch (error) {\n if (!(error instanceof AdminsHeadAdvanced)) throw error;\n return await loadExternalAdminPolicyOnce(input, organizationId, false);\n }\n } catch (error) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n"]}
@@ -2,8 +2,7 @@ import { isProjectionVerificationCancelledError } from "../../../data/keyingProj
2
2
  import { reportAndRethrowKeyingVerificationError, rethrowKeyingVerificationError, } from "../../../data/keyingProjectionVerification/error.js";
3
3
  import { dedupeReferencedPrincipalStates } from "../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js";
4
4
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
5
- import { ensurePrincipalPolicyTables } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
6
- import { loadPrincipalPolicyBundleForReference } from "../../../data/persistence/principalPolicy/principalPolicyReferencePersistence.js";
5
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
7
6
  import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
8
7
  import { errorMessage } from "../../../data/shared/errorMessage.js";
9
8
  import { externalAdminPolicyPersistenceEntries, loadOrganizationExternalAdminPolicy, } from "../externalAdminPolicy.js";
@@ -55,7 +54,6 @@ async function persistScopedPolicy(input) {
55
54
  ],
56
55
  execSql: input.execSql,
57
56
  organizationId: input.organizationId,
58
- updatedAt: new Date().toISOString(),
59
57
  stillCurrent: input.stillCurrent,
60
58
  });
61
59
  return [...externalEntries.map(({ policy }) => policy), validation.policy];
@@ -66,7 +64,7 @@ async function cacheReferencedPrincipalPolicy(execSql, reader, reference, resolv
66
64
  // must escape rather than being hidden by a canonical network retry.
67
65
  const cachedBundle = fresh
68
66
  ? null
69
- : await loadPrincipalPolicyBundleForReference(execSql, reference, localCheckpoint);
67
+ : await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);
70
68
  let bundle = cachedBundle ??
71
69
  (await reader.getCurrentPrincipalPolicy(reference.principalType, reference.principalId));
72
70
  if (!bundle) {
@@ -161,7 +159,7 @@ async function runPrincipalPolicyCache(input) {
161
159
  return [];
162
160
  }
163
161
  try {
164
- await ensurePrincipalPolicyTables(input.execSql);
162
+ await new PrincipalPolicyBundleRepository(input.execSql).ensurePrincipalPolicyTables();
165
163
  const uniqueItems = input.dedupe(input.items);
166
164
  const loadDirectory = createPolicyDirectoryLoader(input);
167
165
  let externalAdminPolicy = null;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EACL,uCAAuC,EACvC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AAClI,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,2BAA2B,EAAE,MAAM,sEAAsE,CAAC;AACnH,OAAO,EAAE,qCAAqC,EAAE,MAAM,+EAA+E,CAAC;AACtI,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAKjE,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EACL,kCAAkC,EAClC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,qCAAqC,EAAE,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;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport {\n reportAndRethrowKeyingVerificationError,\n rethrowKeyingVerificationError,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ensurePrincipalPolicyTables } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport { publishVerifiedPrincipalPolicy } from \"../policyVerification\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await loadPrincipalPolicyBundleForReference(\n execSql,\n reference,\n localCheckpoint,\n );\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await ensurePrincipalPolicyTables(input.execSql);\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EACL,uCAAuC,EACvC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AAClI,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;A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AC,CAAC;AAC/C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,EAChD,OAAO,EACP,mBAAmB,EACnB,OAAO,EACP,GAAG,EACH,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,YAAY,GACuB;IACnC,MAAM,uBAAuB,CAAC;QAC5B,SAAS,EAAE,CAAC,MAAM,EAAE,uBAAuB,EAAE,aAAa,EAAE,EAAE,CAC5D,0BAA0B,CAAC;YACzB,MAAM;YACN,OAAO;YACP,uBAAuB;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport {\n reportAndRethrowKeyingVerificationError,\n rethrowKeyingVerificationError,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport { publishVerifiedPrincipalPolicy } from \"../policyVerification\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).ensurePrincipalPolicyTables();\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
- import { persistVerifiedPrincipalPolicyBundlesAtomically } from "../../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js";
2
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
3
3
  class PolicyCacheAdvanceRace extends Error {
4
4
  verificationError;
5
5
  constructor(verificationError) {
@@ -9,8 +9,9 @@ class PolicyCacheAdvanceRace extends Error {
9
9
  }
10
10
  /** Only a fully verified candidate losing the atomic commit race can retry. */
11
11
  export async function persistPrincipalPolicyCacheEntries(input) {
12
+ const { execSql, ...entries } = input;
12
13
  try {
13
- await persistVerifiedPrincipalPolicyBundlesAtomically(input);
14
+ await new PrincipalPolicyBundleRepository(execSql).persistVerifiedPrincipalPolicyBundlesAtomically(entries);
14
15
  }
15
16
  catch (error) {
16
17
  if (error instanceof KeyingVerificationError && error.code === "rollback")
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCacheAdvance.js","sourceRoot":"","sources":["principalPolicyCacheAdvance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,+CAA+C,EAAE,MAAM,oFAAoF,CAAC;AAErJ,MAAM,sBAAuB,SAAQ,KAAK;IACnB;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;IAE/D,CAAC;CACF;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAA4E;IAE5E,IAAI,CAAC;QACH,MAAM,+CAA+C,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YACvE,MAAM,IAAI,sBAAsB,CAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,SAA8C;IAE9C,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,sBAAsB,CAAC;YAAE,MAAM,KAAK,CAAC;IAC9D,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,KAAK,YAAY,sBAAsB;YAC3C,CAAC,CAAC,KAAK,CAAC,iBAAiB;YACzB,CAAC,CAAC,KAAK,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { persistVerifiedPrincipalPolicyBundlesAtomically } from \"../../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence\";\n\nclass PolicyCacheAdvanceRace extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n }\n}\n\n/** Only a fully verified candidate losing the atomic commit race can retry. */\nexport async function persistPrincipalPolicyCacheEntries(\n input: Parameters<typeof persistVerifiedPrincipalPolicyBundlesAtomically>[0],\n): Promise<void> {\n try {\n await persistVerifiedPrincipalPolicyBundlesAtomically(input);\n } catch (error) {\n if (error instanceof KeyingVerificationError && error.code === \"rollback\")\n throw new PolicyCacheAdvanceRace(error);\n throw error;\n }\n}\n\n/** Discard stale snapshots once; the replacement must pass every normal check. */\nexport async function retryPrincipalPolicyCacheAdvance<Result>(\n operation: (fresh: boolean) => Promise<Result>,\n): Promise<Result> {\n try {\n return await operation(false);\n } catch (error) {\n if (!(error instanceof PolicyCacheAdvanceRace)) throw error;\n }\n try {\n return await operation(true);\n } catch (error) {\n throw error instanceof PolicyCacheAdvanceRace\n ? error.verificationError\n : error;\n }\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCacheAdvance.js","sourceR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Z,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nclass PolicyCacheAdvanceRace extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n }\n}\n\n/** Only a fully verified candidate losing the atomic commit race can retry. */\nexport async function persistPrincipalPolicyCacheEntries(\n input: Parameters<\n PrincipalPolicyBundleRepository[\"persistVerifiedPrincipalPolicyBundlesAtomically\"]\n >[0] & { readonly execSql: ExecSql },\n): Promise<void> {\n const { execSql, ...entries } = input;\n try {\n await new PrincipalPolicyBundleRepository(\n execSql,\n ).persistVerifiedPrincipalPolicyBundlesAtomically(entries);\n } catch (error) {\n if (error instanceof KeyingVerificationError && error.code === \"rollback\")\n throw new PolicyCacheAdvanceRace(error);\n throw error;\n }\n}\n\n/** Discard stale snapshots once; the replacement must pass every normal check. */\nexport async function retryPrincipalPolicyCacheAdvance<Result>(\n operation: (fresh: boolean) => Promise<Result>,\n): Promise<Result> {\n try {\n return await operation(false);\n } catch (error) {\n if (!(error instanceof PolicyCacheAdvanceRace)) throw error;\n }\n try {\n return await operation(true);\n } catch (error) {\n throw error instanceof PolicyCacheAdvanceRace\n ? error.verificationError\n : error;\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { principalPolicyHeadMeetsCheckpoint } from "../../../data/keyingProjectionVerification/index.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
- import { loadPrincipalPolicyBundle } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
4
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
5
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
6
6
  import { verifyOrganizationAdminPolicy } from "../../../data/principals/principalPolicyAdminSigners.js";
7
7
  import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../policyVerification.js";
@@ -30,7 +30,7 @@ export function createPolicyDirectoryLoader(input) {
30
30
  const checkpoint = await new KeyingCheckpointRepository(input.execSql).loadPrincipalPolicyCheckpoint("organization", input.organizationId);
31
31
  let bundle = remote
32
32
  ? null
33
- : await loadPrincipalPolicyBundle(input.execSql, "organization", input.organizationId);
33
+ : await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
34
34
  bundle = bundleMeetingCheckpoint(bundle, checkpoint);
35
35
  bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy("organization", input.organizationId);
36
36
  if (!bundle)
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,yBAAyB,EAAE,MAAM,sEAAsE,CAAC;AACjH,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,sDAAsD,CAAC;AAIrG,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,uBAAuB,CAAC;AAY/B,MAAM,UAAU,4BAA4B,CAC1C,SAAyC,EACzC,MAA+B,EAC/B,SAAkC;IAElC,MAAM,IAAI,GAAG,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,IAAI,CAChD,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS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Q,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = Awaited<ReturnType<typeof loadPrincipalPolicyBundle>>;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\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 directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,sDAAsD,CAAC;AAIrG,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,uBAAuB,CAAC;AAY/B,MA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AC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;QACJ,CAAC;QACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;YACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\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 directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
@@ -2,7 +2,7 @@ import { createPrincipalPolicyHistoryVerifier, KeyingVerificationError, serializ
2
2
  import { isPrincipalPolicySnapshotPage, } from "../../../internal/validators/response/index.js";
3
3
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
4
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
5
- import { loadHeldPrincipalState } from "../../../data/persistence/principalPolicy/heldPrincipalState.js";
5
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
6
  import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
7
7
  import { ownPrincipalHistoryProtection } from "../../../data/principals/principalHistoryProtection.js";
8
8
  import { publishAuthenticatedSigners } from "../../../data/principals/principalIdentityCommitments.js";
@@ -30,8 +30,7 @@ function assertPage(input, page, after) {
30
30
  */
31
31
  async function loadHeldHead(input, held) {
32
32
  const knownCurrentState = held.state.status === "eligible"
33
- ? ((await loadHeldPrincipalState(input.execSql, input.source.head)) ??
34
- undefined)
33
+ ? ((await new PrincipalPolicyBundleRepository(input.execSql).loadHeldPrincipalState(input.source.head)) ?? undefined)
35
34
  : undefined;
36
35
  held.state = transitionHeldHeadState(held.state, {
37
36
  type: knownCurrentState ? "heldLoaded" : "heldMissing",
@@ -1 +1 @@
1
- {"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,GAG9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,sBAAsB,EAAE,MAAM,8DAA8D,CAAC;AACtG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,uDAAuD,CAAC;AACpG,OAAO,EAAE,+BAA+B,EAAE,MAAM,kDAAkD,CAAC;AACnG,OAAO,EAEL,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,wBAAwB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AAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { loadHeldPrincipalState } from \"../../../data/persistence/principalPolicy/heldPrincipalState\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { publishAuthenticatedSigners } from \"../../../data/principals/principalIdentityCommitments\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await loadHeldPrincipalState(input.execSql, input.source.head)) ??\n undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
1
+ {"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uBAAuB,CAC/B,iBAAiB,EACjB,kDAAkD,CACnD,CAAC;IACJ,0EAA0E;IAC1E,oCAAoC,CAAC;QACnC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa;QAChD,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;QAC5C,kBAAkB,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrE,UAAU,CAAC,OAAO,GAAG,4BAA4B,CAAC;QAChD,2CAA2C;QAC3C,UAAU,CAAC,OAAO;QAClB,OAAO,CAAC,YAAY,KAAK,IAAI;QAC7B,OAAO,CAAC,gBAAgB,IAAI,IAAI;KACjC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { publishAuthenticatedSigners } from \"../../../data/principals/principalIdentityCommitments\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadHeldPrincipalState(input.source.head)) ?? undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}