@tearleads/client-sdk 0.1.199 → 0.1.201

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +2 -2
  2. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  3. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
  4. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  5. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +6 -7
  6. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  7. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js +4 -16
  8. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -1
  9. package/data/persistence/principalMutationJournalPersistence.d.ts +20 -13
  10. package/data/persistence/principalMutationJournalPersistence.js +54 -43
  11. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  12. package/data/persistence/principalPolicy/heldPrincipalState.js +2 -11
  13. package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
  14. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +14 -65
  15. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
  16. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +180 -0
  17. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -0
  18. package/data/persistence/principalPolicy/principalPolicyPersistence.js +6 -62
  19. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
  20. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +11 -12
  21. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
  22. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +24 -40
  23. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -1
  24. package/data/principals/organizationGroupRoles.js +2 -2
  25. package/data/principals/organizationGroupRoles.js.map +1 -1
  26. package/data/principals/principalPolicyCrypto.js +2 -2
  27. package/data/principals/principalPolicyCrypto.js.map +1 -1
  28. package/package.json +1 -1
  29. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
  30. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  31. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -5
  32. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  33. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  34. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  35. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +4 -11
  36. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  37. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +7 -9
  38. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  39. package/workflows/organizations/groupShare/shareWithGroup.js +2 -2
  40. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  41. package/workflows/organizations/groups/deleteOrganizationGroup.js +2 -4
  42. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  43. package/workflows/organizations/groups/organizationGroupDirectory.js +2 -4
  44. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  45. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js +5 -7
  46. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js.map +1 -1
  47. package/workflows/organizations/principalMutations/principalMutationJournalSession.js +4 -6
  48. package/workflows/organizations/principalMutations/principalMutationJournalSession.js.map +1 -1
  49. package/workflows/organizations/readModel/localReadModelDetails.js +3 -3
  50. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  51. package/workflows/principals/externalAdminPolicy.js +2 -4
  52. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  53. package/workflows/principals/policyCache/index.js +3 -5
  54. package/workflows/principals/policyCache/index.js.map +1 -1
  55. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +3 -2
  56. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  57. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
  58. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  59. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
  60. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  61. package/workflows/registration/registrationPrincipalPolicyPersistence.js +2 -4
  62. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  63. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
  64. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EACL,uCAAuC,EACvC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AAClI,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,2BAA2B,EAAE,MAAM,sEAAsE,CAAC;AACnH,OAAO,EAAE,qCAAqC,EAAE,MAAM,+EAA+E,CAAC;AACtI,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAKjE,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EACL,kCAAkC,EAClC,gC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SAAS,EAAE,CAAC,MAAM,EAAE,uBAAuB,EAAE,aAAa,EAAE,EAAE,CAC5D,0BAA0B,CAAC;YACzB,MAAM;YACN,OAAO;YACP,uBAAuB;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport {\n reportAndRethrowKeyingVerificationError,\n rethrowKeyingVerificationError,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ensurePrincipalPolicyTables } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport { publishVerifiedPrincipalPolicy } from \"../policyVerification\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await loadPrincipalPolicyBundleForReference(\n execSql,\n reference,\n localCheckpoint,\n );\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await ensurePrincipalPolicyTables(input.execSql);\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EACL,uCAAuC,EACvC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AAClI,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEA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AAY;KACb,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAA8C;IAE9C,MAAM,+BAA+B,CAAC,KAAK,CAAC,CAAC;AAC/C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,EAChD,OAAO,EACP,mBAAmB,EACnB,OAAO,EACP,GAAG,EACH,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,YAAY,GACuB;IACnC,MAAM,uBAAuB,CAAC;QAC5B,SAAS,EAAE,CAAC,MAAM,EAAE,uBAAuB,EAAE,aAAa,EAAE,EAAE,CAC5D,0BAA0B,CAAC;YACzB,MAAM;YACN,OAAO;YACP,uBAAuB;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport {\n reportAndRethrowKeyingVerificationError,\n rethrowKeyingVerificationError,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport { publishVerifiedPrincipalPolicy } from \"../policyVerification\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).ensurePrincipalPolicyTables();\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
