@tearleads/client-sdk 0.1.112 → 0.1.113

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 (34) hide show
  1. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +16 -11
  2. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  3. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js +150 -2
  4. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -1
  5. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js +3 -2
  6. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -1
  7. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.d.ts +14 -1
  8. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js +128 -34
  9. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -1
  10. package/data/persistence/principalHistory/principalHistoryNodeRetention.js +64 -24
  11. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -1
  12. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js +6 -1
  13. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -1
  14. package/data/persistence/principalHistory/principalHistoryRootOwnership.d.ts +45 -0
  15. package/data/persistence/principalHistory/principalHistoryRootOwnership.js +41 -4
  16. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -1
  17. package/data/persistence/principalHistory/principalHistoryStagePersistence.js +12 -8
  18. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -1
  19. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js +35 -1
  20. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -1
  21. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js +62 -1
  22. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -1
  23. package/data/persistence/trustedUserIdentityPinPersistence.js +46 -23
  24. package/data/persistence/trustedUserIdentityPinPersistence.js.map +1 -1
  25. package/data/persistence/verifiedManifestBundlePersistence.js +27 -10
  26. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  27. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.d.ts +222 -0
  28. package/package.json +1 -1
  29. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +13 -12
  30. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  31. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +17 -19
  32. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  33. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +8 -10
  34. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
@@ -3,11 +3,11 @@ import { keyingCheckpointTables, principalPolicyTables, } from "../../sqlite/sch
3
3
  import { verifiedManifestBundleTables } from "../../sqlite/schema/verifiedManifestBundleSchema.js";
4
4
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
- import { assertContainerNotRetired } from "../principalKeys/principalGrantRetirementPersistence.js";
6
+ import { loadContainerRetirementCheck } from "../principalKeys/principalGrantRetirementPersistence.js";
7
7
  import { verifiedManifestBundleRows, writeVerifiedManifestBundlesInTransaction, } from "../verifiedManifestBundlePersistence.js";
8
8
  import { storeDocumentPurgeCheckpointInTransaction, } from "./documentPurgeCheckpointPersistence.js";
9
9
  import { validateAccessManifestCheckpointEvidence } from "./keyingCheckpointEvidence.js";
