@tearleads/client-sdk 0.1.80 → 0.1.82

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 (43) hide show
  1. package/client/organizations/organizationReadModels.js +4 -2
  2. package/client/organizations/organizationReadModels.js.map +1 -1
  3. package/data/keyingProjectionVerification/index.d.ts +1 -0
  4. package/data/keyingProjectionVerification/index.js +1 -0
  5. package/data/keyingProjectionVerification/index.js.map +1 -1
  6. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +1 -1
  7. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  8. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.d.ts +6 -0
  9. package/data/{persistence → keyingProjectionVerification}/principalPolicy/principalPolicyCheckpointSelection.js +1 -1
  10. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  11. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +1 -1
  12. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +1 -1
  14. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  15. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +11 -51
  16. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  17. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +1 -30
  18. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +4 -85
  19. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  20. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +88 -0
  21. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -0
  22. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +53 -0
  23. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -0
  24. package/package.json +1 -1
  25. package/{client/organizations/organizationAccessRestoration.js → workflows/container-contents/recovery/accessRestoration.js} +16 -12
  26. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -0
  27. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  28. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  29. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  30. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  31. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  32. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  33. package/workflows/principals/externalAdminPolicy.js +1 -1
  34. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  35. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  36. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  37. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
  38. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  39. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  40. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  41. package/client/organizations/organizationAccessRestoration.js.map +0 -1
  42. package/data/persistence/principalKeys/principalGrantRetirementPersistence.d.ts +0 -9
  43. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +0 -1
@@ -1,6 +1,6 @@
1
+ import { recoverOrganizationAccess } from "../../workflows/container-contents/recovery/accessRestoration.js";
1
2
  import { loadLocalOrganizationContainerGrants, loadLocalOrganizationDirectoryAndGroups, loadLocalOrganizationGroupContainers, loadLocalOrganizationGroupMembers, loadLocalOrganizationUserDetail, reconcileOrganizationDirectoryAndGroups, } from "../../workflows/organizations/index.js";
2
3
  import { organizationAccessScopeKey, wasOrganizationPresentationAccessDeniedByServer, } from "../../workflows/organizations/readModel/organizationPresentationAccessState.js";
3
- import { recoverOrganizationAccess } from "./organizationAccessRestoration.js";
4
4
  import { loadBoundedOrganizationGroupHistory } from "./organizationGroupHistory.js";
5
5
  import { hydrateOrganizationGroupNamesForRuntime } from "./organizationGroupNameHydration.js";
6
6
  import { loadBoundedOrganizationHistory } from "./organizationHistory.js";
