@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
@@ -2,7 +2,7 @@ import { validateAccessManifestCheckpointEvidence } from "../../persistence/keyi
2
2
  import { accessManifestObjectKey } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
3
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
4
  import { PrincipalAuthorizationCheckpointUnavailableError, validatePrincipalAuthorizationCheckpoints, } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
5
- import { ensurePrincipalPolicyTables } from "../../persistence/principalPolicy/principalPolicyPersistence.js";
5
+ import { PrincipalPolicyBundleRepository } from "../../persistence/principalPolicy/principalPolicyBundleRepository.js";
6
6
  import { registerClientSQLiteCommitGuard } from "../../sqlite/sqliteCommitGuards.js";
7
7
  import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
8
8
  import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
@@ -58,7 +58,7 @@ async function checkPurgeCheckpointCurrency(input, documentPurgeCheckpoint) {
58
58
  verifiedManifests: input.context.verifiedManifests,
59
59
  });
60
60
  if (input.currencyPolicies.length) {
61
- await ensurePrincipalPolicyTables(execSql);
61
+ await new PrincipalPolicyBundleRepository(execSql).ensurePrincipalPolicyTables();
62
62
  await validatePrincipalAuthorizationCheckpoints(transaction, input.currencyPolicies);
63
63
  }
64
64
  if (superseded) {
@@ -1 +1 @@
1
- {"version":3,"file":"documentPurgeCheckpointCurrency.js","sourceRoot":"","sources":["documentPurgeCheckpointCurrency.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,wCAAwC,EAAE,MAAM,8DAA8D,CAAC;AACxH,OAAO,EAAE,uBAAuB,EAAE,MAAM,iEAAiE,CAAC;AAC1G,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EACL,gDAAgD,EAChD,yCAAyC,GAC1C,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,8DAA8D,CAAC;AAC3G,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oDAAoD,CAAC;AACvG,OAAO,EACL,2BAA2B,GAE5B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AAWvF,iFAAiF;AACjF,KAAK,UAAU,qBAAqB,CAAC,KAA2B;IAC9D,MAAM,OAAO,GAA+C,EAAE,CAAC;IAC/D,IAAI,UAAU,GAAG,KAAK,CAAC;IACvB,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,OAA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Q,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC1B,IAAI,KAAK,YAAY,gDAAgD;YACnE,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,KAA2B;IAE3B,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAEC;IAED,OAAO,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedAccessManifestCheckpointEvidence,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"../../persistence/keyingCheckpoints/keyingCheckpointEvidence\";\nimport { accessManifestObjectKey } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n PrincipalAuthorizationCheckpointUnavailableError,\n validatePrincipalAuthorizationCheckpoints,\n} from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport { ensurePrincipalPolicyTables } from \"../../persistence/principalPolicy/principalPolicyPersistence\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { validateAccessManifestCheckpoints } from \"../checkpoints/accessManifestCheckpointEnforcement\";\nimport {\n commitProjectionCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { admitDocumentPurgePolicyCheckpoints } from \"./documentPurgePolicyCheckpoints\";\nimport type { PurgePolicyCurrencyEvidence } from \"./documentPurgePolicyCurrency\";\n\ninterface PurgeCheckpointInput {\n readonly context: ProjectionCheckpointContext;\n readonly execSql: ExecSql;\n readonly principalPolicies: readonly VerifiedPrincipalPolicySelection[];\n readonly currencyPolicies: readonly PurgePolicyCurrencyEvidence[];\n readonly observedPrincipalHeads: readonly ReferencedPrincipalHead[];\n}\n\n/** All artifacts must already be authenticated before currency is considered. */\nasync function currentContainerHeads(input: PurgeCheckpointInput) {\n const current: VerifiedAccessManifestCheckpointEvidence[] = [];\n let superseded = false;\n for (const head of input.context.verifiedHeads) {\n const checkpoint = head.checkpoint;\n const local =\n checkpoint.objectKind === \"container\"\n ? await new KeyingCheckpointRepository(\n input.execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n checkpoint.organizationId,\n checkpoint.objectId,\n )\n : null;\n if (!local || checkpoint.epoch >= local.epoch) {\n current.push(head);\n continue;\n }\n // A newer head does not order this separately signed purge event. Still\n // reject signed forks visible in the supplied evidence before deferring.\n const key = accessManifestObjectKey(checkpoint);\n validateAccessManifestCheckpointEvidence({\n head,\n localCheckpoint: local,\n predecessors: input.context.verifiedManifests.filter(\n (evidence) =>\n accessManifestObjectKey(evidence.checkpoint) === key &&\n evidence.manifestHash !== head.manifestHash,\n ),\n });\n superseded = true;\n }\n return { current, superseded };\n}\n\nasync function checkPurgeCheckpointCurrency(\n input: PurgeCheckpointInput,\n documentPurgeCheckpoint?: DocumentPurgeCheckpoint,\n): Promise<void> {\n // Keep comparison and optional advancement in the same immediate transaction.\n // Pass the locked executor through nested readers and checkpoint commits.\n await runSerializedSqlMutation(input.execSql, async (execSql) => {\n await getClientSQLitePersistenceRuntime(execSql).transaction(\n async (transaction) => {\n const stillCurrent = projectionLifetimeGuard(input.context);\n registerClientSQLiteCommitGuard(execSql, () =>\n assertProjectionVerificationCurrent(stillCurrent),\n );\n const { current, superseded } = await currentContainerHeads({\n ...input,\n execSql,\n });\n // An older container must not conceal a document fork, a policy fork, or\n // conflicting current evidence for another container in the same proof.\n await validateAccessManifestCheckpoints({\n execSql,\n policies: [],\n verifiedHeads: current,\n verifiedManifests: input.context.verifiedManifests,\n });\n if (input.currencyPolicies.length) {\n await ensurePrincipalPolicyTables(execSql);\n await validatePrincipalAuthorizationCheckpoints(\n transaction,\n input.currencyPolicies,\n );\n }\n if (superseded) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge cannot be ordered against a newer container checkpoint\",\n );\n }\n if (documentPurgeCheckpoint) {\n // Only the complete authenticated terminal proof admits these public\n // observations. Page recovery and baseline verification never pin.\n await admitDocumentPurgePolicyCheckpoints({\n transaction,\n organizationId: input.context.organizationId,\n policies: input.principalPolicies,\n heads: input.observedPrincipalHeads,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n await commitProjectionCheckpoints(\n {\n ...input.context,\n policies: [],\n // Currency was rechecked above in this same transaction. Private\n // ancestry bridges must never become newly admitted purge heads.\n authorizationPolicies: [],\n },\n {\n documentPurgeCheckpoint,\n execSql,\n },\n );\n }\n },\n { behavior: \"immediate\" },\n );\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n}\n\nexport function validateDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput,\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input);\n}\n\nexport function commitDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput & {\n readonly documentPurgeCheckpoint: DocumentPurgeCheckpoint;\n },\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input, input.documentPurgeCheckpoint);\n}\n"]}
1
+ {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,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,KAA2B;IAE3B,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAEC;IAED,OAAO,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedAccessManifestCheckpointEvidence,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"../../persistence/keyingCheckpoints/keyingCheckpointEvidence\";\nimport { accessManifestObjectKey } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n PrincipalAuthorizationCheckpointUnavailableError,\n validatePrincipalAuthorizationCheckpoints,\n} from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { validateAccessManifestCheckpoints } from \"../checkpoints/accessManifestCheckpointEnforcement\";\nimport {\n commitProjectionCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { admitDocumentPurgePolicyCheckpoints } from \"./documentPurgePolicyCheckpoints\";\nimport type { PurgePolicyCurrencyEvidence } from \"./documentPurgePolicyCurrency\";\n\ninterface PurgeCheckpointInput {\n readonly context: ProjectionCheckpointContext;\n readonly execSql: ExecSql;\n readonly principalPolicies: readonly VerifiedPrincipalPolicySelection[];\n readonly currencyPolicies: readonly PurgePolicyCurrencyEvidence[];\n readonly observedPrincipalHeads: readonly ReferencedPrincipalHead[];\n}\n\n/** All artifacts must already be authenticated before currency is considered. */\nasync function currentContainerHeads(input: PurgeCheckpointInput) {\n const current: VerifiedAccessManifestCheckpointEvidence[] = [];\n let superseded = false;\n for (const head of input.context.verifiedHeads) {\n const checkpoint = head.checkpoint;\n const local =\n checkpoint.objectKind === \"container\"\n ? await new KeyingCheckpointRepository(\n input.execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n checkpoint.organizationId,\n checkpoint.objectId,\n )\n : null;\n if (!local || checkpoint.epoch >= local.epoch) {\n current.push(head);\n continue;\n }\n // A newer head does not order this separately signed purge event. Still\n // reject signed forks visible in the supplied evidence before deferring.\n const key = accessManifestObjectKey(checkpoint);\n validateAccessManifestCheckpointEvidence({\n head,\n localCheckpoint: local,\n predecessors: input.context.verifiedManifests.filter(\n (evidence) =>\n accessManifestObjectKey(evidence.checkpoint) === key &&\n evidence.manifestHash !== head.manifestHash,\n ),\n });\n superseded = true;\n }\n return { current, superseded };\n}\n\nasync function checkPurgeCheckpointCurrency(\n input: PurgeCheckpointInput,\n documentPurgeCheckpoint?: DocumentPurgeCheckpoint,\n): Promise<void> {\n // Keep comparison and optional advancement in the same immediate transaction.\n // Pass the locked executor through nested readers and checkpoint commits.\n await runSerializedSqlMutation(input.execSql, async (execSql) => {\n await getClientSQLitePersistenceRuntime(execSql).transaction(\n async (transaction) => {\n const stillCurrent = projectionLifetimeGuard(input.context);\n registerClientSQLiteCommitGuard(execSql, () =>\n assertProjectionVerificationCurrent(stillCurrent),\n );\n const { current, superseded } = await currentContainerHeads({\n ...input,\n execSql,\n });\n // An older container must not conceal a document fork, a policy fork, or\n // conflicting current evidence for another container in the same proof.\n await validateAccessManifestCheckpoints({\n execSql,\n policies: [],\n verifiedHeads: current,\n verifiedManifests: input.context.verifiedManifests,\n });\n if (input.currencyPolicies.length) {\n await new PrincipalPolicyBundleRepository(\n execSql,\n ).ensurePrincipalPolicyTables();\n await validatePrincipalAuthorizationCheckpoints(\n transaction,\n input.currencyPolicies,\n );\n }\n if (superseded) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge cannot be ordered against a newer container checkpoint\",\n );\n }\n if (documentPurgeCheckpoint) {\n // Only the complete authenticated terminal proof admits these public\n // observations. Page recovery and baseline verification never pin.\n await admitDocumentPurgePolicyCheckpoints({\n transaction,\n organizationId: input.context.organizationId,\n policies: input.principalPolicies,\n heads: input.observedPrincipalHeads,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n await commitProjectionCheckpoints(\n {\n ...input.context,\n policies: [],\n // Currency was rechecked above in this same transaction. Private\n // ancestry bridges must never become newly admitted purge heads.\n authorizationPolicies: [],\n },\n {\n documentPurgeCheckpoint,\n execSql,\n },\n );\n }\n },\n { behavior: \"immediate\" },\n );\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n}\n\nexport function validateDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput,\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input);\n}\n\nexport function commitDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput & {\n readonly documentPurgeCheckpoint: DocumentPurgeCheckpoint;\n },\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input, input.documentPurgeCheckpoint);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
- import { loadPrincipalPolicyBundleForReference } from "../../persistence/principalPolicy/principalPolicyReferencePersistence.js";
3
+ import { PrincipalPolicyBundleRepository } from "../../persistence/principalPolicy/principalPolicyBundleRepository.js";
4
4
  import { principalPolicyEvidenceEntries, } from "../../principals/principalPolicyEvidence.js";
5
5
  import { principalStateMatchesReference } from "../../principals/principalPolicyStates.js";
6
6
  import { verifiedPrincipalPolicyMeetsCheckpoint } from "./principalPolicyCheckpointSelection.js";
@@ -68,7 +68,7 @@ export async function filterUncachedPrincipalPolicyReferences(input) {
68
68
  return null;
69
69
  }
70
70
  }
71
- const bundle = await loadPrincipalPolicyBundleForReference(input.execSql, reference, checkpoint);
71
+ const bundle = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundleForReference(reference, checkpoint);
72
72
  return bundle ? null : reference;
73
73
  }));