- import { persistVerifiedPrincipalPolicyBundlesAtomically } from "../../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js";
2
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
3
3
  class PolicyCacheAdvanceRace extends Error {
4
4
  verificationError;
5
5
  constructor(verificationError) {
@@ -9,8 +9,9 @@ class PolicyCacheAdvanceRace extends Error {
9
9
  }
10
10
  /** Only a fully verified candidate losing the atomic commit race can retry. */
11
11
  export async function persistPrincipalPolicyCacheEntries(input) {
12
+ const { execSql, ...entries } = input;
12
13
  try {
13
- await persistVerifiedPrincipalPolicyBundlesAtomically(input);
14
+ await new PrincipalPolicyBundleRepository(execSql).persistVerifiedPrincipalPolicyBundlesAtomically(entries);
14
15
  }
15
16
  catch (error) {
16
17
  if (error instanceof KeyingVerificationError && error.code === "rollback")
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCacheAdvance.js","sourceRoot":"","sources":["principalPolicyCacheAdvance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,+CAA+C,EAAE,MAAM,oFAAoF,CAAC;AAErJ,MAAM,sBAAuB,SAAQ,KAAK;IACnB;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;IAE/D,CAAC;CACF;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAA4E;IAE5E,IAAI,CAAC;QACH,MAAM,+CAA+C,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YACvE,MAAM,IAAI,sBAAsB,CAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,SAA8C;IAE9C,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,sBAAsB,CAAC;YAAE,MAAM,KAAK,CAAC;IAC9D,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,KAAK,YAAY,sBAAsB;YAC3C,CAAC,CAAC,KAAK,CAAC,iBAAiB;YACzB,CAAC,CAAC,KAAK,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { persistVerifiedPrincipalPolicyBundlesAtomically } from \"../../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence\";\n\nclass PolicyCacheAdvanceRace extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n }\n}\n\n/** Only a fully verified candidate losing the atomic commit race can retry. */\nexport async function persistPrincipalPolicyCacheEntries(\n input: Parameters<typeof persistVerifiedPrincipalPolicyBundlesAtomically>[0],\n): Promise<void> {\n try {\n await persistVerifiedPrincipalPolicyBundlesAtomically(input);\n } catch (error) {\n if (error instanceof KeyingVerificationError && error.code === \"rollback\")\n throw new PolicyCacheAdvanceRace(error);\n throw error;\n }\n}\n\n/** Discard stale snapshots once; the replacement must pass every normal check. */\nexport async function retryPrincipalPolicyCacheAdvance<Result>(\n operation: (fresh: boolean) => Promise<Result>,\n): Promise<Result> {\n try {\n return await operation(false);\n } catch (error) {\n if (!(error instanceof PolicyCacheAdvanceRace)) throw error;\n }\n try {\n return await operation(true);\n } catch (error) {\n throw error instanceof PolicyCacheAdvanceRace\n ? error.verificationError\n : error;\n }\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCacheAdvance.js","sourceRoot":"","sources":["principalPolicyCacheAdvance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAG5H,MAAM,sBAAuB,SAAQ,KAAK;IACnB;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;IAE/D,CAAC;CACF;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAEoC;IAEpC,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,GAAG,KAAK,CAAC;IACtC,IAAI,CAAC;QACH,MAAM,IAAI,+BAA+B,CACvC,OAAO,CACR,CAAC,+CAA+C,CAAC,OAAO,CAAC,CAAC;IAC7D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YACvE,MAAM,IAAI,sBAAsB,CAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,SAA8C;IAE9C,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,sBAAsB,CAAC;YAAE,MAAM,KAAK,CAAC;IAC9D,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,KAAK,YAAY,sBAAsB;YAC3C,CAAC,CAAC,KAAK,CAAC,iBAAiB;YACzB,CAAC,CAAC,KAAK,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nclass PolicyCacheAdvanceRace extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n }\n}\n\n/** Only a fully verified candidate losing the atomic commit race can retry. */\nexport async function persistPrincipalPolicyCacheEntries(\n input: Parameters<\n PrincipalPolicyBundleRepository[\"persistVerifiedPrincipalPolicyBundlesAtomically\"]\n >[0] & { readonly execSql: ExecSql },\n): Promise<void> {\n const { execSql, ...entries } = input;\n try {\n await new PrincipalPolicyBundleRepository(\n execSql,\n ).persistVerifiedPrincipalPolicyBundlesAtomically(entries);\n } catch (error) {\n if (error instanceof KeyingVerificationError && error.code === \"rollback\")\n throw new PolicyCacheAdvanceRace(error);\n throw error;\n }\n}\n\n/** Discard stale snapshots once; the replacement must pass every normal check. */\nexport async function retryPrincipalPolicyCacheAdvance<Result>(\n operation: (fresh: boolean) => Promise<Result>,\n): Promise<Result> {\n try {\n return await operation(false);\n } catch (error) {\n if (!(error instanceof PolicyCacheAdvanceRace)) throw error;\n }\n try {\n return await operation(true);\n } catch (error) {\n throw error instanceof PolicyCacheAdvanceRace\n ? error.verificationError\n : error;\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { principalPolicyHeadMeetsCheckpoint } from "../../../data/keyingProjectionVerification/index.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
- import { loadPrincipalPolicyBundle } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
4
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
5
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
6
6
  import { verifyOrganizationAdminPolicy } from "../../../data/principals/principalPolicyAdminSigners.js";
7
7
  import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../policyVerification.js";
@@ -30,7 +30,7 @@ export function createPolicyDirectoryLoader(input) {
30
30
  const checkpoint = await new KeyingCheckpointRepository(input.execSql).loadPrincipalPolicyCheckpoint("organization", input.organizationId);
31
31
  let bundle = remote
32
32
  ? null
33
- : await loadPrincipalPolicyBundle(input.execSql, "organization", input.organizationId);
33
+ : await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
34
34
  bundle = bundleMeetingCheckpoint(bundle, checkpoint);
35
35
  bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy("organization", input.organizationId);
36
36
  if (!bundle)
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,yBAAyB,EAAE,MAAM,sEAAsE,CAAC;AACjH,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,sDAAsD,CAAC;AAIrG,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,uBAAuB,CAAC;AAY/B,MAAM,UAAU,4BAA4B,CAC1C,SAAyC,EACzC,MAA+B,EAC/B,SAAkC;IAElC,MAAM,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Ac;YACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = Awaited<ReturnType<typeof loadPrincipalPolicyBundle>>;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAClE,OAAO,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AAG,oCAAoC,CAC/C,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;QACJ,CAAC;QACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;YACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
@@ -2,7 +2,7 @@ import { createPrincipalPolicyHistoryVerifier, KeyingVerificationError, serializ
2
2
  import { isPrincipalPolicySnapshotPage, } from "../../../internal/validators/response/index.js";
3
3
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
4
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
5
- import { loadHeldPrincipalState } from "../../../data/persistence/principalPolicy/heldPrincipalState.js";
5
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
6
  import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
7
7
  import { ownPrincipalHistoryProtection } from "../../../data/principals/principalHistoryProtection.js";
8
8
  import { publishAuthenticatedSigners } from "../../../data/principals/principalIdentityCommitments.js";
@@ -30,8 +30,7 @@ function assertPage(input, page, after) {
30
30
  */
31
31
  async function loadHeldHead(input, held) {
32
32
  const knownCurrentState = held.state.status === "eligible"
33
- ? ((await loadHeldPrincipalState(input.execSql, input.source.head)) ??
34
- undefined)
33
+ ? ((await new PrincipalPolicyBundleRepository(input.execSql).loadHeldPrincipalState(input.source.head)) ?? undefined)
35
34
  : undefined;
36
35
  held.state = transitionHeldHeadState(held.state, {
37
36
  type: knownCurrentState ? "heldLoaded" : "heldMissing",
@@ -1 +1 @@
1
- {"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,GAG9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,sBAAsB,EAAE,MAAM,8DAA8D,CAAC;AACtG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,uDAAuD,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O;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { loadHeldPrincipalState } from \"../../../data/persistence/principalPolicy/heldPrincipalState\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { publishAuthenticatedSigners } from \"../../../data/principals/principalIdentityCommitments\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await loadHeldPrincipalState(input.execSql, input.source.head)) ??\n undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
1
+ {"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,GAG9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,uDAAuD,CAAC;AACpG,OAAO,EAAE,+BAA+B,EAAE,MAAM,kDAAkD,CAAC;AACnG,OAAO,EAEL,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,sCAAsC,EAAE,MAAM,mCAAmC,CAAC;AAC3F,OAAO,EACL,gCAAgC,EAChC,6CAA6C,GAC9C,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,mCAAmC,EACnC,qCAAqC,GACtC,MAAM,kCAAkC,CAAC;AAY1C,SAAS,UAAU,CACjB,KAAoC,EACpC,IAAiC,EACjC,KAAa;IAEb,IACE,CAAC,6BAA6B,CAAC,IAAI,CAAC;QACpC,CAAC,6BAA6B,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC;QACpE,IAAI,CAAC,WAAW,CAAC,YAAY,KAAK,KAAK;QAEvC,MAAM,IA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AI,CAAC,aAAa,KAAK,cAAc;QACpD,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,KAAK,OAAO,CAAC,cAAc;QAE1D,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kDAAkD,CACnD,CAAC;IACJ,0EAA0E;IAC1E,oCAAoC,CAAC;QACnC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa;QAChD,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;QAC5C,kBAAkB,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrE,UAAU,CAAC,OAAO,GAAG,4BAA4B,CAAC;QAChD,2CAA2C;QAC3C,UAAU,CAAC,OAAO;QAClB,OAAO,CAAC,YAAY,KAAK,IAAI;QAC7B,OAAO,CAAC,gBAAgB,IAAI,IAAI;KACjC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { publishAuthenticatedSigners } from \"../../../data/principals/principalIdentityCommitments\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadHeldPrincipalState(input.source.head)) ?? undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { computePrincipalStateHash, makeVerifiedPrincipalPolicy, } from "../../internal/crypto/index.js";
2
- import { seedLocallyAcknowledgedPrincipalPolicyBundles } from "../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js";
2
+ import { PrincipalPolicyBundleRepository } from "../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
3
3
  async function principalPolicyBundleFromInitialRequest(principalType, principalId, policy) {
4
4
  const createdAt = new Date().toISOString();
5
5
  const stateHash = await computePrincipalStateHash(policy.state);
@@ -61,14 +61,12 @@ function verifiedPrincipalPolicyFromBundle(bundle) {
61
61
  });
62
62
  }
63
63
  export async function persistRegistrationPrincipalPolicies(input) {
64
- await seedLocallyAcknowledgedPrincipalPolicyBundles({
64
+ await new PrincipalPolicyBundleRepository(input.execSql).seedLocallyAcknowledgedPrincipalPolicyBundles({
65
65
  entries: [input.adminGroup, input.memberGroup, input.organization].map((bundle) => ({
66
66
  bundle,
67
67
  policy: verifiedPrincipalPolicyFromBundle(bundle),
68
68
  })),
69
- execSql: input.execSql,
70
69
  organizationId: input.organization.currentState.principalId,
71
- updatedAt: new Date().toISOString(),
72
70
  });
73
71
  }
74
72
  //# sourceMappingURL=registrationPrincipalPolicyPersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"registrationPrincipalPolicyPersistence.js","sourceRoot":"","sources":["registrationPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAE5B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,sFAAsF,CAAC;AAGrJ,KAAK,UAAU,uCAAuC,CACpD,aAAuC,EACvC,WAAmB,EACnB,MAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEhE,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QACvD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,MAAM,CAAC,gBAAgB;YAC1B,SAAS;SACV;QACD,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,iBAAiB,EAAE,MAAM,CAAC,UAAU;QACpC,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,QAAQ;YAC5B,SAAS,EAAE,MAAM,C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AC,YAAY,CAAC,WAAW;YAC5C,OAAO,EAAE,MAAM,CAAC,YAAY,CAAC,OAAO;YACpC,SAAS,EAAE,MAAM,CAAC,YAAY,CAAC,SAAS;SACzC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAK1D;IACC,MAAM,6CAA6C,CAAC;QAClD,OAAO,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,GAAG,CACpE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACX,MAAM;YACN,MAAM,EAAE,iCAAiC,CAAC,MAAM,CAAC;SAClD,CAAC,CACH;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,WAAW;QAC3D,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n makeVerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { seedLocallyAcknowledgedPrincipalPolicyBundles } from \"../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nasync function principalPolicyBundleFromInitialRequest(\n principalType: \"group\" | \"organization\",\n principalId: string,\n policy: PutPrincipalPolicyRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n const createdAt = new Date().toISOString();\n const stateHash = await computePrincipalStateHash(policy.state);\n\n return {\n currentState: { ...policy.state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...policy.encryptedPayload,\n createdAt,\n },\n currentGrants: policy.grants,\n currentProjection: policy.projection,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: policy.state.keyEpoch,\n envelopes: policy.memberEnvelopes,\n },\n previousStates: [],\n };\n}\n\nexport async function principalPolicyBundleFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"group\",\n input.groupId,\n input.initialGroupPolicy,\n );\n}\n\nexport async function principalPolicyBundleFromInitialOrganizationRequest(\n input: RegistrationRequest[\"initialOrganizationPolicy\"],\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"organization\",\n input.state.principalId,\n input,\n );\n}\n\nexport async function verifiedPrincipalPolicyFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<VerifiedPrincipalPolicy> {\n const bundle = await principalPolicyBundleFromInitialGroupRequest(input);\n\n return verifiedPrincipalPolicyFromBundle(bundle);\n}\n\nfunction verifiedPrincipalPolicyFromBundle(\n bundle: PrincipalPolicyBundleResponse,\n): VerifiedPrincipalPolicy {\n return makeVerifiedPrincipalPolicy({\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n history: [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ],\n checkpoint: {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n stateHash: bundle.currentState.stateHash,\n },\n });\n}\n\nexport async function persistRegistrationPrincipalPolicies(input: {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}): Promise<void> {\n await seedLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input.adminGroup, input.memberGroup, input.organization].map(\n (bundle) => ({\n bundle,\n policy: verifiedPrincipalPolicyFromBundle(bundle),\n }),\n ),\n execSql: input.execSql,\n organizationId: input.organization.currentState.principalId,\n updatedAt: new Date().toISOString(),\n });\n}\n"]}
1
+ {"version":3,"file":"registrationPrincipalPolicyPersistence.js","sourceRoot":"","sources":["registrationPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAE5B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AAGzH,KAAK,UAAU,uCAAuC,CACpD,aAAuC,EACvC,WAAmB,EACnB,MAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEhE,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QACvD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,MAAM,CAAC,gBAAgB;YAC1B,SAAS;SACV;QACD,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,iBAAiB,EAAE,MAAM,CAAC,UAAU;QACpC,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,QAAQ;YAC5B,SAAS,EAAE,MAAM,CAAC,eAAe;SAClC;QACD,cAAc,EAAE,EAAE;KACnB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,KAAqC;IAErC,OAAO,uCAAuC,CAC5C,OAAO,EACP,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,kBAA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AC,KAK1D;IACC,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,6CAA6C,CAAC;QAC9C,OAAO,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,GAAG,CACpE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACX,MAAM;YACN,MAAM,EAAE,iCAAiC,CAAC,MAAM,CAAC;SAClD,CAAC,CACH;QACD,cAAc,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,WAAW;KAC5D,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n makeVerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { PrincipalPolicyBundleRepository } from \"../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nasync function principalPolicyBundleFromInitialRequest(\n principalType: \"group\" | \"organization\",\n principalId: string,\n policy: PutPrincipalPolicyRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n const createdAt = new Date().toISOString();\n const stateHash = await computePrincipalStateHash(policy.state);\n\n return {\n currentState: { ...policy.state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...policy.encryptedPayload,\n createdAt,\n },\n currentGrants: policy.grants,\n currentProjection: policy.projection,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: policy.state.keyEpoch,\n envelopes: policy.memberEnvelopes,\n },\n previousStates: [],\n };\n}\n\nexport async function principalPolicyBundleFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"group\",\n input.groupId,\n input.initialGroupPolicy,\n );\n}\n\nexport async function principalPolicyBundleFromInitialOrganizationRequest(\n input: RegistrationRequest[\"initialOrganizationPolicy\"],\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"organization\",\n input.state.principalId,\n input,\n );\n}\n\nexport async function verifiedPrincipalPolicyFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<VerifiedPrincipalPolicy> {\n const bundle = await principalPolicyBundleFromInitialGroupRequest(input);\n\n return verifiedPrincipalPolicyFromBundle(bundle);\n}\n\nfunction verifiedPrincipalPolicyFromBundle(\n bundle: PrincipalPolicyBundleResponse,\n): VerifiedPrincipalPolicy {\n return makeVerifiedPrincipalPolicy({\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n history: [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ],\n checkpoint: {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n stateHash: bundle.currentState.stateHash,\n },\n });\n}\n\nexport async function persistRegistrationPrincipalPolicies(input: {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}): Promise<void> {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).seedLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input.adminGroup, input.memberGroup, input.organization].map(\n (bundle) => ({\n bundle,\n policy: verifiedPrincipalPolicyFromBundle(bundle),\n }),\n ),\n organizationId: input.organization.currentState.principalId,\n });\n}\n"]}
@@ -1,18 +0,0 @@
1
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
2
- import { ensurePrincipalPolicyTables, retainPrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
3
- import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
4
- /** Retains a just-verified epoch without promoting it to the mutable head. */
5
- export async function retainVerifiedPrincipalPolicyBundle(input) {
6
- await assertBundleMatchesVerifiedPolicy(input);
7
- await ensurePrincipalPolicyTables(input.execSql);
8
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
9
- const retain = (tx) => retainPrincipalPolicyBundleInTransaction(tx, input.bundle, input.updatedAt, input.organizationId);
10
- if (input.stillCurrent) {
11
- await runtime.guardedTransaction(retain, input.stillCurrent, {
12
- behavior: "immediate",
13
- });
14
- return;
15
- }
16
- await runtime.transaction(retain, { behavior: "immediate" });
17
- }
18
- //# sourceMappingURL=verifiedPrincipalPolicyRetentionPersistence.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyRetentionPersistence.js","sourceRoot":"","sources":["verifiedPrincipalPolicyRetentionPersistence.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAE1F,OAAO,EACL,2BAA2B,EAC3B,wCAAwC,GACzC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAEpF,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAOzD;IACC,MAAM,iCAAiC,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,2BAA2B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,CACb,EAAkE,EAClE,EAAE,CACF,wCAAwC,CACtC,EAAE,EACF,KAAK,CAAC,MAAM,EACZ,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,YAAY,EAAE;YAC3D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n ensurePrincipalPolicyTables,\n retainPrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\n/** Retains a just-verified epoch without promoting it to the mutable head. */\nexport async function retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await ensurePrincipalPolicyTables(input.execSql);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const retain = (\n tx: Parameters<typeof retainPrincipalPolicyBundleInTransaction>[0],\n ) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n );\n if (input.stillCurrent) {\n await runtime.guardedTransaction(retain, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(retain, { behavior: \"immediate\" });\n}\n"]}