@@ -145,9 +145,11 @@ class OrganizationReadModelCoordinatorImpl {
145
145
  directoryAndGroups !== undefined;
146
146
  if (accessWasRestored)
147
147
  await recoverOrganizationAccess({
148
- active,
149
148
  domainScope,
149
+ execSql: active.runtime.infra.execSql,
150
+ organizationId: active.organizationId,
150
151
  stillCurrent,
152
+ userId: active.userId,
151
153
  });
152
154
  if (!stillCurrent())
153
155
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAQ/B,uCAAuC,GACxC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,0BAA0B,EAC1B,+CAA+C,GAChD,MAAM,6EAA6E,CAAC;AAErF,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,uCAAuC,EAAE,MAAM,kCAAkC,CAAC;AAC3F,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAEL,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAEvC,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAGtC,CAAC;AA8CJ,MAAM,oCAAoC;IAOX;IAJZ,sBAAsB,GAAG,IAAI,OAAO,EAGlD,CAAC;IACJ,YAA6B,cAA+B;QAA/B,mBAAc,GAAd,cAAc,CAAiB;I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AAc,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,oCAAoC,CAAC,cAAc,CAAC,CAAC;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationContainerGrants,\n type OrganizationDirectoryAndGroups,\n type OrganizationGroupContainers,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationPolicyHistory,\n type OrganizationUserDetail,\n reconcileOrganizationDirectoryAndGroups,\n} from \"../../workflows/organizations\";\nimport {\n organizationAccessScopeKey,\n wasOrganizationPresentationAccessDeniedByServer,\n} from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { recoverOrganizationAccess } from \"./organizationAccessRestoration\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { hydrateOrganizationGroupNamesForRuntime } from \"./organizationGroupNameHydration\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\nexport interface OrganizationReadModelCoordinator {\n loadLocal(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null>;\n loadLocalGroupMembers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupMembers | null>;\n loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationGroupPolicyHistory | null>;\n loadOrganizationPolicyHistory(\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationPolicyHistory | null>;\n loadLocalGrants(\n organizationId?: string | undefined,\n ): Promise<OrganizationContainerGrants | null>;\n loadLocalGroupContainers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupContainers | null>;\n loadLocalUserDetail(\n userId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationUserDetail | null>;\n /**\n * Resolves `undefined` when the runtime declines without I/O (offline,\n * database not ready, organization mismatch) or when the feed failed with\n * no locally retained projection — passes that must not count as caught\n * up; `null` when the reconcile completed but produced nothing presentable\n * — including an authoritative denial that purged the projection, which\n * consumers must repaint.\n */\n reconcile(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n reconcileAfterMutation(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n}\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, Promise<OrganizationDirectoryAndGroups | null | undefined>>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n const scope = active.runtime.state.domainScope;\n let byKey = this.reconciliationsByScope.get(scope);\n if (!byKey) {\n byKey = new Map();\n this.reconciliationsByScope.set(scope, byKey);\n }\n return byKey;\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n });\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing;\n }\n\n // Snapshot the server-denied flag before reconciling. A reconcile that\n // flips it back to readable means org access was just restored (e.g. the\n // user was re-added to a group), and any write lanes idled by\n // permission-denied submissions have no self re-arm — regaining access is\n // their retry signal, mirroring how billing recovery re-requests all\n // lanes. Only a genuine server denial counts: a local session reset also\n // marks scopes denied, and re-arming on its first reconcile would race the\n // startup sync passes (e.g. pending-create adoption between panes).\n const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer(\n {\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n },\n \"readModel\",\n );\n const domainScope = active.runtime.state.domainScope;\n const stillCurrent = () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n );\n\n const reconciliation = reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n })\n .then(async (directoryAndGroups) => {\n if (!stillCurrent()) return null;\n // Feed success restores retry eligibility even if name decryption fails.\n const accessWasRestored =\n accessWasDenied &&\n directoryAndGroups !== null &&\n directoryAndGroups !== undefined;\n if (accessWasRestored)\n await recoverOrganizationAccess({\n active,\n domainScope,\n stillCurrent,\n });\n if (!stillCurrent()) return null;\n return hydrateOrganizationGroupNamesForRuntime(\n this.runtimeService,\n active,\n domainScope,\n directoryAndGroups,\n );\n })\n .finally(() => {\n if (byKey.get(key) === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, reconciliation);\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n const existing = this.reconciliationMap(active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n if (existing) {\n await existing.catch(() => null);\n }\n return this.reconcile(active.organizationId);\n }\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
1
+ {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+DAA+D,CAAC;AAC1G,OAAO,EACL,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAQ/B,uCAAuC,GACxC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,0BAA0B,EAC1B,+CAA+C,GAChD,MAAM,6EAA6E,CAAC;AAErF,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,uCAAuC,EAAE,MAAM,kCAAkC,CAAC;AAC3F,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAEL,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAEvC,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAGtC,CAAC;AA8CJ,MAAM,oCAAoC;IAOX;IAJZ,sBAAsB,GAAG,IAAI,OAAO,EAGlD,CAAC;IACJ,YAA6B,cAA+B;QAA/B,mBAAc,GAAd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MAAM,CAAC,cAAc,CAAC,CAAC;IAC/C,CAAC;CACF;AAED,MAAM,UAAU,sCAAsC,CACpD,cAA+B;IAE/B,MAAM,QAAQ,GAAG,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,oCAAoC,CAAC,cAAc,CAAC,CAAC;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { recoverOrganizationAccess } from \"../../workflows/container-contents/recovery/accessRestoration\";\nimport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationContainerGrants,\n type OrganizationDirectoryAndGroups,\n type OrganizationGroupContainers,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationPolicyHistory,\n type OrganizationUserDetail,\n reconcileOrganizationDirectoryAndGroups,\n} from \"../../workflows/organizations\";\nimport {\n organizationAccessScopeKey,\n wasOrganizationPresentationAccessDeniedByServer,\n} from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { hydrateOrganizationGroupNamesForRuntime } from \"./organizationGroupNameHydration\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\nexport interface OrganizationReadModelCoordinator {\n loadLocal(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null>;\n loadLocalGroupMembers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupMembers | null>;\n loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationGroupPolicyHistory | null>;\n loadOrganizationPolicyHistory(\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationPolicyHistory | null>;\n loadLocalGrants(\n organizationId?: string | undefined,\n ): Promise<OrganizationContainerGrants | null>;\n loadLocalGroupContainers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupContainers | null>;\n loadLocalUserDetail(\n userId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationUserDetail | null>;\n /**\n * Resolves `undefined` when the runtime declines without I/O (offline,\n * database not ready, organization mismatch) or when the feed failed with\n * no locally retained projection — passes that must not count as caught\n * up; `null` when the reconcile completed but produced nothing presentable\n * — including an authoritative denial that purged the projection, which\n * consumers must repaint.\n */\n reconcile(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n reconcileAfterMutation(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n}\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, Promise<OrganizationDirectoryAndGroups | null | undefined>>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n const scope = active.runtime.state.domainScope;\n let byKey = this.reconciliationsByScope.get(scope);\n if (!byKey) {\n byKey = new Map();\n this.reconciliationsByScope.set(scope, byKey);\n }\n return byKey;\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n });\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing;\n }\n\n // Snapshot the server-denied flag before reconciling. A reconcile that\n // flips it back to readable means org access was just restored (e.g. the\n // user was re-added to a group), and any write lanes idled by\n // permission-denied submissions have no self re-arm — regaining access is\n // their retry signal, mirroring how billing recovery re-requests all\n // lanes. Only a genuine server denial counts: a local session reset also\n // marks scopes denied, and re-arming on its first reconcile would race the\n // startup sync passes (e.g. pending-create adoption between panes).\n const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer(\n {\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n },\n \"readModel\",\n );\n const domainScope = active.runtime.state.domainScope;\n const stillCurrent = () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n );\n\n const reconciliation = reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n })\n .then(async (directoryAndGroups) => {\n if (!stillCurrent()) return null;\n // Feed success restores retry eligibility even if name decryption fails.\n const accessWasRestored =\n accessWasDenied &&\n directoryAndGroups !== null &&\n directoryAndGroups !== undefined;\n if (accessWasRestored)\n await recoverOrganizationAccess({\n domainScope,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n stillCurrent,\n userId: active.userId,\n });\n if (!stillCurrent()) return null;\n return hydrateOrganizationGroupNamesForRuntime(\n this.runtimeService,\n active,\n domainScope,\n directoryAndGroups,\n );\n })\n .finally(() => {\n if (byKey.get(key) === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, reconciliation);\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n const existing = this.reconciliationMap(active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n if (existing) {\n await existing.catch(() => null);\n }\n return this.reconcile(active.organizationId);\n }\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
@@ -10,4 +10,5 @@ export { collectContainerWriterProjectionPrincipalPolicies, verifyContainerWrite
10
10
  export { type DocumentWriterProjectionAuthorization, verifyDocumentWriterProjection, verifyDocumentWriterProjectionAuthorization, } from "./document/documentProjectionVerification.js";
11
11
  export { verifyDocumentPurgeProof, verifyDocumentPurgeProofBaseline, } from "./documentPurge/documentPurgeProofVerification.js";
12
12
  export { mergeProjectionPolicyEvidence } from "./principalPolicy/mergeProjectionPolicyEvidence.js";
13
+ export { principalPolicyHeadMeetsCheckpoint } from "./principalPolicy/principalPolicyCheckpointSelection.js";
13
14
  export { isPrincipalPolicyNotCachedError } from "./principalPolicy/principalPolicyVerification.js";
@@ -16,5 +16,6 @@ export { collectContainerWriterProjectionPrincipalPolicies, verifyContainerWrite
16
16
  export { verifyDocumentWriterProjection, verifyDocumentWriterProjectionAuthorization, } from "./document/documentProjectionVerification.js";
17
17
  export { verifyDocumentPurgeProof, verifyDocumentPurgeProofBaseline, } from "./documentPurge/documentPurgeProofVerification.js";
18
18
  export { mergeProjectionPolicyEvidence } from "./principalPolicy/mergeProjectionPolicyEvidence.js";
19
+ export { principalPolicyHeadMeetsCheckpoint } from "./principalPolicy/principalPolicyCheckpointSelection.js";
19
20
  export { isPrincipalPolicyNotCachedError } from "./principalPolicy/principalPolicyVerification.js";
20
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAC;AAG5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,WAAW,CAAC;AAOnB,OAAO,EACL,sCAAsC,EACtC,wCAAwC,GACzC,MAAM,SAAS,CAAC;AAEjB,MAAM,UAAU,gCAAgC,CAC9C,wBAAsE,EACtE,KAAa;IAEb,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uCAAuC,CAAC,CAAC;IACnE,CAAC;IAED,sEAAsE;IACtE,8EAA8E;IAC9E,OAAO,kCAAkC,CAAC,wBAAwB,CAAC,CAAC;AACtE,CAAC;AAED,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AACtF,OAAO,EAAE,oCAAoC,EAAE,MAAM,8CAA8C,CAAC;AACpG,OAAO,EACL,iDAAiD,EACjD,+BAA+B,GAChC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAEL,8BAA8B,EAC9B,2CAA2C,GAC5C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC","sourcesContent":["import { requireTrustedUserIdentityResolver } from \"../trustedUserIdentity\";\nimport type { ProjectionUserKeyResolver } from \"./types\";\n\nexport { resolveEventContainerPaths } from \"./document/documentDependencyPaths\";\nexport {\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n} from \"./readers\";\n\nexport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nexport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n} from \"./types\";\n\nexport function requireProjectionUserKeyResolver(\n resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined,\n label: string,\n): ProjectionUserKeyResolver {\n if (!resolveProjectionUserKey) {\n throw new Error(`${label} requires projection key verification`);\n }\n\n // A ProjectionUserKey is a TrustedUserIdentity, so the shared adapter\n // provides the untrusted-shape and wrong-user guards (with identity caching).\n return requireTrustedUserIdentityResolver(resolveProjectionUserKey);\n}\n\nexport { verifiedContainerCreateManifest } from \"./container/containerCreateManifest\";\nexport { verifyContainerDestinationProjection } from \"./container/containerDestinationVerification\";\nexport {\n collectContainerWriterProjectionPrincipalPolicies,\n verifyContainerWriterProjection,\n} from \"./container/containerProjectionVerification\";\nexport {\n type DocumentWriterProjectionAuthorization,\n verifyDocumentWriterProjection,\n verifyDocumentWriterProjectionAuthorization,\n} from \"./document/documentProjectionVerification\";\nexport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n} from \"./documentPurge/documentPurgeProofVerification\";\nexport { mergeProjectionPolicyEvidence } from \"./principalPolicy/mergeProjectionPolicyEvidence\";\nexport { isPrincipalPolicyNotCachedError } from \"./principalPolicy/principalPolicyVerification\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAC;AAG5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,WAAW,CAAC;AAOnB,OAAO,EACL,sCAAsC,EACtC,wCAAwC,GACzC,MAAM,SAAS,CAAC;AAEjB,MAAM,UAAU,gCAAgC,CAC9C,wBAAsE,EACtE,KAAa;IAEb,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uCAAuC,CAAC,CAAC;IACnE,CAAC;IAED,sEAAsE;IACtE,8EAA8E;IAC9E,OAAO,kCAAkC,CAAC,wBAAwB,CAAC,CAAC;AACtE,CAAC;AAED,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AACtF,OAAO,EAAE,oCAAoC,EAAE,MAAM,8CAA8C,CAAC;AACpG,OAAO,EACL,iDAAiD,EACjD,+BAA+B,GAChC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAEL,8BAA8B,EAC9B,2CAA2C,GAC5C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC","sourcesContent":["import { requireTrustedUserIdentityResolver } from \"../trustedUserIdentity\";\nimport type { ProjectionUserKeyResolver } from \"./types\";\n\nexport { resolveEventContainerPaths } from \"./document/documentDependencyPaths\";\nexport {\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n} from \"./readers\";\n\nexport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nexport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n} from \"./types\";\n\nexport function requireProjectionUserKeyResolver(\n resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined,\n label: string,\n): ProjectionUserKeyResolver {\n if (!resolveProjectionUserKey) {\n throw new Error(`${label} requires projection key verification`);\n }\n\n // A ProjectionUserKey is a TrustedUserIdentity, so the shared adapter\n // provides the untrusted-shape and wrong-user guards (with identity caching).\n return requireTrustedUserIdentityResolver(resolveProjectionUserKey);\n}\n\nexport { verifiedContainerCreateManifest } from \"./container/containerCreateManifest\";\nexport { verifyContainerDestinationProjection } from \"./container/containerDestinationVerification\";\nexport {\n collectContainerWriterProjectionPrincipalPolicies,\n verifyContainerWriterProjection,\n} from \"./container/containerProjectionVerification\";\nexport {\n type DocumentWriterProjectionAuthorization,\n verifyDocumentWriterProjection,\n verifyDocumentWriterProjectionAuthorization,\n} from \"./document/documentProjectionVerification\";\nexport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n} from \"./documentPurge/documentPurgeProofVerification\";\nexport { mergeProjectionPolicyEvidence } from \"./principalPolicy/mergeProjectionPolicyEvidence\";\nexport { principalPolicyHeadMeetsCheckpoint } from \"./principalPolicy/principalPolicyCheckpointSelection\";\nexport { isPrincipalPolicyNotCachedError } from \"./principalPolicy/principalPolicyVerification\";\n"]}
@@ -1,9 +1,9 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { loadPrincipalPolicyCheckpoint } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
- import { verifiedPrincipalPolicyMeetsCheckpoint } from "../../persistence/principalPolicy/principalPolicyCheckpointSelection.js";
4
3
  import { loadPrincipalPolicyBundleForReference } from "../../persistence/principalPolicy/principalPolicyReferencePersistence.js";
5
4
  import { principalPolicyEvidenceEntries, } from "../../principals/principalPolicyEvidence.js";
6
5
  import { principalStateMatchesReference } from "../../principals/principalPolicyStates.js";
6
+ import { verifiedPrincipalPolicyMeetsCheckpoint } from "./principalPolicyCheckpointSelection.js";
7
7
  /**
8
8
  * Cache key for a referenced principal policy. The in-memory principal-policy
9
9
  * cache is populated and read from several call sites; they must agree on this
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EAAE,sCAAsC,EAAE,MAAM,sEAAsE,CAAC;AAC9H,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAGxF;;;;;GAKG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAkC;IAElC,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,SAAS,CAAC,aAAa;QACvB,SAAS,CAAC,WAAW;QACrB,SAAS,CAAC,OAAO;QACjB,SAAS,CAAC,SAAS;QACnB,SAAS,CAAC,QAAQ;QAClB,SAAS,CAAC,cAAc;KACzB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAE7C,UAAqC;IACrC,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAsB,CAAC;IACxD,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,iBAAiB,CAAC,GAAG,CAAC,4BAA4B,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,UAAU,uCAAuC,CACrD,QAAmD;IAEnD,MAAM,KAAK,GAAG,IAAI,GAAG,EAA0C,CAAC;IAChE,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE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AAG,CACjD,4BAA4B,CAAC,SAAS,CAAC,CACxC,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,IACE,CAAC,wCAAwC,CAAC,YAAY,EAAE,SAAS,CAAC,EAClE,CAAC;gBACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,qEAAqE,CACtE,CAAC;YACJ,CAAC;YACD,IAAI,sCAAsC,CAAC,YAAY,EAAE,UAAU,CAAC,EAAE,CAAC;gBACrE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,qCAAqC,CACxD,KAAK,CAAC,OAAO,EACb,SAAS,EACT,UAAU,CACX,CAAC;QACF,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,SAAS,EAAwC,EAAE,CAAC,SAAS,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"../../persistence/principalPolicy/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport { principalStateMatchesReference } from \"../../principals/principalPolicyStates\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\n/**\n * Cache key for a referenced principal policy. The in-memory principal-policy\n * cache is populated and read from several call sites; they must agree on this\n * format byte-for-byte or a populated entry looks uncached (extra warm fetches)\n * — so this is the single source of truth, imported rather than re-declared.\n */\nexport function referencedPrincipalPolicyKey(\n reference: ReferencedPrincipalHead,\n): string {\n return JSON.stringify([\n reference.principalType,\n reference.principalId,\n reference.version,\n reference.stateHash,\n reference.keyEpoch,\n reference.keyFingerprint,\n ]);\n}\n\n/**\n * Dedupes references by their exact head identity, keyed with\n * {@link referencedPrincipalPolicyKey} so every consumer agrees on what\n * \"the same reference\" means. Later duplicates win, preserving each\n * caller's original last-wins behavior.\n */\nexport function dedupeReferencedPrincipalStates<\n TReference extends ReferencedPrincipalHead,\n>(references: ReadonlyArray<TReference>): TReference[] {\n const referencesByState = new Map<string, TReference>();\n for (const reference of references) {\n referencesByState.set(referencedPrincipalPolicyKey(reference), reference);\n }\n return Array.from(referencesByState.values());\n}\n\nexport function principalPolicyCacheForVerifiedPolicies(\n policies: readonly PrincipalPolicyCurrentEvidence[],\n): Map<string, PrincipalPolicyCurrentEvidence> {\n const cache = new Map<string, PrincipalPolicyCurrentEvidence>();\n for (const policy of policies) {\n const states = principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.state,\n );\n for (const state of states) {\n cache.set(\n referencedPrincipalPolicyKey({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n }),\n policy,\n );\n }\n }\n return cache;\n}\n\nexport function verifiedPrincipalPolicyContainsReference(\n policy: PrincipalPolicyCurrentEvidence,\n reference: ReferencedPrincipalHead,\n): boolean {\n const states = principalPolicyEvidenceEntries(policy).map(\n ({ state }) => state,\n );\n return states.some((state) =>\n principalStateMatchesReference(state, reference),\n );\n}\n\n// Identify which referenced policies are absent from both the in-memory cache\n// and local storage, so the warmer fetches only what is genuinely missing.\nexport async function filterUncachedPrincipalPolicyReferences(input: {\n execSql: ExecSql;\n principalPolicyCache: ReadonlyMap<string, PrincipalPolicyCurrentEvidence>;\n references: readonly ReferencedPrincipalHead[];\n}): Promise<ReferencedPrincipalHead[]> {\n const results = await Promise.all(\n input.references.map(async (reference) => {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n reference.principalType,\n reference.principalId,\n );\n const cachedPolicy = input.principalPolicyCache.get(\n referencedPrincipalPolicyKey(reference),\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, checkpoint)) {\n return null;\n }\n }\n const bundle = await loadPrincipalPolicyBundleForReference(\n input.execSql,\n reference,\n checkpoint,\n );\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAExF,OAAO,EAAE,sCAAsC,EAAE,MAAM,sCAAsC,CAAC;AAE9F;;;;;GAKG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAkC;IAElC,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,SAAS,CAAC,aAAa;QACvB,SAAS,CAAC,WAAW;QACrB,SAAS,CAAC,OAAO;QACjB,SAAS,CAAC,SAAS;QACnB,SAAS,CAAC,QAAQ;QAClB,SAAS,CAAC,cAAc;KACzB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAE7C,UAAqC;IACrC,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAsB,CAAC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;AAC9E,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAAC,KAI7D;IACC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAC/B,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE;QACvC,MAAM,UAAU,GAAG,MAAM,6BAA6B,CACpD,KAAK,CAAC,OAAO,EACb,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC;QACF,MAAM,YAAY,GAAG,KAAK,CAAC,oBAAoB,CAAC,GAAG,CACjD,4BAA4B,CAAC,SAAS,CAAC,CACxC,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,IACE,CAAC,wCAAwC,CAAC,YAAY,EAAE,SAAS,CAAC,EAClE,CAAC;gBACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,qEAAqE,CACtE,CAAC;YACJ,CAAC;YACD,IAAI,sCAAsC,CAAC,YAAY,EAAE,UAAU,CAAC,EAAE,CAAC;gBACrE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,qCAAqC,CACxD,KAAK,CAAC,OAAO,EACb,SAAS,EACT,UAAU,CACX,CAAC;QACF,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,SAAS,EAAwC,EAAE,CAAC,SAAS,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport { principalStateMatchesReference } from \"../../principals/principalPolicyStates\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"./principalPolicyCheckpointSelection\";\n\n/**\n * Cache key for a referenced principal policy. The in-memory principal-policy\n * cache is populated and read from several call sites; they must agree on this\n * format byte-for-byte or a populated entry looks uncached (extra warm fetches)\n * — so this is the single source of truth, imported rather than re-declared.\n */\nexport function referencedPrincipalPolicyKey(\n reference: ReferencedPrincipalHead,\n): string {\n return JSON.stringify([\n reference.principalType,\n reference.principalId,\n reference.version,\n reference.stateHash,\n reference.keyEpoch,\n reference.keyFingerprint,\n ]);\n}\n\n/**\n * Dedupes references by their exact head identity, keyed with\n * {@link referencedPrincipalPolicyKey} so every consumer agrees on what\n * \"the same reference\" means. Later duplicates win, preserving each\n * caller's original last-wins behavior.\n */\nexport function dedupeReferencedPrincipalStates<\n TReference extends ReferencedPrincipalHead,\n>(references: ReadonlyArray<TReference>): TReference[] {\n const referencesByState = new Map<string, TReference>();\n for (const reference of references) {\n referencesByState.set(referencedPrincipalPolicyKey(reference), reference);\n }\n return Array.from(referencesByState.values());\n}\n\nexport function principalPolicyCacheForVerifiedPolicies(\n policies: readonly PrincipalPolicyCurrentEvidence[],\n): Map<string, PrincipalPolicyCurrentEvidence> {\n const cache = new Map<string, PrincipalPolicyCurrentEvidence>();\n for (const policy of policies) {\n const states = principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.state,\n );\n for (const state of states) {\n cache.set(\n referencedPrincipalPolicyKey({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n }),\n policy,\n );\n }\n }\n return cache;\n}\n\nexport function verifiedPrincipalPolicyContainsReference(\n policy: PrincipalPolicyCurrentEvidence,\n reference: ReferencedPrincipalHead,\n): boolean {\n const states = principalPolicyEvidenceEntries(policy).map(\n ({ state }) => state,\n );\n return states.some((state) =>\n principalStateMatchesReference(state, reference),\n );\n}\n\n// Identify which referenced policies are absent from both the in-memory cache\n// and local storage, so the warmer fetches only what is genuinely missing.\nexport async function filterUncachedPrincipalPolicyReferences(input: {\n execSql: ExecSql;\n principalPolicyCache: ReadonlyMap<string, PrincipalPolicyCurrentEvidence>;\n references: readonly ReferencedPrincipalHead[];\n}): Promise<ReferencedPrincipalHead[]> {\n const results = await Promise.all(\n input.references.map(async (reference) => {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n reference.principalType,\n reference.principalId,\n );\n const cachedPolicy = input.principalPolicyCache.get(\n referencedPrincipalPolicyKey(reference),\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, checkpoint)) {\n return null;\n }\n }\n const bundle = await loadPrincipalPolicyBundleForReference(\n input.execSql,\n reference,\n checkpoint,\n );\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import type { PrincipalPolicyAuthorization, PrincipalPolicyCheckpoint } from "../../../internal/crypto/index.js";
2
+ export declare function principalPolicyHeadMeetsCheckpoint(head: {
3
+ readonly stateHash: string;
4
+ readonly version: number;
5
+ }, checkpoint: PrincipalPolicyCheckpoint | null): boolean;
6
+ export declare function verifiedPrincipalPolicyMeetsCheckpoint(policy: PrincipalPolicyAuthorization, checkpoint: PrincipalPolicyCheckpoint | null): boolean;
@@ -1,5 +1,5 @@
1
1
  import { verifyPrincipalPolicyCheckpoint } from "../../../internal/crypto/index.js";
2
- import { assertPrincipalPolicyCheckpointShape } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
2
+ import { assertPrincipalPolicyCheckpointShape } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
3
  export function principalPolicyHeadMeetsCheckpoint(head, checkpoint) {
4
4
  return (!checkpoint ||
5
5
  head.version > checkpoint.version ||
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyCheckpointSelection.js","sourceRoot":"","sources":["principalPolicyCheckpointSelection.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,oCAAoC,EAAE,MAAM,iEAAiE,CAAC;AAEvH,MAAM,UAAU,kCAAkC,CAChD,IAA8D,EAC9D,UAA4C;IAE5C,OAAO,CACL,CAAC,UAAU;QACX,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO;QACjC,CAAC,IAAI,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO;YAClC,IAAI,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,MAAoC,EACpC,UAA4C;IAE5C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACzD,IAAI,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,+BAA+B,CAAC;QAC9B,KAAK,EACH,iBAAiB,IAAI,MAAM;YACzB,CAAC,CAAC,MAAM,CAAC,eAAe;YACxB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;QAC5B,YAAY,EAAE,MAAM,CAAC,KAAK;QAC1B,eAAe,EAAE,UAAU;KAC5B,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { verifyPrincipalPolicyCheckpoint } from \"@tearleads/crypto\";\nimport { assertPrincipalPolicyCheckpointShape } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\n\nexport function principalPolicyHeadMeetsCheckpoint(\n head: { readonly stateHash: string; readonly version: number },\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n return (\n !checkpoint ||\n head.version > checkpoint.version ||\n (head.version === checkpoint.version &&\n head.stateHash === checkpoint.stateHash)\n );\n}\n\nexport function verifiedPrincipalPolicyMeetsCheckpoint(\n policy: PrincipalPolicyAuthorization,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n if (!checkpoint) {\n return true;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, policy);\n if (policy.version < checkpoint.version) {\n return false;\n }\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in policy\n ? policy.retainedHistory\n : (policy.history ?? []),\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n return true;\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { KeyingVerificationError, toFingerprint, verifyPrincipalPolicyBundle, } from "../../../internal/crypto/index.js";
2
2
  import { loadPrincipalPolicyCheckpoint } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
- import { principalPolicyHeadMeetsCheckpoint, verifiedPrincipalPolicyMeetsCheckpoint, } from "../../persistence/principalPolicy/principalPolicyCheckpointSelection.js";
4
3
  import { loadPrincipalPolicyBundle } from "../../persistence/principalPolicy/principalPolicyPersistence.js";
5
4
  import { loadPrincipalPolicyBundleForReference } from "../../persistence/principalPolicy/principalPolicyReferencePersistence.js";
6
5
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../principals/organizationAuthorityDescriptor.js";
@@ -11,6 +10,7 @@ import { ProjectionDependencyUnavailableError } from "../dependencyUnavailable.j
11
10
  import { rethrowProjectionVerificationBoundaryError } from "../error.js";
12
11
  import { assertProjectionVerificationCurrent, generationGuardedPrincipalPolicyWarmer, } from "../types.js";
13
12
  import { filterUncachedPrincipalPolicyReferences, referencedPrincipalPolicyKey, verifiedPrincipalPolicyContainsReference, } from "./principalPolicyCache.js";
13
+ import { principalPolicyHeadMeetsCheckpoint, verifiedPrincipalPolicyMeetsCheckpoint, } from "./principalPolicyCheckpointSelection.js";
14
14
  import { resolveReferencedPrincipalPolicy } from "./resolvedPrincipalPolicy.js";
15
15
  function principalPolicyReferenceLabel(reference) {
16
16
  return `${reference.principalType}:${reference.principalId}@${reference.version}`;
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GACvC,MAAM,sEAAsE,CAAC;AAC9E,OAAO,EAAE,yBAAyB,EAAE,MAAM,8DAA8D,CAAC;AACzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,6BAA6B,EAC7B,yDAAyD,GAC1D,MAAM,8CAA8C,CAAC;AAEtD,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,sBAAsB,GAEvB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,0CAA0C,EAAE,MAAM,UAAU,CAAC;AAMtE,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GACvC,MAAM,UAAU,CAAC;AAClB,OA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AAM,EAAE,CAAC,CAAC;IAClD,2EAA2E;IAC3E,yEAAyE;IACzE,0CAA0C;IAC1C,IACE,+BAA+B;QAC/B,CAAC,+BAA+B,CAAC,gBAAgB,EACjD,CAAC;QACD,MAAM,QAAQ,GAAG,MAAM,uCAAuC,CAAC;YAC7D,OAAO,EAAE,KAAK,CAAC,iBAAiB,CAAC,OAAO;YACxC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;YAChD,UAAU;SACX,CAAC,CAAC;QACH,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxD,MAAM,+BAA+B,CAAC;gBACpC,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,UAAU,EAAE,QAAQ;aACrB,CAAC,CAAC;YACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;IAED,0EAA0E;IAC1E,OAAO,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAC3B,+BAA+B,CAAC;QAC9B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,SAAS;QACT,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"../../persistence/principalPolicy/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundle } from \"../../persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { principalPolicyBundleStates } from \"../../principals/principalPolicyStates\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"../error\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.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\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) return recovered;\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EAAE,yBAAyB,EAAE,MAAM,8DAA8D,CAAC;AACzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,6BAA6B,EAC7B,yDAAyD,GAC1D,MAAM,8CAA8C,CAAC;AAEtD,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,sBAAsB,GAEvB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,0CAA0C,EAAE,MAAM,UAAU,CAAC;AAMtE,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GACvC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,uCAAuC,EACvC,4BAA4B,EAC5B,wCAAwC,GACzC,MAAM,wBAAwB,CAAC;AAChC,OAA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,CAAC;IAClD,2EAA2E;IAC3E,yEAAyE;IACzE,0CAA0C;IAC1C,IACE,+BAA+B;QAC/B,CAAC,+BAA+B,CAAC,gBAAgB,EACjD,CAAC;QACD,MAAM,QAAQ,GAAG,MAAM,uCAAuC,CAAC;YAC7D,OAAO,EAAE,KAAK,CAAC,iBAAiB,CAAC,OAAO;YACxC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;YAChD,UAAU;SACX,CAAC,CAAC;QACH,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxD,MAAM,+BAA+B,CAAC;gBACpC,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,UAAU,EAAE,QAAQ;aACrB,CAAC,CAAC;YACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;IAED,0EAA0E;IAC1E,OAAO,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAC3B,+BAA+B,CAAC;QAC9B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,SAAS;QACT,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { principalPolicyBundleStates } from \"../../principals/principalPolicyStates\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"../error\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"./principalPolicyCheckpointSelection\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.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\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) return recovered;\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { loadPrincipalPolicyCheckpoint } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
- import { verifiedPrincipalPolicyMeetsCheckpoint } from "../../persistence/principalPolicy/principalPolicyCheckpointSelection.js";
4
3
  import { observePrincipalPolicy, } from "../checkpoints/checkpointContext.js";
5
4
  import { observeProjectionLifetime } from "../projectionLifetimes.js";
6
5
  import { assertProjectionVerificationCurrent, } from "../types.js";
7
6
  import { referencedPrincipalPolicyKey, verifiedPrincipalPolicyContainsReference, } from "./principalPolicyCache.js";
7
+ import { verifiedPrincipalPolicyMeetsCheckpoint } from "./principalPolicyCheckpointSelection.js";
8
8
  // Scoped evidence is always resolved through the warmer: its operation memo is
9
9
  // the only reuse of recovered directory and Admins evidence, with one set of
10
10
  // validity rules. The caller's policy cache keeps bare verified policies; it
@@ -1 +1 @@
1
- {"version":3,"file":"resolvedPrincipalPolicy.js","sourceRoot":"","sources":["resolvedPrincipalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EAAE,sCAAsC,EAAE,MAAM,sEAAsE,CAAC;AAC9H,OAAO,EACL,sBAAsB,GAEvB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,E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C;IAC7E,mCAAmC,CAAC,QAAQ,CAAC,CAAC;IAC9C,yBAAyB,CAAC,KAAK,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;IAC7D,IAAI,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAChD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;IACJ,IAAI,CAAC,wCAAwC,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC;QAC3E,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;IACJ,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1D,sBAAsB,CACpB,KAAK,CAAC,iBAAiB,EACvB,MAAM,EACN,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,KAAK,CAAC,oBAAoB,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnD,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"../../persistence/principalPolicy/principalPolicyCheckpointSelection\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { observeProjectionLifetime } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyCache,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../types\";\nimport {\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\n\n// Scoped evidence is always resolved through the warmer: its operation memo is\n// the only reuse of recovered directory and Admins evidence, with one set of\n// validity rules. The caller's policy cache keeps bare verified policies; it\n// never stands in for organization, dependency or lifetime bindings.\nasync function meetsCheckpoints(\n context: ProjectionCheckpointContext,\n result: ResolvedPrincipalPolicyEvidence,\n refreshMissing: boolean,\n): Promise<boolean> {\n for (const policy of [...result.dependencies, result.policy]) {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n context.execSql,\n policy.principalType,\n policy.principalId,\n );\n if (\n refreshMissing &&\n checkpoint &&\n (policy.version < checkpoint.version ||\n (policy.version > checkpoint.version &&\n !policy.retainedHistory.some(\n (entry) => entry.state.version === checkpoint.version,\n )))\n )\n return false;\n if (!verifiedPrincipalPolicyMeetsCheckpoint(policy, checkpoint))\n throw new KeyingVerificationError(\n \"rollback\",\n \"Recovered principal evidence predates the durable checkpoint\",\n );\n }\n return true;\n}\n\ninterface ResolveReferencedPrincipalPolicyInput {\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly reference: ReferencedPrincipalHead;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nasync function recoverEvidence(\n input: ResolveReferencedPrincipalPolicyInput,\n resolve: NonNullable<ReferencedPrincipalPolicyWarmer[\"resolveReference\"]>,\n): Promise<ResolvedPrincipalPolicyEvidence> {\n const read = async (recoveryBatch?: object) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const recovered = await resolve({\n recoveryBatch,\n organizationId: input.organizationId,\n reference: input.reference,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n };\n let result = await read();\n // A concurrent admission may advance a pin after recovery verified it.\n // Refresh once outside the operation's directory view; the fresh\n // recovery and final checkpoint check still reject rollback/equivocation.\n if (!(await meetsCheckpoints(input.checkpointContext, result, true))) {\n assertProjectionVerificationCurrent(result.stillCurrent);\n result = await read({});\n await meetsCheckpoints(input.checkpointContext, result, false);\n }\n return result;\n}\n\nexport async function resolveReferencedPrincipalPolicy(\n input: ResolveReferencedPrincipalPolicyInput,\n): Promise<VerifiedPrincipalPolicyCurrent | null> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const key = referencedPrincipalPolicyKey(input.reference);\n const resolve = input.warmReferencedPrincipalPolicies?.resolveReference;\n if (!resolve) return null;\n const result = await recoverEvidence(input, resolve);\n const evidenceCurrent = result.stillCurrent;\n // The consumer's and every producer's lifetime guard the evidence where it\n // is used: projection admission rechecks them through the context.\n const lifetime = () => input.stillCurrent?.() !== false && evidenceCurrent();\n assertProjectionVerificationCurrent(lifetime);\n observeProjectionLifetime(input.checkpointContext, lifetime);\n if (result.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence belongs to another organization\",\n );\n if (!verifiedPrincipalPolicyContainsReference(result.policy, input.reference))\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence does not contain the exact citation\",\n );\n for (const policy of [...result.dependencies, result.policy])\n observePrincipalPolicy(\n input.checkpointContext,\n policy,\n input.organizationId,\n );\n input.principalPolicyCache.set(key, result.policy);\n return result.policy;\n}\n"]}
1
+ {"version":3,"file":"resolvedPrincipalPolicy.js","sourceRoot":"","sources":["resolvedPrincipalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EACL,sBAAsB,GAEvB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EACL,mCAAmC,GAIpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,4BAA4B,EAC5B,wCAAwC,G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AAiB,EAAE,QAAQ,CAAC,CAAC;IAC7D,IAAI,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAChD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;IACJ,IAAI,CAAC,wCAAwC,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC;QAC3E,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;IACJ,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1D,sBAAsB,CACpB,KAAK,CAAC,iBAAiB,EACvB,MAAM,EACN,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,KAAK,CAAC,oBAAoB,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnD,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { observeProjectionLifetime } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyCache,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../types\";\nimport {\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"./principalPolicyCheckpointSelection\";\n\n// Scoped evidence is always resolved through the warmer: its operation memo is\n// the only reuse of recovered directory and Admins evidence, with one set of\n// validity rules. The caller's policy cache keeps bare verified policies; it\n// never stands in for organization, dependency or lifetime bindings.\nasync function meetsCheckpoints(\n context: ProjectionCheckpointContext,\n result: ResolvedPrincipalPolicyEvidence,\n refreshMissing: boolean,\n): Promise<boolean> {\n for (const policy of [...result.dependencies, result.policy]) {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n context.execSql,\n policy.principalType,\n policy.principalId,\n );\n if (\n refreshMissing &&\n checkpoint &&\n (policy.version < checkpoint.version ||\n (policy.version > checkpoint.version &&\n !policy.retainedHistory.some(\n (entry) => entry.state.version === checkpoint.version,\n )))\n )\n return false;\n if (!verifiedPrincipalPolicyMeetsCheckpoint(policy, checkpoint))\n throw new KeyingVerificationError(\n \"rollback\",\n \"Recovered principal evidence predates the durable checkpoint\",\n );\n }\n return true;\n}\n\ninterface ResolveReferencedPrincipalPolicyInput {\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly reference: ReferencedPrincipalHead;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nasync function recoverEvidence(\n input: ResolveReferencedPrincipalPolicyInput,\n resolve: NonNullable<ReferencedPrincipalPolicyWarmer[\"resolveReference\"]>,\n): Promise<ResolvedPrincipalPolicyEvidence> {\n const read = async (recoveryBatch?: object) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const recovered = await resolve({\n recoveryBatch,\n organizationId: input.organizationId,\n reference: input.reference,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n };\n let result = await read();\n // A concurrent admission may advance a pin after recovery verified it.\n // Refresh once outside the operation's directory view; the fresh\n // recovery and final checkpoint check still reject rollback/equivocation.\n if (!(await meetsCheckpoints(input.checkpointContext, result, true))) {\n assertProjectionVerificationCurrent(result.stillCurrent);\n result = await read({});\n await meetsCheckpoints(input.checkpointContext, result, false);\n }\n return result;\n}\n\nexport async function resolveReferencedPrincipalPolicy(\n input: ResolveReferencedPrincipalPolicyInput,\n): Promise<VerifiedPrincipalPolicyCurrent | null> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const key = referencedPrincipalPolicyKey(input.reference);\n const resolve = input.warmReferencedPrincipalPolicies?.resolveReference;\n if (!resolve) return null;\n const result = await recoverEvidence(input, resolve);\n const evidenceCurrent = result.stillCurrent;\n // The consumer's and every producer's lifetime guard the evidence where it\n // is used: projection admission rechecks them through the context.\n const lifetime = () => input.stillCurrent?.() !== false && evidenceCurrent();\n assertProjectionVerificationCurrent(lifetime);\n observeProjectionLifetime(input.checkpointContext, lifetime);\n if (result.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence belongs to another organization\",\n );\n if (!verifiedPrincipalPolicyContainsReference(result.policy, input.reference))\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence does not contain the exact citation\",\n );\n for (const policy of [...result.dependencies, result.policy])\n observePrincipalPolicy(\n input.checkpointContext,\n policy,\n input.organizationId,\n );\n input.principalPolicyCache.set(key, result.policy);\n return result.policy;\n}\n"]}
@@ -4,8 +4,6 @@ import { verifiedManifestBundleTables } from "../../sqlite/schema/verifiedManife
4
4
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
6
  import { assertContainerNotRetired } from "../principalKeys/principalGrantRetirementPersistence.js";
7
- import { assertPrincipalPolicyBundleStoredInTransaction, writePrincipalPolicyBundleInTransaction, } from "../principalPolicy/principalPolicyPersistence.js";
8
- import { assertBundleMatchesVerifiedPolicy } from "../principalPolicy/verifiedPrincipalPolicyBundle.js";
9
7
  import { verifiedManifestBundleRows, writeVerifiedManifestBundlesInTransaction, } from "../verifiedManifestBundlePersistence.js";
10
8
  import { storeDocumentPurgeCheckpointInTransaction, } from "./documentPurgeCheckpointPersistence.js";
11
9
  import { validateAccessManifestCheckpointEvidence } from "./keyingCheckpointEvidence.js";
@@ -60,7 +58,12 @@ function extendsObservedPolicy(head, candidate) {
60
58
  state.version === candidate.version &&
61
59
  state.stateHash === candidate.stateHash) ?? false);
62
60
  }
63
- async function validatePolicyAdvances(tx, policies) {
61
+ /**
62
+ * Checks, inside the caller's transaction, that each principal's newest policy
63
+ * extends every other candidate and its durable checkpoint. Returns the heads
64
+ * to pin, keyed by principal.
65
+ */
66
+ export async function validatePrincipalPolicyCheckpointAdvances(tx, policies) {
64
67
  const policiesByPrincipal = new Map();
65
68
  for (const policy of policies) {
66
69
  const key = principalPolicyKey(policy);
@@ -103,7 +106,8 @@ async function writeAccessCheckpoints(tx, pending, updatedAt) {
103
106
  await upsertAccessManifestCheckpointInTransaction(tx, checkpoint, updatedAt);
104
107
  }
105
108
  }
106
- async function writePolicyCheckpoints(tx, pending, updatedAt, organizationId) {
109
+ /** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */
110
+ export async function writePrincipalPolicyCheckpoints(tx, pending, updatedAt, organizationId) {
107
111
  for (const policy of pending.values()) {
108
112
  await upsertPrincipalPolicyCheckpointInTransaction(tx, policy.checkpoint, updatedAt, organizationId);
109
113
  }
@@ -133,7 +137,7 @@ export async function validateKeyingCheckpointsAtomically(input) {
133
137
  const verifiedAt = new Date().toISOString();
134
138
  const validate = async (tx) => {
135
139
  await validateAccessAdvances(tx, input.access);
136
- await validatePolicyAdvances(tx, input.policies);
140
+ await validatePrincipalPolicyCheckpointAdvances(tx, input.policies);
137
141
  await validatePrincipalAuthorizationCheckpoints(tx, input.authorizationPolicies ?? []);
138
142
  await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);
139
143
  };
@@ -158,10 +162,10 @@ export async function advanceKeyingCheckpointsAtomically(input) {
158
162
  const runtime = getClientSQLitePersistenceRuntime(input.execSql);
159
163
  const advance = async (tx) => {
160
164
  const access = await validateAccessAdvances(tx, input.access);
161
- const policies = await validatePolicyAdvances(tx, input.policies);
165
+ const policies = await validatePrincipalPolicyCheckpointAdvances(tx, input.policies);
162
166
  await validatePrincipalAuthorizationCheckpoints(tx, input.authorizationPolicies ?? []);
163
167
  await writeAccessCheckpoints(tx, access, updatedAt);
164
- await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);
168
+ await writePrincipalPolicyCheckpoints(tx, policies, updatedAt, input.organizationId);
165
169
  if (input.documentPurgeCheckpoint) {
166
170
  await storeDocumentPurgeCheckpointInTransaction(tx, input.documentPurgeCheckpoint, updatedAt);
167
171
  }
@@ -175,48 +179,4 @@ export async function advanceKeyingCheckpointsAtomically(input) {
175
179
  }
176
180
  await runtime.transaction(advance, { behavior: "immediate" });
177
181
  }
178
- /**
179
- * Persists each verified full policy bundle together with its durable head.
180
- * This prevents a crash or bundle-write failure from leaving a checkpoint
181
- * without the exact same-head payload and member-envelope evidence.
182
- */
183
- export async function persistVerifiedPrincipalPolicyBundlesAtomically(input) {
184
- const seen = new Set();
185
- for (const entry of input.entries) {
186
- const key = principalPolicyKey(entry.policy);
187
- if (seen.has(key)) {
188
- throw new KeyingVerificationError("duplicate_entry", `verified policy bundle batch repeats ${key}`);
189
- }
190
- seen.add(key);
191
- }
192
- await Promise.all(input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)));
193
- await ensureSqlTables(input.execSql, [
194
- ...principalPolicyTables,
195
- ...keyingCheckpointTables,
196
- ]);
197
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
198
- const persist = async (tx) => {
199
- const policies = await validatePolicyAdvances(tx, input.entries.map((entry) => entry.policy));
200
- for (const entry of input.entries) {
201
- await writePrincipalPolicyBundleInTransaction(tx, entry.bundle, input.updatedAt, input.organizationId);
202
- await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);
203
- }
204
- await writePolicyCheckpoints(tx, policies, input.updatedAt, input.organizationId);
205
- for (const policy of policies.values()) {
206
- const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);
207
- if (!checkpoint ||
208
- checkpoint.version !== policy.version ||
209
- checkpoint.stateHash !== policy.stateHash) {
210
- throw new Error("Verified principal policy checkpoint was not persisted");
211
- }
212
- }
213
- };
214
- if (input.stillCurrent) {
215
- await runtime.guardedTransaction(persist, input.stillCurrent, {
216
- behavior: "immediate",
217
- });
218
- return;
219
- }
220
- await runtime.transaction(persist, { behavior: "immediate" });
221
- }
222
182
  //# sourceMappingURL=keyingCheckpointAdvancePersistence.js.map