74
74
  return results.filter((reference) => reference !== null);
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAExF,OAAO,EAAE,sCAAsC,EAAE,MAAM,sCAAsC,CAAC;AAE9F;;;;;GAKG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAkC;IAElC,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,SAAS,CAAC,aAAa;QACvB,SAAS,CAAC,WAAW;QACrB,SAAS,CAAC,OAAO;QACjB,SAAS,CAAC,SAAS;QACnB,SAAS,CAAC,QAAQ;QAClB,SAAS,CAAC,cAAc;KACzB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B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CAAC,KAAK,EAAE,SAAS,CAAC,CACjD,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAAC,KAI7D;IACC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAC/B,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE;QACvC,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,KAAK,CAAC,OAAO,CACd,CAAC,6BAA6B,CAC7B,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC;QACF,MAAM,YAAY,GAAG,KAAK,CAAC,oBAAoB,CAAC,GAAG,CACjD,4BAA4B,CAAC,SAAS,CAAC,CACxC,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,IACE,CAAC,wCAAwC,CAAC,YAAY,EAAE,SAAS,CAAC,EAClE,CAAC;gBACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,qEAAqE,CACtE,CAAC;YACJ,CAAC;YACD,IAAI,sCAAsC,CAAC,YAAY,EAAE,UAAU,CAAC,EAAE,CAAC;gBACrE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,qCAAqC,CACxD,KAAK,CAAC,OAAO,EACb,SAAS,EACT,UAAU,CACX,CAAC;QACF,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,SAAS,EAAwC,EAAE,CAAC,SAAS,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport { principalStateMatchesReference } from \"../../principals/principalPolicyStates\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"./principalPolicyCheckpointSelection\";\n\n/**\n * Cache key for a referenced principal policy. The in-memory principal-policy\n * cache is populated and read from several call sites; they must agree on this\n * format byte-for-byte or a populated entry looks uncached (extra warm fetches)\n * — so this is the single source of truth, imported rather than re-declared.\n */\nexport function referencedPrincipalPolicyKey(\n reference: ReferencedPrincipalHead,\n): string {\n return JSON.stringify([\n reference.principalType,\n reference.principalId,\n reference.version,\n reference.stateHash,\n reference.keyEpoch,\n reference.keyFingerprint,\n ]);\n}\n\n/**\n * Dedupes references by their exact head identity, keyed with\n * {@link referencedPrincipalPolicyKey} so every consumer agrees on what\n * \"the same reference\" means. Later duplicates win, preserving each\n * caller's original last-wins behavior.\n */\nexport function dedupeReferencedPrincipalStates<\n TReference extends ReferencedPrincipalHead,\n>(references: ReadonlyArray<TReference>): TReference[] {\n const referencesByState = new Map<string, TReference>();\n for (const reference of references) {\n referencesByState.set(referencedPrincipalPolicyKey(reference), reference);\n }\n return Array.from(referencesByState.values());\n}\n\nexport function principalPolicyCacheForVerifiedPolicies(\n policies: readonly PrincipalPolicyCurrentEvidence[],\n): Map<string, PrincipalPolicyCurrentEvidence> {\n const cache = new Map<string, PrincipalPolicyCurrentEvidence>();\n for (const policy of policies) {\n const states = principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.state,\n );\n for (const state of states) {\n cache.set(\n referencedPrincipalPolicyKey({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n }),\n policy,\n );\n }\n }\n return cache;\n}\n\nexport function verifiedPrincipalPolicyContainsReference(\n policy: PrincipalPolicyCurrentEvidence,\n reference: ReferencedPrincipalHead,\n): boolean {\n const states = principalPolicyEvidenceEntries(policy).map(\n ({ state }) => state,\n );\n return states.some((state) =>\n principalStateMatchesReference(state, reference),\n );\n}\n\n// Identify which referenced policies are absent from both the in-memory cache\n// and local storage, so the warmer fetches only what is genuinely missing.\nexport async function filterUncachedPrincipalPolicyReferences(input: {\n execSql: ExecSql;\n principalPolicyCache: ReadonlyMap<string, PrincipalPolicyCurrentEvidence>;\n references: readonly ReferencedPrincipalHead[];\n}): Promise<ReferencedPrincipalHead[]> {\n const results = await Promise.all(\n input.references.map(async (reference) => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const cachedPolicy = input.principalPolicyCache.get(\n referencedPrincipalPolicyKey(reference),\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, checkpoint)) {\n return null;\n }\n }\n const bundle = await loadPrincipalPolicyBundleForReference(\n input.execSql,\n reference,\n checkpoint,\n );\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EAAE,+BAA+B,EAAE,MAAM,mEAAmE,CAAC;AACpH,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,8BAA8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CAAC,OAAO,CACd,CAAC,qCAAqC,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,SAAS,EAAwC,EAAE,CAAC,SAAS,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport { principalStateMatchesReference } from \"../../principals/principalPolicyStates\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"./principalPolicyCheckpointSelection\";\n\n/**\n * Cache key for a referenced principal policy. The in-memory principal-policy\n * cache is populated and read from several call sites; they must agree on this\n * format byte-for-byte or a populated entry looks uncached (extra warm fetches)\n * — so this is the single source of truth, imported rather than re-declared.\n */\nexport function referencedPrincipalPolicyKey(\n reference: ReferencedPrincipalHead,\n): string {\n return JSON.stringify([\n reference.principalType,\n reference.principalId,\n reference.version,\n reference.stateHash,\n reference.keyEpoch,\n reference.keyFingerprint,\n ]);\n}\n\n/**\n * Dedupes references by their exact head identity, keyed with\n * {@link referencedPrincipalPolicyKey} so every consumer agrees on what\n * \"the same reference\" means. Later duplicates win, preserving each\n * caller's original last-wins behavior.\n */\nexport function dedupeReferencedPrincipalStates<\n TReference extends ReferencedPrincipalHead,\n>(references: ReadonlyArray<TReference>): TReference[] {\n const referencesByState = new Map<string, TReference>();\n for (const reference of references) {\n referencesByState.set(referencedPrincipalPolicyKey(reference), reference);\n }\n return Array.from(referencesByState.values());\n}\n\nexport function principalPolicyCacheForVerifiedPolicies(\n policies: readonly PrincipalPolicyCurrentEvidence[],\n): Map<string, PrincipalPolicyCurrentEvidence> {\n const cache = new Map<string, PrincipalPolicyCurrentEvidence>();\n for (const policy of policies) {\n const states = principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.state,\n );\n for (const state of states) {\n cache.set(\n referencedPrincipalPolicyKey({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n }),\n policy,\n );\n }\n }\n return cache;\n}\n\nexport function verifiedPrincipalPolicyContainsReference(\n policy: PrincipalPolicyCurrentEvidence,\n reference: ReferencedPrincipalHead,\n): boolean {\n const states = principalPolicyEvidenceEntries(policy).map(\n ({ state }) => state,\n );\n return states.some((state) =>\n principalStateMatchesReference(state, reference),\n );\n}\n\n// Identify which referenced policies are absent from both the in-memory cache\n// and local storage, so the warmer fetches only what is genuinely missing.\nexport async function filterUncachedPrincipalPolicyReferences(input: {\n execSql: ExecSql;\n principalPolicyCache: ReadonlyMap<string, PrincipalPolicyCurrentEvidence>;\n references: readonly ReferencedPrincipalHead[];\n}): Promise<ReferencedPrincipalHead[]> {\n const results = await Promise.all(\n input.references.map(async (reference) => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const cachedPolicy = input.principalPolicyCache.get(\n referencedPrincipalPolicyKey(reference),\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, checkpoint)) {\n return null;\n }\n }\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(reference, checkpoint);\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { KeyingVerificationError, verifyPrincipalPolicyBundle, } from "../../../internal/crypto/index.js";
2
2
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
- import { loadPrincipalPolicyBundle } from "../../persistence/principalPolicy/principalPolicyPersistence.js";
4
- import { loadPrincipalPolicyBundleForReference } from "../../persistence/principalPolicy/principalPolicyReferencePersistence.js";
3
+ import { PrincipalPolicyBundleRepository } from "../../persistence/principalPolicy/principalPolicyBundleRepository.js";
5
4
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../principals/organizationAuthorityDescriptor.js";
6
5
  import { assertPrincipalIdentityCommitments, publishVerifiedPolicyBundle, } from "../../principals/principalIdentityCommitments.js";