10
- import { accessManifestObjectKey, loadStoredAccessManifestCheckpoint, loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertAccessManifestCheckpointInTransaction, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpointPersistence.js";
10
+ import { accessManifestObjectKey, loadAccessManifestCheckpointRows, loadStoredPrincipalPolicyCheckpoints, principalPolicyKey, upsertAccessManifestCheckpointsInTransaction, upsertPrincipalPolicyCheckpointsInTransaction, } from "./keyingCheckpointPersistence.js";
11
11
  import { validatePrincipalAuthorizationCheckpoints } from "./principalAuthorizationCheckpoints.js";
12
12
  function validateAccessAdvance(advance, localCheckpoint) {
13
13
  const current = {
@@ -40,13 +40,21 @@ function validateAccessAdvance(advance, localCheckpoint) {
40
40
  }
41
41
  async function validateAccessAdvances(tx, advances) {
42
42
  const pending = new Map();
43
+ if (advances.length === 0)
44
+ return pending;
45
+ // Set reads first; the checks then replay in order, so the same advance
46
+ // fails first with the same error.
47
+ const heads = advances.map((advance) => advance.head.checkpoint);
48
+ const assertNotRetired = await loadContainerRetirementCheck(tx, heads);
49
+ const stored = await loadAccessManifestCheckpointRows(tx, heads);
43
50
  for (const advance of advances) {
44
- await assertContainerNotRetired(tx, advance.head.checkpoint);
51
+ assertNotRetired(advance.head.checkpoint);
45
52
  const key = accessManifestObjectKey(advance.head.checkpoint);
46
53
  if (pending.has(key)) {
47
54
  throw new KeyingVerificationError("equivocation", `projection declares multiple access checkpoint heads for ${key}`);
48
55
  }
49
- const localCheckpoint = await loadStoredAccessManifestCheckpoint(tx, advance.head.checkpoint);
56
+ const row = stored.get(key);
57
+ const localCheckpoint = row ? { ...advance.head.checkpoint, ...row } : null;
50
58
  pending.set(key, validateAccessAdvance(advance, localCheckpoint));
51
59
  }
52
60
  return pending;
@@ -72,6 +80,7 @@ export async function validatePrincipalPolicyCheckpointAdvances(tx, policies) {
72
80
  policiesByPrincipal.set(key, candidates);
73
81
  }
74
82
  const pending = new Map();
83
+ const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);
75
84
  for (const key of [...policiesByPrincipal.keys()].sort()) {
76
85
  const candidates = policiesByPrincipal.get(key) ?? [];
77
86
  const maxVersion = Math.max(...candidates.map((policy) => policy.version));
@@ -91,7 +100,7 @@ export async function validatePrincipalPolicyCheckpointAdvances(tx, policies) {
91
100
  throw new KeyingVerificationError("stale_predecessor", `principal policy head does not extend observed state for ${key}`);
92
101
  }
93
102
  }
94
- const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);
103
+ const localCheckpoint = stored.get(key) ?? null;
95
104
  verifyPrincipalPolicyCheckpoint({
96
105
  chain: "retainedHistory" in head ? head.retainedHistory : (head.history ?? []),
97
106
  currentState: head.state,
@@ -102,15 +111,11 @@ export async function validatePrincipalPolicyCheckpointAdvances(tx, policies) {
102
111
  return pending;
103
112
  }
104
113
  async function writeAccessCheckpoints(tx, pending, updatedAt) {
105
- for (const { checkpoint } of pending.values()) {
106
- await upsertAccessManifestCheckpointInTransaction(tx, checkpoint, updatedAt);
107
- }
114
+ await upsertAccessManifestCheckpointsInTransaction(tx, [...pending.values()].map(({ checkpoint }) => checkpoint), updatedAt);
108
115
  }
109
116
  /** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */
110
117
  export async function writePrincipalPolicyCheckpoints(tx, pending, updatedAt, organizationId) {
111
- for (const policy of pending.values()) {
112
- await upsertPrincipalPolicyCheckpointInTransaction(tx, policy.checkpoint, updatedAt, organizationId);
113
- }
118
+ await upsertPrincipalPolicyCheckpointsInTransaction(tx, [...pending.values()].map((policy) => policy.checkpoint), updatedAt, organizationId);
114
119
  }
115
120
  /**
116
121
  * Digests the verified bundles and ensures every table the batch touches,
@@ -1 +1 @@
1
- {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAIvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,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C,uBAAuB,EAAE,CAAC;YAClC,MAAM,yCAAyC,CAC7C,EAAE,EACF,KAAK,CAAC,uBAAuB,EAC7B,SAAS,CACV,CAAC;QACJ,CAAC;QACD,MAAM,yCAAyC,CAAC,EAAE,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;IAC7E,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../../sqlite/schema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { assertContainerNotRetired } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\n/**\n * Checks, inside the caller's transaction, that each principal's newest policy\n * extends every other candidate and its durable checkpoint. Returns the heads\n * to pin, keyed by principal.\n */\nexport async function validatePrincipalPolicyCheckpointAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\n/** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */\nexport async function writePrincipalPolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\n/**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\nasync function prepareKeyingCheckpointBatch(\n input: KeyingCheckpointValidationInput,\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n input.verifiedBundles ?? [],\n );\n await ensureSqlTables(input.execSql, [\n ...(input.policies.length > 0 ||\n (input.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ]);\n return bundleRows;\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const verifiedAt = new Date().toISOString();\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePrincipalPolicyCheckpointAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput & {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n },\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n input.policies,\n );\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n input.organizationId,\n );\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n"]}
1
+ {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAIvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,4BAA4B,EAAE,MAAM,sDAAsD,CAAC;AACpG,OAAO,EAGL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,EACL,uBAAuB,EACvB,gCAAgC,EAChC,oCAAoC,EACpC,kBAAkB,EAClB,4CAA4C,EAC5C,6CAA6C,GAC9C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AA8BhG,SAAS,qBAAqB,CAC5B,OAAwC,EACxC,eAAgD;IAEhD,MAAM,OAAO,GAAG;QACd,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU;QAC1B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AC;QACF,IAAI,KAAK,CAAC,uBAAuB,EAAE,CAAC;YAClC,MAAM,yCAAyC,CAC7C,EAAE,EACF,KAAK,CAAC,uBAAuB,EAC7B,SAAS,CACV,CAAC;QACJ,CAAC;QACD,MAAM,yCAAyC,CAAC,EAAE,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;IAC7E,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../../sqlite/schema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { loadContainerRetirementCheck } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadAccessManifestCheckpointRows,\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n upsertAccessManifestCheckpointsInTransaction,\n upsertPrincipalPolicyCheckpointsInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n if (advances.length === 0) return pending;\n // Set reads first; the checks then replay in order, so the same advance\n // fails first with the same error.\n const heads = advances.map((advance) => advance.head.checkpoint);\n const assertNotRetired = await loadContainerRetirementCheck(tx, heads);\n const stored = await loadAccessManifestCheckpointRows(tx, heads);\n\n for (const advance of advances) {\n assertNotRetired(advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const row = stored.get(key);\n const localCheckpoint = row ? { ...advance.head.checkpoint, ...row } : null;\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\n/**\n * Checks, inside the caller's transaction, that each principal's newest policy\n * extends every other candidate and its durable checkpoint. Returns the heads\n * to pin, keyed by principal.\n */\nexport async function validatePrincipalPolicyCheckpointAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = stored.get(key) ?? null;\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n await upsertAccessManifestCheckpointsInTransaction(\n tx,\n [...pending.values()].map(({ checkpoint }) => checkpoint),\n updatedAt,\n );\n}\n\n/** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */\nexport async function writePrincipalPolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await upsertPrincipalPolicyCheckpointsInTransaction(\n tx,\n [...pending.values()].map((policy) => policy.checkpoint),\n updatedAt,\n organizationId,\n );\n}\n\n/**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\nasync function prepareKeyingCheckpointBatch(\n input: KeyingCheckpointValidationInput,\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n input.verifiedBundles ?? [],\n );\n await ensureSqlTables(input.execSql, [\n ...(input.policies.length > 0 ||\n (input.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ]);\n return bundleRows;\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const verifiedAt = new Date().toISOString();\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePrincipalPolicyCheckpointAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput & {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n },\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n input.policies,\n );\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n input.organizationId,\n );\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n"]}
@@ -1,9 +1,11 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
- import { and, eq } from "drizzle-orm";
2
+ import { and, eq, inArray } from "drizzle-orm";
3
3
  import { accessManifestCheckpoints, keyingCheckpointTables, principalPolicyCheckpoints, } from "../../sqlite/schema/index.js";
4
+ import { sqliteInsertBatchSize, sqliteRowsPerStatement, } from "../../sqlite/sqliteBindBudget.js";
4
5
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
6
+ import { excludedValue } from "../../sqlite/sqliteUpsert.js";
5
7
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
- import { recordPrincipalPolicyOrganizationInTransaction } from "../principalPolicy/principalPolicyOrganizationPersistence.js";
8
+ import { recordPrincipalPolicyOrganizationInTransaction, recordPrincipalPolicyOrganizationsInTransaction, } from "../principalPolicy/principalPolicyOrganizationPersistence.js";
7
9
  /** One key format per checkpoint identity, shared by every batch validator. */
8
10
  export function accessManifestObjectKey(identity) {
9
11
  return JSON.stringify([
@@ -37,6 +39,80 @@ async function loadPrincipalPolicyCheckpointRow(handle, identity) {
37
39
  .limit(1);
38
40
  return rows[0] ?? null;
39
41
  }
42
+ // An access lookup binds its kind and organization once; a policy lookup its type.
43
+ const ACCESS_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 2);
44
+ const POLICY_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 1);
45
+ const ACCESS_WRITE_BATCH_SIZE = sqliteInsertBatchSize(accessManifestCheckpoints);
46
+ const POLICY_WRITE_BATCH_SIZE = sqliteInsertBatchSize(principalPolicyCheckpoints);
47
+ /** Splits `values` into consecutive slices of at most `size`. */
48
+ function checkpointBatches(values, size) {
49
+ const result = [];
50
+ for (let index = 0; index < values.length; index += size)
51
+ result.push(values.slice(index, index + size));
52
+ return result;
53
+ }
54
+ /** Distinct ids per group key, in first-seen order. */
55
+ function groupIds(items, group, id) {
56
+ const groups = new Map();
57
+ for (const item of items) {
58
+ const entry = groups.get(group(item)) ?? { first: item, ids: [] };
59
+ if (!entry.ids.includes(id(item)))
60
+ entry.ids.push(id(item));
61
+ groups.set(group(item), entry);
62
+ }
63
+ return groups;
64
+ }
65
+ /**
66
+ * Every stored access checkpoint row for `identities`, keyed by
67
+ * `accessManifestObjectKey`: one read per object kind and organization.
68
+ */
69
+ export async function loadAccessManifestCheckpointRows(handle, identities) {
70
+ const stored = new Map();
71
+ const groups = groupIds(identities, (identity) => JSON.stringify([identity.objectKind, identity.organizationId]), (identity) => identity.objectId);
72
+ for (const { first, ids } of groups.values())
73
+ for (const batch of checkpointBatches(ids, ACCESS_LOOKUP_BATCH_SIZE)) {
74
+ const rows = await handle
75
+ .select({
76
+ objectId: accessManifestCheckpoints.objectId,
77
+ epoch: accessManifestCheckpoints.epoch,
78
+ manifestHash: accessManifestCheckpoints.manifestHash,
79
+ })
80
+ .from(accessManifestCheckpoints)
81
+ .where(and(eq(accessManifestCheckpoints.objectKind, first.objectKind), eq(accessManifestCheckpoints.organizationId, first.organizationId), inArray(accessManifestCheckpoints.objectId, batch)));
82
+ for (const { objectId, ...row } of rows)
83
+ stored.set(accessManifestObjectKey({ ...first, objectId }), row);
84
+ }
85
+ return stored;
86
+ }
87
+ /**
88
+ * Every stored policy checkpoint for `identities`, keyed by
89
+ * `principalPolicyKey`: one read per principal type.
90
+ */
91
+ export async function loadStoredPrincipalPolicyCheckpoints(handle, identities) {
92
+ const stored = new Map();
93
+ const groups = groupIds(identities, (identity) => identity.principalType, (identity) => identity.principalId);
94
+ for (const { first, ids } of groups.values())
95
+ for (const batch of checkpointBatches(ids, POLICY_LOOKUP_BATCH_SIZE)) {
96
+ const rows = await handle
97
+ .select({
98
+ principalId: principalPolicyCheckpoints.principalId,
99
+ version: principalPolicyCheckpoints.version,
100
+ stateHash: principalPolicyCheckpoints.stateHash,
101
+ })
102
+ .from(principalPolicyCheckpoints)
103
+ .where(and(eq(principalPolicyCheckpoints.principalType, first.principalType), inArray(principalPolicyCheckpoints.principalId, batch)));
104
+ for (const row of rows) {
105
+ const checkpoint = {
106
+ principalType: first.principalType,
107
+ principalId: row.principalId,
108
+ version: row.version,
109
+ stateHash: row.stateHash,
110
+ };
111
+ stored.set(principalPolicyKey(checkpoint), checkpoint);
112
+ }
113
+ }
114
+ return stored;
115
+ }
40
116
  /**
41
117
  * A loaded checkpoint row merged back with the identity it was looked up by —
42
118
  * the full checkpoint shape every comparison consumes.
@@ -98,6 +174,78 @@ export async function upsertPrincipalPolicyCheckpointInTransaction(tx, checkpoin
98
174
  })
99
175
  .run();
100
176
  }
177
+ /**
178
+ * Upserts every checkpoint in multi-row statements; a repeated identity keeps
179
+ * its last checkpoint, as sequential upserts would.
180
+ */
181
+ export async function upsertAccessManifestCheckpointsInTransaction(tx, checkpoints, updatedAt) {
182
+ const rows = new Map(checkpoints.map((checkpoint) => [
183
+ accessManifestObjectKey(checkpoint),
184
+ {
185
+ objectKind: checkpoint.objectKind,
186
+ organizationId: checkpoint.organizationId,
187
+ objectId: checkpoint.objectId,
188
+ epoch: checkpoint.epoch,
189
+ manifestHash: checkpoint.manifestHash,
190
+ updatedAt,
191
+ },
192
+ ]));
193
+ for (const batch of checkpointBatches([...rows.values()], ACCESS_WRITE_BATCH_SIZE))
194
+ await tx
195
+ .insert(accessManifestCheckpoints)
196
+ .values(batch)
197
+ .onConflictDoUpdate({
198
+ target: [
199
+ accessManifestCheckpoints.objectKind,
200
+ accessManifestCheckpoints.organizationId,
201
+ accessManifestCheckpoints.objectId,
202
+ ],
203
+ set: {
204
+ epoch: excludedValue(accessManifestCheckpoints.epoch),
205
+ manifestHash: excludedValue(accessManifestCheckpoints.manifestHash),
206
+ updatedAt: excludedValue(accessManifestCheckpoints.updatedAt),
207
+ },
208
+ })
209
+ .run();
210
+ }
211
+ /**
212
+ * Records every checkpoint's cache ownership, failing on the first conflict in
213
+ * order as `upsertPrincipalPolicyCheckpointInTransaction` would, then upserts
214
+ * the checkpoints in multi-row statements.
215
+ */
216
+ export async function upsertPrincipalPolicyCheckpointsInTransaction(tx, checkpoints, updatedAt, organizationId) {
217
+ await recordPrincipalPolicyOrganizationsInTransaction(tx, checkpoints.map((checkpoint) => ({
218
+ organizationId,
219
+ principalId: checkpoint.principalId,
220
+ principalType: checkpoint.principalType,
221
+ })));
222
+ const rows = new Map(checkpoints.map((checkpoint) => [
223
+ principalPolicyKey(checkpoint),
224
+ {
225
+ principalType: checkpoint.principalType,
226
+ principalId: checkpoint.principalId,
227
+ version: checkpoint.version,
228
+ stateHash: checkpoint.stateHash,
229
+ updatedAt,
230
+ },
231
+ ]));
232
+ for (const batch of checkpointBatches([...rows.values()], POLICY_WRITE_BATCH_SIZE))
233
+ await tx
234
+ .insert(principalPolicyCheckpoints)
235
+ .values(batch)
236
+ .onConflictDoUpdate({
237
+ target: [
238
+ principalPolicyCheckpoints.principalType,
239
+ principalPolicyCheckpoints.principalId,
240
+ ],
241
+ set: {
242
+ version: excludedValue(principalPolicyCheckpoints.version),
243
+ stateHash: excludedValue(principalPolicyCheckpoints.stateHash),
244
+ updatedAt: excludedValue(principalPolicyCheckpoints.updatedAt),
245
+ },
246
+ })
247
+ .run();
248
+ }
101
249
  // Lazily create the checkpoint tables on first access. Every load/save below
102
250
  // calls this, so the tables exist on demand; it is intentionally module-private
103
251
  // (no caller outside this file needs it, and exporting it tripped knip).
@@ -1 +1 @@
1
- {"version":3,"file":"keyingCheckpointPersistence.js","sourceRoot":"","sources":["keyingCheckpointPersistence.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAGL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,8CAA8C,EAAE,MAAM,2DAA2D,CAAC;AAc3H,+EAA+E;AAC/E,MAAM,UAAU,uBAAuB,CACrC,QAA0C;IAE1C,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,QAAQ,CAAC,UAAU;QACnB,QAAQ,CAAC,cAAc;QACvB,QAAQ,CAAC,QAAQ;KAClB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,QAA2C;IAE3C,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,aAAa,EAAE,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC;AACxE,CAAC;AAED,KAAK,UAAU,+BAA+B,CAC5C,MAAwB,EACxB,QAA0C;IAE1C,MAAM,IAAI,GAAG,MAAM,MAAM;SACtB,MAAM,CAAC;QACN,KAAK,EAAE,yBAAyB,CAAC,KAAK;QACtC,YAAY,EAAE,yBAAyB,CAAC,YAAY;KACrD,CAAC;SACD,IAAI,CAAC,yBAAyB,CAAC;SAC/B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,yBAAyB,CAAC,UAAU,EAAE,QAAQ,CAAC,UAAU,CAAC,EAC7D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,IAAI,CAAC,WAAW,EAC3C,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,0DAA0D,CAC3D,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC;QACrC,UAAU,CAAC,OAAO,GAAG,CAAC;QACtB,UAAU,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EACjC,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,0CAA0C,CAC3C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccessManifestCheckpoint,\n AccessObjectKind,\n ManagedPrincipalKind,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { and, eq } from \"drizzle-orm\";\nimport {\n accessManifestCheckpoints,\n keyingCheckpointTables,\n principalPolicyCheckpoints,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { recordPrincipalPolicyOrganizationInTransaction } from \"../principalPolicy/principalPolicyOrganizationPersistence\";\n\ntype CheckpointHandle = ClientSQLiteDatabase | ClientSQLiteTransactionScope;\n\ntype AccessManifestCheckpointIdentity = Pick<\n AccessManifestCheckpoint,\n \"objectKind\" | \"organizationId\" | \"objectId\"\n>;\n\ntype PrincipalPolicyCheckpointIdentity = Pick<\n PrincipalPolicyCheckpoint,\n \"principalType\" | \"principalId\"\n>;\n\n/** One key format per checkpoint identity, shared by every batch validator. */\nexport function accessManifestObjectKey(\n identity: AccessManifestCheckpointIdentity,\n): string {\n return JSON.stringify([\n identity.objectKind,\n identity.organizationId,\n identity.objectId,\n ]);\n}\n\nexport function principalPolicyKey(\n identity: PrincipalPolicyCheckpointIdentity,\n): string {\n return JSON.stringify([identity.principalType, identity.principalId]);\n}\n\nasync function loadAccessManifestCheckpointRow(\n handle: CheckpointHandle,\n identity: AccessManifestCheckpointIdentity,\n): Promise<Pick<AccessManifestCheckpoint, \"epoch\" | \"manifestHash\"> | null> {\n const rows = await handle\n .select({\n epoch: accessManifestCheckpoints.epoch,\n manifestHash: accessManifestCheckpoints.manifestHash,\n })\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, identity.objectKind),\n eq(accessManifestCheckpoints.organizationId, identity.organizationId),\n eq(accessManifestCheckpoints.objectId, identity.objectId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\nasync function loadPrincipalPolicyCheckpointRow(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<Pick<PrincipalPolicyCheckpoint, \"version\" | \"stateHash\"> | null> {\n const rows = await handle\n .select({\n version: principalPolicyCheckpoints.version,\n stateHash: principalPolicyCheckpoints.stateHash,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, identity.principalType),\n eq(principalPolicyCheckpoints.principalId, identity.principalId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\n/**\n * A loaded checkpoint row merged back with the identity it was looked up by —\n * the full checkpoint shape every comparison consumes.\n */\nexport async function loadStoredAccessManifestCheckpoint(\n handle: CheckpointHandle,\n checkpoint: AccessManifestCheckpoint,\n): Promise<AccessManifestCheckpoint | null> {\n const row = await loadAccessManifestCheckpointRow(handle, checkpoint);\n return row ? { ...checkpoint, ...row } : null;\n}\n\nexport async function loadStoredPrincipalPolicyCheckpoint(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<PrincipalPolicyCheckpoint | null> {\n const row = await loadPrincipalPolicyCheckpointRow(handle, identity);\n return row\n ? {\n principalType: identity.principalType,\n principalId: identity.principalId,\n ...row,\n }\n : null;\n}\n\n/** Every principal with a durable policy checkpoint. */\nexport function listPrincipalPolicyCheckpointPrincipals(\n handle: CheckpointHandle,\n): Promise<{ id: string; type: string }[]> {\n return handle\n .selectDistinct({\n id: principalPolicyCheckpoints.principalId,\n type: principalPolicyCheckpoints.principalType,\n })\n .from(principalPolicyCheckpoints);\n}\n\nexport async function upsertAccessManifestCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: AccessManifestCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(accessManifestCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n accessManifestCheckpoints.objectKind,\n accessManifestCheckpoints.organizationId,\n accessManifestCheckpoints.objectId,\n ],\n set: row,\n })\n .run();\n}\n\nexport async function upsertPrincipalPolicyCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: PrincipalPolicyCheckpoint,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: checkpoint.principalId,\n principalType: checkpoint.principalType,\n });\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(principalPolicyCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n principalPolicyCheckpoints.principalType,\n principalPolicyCheckpoints.principalId,\n ],\n set: row,\n })\n .run();\n}\n\n// Lazily create the checkpoint tables on first access. Every load/save below\n// calls this, so the tables exist on demand; it is intentionally module-private\n// (no caller outside this file needs it, and exporting it tripped knip).\nasync function ensureKeyingCheckpointTables(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n}\n\nexport async function loadAccessManifestCheckpoint(\n execSql: ExecSql,\n objectKind: AccessObjectKind,\n organizationId: string,\n objectId: string,\n): Promise<AccessManifestCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadAccessManifestCheckpointRow(db, {\n objectKind,\n organizationId,\n objectId,\n });\n\n return row ? { objectKind, objectId, organizationId, ...row } : null;\n}\n\nexport async function loadPrincipalPolicyCheckpoint(\n execSql: ExecSql,\n principalType: ManagedPrincipalKind,\n principalId: string,\n): Promise<PrincipalPolicyCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadPrincipalPolicyCheckpointRow(db, {\n principalType,\n principalId,\n });\n\n return row ? { principalType, principalId, ...row } : null;\n}\n/**\n * The shared shape/ownership guard every checkpoint comparison runs before\n * trusting a durable pin: the pin must belong to the compared principal and\n * carry a well-formed version and hash.\n */\nexport function assertPrincipalPolicyCheckpointShape(\n checkpoint: PrincipalPolicyCheckpoint,\n head: PrincipalPolicyCheckpointIdentity,\n): void {\n if (\n checkpoint.principalType !== head.principalType ||\n checkpoint.principalId !== head.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy checkpoint belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(checkpoint.version) ||\n checkpoint.version < 1 ||\n checkpoint.stateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy checkpoint is malformed\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"keyingCheckpointPersistence.js","sourceRoot":"","sources":["keyingCheckpointPersistence.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,yBAAyB,EACzB,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAGL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAgB,eAA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,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,GAAG,GAAG,MAAM,gCAAgC,CAAC,EAAE,EAAE;QACrD,aAAa;QACb,WAAW;KACZ,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7D,CAAC;AACD;;;;GAIG;AACH,MAAM,UAAU,oCAAoC,CAClD,UAAqC,EACrC,IAAuC;IAEvC,IACE,UAAU,CAAC,aAAa,KAAK,IAAI,CAAC,aAAa;QAC/C,UAAU,CAAC,WAAW,KAAK,IAAI,CAAC,WAAW,EAC3C,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,0DAA0D,CAC3D,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC;QACrC,UAAU,CAAC,OAAO,GAAG,CAAC;QACtB,UAAU,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EACjC,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,0CAA0C,CAC3C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccessManifestCheckpoint,\n AccessObjectKind,\n ManagedPrincipalKind,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { and, eq, inArray } from \"drizzle-orm\";\nimport {\n accessManifestCheckpoints,\n keyingCheckpointTables,\n principalPolicyCheckpoints,\n} from \"../../sqlite/schema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n recordPrincipalPolicyOrganizationInTransaction,\n recordPrincipalPolicyOrganizationsInTransaction,\n} from \"../principalPolicy/principalPolicyOrganizationPersistence\";\n\ntype CheckpointHandle = ClientSQLiteDatabase | ClientSQLiteTransactionScope;\n\ntype AccessManifestCheckpointIdentity = Pick<\n AccessManifestCheckpoint,\n \"objectKind\" | \"organizationId\" | \"objectId\"\n>;\n\ntype PrincipalPolicyCheckpointIdentity = Pick<\n PrincipalPolicyCheckpoint,\n \"principalType\" | \"principalId\"\n>;\n\n/** One key format per checkpoint identity, shared by every batch validator. */\nexport function accessManifestObjectKey(\n identity: AccessManifestCheckpointIdentity,\n): string {\n return JSON.stringify([\n identity.objectKind,\n identity.organizationId,\n identity.objectId,\n ]);\n}\n\nexport function principalPolicyKey(\n identity: PrincipalPolicyCheckpointIdentity,\n): string {\n return JSON.stringify([identity.principalType, identity.principalId]);\n}\n\nasync function loadAccessManifestCheckpointRow(\n handle: CheckpointHandle,\n identity: AccessManifestCheckpointIdentity,\n): Promise<Pick<AccessManifestCheckpoint, \"epoch\" | \"manifestHash\"> | null> {\n const rows = await handle\n .select({\n epoch: accessManifestCheckpoints.epoch,\n manifestHash: accessManifestCheckpoints.manifestHash,\n })\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, identity.objectKind),\n eq(accessManifestCheckpoints.organizationId, identity.organizationId),\n eq(accessManifestCheckpoints.objectId, identity.objectId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\nasync function loadPrincipalPolicyCheckpointRow(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<Pick<PrincipalPolicyCheckpoint, \"version\" | \"stateHash\"> | null> {\n const rows = await handle\n .select({\n version: principalPolicyCheckpoints.version,\n stateHash: principalPolicyCheckpoints.stateHash,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, identity.principalType),\n eq(principalPolicyCheckpoints.principalId, identity.principalId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\n// An access lookup binds its kind and organization once; a policy lookup its type.\nconst ACCESS_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 2);\nconst POLICY_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\nconst ACCESS_WRITE_BATCH_SIZE = sqliteInsertBatchSize(\n accessManifestCheckpoints,\n);\nconst POLICY_WRITE_BATCH_SIZE = sqliteInsertBatchSize(\n principalPolicyCheckpoints,\n);\n\n/** Splits `values` into consecutive slices of at most `size`. */\nfunction checkpointBatches<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\n/** Distinct ids per group key, in first-seen order. */\nfunction groupIds<T>(\n items: readonly T[],\n group: (item: T) => string,\n id: (item: T) => string,\n): Map<string, { readonly first: T; readonly ids: string[] }> {\n const groups = new Map<string, { first: T; ids: string[] }>();\n for (const item of items) {\n const entry = groups.get(group(item)) ?? { first: item, ids: [] };\n if (!entry.ids.includes(id(item))) entry.ids.push(id(item));\n groups.set(group(item), entry);\n }\n return groups;\n}\n\n/**\n * Every stored access checkpoint row for `identities`, keyed by\n * `accessManifestObjectKey`: one read per object kind and organization.\n */\nexport async function loadAccessManifestCheckpointRows(\n handle: CheckpointHandle,\n identities: readonly AccessManifestCheckpointIdentity[],\n): Promise<\n Map<string, Pick<AccessManifestCheckpoint, \"epoch\" | \"manifestHash\">>\n> {\n const stored = new Map<\n string,\n Pick<AccessManifestCheckpoint, \"epoch\" | \"manifestHash\">\n >();\n const groups = groupIds(\n identities,\n (identity) =>\n JSON.stringify([identity.objectKind, identity.organizationId]),\n (identity) => identity.objectId,\n );\n for (const { first, ids } of groups.values())\n for (const batch of checkpointBatches(ids, ACCESS_LOOKUP_BATCH_SIZE)) {\n const rows = await handle\n .select({\n objectId: accessManifestCheckpoints.objectId,\n epoch: accessManifestCheckpoints.epoch,\n manifestHash: accessManifestCheckpoints.manifestHash,\n })\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, first.objectKind),\n eq(accessManifestCheckpoints.organizationId, first.organizationId),\n inArray(accessManifestCheckpoints.objectId, batch),\n ),\n );\n for (const { objectId, ...row } of rows)\n stored.set(accessManifestObjectKey({ ...first, objectId }), row);\n }\n return stored;\n}\n\n/**\n * Every stored policy checkpoint for `identities`, keyed by\n * `principalPolicyKey`: one read per principal type.\n */\nexport async function loadStoredPrincipalPolicyCheckpoints(\n handle: CheckpointHandle,\n identities: readonly PrincipalPolicyCheckpointIdentity[],\n): Promise<Map<string, PrincipalPolicyCheckpoint>> {\n const stored = new Map<string, PrincipalPolicyCheckpoint>();\n const groups = groupIds(\n identities,\n (identity) => identity.principalType,\n (identity) => identity.principalId,\n );\n for (const { first, ids } of groups.values())\n for (const batch of checkpointBatches(ids, POLICY_LOOKUP_BATCH_SIZE)) {\n const rows = await handle\n .select({\n principalId: principalPolicyCheckpoints.principalId,\n version: principalPolicyCheckpoints.version,\n stateHash: principalPolicyCheckpoints.stateHash,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, first.principalType),\n inArray(principalPolicyCheckpoints.principalId, batch),\n ),\n );\n for (const row of rows) {\n const checkpoint = {\n principalType: first.principalType,\n principalId: row.principalId,\n version: row.version,\n stateHash: row.stateHash,\n };\n stored.set(principalPolicyKey(checkpoint), checkpoint);\n }\n }\n return stored;\n}\n\n/**\n * A loaded checkpoint row merged back with the identity it was looked up by —\n * the full checkpoint shape every comparison consumes.\n */\nexport async function loadStoredAccessManifestCheckpoint(\n handle: CheckpointHandle,\n checkpoint: AccessManifestCheckpoint,\n): Promise<AccessManifestCheckpoint | null> {\n const row = await loadAccessManifestCheckpointRow(handle, checkpoint);\n return row ? { ...checkpoint, ...row } : null;\n}\n\nexport async function loadStoredPrincipalPolicyCheckpoint(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<PrincipalPolicyCheckpoint | null> {\n const row = await loadPrincipalPolicyCheckpointRow(handle, identity);\n return row\n ? {\n principalType: identity.principalType,\n principalId: identity.principalId,\n ...row,\n }\n : null;\n}\n\n/** Every principal with a durable policy checkpoint. */\nexport function listPrincipalPolicyCheckpointPrincipals(\n handle: CheckpointHandle,\n): Promise<{ id: string; type: string }[]> {\n return handle\n .selectDistinct({\n id: principalPolicyCheckpoints.principalId,\n type: principalPolicyCheckpoints.principalType,\n })\n .from(principalPolicyCheckpoints);\n}\n\nexport async function upsertAccessManifestCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: AccessManifestCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(accessManifestCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n accessManifestCheckpoints.objectKind,\n accessManifestCheckpoints.organizationId,\n accessManifestCheckpoints.objectId,\n ],\n set: row,\n })\n .run();\n}\n\nexport async function upsertPrincipalPolicyCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: PrincipalPolicyCheckpoint,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: checkpoint.principalId,\n principalType: checkpoint.principalType,\n });\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(principalPolicyCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n principalPolicyCheckpoints.principalType,\n principalPolicyCheckpoints.principalId,\n ],\n set: row,\n })\n .run();\n}\n\n/**\n * Upserts every checkpoint in multi-row statements; a repeated identity keeps\n * its last checkpoint, as sequential upserts would.\n */\nexport async function upsertAccessManifestCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoints: readonly AccessManifestCheckpoint[],\n updatedAt: string,\n): Promise<void> {\n const rows = new Map(\n checkpoints.map((checkpoint) => [\n accessManifestObjectKey(checkpoint),\n {\n objectKind: checkpoint.objectKind,\n organizationId: checkpoint.organizationId,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n manifestHash: checkpoint.manifestHash,\n updatedAt,\n },\n ]),\n );\n for (const batch of checkpointBatches(\n [...rows.values()],\n ACCESS_WRITE_BATCH_SIZE,\n ))\n await tx\n .insert(accessManifestCheckpoints)\n .values(batch)\n .onConflictDoUpdate({\n target: [\n accessManifestCheckpoints.objectKind,\n accessManifestCheckpoints.organizationId,\n accessManifestCheckpoints.objectId,\n ],\n set: {\n epoch: excludedValue(accessManifestCheckpoints.epoch),\n manifestHash: excludedValue(accessManifestCheckpoints.manifestHash),\n updatedAt: excludedValue(accessManifestCheckpoints.updatedAt),\n },\n })\n .run();\n}\n\n/**\n * Records every checkpoint's cache ownership, failing on the first conflict in\n * order as `upsertPrincipalPolicyCheckpointInTransaction` would, then upserts\n * the checkpoints in multi-row statements.\n */\nexport async function upsertPrincipalPolicyCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoints: readonly PrincipalPolicyCheckpoint[],\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyOrganizationsInTransaction(\n tx,\n checkpoints.map((checkpoint) => ({\n organizationId,\n principalId: checkpoint.principalId,\n principalType: checkpoint.principalType,\n })),\n );\n const rows = new Map(\n checkpoints.map((checkpoint) => [\n principalPolicyKey(checkpoint),\n {\n principalType: checkpoint.principalType,\n principalId: checkpoint.principalId,\n version: checkpoint.version,\n stateHash: checkpoint.stateHash,\n updatedAt,\n },\n ]),\n );\n for (const batch of checkpointBatches(\n [...rows.values()],\n POLICY_WRITE_BATCH_SIZE,\n ))\n await tx\n .insert(principalPolicyCheckpoints)\n .values(batch)\n .onConflictDoUpdate({\n target: [\n principalPolicyCheckpoints.principalType,\n principalPolicyCheckpoints.principalId,\n ],\n set: {\n version: excludedValue(principalPolicyCheckpoints.version),\n stateHash: excludedValue(principalPolicyCheckpoints.stateHash),\n updatedAt: excludedValue(principalPolicyCheckpoints.updatedAt),\n },\n })\n .run();\n}\n\n// Lazily create the checkpoint tables on first access. Every load/save below\n// calls this, so the tables exist on demand; it is intentionally module-private\n// (no caller outside this file needs it, and exporting it tripped knip).\nasync function ensureKeyingCheckpointTables(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n}\n\nexport async function loadAccessManifestCheckpoint(\n execSql: ExecSql,\n objectKind: AccessObjectKind,\n organizationId: string,\n objectId: string,\n): Promise<AccessManifestCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadAccessManifestCheckpointRow(db, {\n objectKind,\n organizationId,\n objectId,\n });\n\n return row ? { objectKind, objectId, organizationId, ...row } : null;\n}\n\nexport async function loadPrincipalPolicyCheckpoint(\n execSql: ExecSql,\n principalType: ManagedPrincipalKind,\n principalId: string,\n): Promise<PrincipalPolicyCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadPrincipalPolicyCheckpointRow(db, {\n principalType,\n principalId,\n });\n\n return row ? { principalType, principalId, ...row } : null;\n}\n/**\n * The shared shape/ownership guard every checkpoint comparison runs before\n * trusting a durable pin: the pin must belong to the compared principal and\n * carry a well-formed version and hash.\n */\nexport function assertPrincipalPolicyCheckpointShape(\n checkpoint: PrincipalPolicyCheckpoint,\n head: PrincipalPolicyCheckpointIdentity,\n): void {\n if (\n checkpoint.principalType !== head.principalType ||\n checkpoint.principalId !== head.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy checkpoint belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(checkpoint.version) ||\n checkpoint.version < 1 ||\n checkpoint.stateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy checkpoint is malformed\",\n );\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError, verifyPrincipalPolicyCheckpoint, } from "../../../internal/crypto/index.js";
2
- import { loadStoredPrincipalPolicyCheckpoint } from "./keyingCheckpointPersistence.js";
2
+ import { loadStoredPrincipalPolicyCheckpoints, principalPolicyKey, } from "./keyingCheckpointPersistence.js";
3
3
  export class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {
4
4
  constructor() {
5
5
  super("missing_dependency", "Public authorization cannot connect to the latest durable checkpoint");
@@ -7,8 +7,9 @@ export class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVeri
7
7
  }
8
8
  /** Validate public evidence or a verified private ancestry bridge without admitting pins. */
9
9
  export async function validatePrincipalAuthorizationCheckpoints(tx, policies) {
10
+ const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);
10
11
  for (const policy of policies) {
11
- const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);
12
+ const checkpoint = stored.get(principalPolicyKey(policy));
12
13
  if (!checkpoint)
13
14
  continue;
14
15
  const matchingHead = policies.filter((other) => other.principalType === policy.principalType &&
@@ -1 +1 @@
1
- {"version":3,"file":"principalAuthorizationCheckpoints.js","sourceRoot":"","sources":["principalAuthorizationCheckpoints.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAEpF,MAAM,OAAO,gDAAiD,SAAQ,uBAAuB;IAC3F;QACE,KAAK,CACH,oBAAoB,EACpB,sEAAsE,CACvE,CAAC;IACJ,CAAC;CACF;AAED,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,QAGG;IAEH,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;QACzE,IAAI,CAAC,UAAU;YAAE,SAAS;QAC1B,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAClC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,MAAM,CAAC,aAAa;YAC5C,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;YACxC,KAAK,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,CACvC,CAAC;QACF,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;QACrE,IACE,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;YACnC,CAAC,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;gBAClC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAAC,CAAC;YAEnE,MAAM,IAAI,gDAAgD,EAAE,CAAC;QAC/D,+BAA+B,CAAC;YAC9B,KAAK;YACL,YAAY,EAAE,MAAM,CAAC,KAAK;YAC1B,eAAe,EAAE,UAAU;SAC5B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadStoredPrincipalPolicyCheckpoint } from \"./keyingCheckpointPersistence\";\n\nexport class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {\n constructor() {\n super(\n \"missing_dependency\",\n \"Public authorization cannot connect to the latest durable checkpoint\",\n );\n }\n}\n\n/** Validate public evidence or a verified private ancestry bridge without admitting pins. */\nexport async function validatePrincipalAuthorizationCheckpoints(\n tx: ClientSQLiteTransactionScope,\n policies: readonly (\n | VerifiedPrincipalPolicySelection\n | VerifiedPrincipalPolicyCurrent\n )[],\n): Promise<void> {\n for (const policy of policies) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (!checkpoint) continue;\n const matchingHead = policies.filter(\n (other) =>\n other.principalType === policy.principalType &&\n other.principalId === policy.principalId &&\n other.stateHash === policy.stateHash,\n );\n const chain = matchingHead.flatMap((other) => other.retainedHistory);\n if (\n checkpoint.version > policy.version ||\n (checkpoint.version < policy.version &&\n !chain.some(({ state }) => state.version === checkpoint.version))\n )\n throw new PrincipalAuthorizationCheckpointUnavailableError();\n verifyPrincipalPolicyCheckpoint({\n chain,\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"principalAuthorizationCheckpoints.js","sourceRoot":"","sources":["principalAuthorizationCheckpoints.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,oCAAoC,EACpC,kBAAkB,GACnB,MAAM,+BAA+B,CAAC;AAEvC,MAAM,OAAO,gDAAiD,SAAQ,uBAAuB;IAC3F;QACE,KAAK,CACH,oBAAoB,EACpB,sEAAsE,CACvE,CAAC;IACJ,CAAC;CACF;AAED,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,QAGG;IAEH,MAAM,MAAM,GAAG,MAAM,oCAAoC,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;IACxE,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1D,IAAI,CAAC,UAAU;YAAE,SAAS;QAC1B,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAClC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,MAAM,CAAC,aAAa;YAC5C,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;YACxC,KAAK,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,CACvC,CAAC;QACF,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;QACrE,IACE,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;YACnC,CAAC,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;gBAClC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAAC,CAAC;YAEnE,MAAM,IAAI,gDAAgD,EAAE,CAAC;QAC/D,+BAA+B,CAAC;YAC9B,KAAK;YACL,YAAY,EAAE,MAAM,CAAC,KAAK;YAC1B,eAAe,EAAE,UAAU;SAC5B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n} from \"./keyingCheckpointPersistence\";\n\nexport class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {\n constructor() {\n super(\n \"missing_dependency\",\n \"Public authorization cannot connect to the latest durable checkpoint\",\n );\n }\n}\n\n/** Validate public evidence or a verified private ancestry bridge without admitting pins. */\nexport async function validatePrincipalAuthorizationCheckpoints(\n tx: ClientSQLiteTransactionScope,\n policies: readonly (\n | VerifiedPrincipalPolicySelection\n | VerifiedPrincipalPolicyCurrent\n )[],\n): Promise<void> {\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);\n for (const policy of policies) {\n const checkpoint = stored.get(principalPolicyKey(policy));\n if (!checkpoint) continue;\n const matchingHead = policies.filter(\n (other) =>\n other.principalType === policy.principalType &&\n other.principalId === policy.principalId &&\n other.stateHash === policy.stateHash,\n );\n const chain = matchingHead.flatMap((other) => other.retainedHistory);\n if (\n checkpoint.version > policy.version ||\n (checkpoint.version < policy.version &&\n !chain.some(({ state }) => state.version === checkpoint.version))\n )\n throw new PrincipalAuthorizationCheckpointUnavailableError();\n verifyPrincipalPolicyCheckpoint({\n chain,\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n }\n}\n"]}
@@ -2,6 +2,7 @@ import { type PrincipalHistoryIndexNode, type PrincipalPolicyHistoryReferencePro
2
2
  import { type PrincipalPolicyStateChainEntryResponse } from "../../../internal/validators/response/index.js";
3
3
  import { type ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
4
4
  import { type ExecSql } from "../../sqlite/sqlSchema.js";
5
+ import type { PrincipalHistoryRootEdges } from "./principalHistoryRootOwnership.js";
5
6
  export interface PrincipalHistoryEvidencePage {
6
7
  readonly indexRootHash: string;
7
8
  readonly scopeId: string;
@@ -21,7 +22,19 @@ export declare function preparePrincipalHistoryEvidencePage(input: {
21
22
  readonly nodes: readonly PrincipalHistoryIndexNode[];
22
23
  }): Promise<PrincipalHistoryEvidencePage>;
23
24
  /** Publish in the same guarded transaction as the accepted page's progress. */
24
- export declare function writePrincipalHistoryEvidencePage(tx: ClientSQLiteTransactionScope, page: PrincipalHistoryEvidencePage): Promise<void>;
25
+ export declare function writePrincipalHistoryEvidencePage(tx: ClientSQLiteTransactionScope, page: PrincipalHistoryEvidencePage, rootEdges?: PrincipalHistoryRootEdges | undefined): Promise<void>;
26
+ /**
27
+ * Returns untrusted material, in `versions` order. The caller must verify it
28
+ * against the issued root. Index nodes are read one level at a time for every
29
+ * version and entries in one set read; the first version that fails, in
30
+ * order, throws the error loading it alone would.
31
+ */
32
+ export declare function loadPrincipalHistoryReferences(input: {
33
+ readonly execSql: ExecSql;
34
+ readonly scopeId: string;
35
+ readonly history: VerifiedPrincipalPolicyHistory;
36
+ readonly versions: readonly number[];
37
+ }): Promise<PrincipalPolicyHistoryReferenceProof[]>;
25
38
  /** Returns untrusted material. The caller must verify it against the issued root. */
26
39
  export declare function loadPrincipalHistoryReference(input: {
27
40
  readonly execSql: ExecSql;