7
6
  import { organizationAdminExternalAuthority, principalPolicyReferenceFromBundle, verifyOrganizationAdminPolicy, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../principals/principalPolicyAdminSigners.js";
@@ -35,7 +34,7 @@ export function isPrincipalPolicyNotCachedError(error) {
35
34
  }
36
35
  async function loadOrganizationPolicyForVerification(input) {
37
36
  const execSql = input.checkpointContext.execSql;
38
- let bundle = await loadPrincipalPolicyBundle(execSql, "organization", input.organizationId);
37
+ let bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
39
38
  if (!bundle) {
40
39
  return undefined;
41
40
  }
@@ -46,7 +45,7 @@ async function loadOrganizationPolicyForVerification(input) {
46
45
  organizationId: input.organizationId,
47
46
  references: [principalPolicyReferenceFromBundle(bundle)],
48
47
  });
49
- bundle = await loadPrincipalPolicyBundle(execSql, "organization", input.organizationId);
48
+ bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
50
49
  localCheckpoint = await new KeyingCheckpointRepository(execSql).loadPrincipalPolicyCheckpoint("organization", input.organizationId);
51
50
  if (!bundle) {
52
51
  return undefined;
@@ -62,7 +61,7 @@ function assertReservedAdminsPolicyShape(policy) {
62
61
  }
63
62
  }
64
63
  async function verifyOrganizationAdminsPolicy(input) {
65
- const adminBundle = await loadPrincipalPolicyBundle(input.execSql, "group", input.adminGroupId);
64
+ const adminBundle = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("group", input.adminGroupId);
66
65
  if (!adminBundle) {
67
66
  return undefined;
68
67
  }
@@ -177,7 +176,7 @@ async function verifyReferencedPrincipalPolicy(input) {
177
176
  }
178
177
  }
179
178
  const referenceLabel = principalPolicyReferenceLabel(input.reference);
180
- let bundle = await loadPrincipalPolicyBundleForReference(execSql, input.reference, localCheckpoint);
179
+ let bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);
181
180
  if (!bundle && input.warmReferencedPrincipalPolicies) {
182
181
  // The reference is not cached locally — the common case for a member who
183
182
  // gained access via another org's group grant and never hydrated that
@@ -186,7 +185,7 @@ async function verifyReferencedPrincipalPolicy(input) {
186
185
  organizationId: input.organizationId,
187
186
  references: [input.reference],
188
187
  });
189
- bundle = await loadPrincipalPolicyBundleForReference(execSql, input.reference, localCheckpoint);
188
+ bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);
190
189
  }
191
190
  if (!bundle) {
192
191
  throw new PrincipalPolicyNotCachedError(referenceLabel);
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAIvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EAAE,yBA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,KAAK,CAAC,YAAY,CAAC,CAAC;YACxD,MAAM,+BAA+B,CAAC;gBACpC,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,UAAU,EAAE,QAAQ;aACrB,CAAC,CAAC;YACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;IAED,0EAA0E;IAC1E,OAAO,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAC3B,+BAA+B,CAAC;QAC9B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,SAAS;QACT,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { loadPrincipalPolicyBundle } from \"../../persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n assertPrincipalIdentityCommitments,\n publishVerifiedPolicyBundle,\n} from \"../../principals/principalIdentityCommitments\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { rethrowProjectionVerificationBoundaryError } from \"../error\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"./principalPolicyCheckpointSelection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./principalPolicySigners\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n /** The verification's lifetime, checked inside every pin write. */\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n await publishVerifiedPolicyBundle(adminBundle, input.resolveUserKey, () =>\n assertProjectionVerificationCurrent(input.stillCurrent),\n );\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await publishVerifiedPolicyBundle(\n organizationPolicy.bundle,\n input.resolveUserKey,\n () => assertProjectionVerificationCurrent(input.stillCurrent),\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\n/**\n * Fresh or reused: check every projection, history included; pin first\n * sights within the verification's lifetime. A freshly verified `bundle` also\n * pins its signers.\n */\nasync function assertVerifiedPolicyCommitments(\n policy: PrincipalPolicyCurrentEvidence,\n scope: {\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n bundle?: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const assertCurrent = () =>\n assertProjectionVerificationCurrent(scope.stillCurrent);\n await assertPrincipalIdentityCommitments({\n assertCurrent,\n authenticated: true,\n projections: [\n policy.projection,\n ...principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.projection,\n ),\n ],\n resolveTrustedUserIdentity: scope.resolveUserKey,\n });\n if (bundle)\n await publishVerifiedPolicyBundle(\n bundle,\n scope.resolveUserKey,\n assertCurrent,\n );\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) {\n await assertVerifiedPolicyCommitments(recovered, input);\n return recovered;\n }\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n await assertVerifiedPolicyCommitments(cachedPolicy, input);\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await assertVerifiedPolicyCommitments(verified.value, input, bundle);\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAIvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EAAE,+BAA+B,EAAE,MAAM,mEAAmE,CAAC;AACpH,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,kCAAkC,EAClC,2BAA2B,GAC5B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,6BAA6B,EAC7B,yDAAyD,GAC1D,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,sBAAsB,GAEvB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,0CAA0C,EAAE,MAAM,UAAU,CAAC;AAMtE,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GACvC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,uCAAuC,EACvC,4BAA4B,EAC5B,wCAAwC,GACzC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GACvC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,sCAAsC,EAAE,MAAM,0BAA0B,CAAC;AAClF,OAAO,EAAE,gCAAgC,EAAE,MAA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rincipalHead,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n assertPrincipalIdentityCommitments,\n publishVerifiedPolicyBundle,\n} from \"../../principals/principalIdentityCommitments\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { rethrowProjectionVerificationBoundaryError } from \"../error\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"./principalPolicyCheckpointSelection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./principalPolicySigners\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n /** The verification's lifetime, checked inside every pin write. */\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"group\", input.adminGroupId);\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n await publishVerifiedPolicyBundle(adminBundle, input.resolveUserKey, () =>\n assertProjectionVerificationCurrent(input.stillCurrent),\n );\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await publishVerifiedPolicyBundle(\n organizationPolicy.bundle,\n input.resolveUserKey,\n () => assertProjectionVerificationCurrent(input.stillCurrent),\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\n/**\n * Fresh or reused: check every projection, history included; pin first\n * sights within the verification's lifetime. A freshly verified `bundle` also\n * pins its signers.\n */\nasync function assertVerifiedPolicyCommitments(\n policy: PrincipalPolicyCurrentEvidence,\n scope: {\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n bundle?: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const assertCurrent = () =>\n assertProjectionVerificationCurrent(scope.stillCurrent);\n await assertPrincipalIdentityCommitments({\n assertCurrent,\n authenticated: true,\n projections: [\n policy.projection,\n ...principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.projection,\n ),\n ],\n resolveTrustedUserIdentity: scope.resolveUserKey,\n });\n if (bundle)\n await publishVerifiedPolicyBundle(\n bundle,\n scope.resolveUserKey,\n assertCurrent,\n );\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) {\n await assertVerifiedPolicyCommitments(recovered, input);\n return recovered;\n }\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n await assertVerifiedPolicyCommitments(cachedPolicy, input);\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await assertVerifiedPolicyCommitments(verified.value, input, bundle);\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
@@ -1,24 +1,12 @@
1
1
  import { isCurrentPrincipalMemberEnvelopesResponse, } from "../../../internal/validators/response/index.js";
2
2
  import { and, desc, eq, sql } from "drizzle-orm";
3
3
  import { principalCurrentFingerprintJson, principalStateFingerprintJson, } from "../../sqlite/principalKeyFingerprintJson.js";
4
- import { principalHistoryEvidenceTables, principalHistoryPrefixes, } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
4
+ import { principalHistoryPrefixes } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
5
5
  import { principalKeyEnvelopeArchive } from "../../sqlite/schema/principalHistoryRetentionSchema.js";
6
6
  import { principalHistoryStages } from "../../sqlite/schema/principalHistoryStageSchema.js";
7
- import { principalPolicyBundles, principalPolicyTables, } from "../../sqlite/schema/principalPolicySchema.js";
8
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
9
- import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
10
- /**
11
- * Untrusted encrypted key candidates, never authorization evidence. The actual
12
- * private key must open the requested recipient wrap; the projection verifier
13
- * separately checks the signed KEK material identity and all policy authority.
14
- * Read only envelopes for the requested fingerprints, never signed histories.
15
- */
16
- export async function loadPrincipalKeyEnvelopeCandidates(execSql, fingerprints) {
17
- await ensureSqlTables(execSql, [
18
- ...principalPolicyTables,
19
- ...principalHistoryEvidenceTables,
20
- ]);
21
- const { db } = getClientSQLitePersistenceRuntime(execSql);
7
+ import { principalPolicyBundles } from "../../sqlite/schema/principalPolicySchema.js";
8
+ /** Each source's newest envelopes per fingerprint; tables already ensured. */
9
+ export async function selectPrincipalKeyEnvelopeCandidates(db, fingerprints) {
22
10
  const candidates = [];
23
11
  for (const fingerprint of new Set(fingerprints)) {
24
12
  const encoded = [];
@@ -1 +1 @@
1
- {"version":3,"file":"principalKeyEnvelopeCandidates.js","sourceRoot":"","sources":["principalKeyEnvelopeCandidates.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,yCAAyC,GAC1C,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,+BAA+B,EAC/B,6BAA6B,GAC9B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,qDAAqD,CAAC;AAClG,OAAO,EAAE,sBAAsB,EAAE,MAAM,iDAAiD,CAAC;AACzF,OAAO,EACL,sBAAsB,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,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACzC,UAAU,CAAC,IAAI,CAAC,GAAG,wBAAwB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA0B,EAC1B,WAAmB;IAEnB,MAAM,UAAU,GAAoC,EAAE,CAAC;IACvD,KAAK,MAAM,IAAI,IAAI,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QACpC,IAAI,SAAkB,CAAC;QACvB,IAAI,CAAC;YACH,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;QACD,IAAI,CAAC,yCAAyC,CAAC,SAAS,CAAC;YAAE,SAAS;QACpE,UAAU,CAAC,IAAI,CAAC;YACd,YAAY,EAAE;gBACZ,aAAa,EAAE,SAAS,CAAC,aAAa;gBACtC,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,SAAS,EAAE,SAAS,CAAC,SAAS;gBAC9B,cAAc,EAAE,WAAW;aAC5B;YACD,sBAAsB,EAAE,SAAS;SAClC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import {\n type CurrentPrincipalMemberEnvelopesResponse,\n isCurrentPrincipalMemberEnvelopesResponse,\n} from \"@tearleads/validators/response\";\nimport { and, desc, eq, sql } from \"drizzle-orm\";\nimport {\n principalCurrentFingerprintJson,\n principalStateFingerprintJson,\n} from \"../../sqlite/principalKeyFingerprintJson\";\nimport {\n principalHistoryEvidenceTables,\n principalHistoryPrefixes,\n} from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport { principalKeyEnvelopeArchive } from \"../../sqlite/schema/principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"../../sqlite/schema/principalHistoryStageSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\nexport interface PrincipalKeyEnvelopeCandidate {\n readonly currentState: {\n readonly principalType: \"group\" | \"organization\";\n readonly principalId: string;\n readonly stateHash: string;\n readonly keyFingerprint: string;\n };\n readonly currentMemberEnvelopes: CurrentPrincipalMemberEnvelopesResponse;\n}\n\n/**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\nexport async function loadPrincipalKeyEnvelopeCandidates(\n execSql: ExecSql,\n fingerprints: readonly string[],\n): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const candidates: PrincipalKeyEnvelopeCandidate[] = [];\n for (const fingerprint of new Set(fingerprints)) {\n const encoded: string[] = [];\n const [archived] = await db\n .select({ envelopes: principalKeyEnvelopeArchive.envelopesJson })\n .from(principalKeyEnvelopeArchive)\n .where(eq(principalKeyEnvelopeArchive.keyFingerprint, fingerprint))\n .orderBy(desc(principalKeyEnvelopeArchive.version))\n .limit(1);\n if (archived) encoded.push(archived.envelopes);\n // The newest current head and the newest retained bundle each offer one.\n for (const isCurrent of [true, false]) {\n const [row] = await db\n .select({\n envelopes: principalPolicyBundles.currentMemberEnvelopesJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(\n principalStateFingerprintJson(\n principalPolicyBundles.currentStateJson,\n ),\n fingerprint,\n ),\n eq(principalPolicyBundles.isCurrent, isCurrent),\n ),\n )\n .orderBy(desc(principalPolicyBundles.updatedAt))\n .limit(1);\n if (row) encoded.push(row.envelopes);\n }\n const [prefix] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryPrefixes.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryPrefixes)\n .where(\n eq(\n principalCurrentFingerprintJson(principalHistoryPrefixes.currentJson),\n fingerprint,\n ),\n )\n .orderBy(desc(principalHistoryPrefixes.version))\n .limit(1);\n if (prefix) encoded.push(prefix.envelopes);\n const [stage] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryStages.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryStages)\n .where(\n and(\n eq(\n principalCurrentFingerprintJson(principalHistoryStages.currentJson),\n fingerprint,\n ),\n eq(principalHistoryStages.complete, true),\n ),\n )\n .orderBy(desc(principalHistoryStages.afterVersion))\n .limit(1);\n if (stage) encoded.push(stage.envelopes);\n candidates.push(...decodeEnvelopeCandidates(encoded, fingerprint));\n }\n return candidates;\n}\n\n/** Distinct, well-formed envelope sets; malformed JSON is skipped. */\nfunction decodeEnvelopeCandidates(\n encoded: readonly string[],\n fingerprint: string,\n): PrincipalKeyEnvelopeCandidate[] {\n const candidates: PrincipalKeyEnvelopeCandidate[] = [];\n for (const json of new Set(encoded)) {\n let envelopes: unknown;\n try {\n envelopes = JSON.parse(json);\n } catch {\n continue;\n }\n if (!isCurrentPrincipalMemberEnvelopesResponse(envelopes)) continue;\n candidates.push({\n currentState: {\n principalType: envelopes.principalType,\n principalId: envelopes.principalId,\n stateHash: envelopes.stateHash,\n keyFingerprint: fingerprint,\n },\n currentMemberEnvelopes: envelopes,\n });\n }\n return candidates;\n}\n"]}
1
+ {"version":3,"file":"principalKeyEnvelopeCandidates.js","sourceRoot":"","sources":["principalKeyEnvelopeCandidates.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,yCAAyC,GAC1C,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,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KAAK,CAAC,SAAS,CAAC,CAAC;QACzC,UAAU,CAAC,IAAI,CAAC,GAAG,wBAAwB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA0B,EAC1B,WAAmB;IAEnB,MAAM,UAAU,GAAoC,EAAE,CAAC;IACvD,KAAK,MAAM,IAAI,IAAI,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QACpC,IAAI,SAAkB,CAAC;QACvB,IAAI,CAAC;YACH,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;QACD,IAAI,CAAC,yCAAyC,CAAC,SAAS,CAAC;YAAE,SAAS;QACpE,UAAU,CAAC,IAAI,CAAC;YACd,YAAY,EAAE;gBACZ,aAAa,EAAE,SAAS,CAAC,aAAa;gBACtC,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,SAAS,EAAE,SAAS,CAAC,SAAS;gBAC9B,cAAc,EAAE,WAAW;aAC5B;YACD,sBAAsB,EAAE,SAAS;SAClC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import {\n type CurrentPrincipalMemberEnvelopesResponse,\n isCurrentPrincipalMemberEnvelopesResponse,\n} from \"@tearleads/validators/response\";\nimport { and, desc, eq, sql } from \"drizzle-orm\";\nimport {\n principalCurrentFingerprintJson,\n principalStateFingerprintJson,\n} from \"../../sqlite/principalKeyFingerprintJson\";\nimport { principalHistoryPrefixes } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport { principalKeyEnvelopeArchive } from \"../../sqlite/schema/principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"../../sqlite/schema/principalHistoryStageSchema\";\nimport { principalPolicyBundles } from \"../../sqlite/schema/principalPolicySchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\n\nexport interface PrincipalKeyEnvelopeCandidate {\n readonly currentState: {\n readonly principalType: \"group\" | \"organization\";\n readonly principalId: string;\n readonly stateHash: string;\n readonly keyFingerprint: string;\n };\n readonly currentMemberEnvelopes: CurrentPrincipalMemberEnvelopesResponse;\n}\n\n/** Each source's newest envelopes per fingerprint; tables already ensured. */\nexport async function selectPrincipalKeyEnvelopeCandidates(\n db: ClientSQLiteDatabase,\n fingerprints: readonly string[],\n): Promise<PrincipalKeyEnvelopeCandidate[]> {\n const candidates: PrincipalKeyEnvelopeCandidate[] = [];\n for (const fingerprint of new Set(fingerprints)) {\n const encoded: string[] = [];\n const [archived] = await db\n .select({ envelopes: principalKeyEnvelopeArchive.envelopesJson })\n .from(principalKeyEnvelopeArchive)\n .where(eq(principalKeyEnvelopeArchive.keyFingerprint, fingerprint))\n .orderBy(desc(principalKeyEnvelopeArchive.version))\n .limit(1);\n if (archived) encoded.push(archived.envelopes);\n // The newest current head and the newest retained bundle each offer one.\n for (const isCurrent of [true, false]) {\n const [row] = await db\n .select({\n envelopes: principalPolicyBundles.currentMemberEnvelopesJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(\n principalStateFingerprintJson(\n principalPolicyBundles.currentStateJson,\n ),\n fingerprint,\n ),\n eq(principalPolicyBundles.isCurrent, isCurrent),\n ),\n )\n .orderBy(desc(principalPolicyBundles.updatedAt))\n .limit(1);\n if (row) encoded.push(row.envelopes);\n }\n const [prefix] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryPrefixes.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryPrefixes)\n .where(\n eq(\n principalCurrentFingerprintJson(principalHistoryPrefixes.currentJson),\n fingerprint,\n ),\n )\n .orderBy(desc(principalHistoryPrefixes.version))\n .limit(1);\n if (prefix) encoded.push(prefix.envelopes);\n const [stage] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryStages.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryStages)\n .where(\n and(\n eq(\n principalCurrentFingerprintJson(principalHistoryStages.currentJson),\n fingerprint,\n ),\n eq(principalHistoryStages.complete, true),\n ),\n )\n .orderBy(desc(principalHistoryStages.afterVersion))\n .limit(1);\n if (stage) encoded.push(stage.envelopes);\n candidates.push(...decodeEnvelopeCandidates(encoded, fingerprint));\n }\n return candidates;\n}\n\n/** Distinct, well-formed envelope sets; malformed JSON is skipped. */\nfunction decodeEnvelopeCandidates(\n encoded: readonly string[],\n fingerprint: string,\n): PrincipalKeyEnvelopeCandidate[] {\n const candidates: PrincipalKeyEnvelopeCandidate[] = [];\n for (const json of new Set(encoded)) {\n let envelopes: unknown;\n try {\n envelopes = JSON.parse(json);\n } catch {\n continue;\n }\n if (!isCurrentPrincipalMemberEnvelopesResponse(envelopes)) continue;\n candidates.push({\n currentState: {\n principalType: envelopes.principalType,\n principalId: envelopes.principalId,\n stateHash: envelopes.stateHash,\n keyFingerprint: fingerprint,\n },\n currentMemberEnvelopes: envelopes,\n });\n }\n return candidates;\n}\n"]}
@@ -4,16 +4,23 @@ export type PrincipalMutationJournalRow = Omit<typeof principalMutationJournal.$
4
4
  export declare class PendingPrincipalMutationError extends Error {
5
5
  constructor();
6
6
  }
7
- export declare function loadPrincipalMutationJournal(execSql: ExecSql, scopeId: string): Promise<PrincipalMutationJournalRow | null>;
8
- /** Claim the organization lane before dispatch; never overwrite unresolved work. */
9
- export declare function claimPrincipalMutationJournal(input: {
10
- readonly execSql: ExecSql;
11
- readonly row: PrincipalMutationJournalRow;
12
- readonly stillCurrent: () => boolean;
13
- }): Promise<void>;
14
- /** A late acknowledgement cannot retire another operation's journal entry. */
15
- export declare function clearPrincipalMutationJournal(input: {
16
- readonly execSql: ExecSql;
17
- readonly row: PrincipalMutationJournalRow;
18
- readonly stillCurrent: () => boolean;
19
- }): Promise<boolean>;
7
+ /**
8
+ * The principal mutation journal, bound to one executor: at most one
9
+ * unresolved signed mutation per organization lane. Each write runs its own
10
+ * immediate guarded transaction and throws when `stillCurrent` refuses it.
11
+ */
12
+ export declare class PrincipalMutationJournalRepository {
13
+ private readonly execSql;
14
+ constructor(execSql: ExecSql);
15
+ loadPrincipalMutationJournal(scopeId: string): Promise<PrincipalMutationJournalRow | null>;
16
+ /** Claim the organization lane before dispatch; never overwrite unresolved work. */
17
+ claimPrincipalMutationJournal(input: {
18
+ readonly row: PrincipalMutationJournalRow;
19
+ readonly stillCurrent: () => boolean;
20
+ }): Promise<void>;
21
+ /** A late acknowledgement cannot retire another operation's journal entry. */
22
+ clearPrincipalMutationJournal(input: {
23
+ readonly row: PrincipalMutationJournalRow;
24
+ readonly stillCurrent: () => boolean;
25
+ }): Promise<boolean>;
26
+ }
@@ -9,50 +9,61 @@ export class PendingPrincipalMutationError extends Error {
9
9
  this.name = "PendingPrincipalMutationError";
10
10
  }
11
11
  }
12
- export async function loadPrincipalMutationJournal(execSql, scopeId) {
13
- await ensureSqlTables(execSql, principalMutationJournalTables);
14
- const { db } = getClientSQLitePersistenceRuntime(execSql);
15
- const [row] = await db
16
- .select({
17
- scopeId: principalMutationJournal.scopeId,
18
- organizationId: principalMutationJournal.organizationId,
19
- serializedRequest: principalMutationJournal.serializedRequest,
20
- signature: principalMutationJournal.signature,
21
- })
22
- .from(principalMutationJournal)
23
- .where(eq(principalMutationJournal.scopeId, scopeId))
24
- .limit(1);
25
- return row ?? null;
26
- }
27
- /** Claim the organization lane before dispatch; never overwrite unresolved work. */
28
- export async function claimPrincipalMutationJournal(input) {
29
- const row = { ...input.row };
30
- await ensureSqlTables(input.execSql, principalMutationJournalTables);
31
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
32
- const result = await runtime.guardedTransaction(async (tx) => {
33
- const [existing] = await tx
34
- .select({ scopeId: principalMutationJournal.scopeId })
12
+ /**
13
+ * The principal mutation journal, bound to one executor: at most one
14
+ * unresolved signed mutation per organization lane. Each write runs its own
15
+ * immediate guarded transaction and throws when `stillCurrent` refuses it.
16
+ */
17
+ export class PrincipalMutationJournalRepository {
18
+ execSql;
19
+ constructor(execSql) {
20
+ this.execSql = execSql;
21
+ }
22
+ async loadPrincipalMutationJournal(scopeId) {
23
+ await ensureSqlTables(this.execSql, principalMutationJournalTables);
24
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
25
+ const [row] = await db
26
+ .select({
27
+ scopeId: principalMutationJournal.scopeId,
28
+ organizationId: principalMutationJournal.organizationId,
29
+ serializedRequest: principalMutationJournal.serializedRequest,
30
+ signature: principalMutationJournal.signature,
31
+ })
35
32
  .from(principalMutationJournal)
36
- .where(eq(principalMutationJournal.scopeId, row.scopeId))
33
+ .where(eq(principalMutationJournal.scopeId, scopeId))
37
34
  .limit(1);
38
- if (existing)
39
- throw new PendingPrincipalMutationError();
40
- await tx.insert(principalMutationJournal).values(row).run();
41
- }, input.stillCurrent, { behavior: "immediate" });
42
- assertProjectionVerificationCurrent(() => result.committed);
43
- }
44
- /** A late acknowledgement cannot retire another operation's journal entry. */
45
- export async function clearPrincipalMutationJournal(input) {
46
- const row = { ...input.row };
47
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
48
- const result = await runtime.guardedTransaction(async (tx) => {
49
- const deleted = await tx
50
- .delete(principalMutationJournal)
51
- .where(and(eq(principalMutationJournal.scopeId, row.scopeId), eq(principalMutationJournal.organizationId, row.organizationId), eq(principalMutationJournal.serializedRequest, row.serializedRequest), eq(principalMutationJournal.signature, row.signature)))
52
- .returning({ scopeId: principalMutationJournal.scopeId });
53
- return deleted.length > 0;
54
- }, input.stillCurrent, { behavior: "immediate" });
55
- assertProjectionVerificationCurrent(() => result.committed);
56
- return result.result === true;
35
+ return row ?? null;
36
+ }
37
+ /** Claim the organization lane before dispatch; never overwrite unresolved work. */
38
+ async claimPrincipalMutationJournal(input) {
39
+ const row = { ...input.row };
40
+ await ensureSqlTables(this.execSql, principalMutationJournalTables);
41
+ const runtime = getClientSQLitePersistenceRuntime(this.execSql);
42
+ const result = await runtime.guardedTransaction(async (tx) => {
43
+ const [existing] = await tx
44
+ .select({ scopeId: principalMutationJournal.scopeId })
45
+ .from(principalMutationJournal)
46
+ .where(eq(principalMutationJournal.scopeId, row.scopeId))
47
+ .limit(1);
48
+ if (existing)
49
+ throw new PendingPrincipalMutationError();
50
+ await tx.insert(principalMutationJournal).values(row).run();
51
+ }, input.stillCurrent, { behavior: "immediate" });
52
+ assertProjectionVerificationCurrent(() => result.committed);
53
+ }
54
+ /** A late acknowledgement cannot retire another operation's journal entry. */
55
+ async clearPrincipalMutationJournal(input) {
56
+ const row = { ...input.row };
57
+ const runtime = getClientSQLitePersistenceRuntime(this.execSql);
58
+ const result = await runtime.guardedTransaction(async (tx) => {
59
+ const deleted = await tx
60
+ .delete(principalMutationJournal)
61
+ .where(and(eq(principalMutationJournal.scopeId, row.scopeId), eq(principalMutationJournal.organizationId, row.organizationId), eq(principalMutationJournal.serializedRequest, row.serializedRequest), eq(principalMutationJournal.signature, row.signature)))
62
+ .returning({ scopeId: principalMutationJournal.scopeId });
63
+ return deleted.length > 0;
64
+ }, input.stillCurrent, { behavior: "immediate" });
65
+ assertProjectionVerificationCurrent(() => result.committed);
66
+ return result.result === true;
67
+ }
57
68
  }
58
69
  //# sourceMappingURL=principalMutationJournalPersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationJournalPersistence.js","sourceRoot":"","sources":["principalMutationJournalPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAOpE,MAAM,OAAO,6BAA8B,SA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GAAG,CAAC,CAAC;IAC5B,CAAC,EACD,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC,MAAM,KAAK,IAAI,CAAC;AAChC,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"../sqlite/schema/principalMutationJournalSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nexport type PrincipalMutationJournalRow = Omit<\n typeof principalMutationJournal.$inferSelect,\n \"identityBundleFormat\"\n>;\n\nexport class PendingPrincipalMutationError extends Error {\n constructor() {\n super(\n \"Resolve the pending principal mutation or explicitly abandon its retry before submitting another\",\n );\n this.name = \"PendingPrincipalMutationError\";\n }\n}\n\nexport async function loadPrincipalMutationJournal(\n execSql: ExecSql,\n scopeId: string,\n): Promise<PrincipalMutationJournalRow | null> {\n await ensureSqlTables(execSql, principalMutationJournalTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select({\n scopeId: principalMutationJournal.scopeId,\n organizationId: principalMutationJournal.organizationId,\n serializedRequest: principalMutationJournal.serializedRequest,\n signature: principalMutationJournal.signature,\n })\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, scopeId))\n .limit(1);\n return row ?? null;\n}\n\n/** Claim the organization lane before dispatch; never overwrite unresolved work. */\nexport async function claimPrincipalMutationJournal(input: {\n readonly execSql: ExecSql;\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const row = { ...input.row };\n await ensureSqlTables(input.execSql, principalMutationJournalTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [existing] = await tx\n .select({ scopeId: principalMutationJournal.scopeId })\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, row.scopeId))\n .limit(1);\n if (existing) throw new PendingPrincipalMutationError();\n await tx.insert(principalMutationJournal).values(row).run();\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n\n/** A late acknowledgement cannot retire another operation's journal entry. */\nexport async function clearPrincipalMutationJournal(input: {\n readonly execSql: ExecSql;\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const row = { ...input.row };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const deleted = await tx\n .delete(principalMutationJournal)\n .where(\n and(\n eq(principalMutationJournal.scopeId, row.scopeId),\n eq(principalMutationJournal.organizationId, row.organizationId),\n eq(\n principalMutationJournal.serializedRequest,\n row.serializedRequest,\n ),\n eq(principalMutationJournal.signature, row.signature),\n ),\n )\n .returning({ scopeId: principalMutationJournal.scopeId });\n return deleted.length > 0;\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n return result.result === true;\n}\n"]}
1
+ {"version":3,"file":"principalMutationJournalPersistence.js","sourceRoot":"","sources":["principalMutationJournalPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAOpE,MAAM,OAAO,6BAA8B,SAAQ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ACtD,CACF;iBACA,SAAS,CAAC,EAAE,OAAO,EAAE,wBAAwB,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,OAAO,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;QAC5B,CAAC,EACD,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC5D,OAAO,MAAM,CAAC,MAAM,KAAK,IAAI,CAAC;IAChC,CAAC;CACF","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"../sqlite/schema/principalMutationJournalSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nexport type PrincipalMutationJournalRow = Omit<\n typeof principalMutationJournal.$inferSelect,\n \"identityBundleFormat\"\n>;\n\nexport class PendingPrincipalMutationError extends Error {\n constructor() {\n super(\n \"Resolve the pending principal mutation or explicitly abandon its retry before submitting another\",\n );\n this.name = \"PendingPrincipalMutationError\";\n }\n}\n\n/**\n * The principal mutation journal, bound to one executor: at most one\n * unresolved signed mutation per organization lane. Each write runs its own\n * immediate guarded transaction and throws when `stillCurrent` refuses it.\n */\nexport class PrincipalMutationJournalRepository {\n private readonly execSql: ExecSql;\n\n constructor(execSql: ExecSql) {\n this.execSql = execSql;\n }\n\n async loadPrincipalMutationJournal(\n scopeId: string,\n ): Promise<PrincipalMutationJournalRow | null> {\n await ensureSqlTables(this.execSql, principalMutationJournalTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({\n scopeId: principalMutationJournal.scopeId,\n organizationId: principalMutationJournal.organizationId,\n serializedRequest: principalMutationJournal.serializedRequest,\n signature: principalMutationJournal.signature,\n })\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, scopeId))\n .limit(1);\n return row ?? null;\n }\n\n /** Claim the organization lane before dispatch; never overwrite unresolved work. */\n async claimPrincipalMutationJournal(input: {\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n }): Promise<void> {\n const row = { ...input.row };\n await ensureSqlTables(this.execSql, principalMutationJournalTables);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [existing] = await tx\n .select({ scopeId: principalMutationJournal.scopeId })\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, row.scopeId))\n .limit(1);\n if (existing) throw new PendingPrincipalMutationError();\n await tx.insert(principalMutationJournal).values(row).run();\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n }\n\n /** A late acknowledgement cannot retire another operation's journal entry. */\n async clearPrincipalMutationJournal(input: {\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n }): Promise<boolean> {\n const row = { ...input.row };\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const deleted = await tx\n .delete(principalMutationJournal)\n .where(\n and(\n eq(principalMutationJournal.scopeId, row.scopeId),\n eq(principalMutationJournal.organizationId, row.organizationId),\n eq(\n principalMutationJournal.serializedRequest,\n row.serializedRequest,\n ),\n eq(principalMutationJournal.signature, row.signature),\n ),\n )\n .returning({ scopeId: principalMutationJournal.scopeId });\n return deleted.length > 0;\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n return result.result === true;\n }\n}\n"]}
@@ -3,8 +3,6 @@ import { and, eq, inArray, or } from "drizzle-orm";
3
3
  import { principalHeadMatchesReference } from "../../principals/organizationAuthorityDescriptor.js";
4
4
  import { principalPolicyBundleReferences, principalPolicyBundles, } from "../../sqlite/schema/index.js";
5
5
  import { principalHistoryEntries, principalHistoryEntryStateHashJson, } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
6
- import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
7
- import { ensurePrincipalPolicyTables } from "./principalPolicyPersistence.js";
8
6
  /** Candidate rows per source; equal hashes rarely repeat across scopes. */
9
7
  const HELD_STATE_CANDIDATES = 8;
10
8
  function parsedJson(json) {
@@ -74,15 +72,8 @@ async function bundleState(db, head) {
74
72
  }
75
73
  return null;
76
74
  }
77
- /**
78
- * A signed state this device stored for exactly `head`: history evidence it
79
- * verified or acknowledged, or a cached policy bundle chain. It is untrusted;
80
- * the caller verifies it as it would a served copy, and a miss only means the
81
- * server sends one.
82
- */
83
- export async function loadHeldPrincipalState(execSql, head) {
84
- await ensurePrincipalPolicyTables(execSql);
85
- const { db } = getClientSQLitePersistenceRuntime(execSql);
75
+ /** History evidence first, then cached bundle chains; tables already ensured. */
76
+ export async function selectHeldPrincipalState(db, head) {
86
77
  return (await evidenceState(db, head)) ?? bundleState(db, head);
87
78
  }
88
79
  //# sourceMappingURL=heldPrincipalState.js.map