@tearleads/client-sdk 0.1.196 → 0.1.198
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.
- package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +13 -5
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +30 -44
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryEvidencePersistence.d.ts +3 -13
- package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js +2 -18
- package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryPrefixPersistence.d.ts +119 -15
- package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js +69 -99
- package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryRepository.js +134 -0
- package/data/persistence/principalHistory/principalHistoryRepository.js.map +1 -0
- package/data/persistence/principalHistory/principalHistoryStagePersistence.d.ts +119 -8
- package/data/persistence/principalHistory/principalHistoryStagePersistence.js +49 -80
- package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryStageRetention.js +2 -2
- package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -1
- package/internal/loro/changeTimestamps.d.ts +26 -0
- package/internal/loro/changeTimestamps.js +29 -0
- package/internal/loro/changeTimestamps.js.map +1 -0
- package/internal/loro/document.js +2 -0
- package/internal/loro/document.js.map +1 -1
- package/internal/loro/index.d.ts +1 -0
- package/internal/loro/index.js +1 -0
- package/internal/loro/index.js.map +1 -1
- package/package.json +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +3 -3
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +2 -2
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
- package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +7 -6
- package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +4 -6
- package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +2 -3
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +3 -3
- package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +4 -5
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -3
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +9 -14
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +3 -5
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +2 -3
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type PrincipalPolicyCheckpoint, type VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
|
|
2
|
-
import {
|
|
2
|
+
import type { ClientSQLiteTransactionScope } from "../sqlite/sqlitePersistenceRuntime.js";
|
|
3
3
|
import { type PrincipalHistoryEvidencePage } from "./principalHistory/principalHistoryEvidencePersistence.js";
|
|
4
4
|
import type { PrincipalHistoryPrefix } from "./principalHistory/principalHistoryPrefixPersistence.js";
|
|
5
5
|
import type { PrincipalHistoryStage } from "./principalHistory/principalHistoryStagePersistence.js";
|
|
@@ -29,11 +29,19 @@ export interface AcknowledgedPrincipalCurrentRetirement {
|
|
|
29
29
|
readonly principalType: VerifiedPrincipalPolicyCurrent["principalType"];
|
|
30
30
|
readonly containerIds: readonly string[];
|
|
31
31
|
}
|
|
32
|
-
|
|
33
|
-
export
|
|
34
|
-
readonly execSql: ExecSql;
|
|
32
|
+
export declare function assertPublicationScope(entries: readonly AcknowledgedPrincipalCurrentPublication[], organizationId: string): void;
|
|
33
|
+
export interface AcknowledgedPrincipalCurrents {
|
|
35
34
|
readonly organizationId: string;
|
|
36
35
|
readonly entries: readonly ReconciledPrincipalCurrentPublication[];
|
|
37
36
|
readonly retirements?: readonly AcknowledgedPrincipalCurrentRetirement[] | undefined;
|
|
38
37
|
readonly stillCurrent: () => boolean;
|
|
39
|
-
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Validates owned, scope-checked publications against their observed pins and
|
|
41
|
+
* stores them. `now` is read where each row's timestamp is written.
|
|
42
|
+
*/
|
|
43
|
+
export declare function persistAcknowledgedPrincipalCurrentsInTransaction(tx: ClientSQLiteTransactionScope, input: {
|
|
44
|
+
readonly organizationId: string;
|
|
45
|
+
readonly entries: readonly ReconciledPrincipalCurrentPublication[];
|
|
46
|
+
readonly retirements: readonly AcknowledgedPrincipalCurrentRetirement[];
|
|
47
|
+
}, now: () => Date): Promise<void>;
|
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError, verifyPrincipalPolicyCheckpoint, } from "../../internal/crypto/index.js";
|
|
2
2
|
import { eq } from "drizzle-orm";
|
|
3
|
-
import { assertProjectionVerificationCurrent } from "../keyingProjectionVerification/types.js";
|
|
4
|
-
import { keyingCheckpointTables } from "../sqlite/schema/keyingCheckpointSchema.js";
|
|
5
3
|
import { principalHistoryPrefixes } from "../sqlite/schema/principalHistoryEvidenceSchema.js";
|
|
6
4
|
import { principalHistoryStages } from "../sqlite/schema/principalHistoryStageSchema.js";
|
|
7
|
-
import { principalPolicyTables } from "../sqlite/schema/principalPolicySchema.js";
|
|
8
|
-
import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
|
|
9
|
-
import { ensureSqlTables } from "../sqlite/sqlSchema.js";
|
|
10
5
|
import { loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpoints/keyingCheckpointPersistence.js";
|
|
11
6
|
import { writePrincipalHistoryEvidencePage, } from "./principalHistory/principalHistoryEvidencePersistence.js";
|
|
12
7
|
import { reclaimPrincipalHistoryNodes } from "./principalHistory/principalHistoryNodeRetention.js";
|
|
@@ -21,7 +16,7 @@ export class PrincipalAcknowledgementChangedError extends Error {
|
|
|
21
16
|
this.name = "PrincipalAcknowledgementChangedError";
|
|
22
17
|
}
|
|
23
18
|
}
|
|
24
|
-
function assertPublicationScope(entries, organizationId) {
|
|
19
|
+
export function assertPublicationScope(entries, organizationId) {
|
|
25
20
|
const seen = new Set();
|
|
26
21
|
for (const entry of entries) {
|
|
27
22
|
const key = principalPolicyKey(entry.policy);
|
|
@@ -70,14 +65,11 @@ async function validatePublication(tx, entry) {
|
|
|
70
65
|
if ((prefix?.progress ?? null) !== entry.observedPrefixProgress)
|
|
71
66
|
throw new PrincipalAcknowledgementChangedError();
|
|
72
67
|
}
|
|
73
|
-
async function archiveAcknowledgedStageKeys(tx, entry) {
|
|
68
|
+
async function archiveAcknowledgedStageKeys(tx, entry, now) {
|
|
74
69
|
for (const stage of [entry.predecessorStage, entry.stage]) {
|
|
75
70
|
if (!stage)
|
|
76
71
|
continue;
|
|
77
|
-
await touchPrincipalHistoryStage(tx, {
|
|
78
|
-
id: stage.id,
|
|
79
|
-
scopeId: entry.prefix.scopeId,
|
|
80
|
-
});
|
|
72
|
+
await touchPrincipalHistoryStage(tx, { id: stage.id, scopeId: entry.prefix.scopeId }, now().getTime());
|
|
81
73
|
await archivePrincipalHistoryKeyEnvelopes(tx, {
|
|
82
74
|
...stage,
|
|
83
75
|
version: stage.afterVersion + 1,
|
|
@@ -92,7 +84,7 @@ async function loadStageRootOwner(tx, id) {
|
|
|
92
84
|
.limit(1);
|
|
93
85
|
return owner;
|
|
94
86
|
}
|
|
95
|
-
async function retainPredecessorStage(tx, entry) {
|
|
87
|
+
async function retainPredecessorStage(tx, entry, now) {
|
|
96
88
|
// Preserve a prefix-only predecessor without replacing an existing completion.
|
|
97
89
|
if (!entry.predecessorStage || !entry.predecessorIndexRootHash)
|
|
98
90
|
return;
|
|
@@ -102,7 +94,11 @@ async function retainPredecessorStage(tx, entry) {
|
|
|
102
94
|
rootHash: entry.predecessorIndexRootHash,
|
|
103
95
|
};
|
|
104
96
|
const previous = await loadStageRootOwner(tx, entry.predecessorStage.id);
|
|
105
|
-
const row = {
|
|
97
|
+
const row = {
|
|
98
|
+
...entry.predecessorStage,
|
|
99
|
+
...root,
|
|
100
|
+
touchedAt: now().getTime(),
|
|
101
|
+
};
|
|
106
102
|
const written = await tx
|
|
107
103
|
.insert(principalHistoryStages)
|
|
108
104
|
.values(row)
|
|
@@ -118,14 +114,14 @@ async function retainPredecessorStage(tx, entry) {
|
|
|
118
114
|
}
|
|
119
115
|
// A fully authenticated publication supersedes an in-flight stage for this
|
|
120
116
|
// exact head. Its other writer fails its progress CAS and resumes.
|
|
121
|
-
async function saveAcknowledgedStage(tx, entry) {
|
|
117
|
+
async function saveAcknowledgedStage(tx, entry, now) {
|
|
122
118
|
const root = {
|
|
123
119
|
scopeId: entry.prefix.scopeId,
|
|
124
120
|
organizationId: entry.stage.organizationId,
|
|
125
121
|
rootHash: entry.evidence.indexRootHash,
|
|
126
122
|
};
|
|
127
123
|
const previous = await loadStageRootOwner(tx, entry.stage.id);
|
|
128
|
-
const row = { ...entry.stage, ...root, touchedAt:
|
|
124
|
+
const row = { ...entry.stage, ...root, touchedAt: now().getTime() };
|
|
129
125
|
await tx
|
|
130
126
|
.insert(principalHistoryStages)
|
|
131
127
|
.values(row)
|
|
@@ -159,42 +155,32 @@ async function storeRetirement(tx, entries, retirement, organizationId) {
|
|
|
159
155
|
throw new KeyingVerificationError("object_mismatch", "Retirement must accompany its acknowledged principal");
|
|
160
156
|
await storePrincipalGrantRetirements(tx, { ...retirement, policy, organizationId }, entries.map((entry) => entry.policy), organizationId);
|
|
161
157
|
}
|
|
162
|
-
async function storeAcknowledgedPublication(tx, entry, organizationId) {
|
|
158
|
+
async function storeAcknowledgedPublication(tx, entry, organizationId, now) {
|
|
163
159
|
await writePrincipalHistoryEvidencePage(tx, entry.evidence);
|
|
164
|
-
await retainPredecessorStage(tx, entry);
|
|
165
|
-
await saveAcknowledgedStage(tx, entry);
|
|
166
|
-
await archiveAcknowledgedStageKeys(tx, entry);
|
|
160
|
+
await retainPredecessorStage(tx, entry, now);
|
|
161
|
+
await saveAcknowledgedStage(tx, entry, now);
|
|
162
|
+
await archiveAcknowledgedStageKeys(tx, entry, now);
|
|
167
163
|
if (!entry.preservePrefix)
|
|
168
164
|
await saveAcknowledgedPrefix(tx, entry);
|
|
169
165
|
await reclaimCompletedPrincipalHistoryStages(tx, entry.retainedPrefix);
|
|
170
166
|
await reclaimPrincipalHistoryNodes(tx, entry.retainedPrefix);
|
|
171
167
|
if (!entry.observedCheckpoint ||
|
|
172
168
|
entry.observedCheckpoint.version < entry.policy.version)
|
|
173
|
-
await upsertPrincipalPolicyCheckpointInTransaction(tx, entry.policy.checkpoint,
|
|
169
|
+
await upsertPrincipalPolicyCheckpointInTransaction(tx, entry.policy.checkpoint, now().toISOString(), organizationId);
|
|
174
170
|
}
|
|
175
|
-
/**
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
for (const entry of entries)
|
|
190
|
-
await validatePublication(tx, entry);
|
|
191
|
-
for (const retirement of retirements) {
|
|
192
|
-
await storeRetirement(tx, entries, retirement, organizationId);
|
|
193
|
-
}
|
|
194
|
-
for (const entry of entries) {
|
|
195
|
-
await storeAcknowledgedPublication(tx, entry, organizationId);
|
|
196
|
-
}
|
|
197
|
-
}, stillCurrent, { behavior: "immediate" });
|
|
198
|
-
assertProjectionVerificationCurrent(() => stored.committed);
|
|
171
|
+
/**
|
|
172
|
+
* Validates owned, scope-checked publications against their observed pins and
|
|
173
|
+
* stores them. `now` is read where each row's timestamp is written.
|
|
174
|
+
*/
|
|
175
|
+
export async function persistAcknowledgedPrincipalCurrentsInTransaction(tx, input, now) {
|
|
176
|
+
const { entries, organizationId } = input;
|
|
177
|
+
for (const entry of entries)
|
|
178
|
+
await validatePublication(tx, entry);
|
|
179
|
+
for (const retirement of input.retirements) {
|
|
180
|
+
await storeRetirement(tx, entries, retirement, organizationId);
|
|
181
|
+
}
|
|
182
|
+
for (const entry of entries) {
|
|
183
|
+
await storeAcknowledgedPublication(tx, entry, organizationId, now);
|
|
184
|
+
}
|
|
199
185
|
}
|
|
200
186
|
//# sourceMappingURL=principalCurrentAcknowledgementPersistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalCurrentAcknowledgementPersistence.js","sourceRoot":"","sources":["principalCurrentAcknowledgementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,mCAAmC,EAAE,MAAM,u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W,GAAG,eAAe,CAAC,KAAK,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC5C,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IACxC,sBAAsB,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IAChD,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,MAAM,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE;QACnC,GAAG,qBAAqB;QACxB,GAAG,sBAAsB;KAC1B,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC7C,KAAK,EAAE,EAAE,EAAE,EAAE;QACX,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,MAAM,mBAAmB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QAClE,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;YACrC,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC;QACjE,CAAC;QACD,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC5B,MAAM,4BAA4B,CAAC,EAAE,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC;QAChE,CAAC;IACH,CAAC,EACD,YAAY,EACZ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport { keyingCheckpointTables } from \"../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryPrefixes } from \"../sqlite/schema/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/schema/principalHistoryStageSchema\";\nimport { principalPolicyTables } from \"../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistory/principalHistoryEvidencePersistence\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistory/principalHistoryNodeRetention\";\nimport type { PrincipalHistoryPrefix } from \"./principalHistory/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryPrefixRootOwnerColumns,\n principalHistoryRootRetention,\n principalHistoryStageRootOwnerColumns,\n writePrincipalHistoryRootEdges,\n} from \"./principalHistory/principalHistoryRootOwnership\";\nimport type { PrincipalHistoryStage } from \"./principalHistory/principalHistoryStagePersistence\";\nimport {\n reclaimCompletedPrincipalHistoryStages,\n touchPrincipalHistoryStage,\n} from \"./principalHistory/principalHistoryStageRetention\";\nimport { storePrincipalGrantRetirements } from \"./principalKeys/principalGrantRetirementPersistence\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeys/principalKeyEnvelopeArchivePersistence\";\n\n/** Owned output of authenticated prefix extension and exact receipt verification. */\nexport interface AcknowledgedPrincipalCurrentPublication {\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly prefix: PrincipalHistoryPrefix;\n readonly previousPrefixProgress: string | null;\n readonly stage: PrincipalHistoryStage;\n readonly predecessorStage: PrincipalHistoryStage | null;\n readonly predecessorIndexRootHash: string | null;\n readonly evidence: PrincipalHistoryEvidencePage;\n}\n\nexport interface ReconciledPrincipalCurrentPublication\n extends AcknowledgedPrincipalCurrentPublication {\n readonly preservePrefix: boolean;\n readonly observedPrefixProgress: string | null;\n readonly observedCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly retainedPrefix: PrincipalHistoryPrefix;\n readonly checkpointPolicy: VerifiedPrincipalPolicyCurrent;\n}\n\n/** A local writer won the CAS; retry the same authenticated receipt without HTTP. */\nexport class PrincipalAcknowledgementChangedError extends Error {\n constructor() {\n super(\n \"Authenticated principal progress changed during acknowledgement; retry retention\",\n );\n this.name = \"PrincipalAcknowledgementChangedError\";\n }\n}\n\nexport interface AcknowledgedPrincipalCurrentRetirement {\n readonly principalId: string;\n readonly principalType: VerifiedPrincipalPolicyCurrent[\"principalType\"];\n readonly containerIds: readonly string[];\n}\n\nfunction assertPublicationScope(\n entries: readonly AcknowledgedPrincipalCurrentPublication[],\n organizationId: string,\n) {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key))\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Acknowledged current batch repeats a principal\",\n );\n seen.add(key);\n if (\n entry.prefix.organizationId !== organizationId ||\n (entry.predecessorStage === null) !==\n (entry.predecessorIndexRootHash === null) ||\n entry.stage.organizationId !== organizationId ||\n (entry.predecessorStage\n ? entry.predecessorStage.organizationId !== organizationId ||\n !entry.predecessorStage.complete ||\n entry.predecessorStage.afterVersion !== entry.policy.version - 2\n : entry.policy.principalType !== \"group\" ||\n entry.policy.version !== 1 ||\n entry.policy.state.prevStateHash !== null ||\n entry.previousPrefixProgress !== null) ||\n entry.evidence.organizationId !== organizationId ||\n entry.prefix.scopeId !== entry.evidence.scopeId ||\n entry.prefix.version !== entry.policy.version ||\n entry.stage.afterVersion !== entry.policy.version - 1 ||\n !entry.stage.complete ||\n entry.stage.currentJson !== entry.prefix.currentJson\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged current publication is outside its scope\",\n );\n }\n}\n\nasync function validatePublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(\n tx,\n entry.policy,\n );\n if (\n checkpoint?.version !== entry.observedCheckpoint?.version ||\n checkpoint?.stateHash !== entry.observedCheckpoint?.stateHash\n )\n throw new PrincipalAcknowledgementChangedError();\n verifyPrincipalPolicyCheckpoint({\n chain: entry.checkpointPolicy.retainedHistory,\n currentState: entry.checkpointPolicy.state,\n localCheckpoint: checkpoint,\n });\n if (\n (!checkpoint && entry.policy.version !== 1) ||\n (checkpoint && entry.policy.version > checkpoint.version + 1)\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledged current policy must directly extend its durable checkpoint\",\n );\n const [prefix] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))\n .limit(1);\n if ((prefix?.progress ?? null) !== entry.observedPrefixProgress)\n throw new PrincipalAcknowledgementChangedError();\n}\n\nasync function archiveAcknowledgedStageKeys(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n for (const stage of [entry.predecessorStage, entry.stage]) {\n if (!stage) continue;\n await touchPrincipalHistoryStage(tx, {\n id: stage.id,\n scopeId: entry.prefix.scopeId,\n });\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n }\n}\n\nasync function loadStageRootOwner(\n tx: ClientSQLiteTransactionScope,\n id: string,\n) {\n const [owner] = await tx\n .select(principalHistoryStageRootOwnerColumns)\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, id))\n .limit(1);\n return owner;\n}\n\nasync function retainPredecessorStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n // Preserve a prefix-only predecessor without replacing an existing completion.\n if (!entry.predecessorStage || !entry.predecessorIndexRootHash) return;\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.predecessorIndexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.predecessorStage.id);\n const row = { ...entry.predecessorStage, ...root, touchedAt: Date.now() };\n const written = await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: row,\n setWhere: eq(principalHistoryStages.complete, false),\n })\n .returning({ id: principalHistoryStages.id });\n // An existing completion keeps its row, so it also keeps its root.\n if (written.length > 0)\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\n// A fully authenticated publication supersedes an in-flight stage for this\n// exact head. Its other writer fails its progress CAS and resumes.\nasync function saveAcknowledgedStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.stage.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.stage.id);\n const row = { ...entry.stage, ...root, touchedAt: Date.now() };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function saveAcknowledgedPrefix(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const [previous] = await tx\n .select(principalHistoryPrefixRootOwnerColumns)\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, root.scopeId))\n .limit(1);\n const row = { ...entry.prefix, rootHash: root.rootHash };\n await tx\n .insert(principalHistoryPrefixes)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryPrefixes.scopeId, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function storeRetirement(\n tx: ClientSQLiteTransactionScope,\n entries: readonly ReconciledPrincipalCurrentPublication[],\n retirement: AcknowledgedPrincipalCurrentRetirement,\n organizationId: string,\n) {\n const policy = entries.find(\n (entry) =>\n entry.policy.principalId === retirement.principalId &&\n entry.policy.principalType === retirement.principalType,\n )?.policy;\n if (!policy)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged principal\",\n );\n await storePrincipalGrantRetirements(\n tx,\n { ...retirement, policy, organizationId },\n entries.map((entry) => entry.policy),\n organizationId,\n );\n}\n\nasync function storeAcknowledgedPublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n organizationId: string,\n) {\n await writePrincipalHistoryEvidencePage(tx, entry.evidence);\n await retainPredecessorStage(tx, entry);\n await saveAcknowledgedStage(tx, entry);\n await archiveAcknowledgedStageKeys(tx, entry);\n if (!entry.preservePrefix) await saveAcknowledgedPrefix(tx, entry);\n await reclaimCompletedPrincipalHistoryStages(tx, entry.retainedPrefix);\n await reclaimPrincipalHistoryNodes(tx, entry.retainedPrefix);\n if (\n !entry.observedCheckpoint ||\n entry.observedCheckpoint.version < entry.policy.version\n )\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n entry.policy.checkpoint,\n new Date().toISOString(),\n organizationId,\n );\n}\n\n/** Store current artifacts and resumable progress in the same transaction as their pins. */\nexport async function persistAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly ReconciledPrincipalCurrentPublication[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const entries = structuredClone(input.entries);\n const retirements = structuredClone(input.retirements ?? []);\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n assertPublicationScope(entries, organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const stored = await runtime.guardedTransaction(\n async (tx) => {\n for (const entry of entries) await validatePublication(tx, entry);\n for (const retirement of retirements) {\n await storeRetirement(tx, entries, retirement, organizationId);\n }\n for (const entry of entries) {\n await storeAcknowledgedPublication(tx, entry, organizationId);\n }\n },\n stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => stored.committed);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalCurrentAcknowledgementPersistence.js","sourceRoot":"","sources":["principalCurrentAcknowledgementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,iDAAiD,CAAC;AAC3F,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AAEtF,OAAO,EACL,mCAAmC,EACnC,kBAAkB,EAClB,4CAA4C,GAC7C,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAEhG,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAE1D,OAAO,EACL,sCAAsC,EACtC,0BAA0B,GAC3B,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,8BAA8B,EAAE,MAAM,qDAAqD,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,wDAAwD,CAAC;AAsB7G,qFAAqF;AACrF,MAAM,OAAO,oCAAqC,SAAQ,KAAK;I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AAE,KAAK,CAAC,cAAc,CAAC,CAAC;IACvE,MAAM,4BAA4B,CAAC,EAAE,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;IAC7D,IACE,CAAC,KAAK,CAAC,kBAAkB;QACzB,KAAK,CAAC,kBAAkB,CAAC,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO;QAEvD,MAAM,4CAA4C,CAChD,EAAE,EACF,KAAK,CAAC,MAAM,CAAC,UAAU,EACvB,GAAG,EAAE,CAAC,WAAW,EAAE,EACnB,cAAc,CACf,CAAC;AACN,CAAC;AAWD;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,iDAAiD,CACrE,EAAgC,EAChC,KAIC,EACD,GAAe;IAEf,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IAC1C,KAAK,MAAM,KAAK,IAAI,OAAO;QAAE,MAAM,mBAAmB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAClE,KAAK,MAAM,UAAU,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QAC3C,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC;IACjE,CAAC;IACD,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,4BAA4B,CAAC,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,CAAC,CAAC;IACrE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { principalHistoryPrefixes } from \"../sqlite/schema/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/schema/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport {\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistory/principalHistoryEvidencePersistence\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistory/principalHistoryNodeRetention\";\nimport type { PrincipalHistoryPrefix } from \"./principalHistory/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryPrefixRootOwnerColumns,\n principalHistoryRootRetention,\n principalHistoryStageRootOwnerColumns,\n writePrincipalHistoryRootEdges,\n} from \"./principalHistory/principalHistoryRootOwnership\";\nimport type { PrincipalHistoryStage } from \"./principalHistory/principalHistoryStagePersistence\";\nimport {\n reclaimCompletedPrincipalHistoryStages,\n touchPrincipalHistoryStage,\n} from \"./principalHistory/principalHistoryStageRetention\";\nimport { storePrincipalGrantRetirements } from \"./principalKeys/principalGrantRetirementPersistence\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeys/principalKeyEnvelopeArchivePersistence\";\n\n/** Owned output of authenticated prefix extension and exact receipt verification. */\nexport interface AcknowledgedPrincipalCurrentPublication {\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly prefix: PrincipalHistoryPrefix;\n readonly previousPrefixProgress: string | null;\n readonly stage: PrincipalHistoryStage;\n readonly predecessorStage: PrincipalHistoryStage | null;\n readonly predecessorIndexRootHash: string | null;\n readonly evidence: PrincipalHistoryEvidencePage;\n}\n\nexport interface ReconciledPrincipalCurrentPublication\n extends AcknowledgedPrincipalCurrentPublication {\n readonly preservePrefix: boolean;\n readonly observedPrefixProgress: string | null;\n readonly observedCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly retainedPrefix: PrincipalHistoryPrefix;\n readonly checkpointPolicy: VerifiedPrincipalPolicyCurrent;\n}\n\n/** A local writer won the CAS; retry the same authenticated receipt without HTTP. */\nexport class PrincipalAcknowledgementChangedError extends Error {\n constructor() {\n super(\n \"Authenticated principal progress changed during acknowledgement; retry retention\",\n );\n this.name = \"PrincipalAcknowledgementChangedError\";\n }\n}\n\nexport interface AcknowledgedPrincipalCurrentRetirement {\n readonly principalId: string;\n readonly principalType: VerifiedPrincipalPolicyCurrent[\"principalType\"];\n readonly containerIds: readonly string[];\n}\n\nexport function assertPublicationScope(\n entries: readonly AcknowledgedPrincipalCurrentPublication[],\n organizationId: string,\n) {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key))\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Acknowledged current batch repeats a principal\",\n );\n seen.add(key);\n if (\n entry.prefix.organizationId !== organizationId ||\n (entry.predecessorStage === null) !==\n (entry.predecessorIndexRootHash === null) ||\n entry.stage.organizationId !== organizationId ||\n (entry.predecessorStage\n ? entry.predecessorStage.organizationId !== organizationId ||\n !entry.predecessorStage.complete ||\n entry.predecessorStage.afterVersion !== entry.policy.version - 2\n : entry.policy.principalType !== \"group\" ||\n entry.policy.version !== 1 ||\n entry.policy.state.prevStateHash !== null ||\n entry.previousPrefixProgress !== null) ||\n entry.evidence.organizationId !== organizationId ||\n entry.prefix.scopeId !== entry.evidence.scopeId ||\n entry.prefix.version !== entry.policy.version ||\n entry.stage.afterVersion !== entry.policy.version - 1 ||\n !entry.stage.complete ||\n entry.stage.currentJson !== entry.prefix.currentJson\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged current publication is outside its scope\",\n );\n }\n}\n\nasync function validatePublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(\n tx,\n entry.policy,\n );\n if (\n checkpoint?.version !== entry.observedCheckpoint?.version ||\n checkpoint?.stateHash !== entry.observedCheckpoint?.stateHash\n )\n throw new PrincipalAcknowledgementChangedError();\n verifyPrincipalPolicyCheckpoint({\n chain: entry.checkpointPolicy.retainedHistory,\n currentState: entry.checkpointPolicy.state,\n localCheckpoint: checkpoint,\n });\n if (\n (!checkpoint && entry.policy.version !== 1) ||\n (checkpoint && entry.policy.version > checkpoint.version + 1)\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledged current policy must directly extend its durable checkpoint\",\n );\n const [prefix] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))\n .limit(1);\n if ((prefix?.progress ?? null) !== entry.observedPrefixProgress)\n throw new PrincipalAcknowledgementChangedError();\n}\n\nasync function archiveAcknowledgedStageKeys(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n for (const stage of [entry.predecessorStage, entry.stage]) {\n if (!stage) continue;\n await touchPrincipalHistoryStage(\n tx,\n { id: stage.id, scopeId: entry.prefix.scopeId },\n now().getTime(),\n );\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n }\n}\n\nasync function loadStageRootOwner(\n tx: ClientSQLiteTransactionScope,\n id: string,\n) {\n const [owner] = await tx\n .select(principalHistoryStageRootOwnerColumns)\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, id))\n .limit(1);\n return owner;\n}\n\nasync function retainPredecessorStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n // Preserve a prefix-only predecessor without replacing an existing completion.\n if (!entry.predecessorStage || !entry.predecessorIndexRootHash) return;\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.predecessorIndexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.predecessorStage.id);\n const row = {\n ...entry.predecessorStage,\n ...root,\n touchedAt: now().getTime(),\n };\n const written = await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: row,\n setWhere: eq(principalHistoryStages.complete, false),\n })\n .returning({ id: principalHistoryStages.id });\n // An existing completion keeps its row, so it also keeps its root.\n if (written.length > 0)\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\n// A fully authenticated publication supersedes an in-flight stage for this\n// exact head. Its other writer fails its progress CAS and resumes.\nasync function saveAcknowledgedStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.stage.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.stage.id);\n const row = { ...entry.stage, ...root, touchedAt: now().getTime() };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function saveAcknowledgedPrefix(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const [previous] = await tx\n .select(principalHistoryPrefixRootOwnerColumns)\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, root.scopeId))\n .limit(1);\n const row = { ...entry.prefix, rootHash: root.rootHash };\n await tx\n .insert(principalHistoryPrefixes)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryPrefixes.scopeId, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function storeRetirement(\n tx: ClientSQLiteTransactionScope,\n entries: readonly ReconciledPrincipalCurrentPublication[],\n retirement: AcknowledgedPrincipalCurrentRetirement,\n organizationId: string,\n) {\n const policy = entries.find(\n (entry) =>\n entry.policy.principalId === retirement.principalId &&\n entry.policy.principalType === retirement.principalType,\n )?.policy;\n if (!policy)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged principal\",\n );\n await storePrincipalGrantRetirements(\n tx,\n { ...retirement, policy, organizationId },\n entries.map((entry) => entry.policy),\n organizationId,\n );\n}\n\nasync function storeAcknowledgedPublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n organizationId: string,\n now: () => Date,\n) {\n await writePrincipalHistoryEvidencePage(tx, entry.evidence);\n await retainPredecessorStage(tx, entry, now);\n await saveAcknowledgedStage(tx, entry, now);\n await archiveAcknowledgedStageKeys(tx, entry, now);\n if (!entry.preservePrefix) await saveAcknowledgedPrefix(tx, entry);\n await reclaimCompletedPrincipalHistoryStages(tx, entry.retainedPrefix);\n await reclaimPrincipalHistoryNodes(tx, entry.retainedPrefix);\n if (\n !entry.observedCheckpoint ||\n entry.observedCheckpoint.version < entry.policy.version\n )\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n entry.policy.checkpoint,\n now().toISOString(),\n organizationId,\n );\n}\n\nexport interface AcknowledgedPrincipalCurrents {\n readonly organizationId: string;\n readonly entries: readonly ReconciledPrincipalCurrentPublication[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * Validates owned, scope-checked publications against their observed pins and\n * stores them. `now` is read where each row's timestamp is written.\n */\nexport async function persistAcknowledgedPrincipalCurrentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly organizationId: string;\n readonly entries: readonly ReconciledPrincipalCurrentPublication[];\n readonly retirements: readonly AcknowledgedPrincipalCurrentRetirement[];\n },\n now: () => Date,\n): Promise<void> {\n const { entries, organizationId } = input;\n for (const entry of entries) await validatePublication(tx, entry);\n for (const retirement of input.retirements) {\n await storeRetirement(tx, entries, retirement, organizationId);\n }\n for (const entry of entries) {\n await storeAcknowledgedPublication(tx, entry, organizationId, now);\n }\n}\n"]}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { type PrincipalHistoryIndexNode, type PrincipalPolicyHistoryReferenceProof, type
|
|
1
|
+
import { type PrincipalHistoryIndexNode, type PrincipalPolicyHistoryReferenceProof, type VerifiedPrincipalPolicyHistory } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { type PrincipalPolicyStateChainEntryResponse } from "../../../internal/validators/response/index.js";
|
|
3
|
-
import {
|
|
4
|
-
import { type ExecSql } from "../../sqlite/sqlSchema.js";
|
|
3
|
+
import type { ClientSQLiteDatabase, ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
5
4
|
import type { PrincipalHistoryRootEdges } from "./principalHistoryRootOwnership.js";
|
|
6
5
|
export interface PrincipalHistoryEvidencePage {
|
|
7
6
|
readonly indexRootHash: string;
|
|
@@ -29,17 +28,8 @@ export declare function writePrincipalHistoryEvidencePage(tx: ClientSQLiteTransa
|
|
|
29
28
|
* version and entries in one set read; the first version that fails, in
|
|
30
29
|
* order, throws the error loading it alone would.
|
|
31
30
|
*/
|
|
32
|
-
export declare function
|
|
33
|
-
readonly execSql: ExecSql;
|
|
31
|
+
export declare function readPrincipalHistoryReferences(db: ClientSQLiteDatabase, input: {
|
|
34
32
|
readonly scopeId: string;
|
|
35
33
|
readonly history: VerifiedPrincipalPolicyHistory;
|
|
36
34
|
readonly versions: readonly number[];
|
|
37
35
|
}): Promise<PrincipalPolicyHistoryReferenceProof[]>;
|
|
38
|
-
/** Returns untrusted material. The caller must verify it against the issued root. */
|
|
39
|
-
export declare function loadPrincipalHistoryReference(input: {
|
|
40
|
-
readonly execSql: ExecSql;
|
|
41
|
-
readonly scopeId: string;
|
|
42
|
-
readonly history: VerifiedPrincipalPolicyHistory;
|
|
43
|
-
readonly version: number;
|
|
44
|
-
readonly expectedReference?: ReferencedPrincipalHead | undefined;
|
|
45
|
-
}): Promise<PrincipalPolicyHistoryReferenceProof>;
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { compareCanonicalStrings, KeyingVerificationError, PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT, principalHistoryIndexLeaf, resolvePrincipalHistoryIndexProof, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { isPrincipalPolicyStateChainEntryResponse, } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import { and, eq, inArray, isNotNull } from "drizzle-orm";
|
|
4
|
-
import { principalHistoryEntries,
|
|
4
|
+
import { principalHistoryEntries, principalHistoryNodes, } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
|
|
5
5
|
import { sqliteInsertBatchSize, sqliteRowsPerStatement, } from "../../sqlite/sqliteBindBudget.js";
|
|
6
|
-
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
7
6
|
import { excludedValue } from "../../sqlite/sqliteUpsert.js";
|
|
8
|
-
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
9
7
|
import { writePrincipalHistoryNodes } from "./principalHistoryNodeRetention.js";
|
|
10
8
|
const ENTRY_WRITE_BATCH_SIZE = sqliteInsertBatchSize(principalHistoryEntries);
|
|
11
9
|
/** Prepare only a page accepted by the signature/authorization verifier. */
|
|
@@ -160,9 +158,7 @@ function parsePrincipalHistoryEntry(entryJson) {
|
|
|
160
158
|
* version and entries in one set read; the first version that fails, in
|
|
161
159
|
* order, throws the error loading it alone would.
|
|
162
160
|
*/
|
|
163
|
-
export async function
|
|
164
|
-
await ensureSqlTables(input.execSql, principalHistoryEvidenceTables);
|
|
165
|
-
const { db } = getClientSQLitePersistenceRuntime(input.execSql);
|
|
161
|
+
export async function readPrincipalHistoryReferences(db, input) {
|
|
166
162
|
const resolved = await resolvePrincipalHistoryProofs(db, input);
|
|
167
163
|
const entries = await loadPrincipalHistoryEntryJson(db, input.scopeId, resolved.flatMap((result) => "value" in result ? [result.value.leafHash] : []));
|
|
168
164
|
return resolved.map((result) => {
|
|
@@ -183,16 +179,4 @@ export async function loadPrincipalHistoryReferences(input) {
|
|
|
183
179
|
};
|
|
184
180
|
});
|
|
185
181
|
}
|
|
186
|
-
/** Returns untrusted material. The caller must verify it against the issued root. */
|
|
187
|
-
export async function loadPrincipalHistoryReference(input) {
|
|
188
|
-
const [loaded] = await loadPrincipalHistoryReferences({
|
|
189
|
-
...input,
|
|
190
|
-
versions: [input.version],
|
|
191
|
-
});
|
|
192
|
-
if (!loaded)
|
|
193
|
-
throw new Error("Principal history reference was not loaded");
|
|
194
|
-
return input.expectedReference
|
|
195
|
-
? { ...loaded, reference: input.expectedReference }
|
|
196
|
-
: loaded;
|
|
197
|
-
}
|
|
198
182
|
//# sourceMappingURL=principalHistoryEvidencePersistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryEvidencePersistence.js","sourceRoot":"","sources":["principalHistoryEvidencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,kCAAkC,EAGlC,yBAAyB,EAEzB,iCAAiC,GAElC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wCAAwC,GAEzC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,uBAAuB,EACvB,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,oDAAoD,CAAC;AAC5D,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,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAG7E,MAAM,sBAAsB,GAAG,qBAAqB,CAAC,uBAAuB,CAAC,CAAC;AAa9E,4EAA4E;AAC5E,MAA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CAAC,CAAC,CAAC;AACL,CAAC;AAED,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAMnD;IACC,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,8BAA8B,CAAC;QACpD,GAAG,KAAK;QACR,QAAQ,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;KAC1B,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAC3E,OAAO,KAAK,CAAC,iBAAiB;QAC5B,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,iBAAiB,EAAE;QACnD,CAAC,CAAC,MAAM,CAAC;AACb,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalHistoryIndexNode,\n type PrincipalPolicyHistoryReferenceProof,\n principalHistoryIndexLeaf,\n type ReferencedPrincipalHead,\n resolvePrincipalHistoryIndexProof,\n type VerifiedPrincipalPolicyHistory,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyStateChainEntryResponse,\n type PrincipalPolicyStateChainEntryResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, isNotNull } from \"drizzle-orm\";\nimport {\n principalHistoryEntries,\n principalHistoryEvidenceTables,\n principalHistoryNodes,\n} from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\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 { writePrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport type { PrincipalHistoryRootEdges } from \"./principalHistoryRootOwnership\";\n\nconst ENTRY_WRITE_BATCH_SIZE = sqliteInsertBatchSize(principalHistoryEntries);\n\nexport interface PrincipalHistoryEvidencePage {\n readonly indexRootHash: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly entries: readonly {\n readonly leafHash: string;\n readonly entryJson: string;\n }[];\n readonly nodes: readonly PrincipalHistoryIndexNode[];\n}\n\n/** Prepare only a page accepted by the signature/authorization verifier. */\nexport async function preparePrincipalHistoryEvidencePage(input: {\n readonly indexRootHash: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly entries: readonly PrincipalPolicyStateChainEntryResponse[];\n readonly nodes: readonly PrincipalHistoryIndexNode[];\n}): Promise<PrincipalHistoryEvidencePage> {\n if (\n input.entries.length > PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT ||\n input.nodes.length > 2 * PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal evidence page exceeds its batch budget\",\n );\n const owned = structuredClone(input);\n return {\n ...owned,\n entries: await Promise.all(\n owned.entries.map(async (entry) => ({\n leafHash: await principalHistoryIndexLeaf(entry.state),\n entryJson: JSON.stringify(entry),\n })),\n ),\n };\n}\n\n/** Publish in the same guarded transaction as the accepted page's progress. */\nexport async function writePrincipalHistoryEvidencePage(\n tx: ClientSQLiteTransactionScope,\n page: PrincipalHistoryEvidencePage,\n rootEdges?: PrincipalHistoryRootEdges | undefined,\n): Promise<void> {\n const scope = { scopeId: page.scopeId, organizationId: page.organizationId };\n // A repeated leaf keeps its last entry, as sequential upserts would.\n const entries = new Map(\n page.entries.map((entry) => [\n entry.leafHash,\n { ...scope, leafHash: entry.leafHash, entryJson: entry.entryJson },\n ]),\n );\n const rows = [...entries.values()].sort((a, b) =>\n compareCanonicalStrings(a.leafHash, b.leafHash),\n );\n for (let index = 0; index < rows.length; index += ENTRY_WRITE_BATCH_SIZE)\n await tx\n .insert(principalHistoryEntries)\n .values(rows.slice(index, index + ENTRY_WRITE_BATCH_SIZE))\n .onConflictDoUpdate({\n target: [\n principalHistoryEntries.scopeId,\n principalHistoryEntries.leafHash,\n ],\n set: {\n organizationId: excludedValue(principalHistoryEntries.organizationId),\n entryJson: excludedValue(principalHistoryEntries.entryJson),\n },\n })\n .run();\n await writePrincipalHistoryNodes(\n tx,\n scope,\n [...page.nodes].sort((a, b) => compareCanonicalStrings(a.hash, b.hash)),\n rootEdges,\n );\n}\n\ntype ResolvedPrincipalHistoryProof = Awaited<\n ReturnType<typeof resolvePrincipalHistoryIndexProof>\n>;\n\n// The scope id binds once per lookup.\nconst HASH_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\n/** Thrown by the preloaded node reader to ask the next level's set read for a hash. */\nclass PrincipalHistoryNodeNotLoaded {\n constructor(readonly hash: string) {}\n}\n\nfunction hashBatches(hashes: readonly string[]): string[][] {\n const result: string[][] = [];\n for (let index = 0; index < hashes.length; index += HASH_LOOKUP_BATCH_SIZE)\n result.push(hashes.slice(index, index + HASH_LOOKUP_BATCH_SIZE));\n return result;\n}\n\n/**\n * Reads `hashes` into `into`, absent ones as null. Only stored nodes are proof\n * material; a liveness placeholder without child hashes reads as absent.\n */\nasync function loadStoredPrincipalHistoryNodes(\n db: ClientSQLiteDatabase,\n scopeId: string,\n hashes: ReadonlySet<string>,\n into: Map<string, PrincipalHistoryIndexNode | null>,\n): Promise<void> {\n for (const batch of hashBatches([...hashes])) {\n for (const hash of batch) into.set(hash, null);\n const rows = await db\n .select({\n hash: principalHistoryNodes.hash,\n leftHash: principalHistoryNodes.leftHash,\n rightHash: principalHistoryNodes.rightHash,\n })\n .from(principalHistoryNodes)\n .where(\n and(\n eq(principalHistoryNodes.scopeId, scopeId),\n inArray(principalHistoryNodes.hash, batch),\n isNotNull(principalHistoryNodes.leftHash),\n isNotNull(principalHistoryNodes.rightHash),\n ),\n );\n for (const { hash, leftHash, rightHash } of rows)\n if (leftHash !== null && rightHash !== null)\n into.set(hash, { hash, leftHash, rightHash });\n }\n}\n\n/**\n * Resolves every version's index path level by level: each pass walks every\n * unfinished version over the nodes read so far, and one set read per level\n * supplies the nodes the walks stopped at. A node absent after its read stays\n * missing, so the unchanged verifier fails that version as it would serially.\n */\nasync function resolvePrincipalHistoryProofs(\n db: ClientSQLiteDatabase,\n input: {\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly versions: readonly number[];\n },\n): Promise<({ value: ResolvedPrincipalHistoryProof } | { error: unknown })[]> {\n const nodes = new Map<string, PrincipalHistoryIndexNode | null>();\n const results: (\n | { value: ResolvedPrincipalHistoryProof }\n | { error: unknown }\n )[] = [];\n let pending = input.versions.map((_, index) => index);\n while (pending.length > 0) {\n const needed = new Set<string>();\n const unfinished: number[] = [];\n for (const index of pending) {\n try {\n results[index] = {\n value: await resolvePrincipalHistoryIndexProof({\n rootHash: input.history.indexRootHash,\n treeSize: input.history.currentEntry.state.version,\n version: input.versions[index] ?? 0,\n readNode: async (hash) => {\n const node = nodes.get(hash);\n if (node === undefined)\n throw new PrincipalHistoryNodeNotLoaded(hash);\n return node;\n },\n }),\n };\n } catch (error) {\n if (!(error instanceof PrincipalHistoryNodeNotLoaded)) {\n results[index] = { error };\n continue;\n }\n needed.add(error.hash);\n unfinished.push(index);\n }\n }\n await loadStoredPrincipalHistoryNodes(db, input.scopeId, needed, nodes);\n pending = unfinished;\n }\n return results;\n}\n\nasync function loadPrincipalHistoryEntryJson(\n db: ClientSQLiteDatabase,\n scopeId: string,\n leafHashes: readonly string[],\n): Promise<Map<string, string>> {\n const entries = new Map<string, string>();\n for (const batch of hashBatches([...new Set(leafHashes)])) {\n const rows = await db\n .select({\n leafHash: principalHistoryEntries.leafHash,\n entryJson: principalHistoryEntries.entryJson,\n })\n .from(principalHistoryEntries)\n .where(\n and(\n eq(principalHistoryEntries.scopeId, scopeId),\n inArray(principalHistoryEntries.leafHash, batch),\n ),\n );\n for (const row of rows) entries.set(row.leafHash, row.entryJson);\n }\n return entries;\n}\n\nfunction parsePrincipalHistoryEntry(\n entryJson: string | undefined,\n): PrincipalPolicyStateChainEntryResponse {\n let entry: unknown;\n try {\n entry = entryJson === undefined ? null : JSON.parse(entryJson);\n } catch {\n entry = null;\n }\n if (!isPrincipalPolicyStateChainEntryResponse(entry))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history entry is missing or corrupt\",\n );\n return entry;\n}\n\n/**\n * Returns untrusted material, in `versions` order. The caller must verify it\n * against the issued root. Index nodes are read one level at a time for every\n * version and entries in one set read; the first version that fails, in\n * order, throws the error loading it alone would.\n */\nexport async function loadPrincipalHistoryReferences(input: {\n readonly execSql: ExecSql;\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly versions: readonly number[];\n}): Promise<PrincipalPolicyHistoryReferenceProof[]> {\n await ensureSqlTables(input.execSql, principalHistoryEvidenceTables);\n const { db } = getClientSQLitePersistenceRuntime(input.execSql);\n const resolved = await resolvePrincipalHistoryProofs(db, input);\n const entries = await loadPrincipalHistoryEntryJson(\n db,\n input.scopeId,\n resolved.flatMap((result) =>\n \"value\" in result ? [result.value.leafHash] : [],\n ),\n );\n return resolved.map((result) => {\n if (!(\"value\" in result)) throw result.error;\n const entry = parsePrincipalHistoryEntry(\n entries.get(result.value.leafHash),\n );\n return {\n reference: {\n principalType: entry.state.principalType,\n principalId: entry.state.principalId,\n version: entry.state.version,\n keyEpoch: entry.state.keyEpoch,\n stateHash: entry.state.stateHash,\n keyFingerprint: entry.state.keyFingerprint,\n },\n entry,\n proof: result.value.proof,\n };\n });\n}\n\n/** Returns untrusted material. The caller must verify it against the issued root. */\nexport async function loadPrincipalHistoryReference(input: {\n readonly execSql: ExecSql;\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly version: number;\n readonly expectedReference?: ReferencedPrincipalHead | undefined;\n}): Promise<PrincipalPolicyHistoryReferenceProof> {\n const [loaded] = await loadPrincipalHistoryReferences({\n ...input,\n versions: [input.version],\n });\n if (!loaded) throw new Error(\"Principal history reference was not loaded\");\n return input.expectedReference\n ? { ...loaded, reference: input.expectedReference }\n : loaded;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalHistoryEvidencePersistence.js","sourceRoot":"","sources":["principalHistoryEvidencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,kCAAkC,EAGlC,yBAAyB,EACzB,iCAAiC,GAElC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wCAAwC,GAEzC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,+BAA+B,CAAC;AAKvC,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAG7E,MAAM,sBAAsB,GAAG,qBAAqB,CAAC,uBAAuB,CAAC,CAAC;AAa9E,4EAA4E;AAC5E,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,IACE,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,kCAAkC;QACzD,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,kCAAkC;QAE3D,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,kDAAkD,CACnD,CAAC;IACJ,MAAM,KAAK,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;IACrC,OAAO;QACL,GAAG,KAAK;QACR,OAAO,EAAE,MAAM,OAAO,CAAC,GAAG,CACxB,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC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AO,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QAC7B,IAAI,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC;YAAE,MAAM,MAAM,CAAC,KAAK,CAAC;QAC7C,MAAM,KAAK,GAAG,0BAA0B,CACtC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CACnC,CAAC;QACF,OAAO;YACL,SAAS,EAAE;gBACT,aAAa,EAAE,KAAK,CAAC,KAAK,CAAC,aAAa;gBACxC,WAAW,EAAE,KAAK,CAAC,KAAK,CAAC,WAAW;gBACpC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO;gBAC5B,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,QAAQ;gBAC9B,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS;gBAChC,cAAc,EAAE,KAAK,CAAC,KAAK,CAAC,cAAc;aAC3C;YACD,KAAK;YACL,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK;SAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalHistoryIndexNode,\n type PrincipalPolicyHistoryReferenceProof,\n principalHistoryIndexLeaf,\n resolvePrincipalHistoryIndexProof,\n type VerifiedPrincipalPolicyHistory,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyStateChainEntryResponse,\n type PrincipalPolicyStateChainEntryResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, isNotNull } from \"drizzle-orm\";\nimport {\n principalHistoryEntries,\n principalHistoryNodes,\n} from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../../sqlite/sqliteBindBudget\";\nimport type {\n ClientSQLiteDatabase,\n ClientSQLiteTransactionScope,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../sqlite/sqliteUpsert\";\nimport { writePrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport type { PrincipalHistoryRootEdges } from \"./principalHistoryRootOwnership\";\n\nconst ENTRY_WRITE_BATCH_SIZE = sqliteInsertBatchSize(principalHistoryEntries);\n\nexport interface PrincipalHistoryEvidencePage {\n readonly indexRootHash: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly entries: readonly {\n readonly leafHash: string;\n readonly entryJson: string;\n }[];\n readonly nodes: readonly PrincipalHistoryIndexNode[];\n}\n\n/** Prepare only a page accepted by the signature/authorization verifier. */\nexport async function preparePrincipalHistoryEvidencePage(input: {\n readonly indexRootHash: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly entries: readonly PrincipalPolicyStateChainEntryResponse[];\n readonly nodes: readonly PrincipalHistoryIndexNode[];\n}): Promise<PrincipalHistoryEvidencePage> {\n if (\n input.entries.length > PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT ||\n input.nodes.length > 2 * PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal evidence page exceeds its batch budget\",\n );\n const owned = structuredClone(input);\n return {\n ...owned,\n entries: await Promise.all(\n owned.entries.map(async (entry) => ({\n leafHash: await principalHistoryIndexLeaf(entry.state),\n entryJson: JSON.stringify(entry),\n })),\n ),\n };\n}\n\n/** Publish in the same guarded transaction as the accepted page's progress. */\nexport async function writePrincipalHistoryEvidencePage(\n tx: ClientSQLiteTransactionScope,\n page: PrincipalHistoryEvidencePage,\n rootEdges?: PrincipalHistoryRootEdges | undefined,\n): Promise<void> {\n const scope = { scopeId: page.scopeId, organizationId: page.organizationId };\n // A repeated leaf keeps its last entry, as sequential upserts would.\n const entries = new Map(\n page.entries.map((entry) => [\n entry.leafHash,\n { ...scope, leafHash: entry.leafHash, entryJson: entry.entryJson },\n ]),\n );\n const rows = [...entries.values()].sort((a, b) =>\n compareCanonicalStrings(a.leafHash, b.leafHash),\n );\n for (let index = 0; index < rows.length; index += ENTRY_WRITE_BATCH_SIZE)\n await tx\n .insert(principalHistoryEntries)\n .values(rows.slice(index, index + ENTRY_WRITE_BATCH_SIZE))\n .onConflictDoUpdate({\n target: [\n principalHistoryEntries.scopeId,\n principalHistoryEntries.leafHash,\n ],\n set: {\n organizationId: excludedValue(principalHistoryEntries.organizationId),\n entryJson: excludedValue(principalHistoryEntries.entryJson),\n },\n })\n .run();\n await writePrincipalHistoryNodes(\n tx,\n scope,\n [...page.nodes].sort((a, b) => compareCanonicalStrings(a.hash, b.hash)),\n rootEdges,\n );\n}\n\ntype ResolvedPrincipalHistoryProof = Awaited<\n ReturnType<typeof resolvePrincipalHistoryIndexProof>\n>;\n\n// The scope id binds once per lookup.\nconst HASH_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\n/** Thrown by the preloaded node reader to ask the next level's set read for a hash. */\nclass PrincipalHistoryNodeNotLoaded {\n constructor(readonly hash: string) {}\n}\n\nfunction hashBatches(hashes: readonly string[]): string[][] {\n const result: string[][] = [];\n for (let index = 0; index < hashes.length; index += HASH_LOOKUP_BATCH_SIZE)\n result.push(hashes.slice(index, index + HASH_LOOKUP_BATCH_SIZE));\n return result;\n}\n\n/**\n * Reads `hashes` into `into`, absent ones as null. Only stored nodes are proof\n * material; a liveness placeholder without child hashes reads as absent.\n */\nasync function loadStoredPrincipalHistoryNodes(\n db: ClientSQLiteDatabase,\n scopeId: string,\n hashes: ReadonlySet<string>,\n into: Map<string, PrincipalHistoryIndexNode | null>,\n): Promise<void> {\n for (const batch of hashBatches([...hashes])) {\n for (const hash of batch) into.set(hash, null);\n const rows = await db\n .select({\n hash: principalHistoryNodes.hash,\n leftHash: principalHistoryNodes.leftHash,\n rightHash: principalHistoryNodes.rightHash,\n })\n .from(principalHistoryNodes)\n .where(\n and(\n eq(principalHistoryNodes.scopeId, scopeId),\n inArray(principalHistoryNodes.hash, batch),\n isNotNull(principalHistoryNodes.leftHash),\n isNotNull(principalHistoryNodes.rightHash),\n ),\n );\n for (const { hash, leftHash, rightHash } of rows)\n if (leftHash !== null && rightHash !== null)\n into.set(hash, { hash, leftHash, rightHash });\n }\n}\n\n/**\n * Resolves every version's index path level by level: each pass walks every\n * unfinished version over the nodes read so far, and one set read per level\n * supplies the nodes the walks stopped at. A node absent after its read stays\n * missing, so the unchanged verifier fails that version as it would serially.\n */\nasync function resolvePrincipalHistoryProofs(\n db: ClientSQLiteDatabase,\n input: {\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly versions: readonly number[];\n },\n): Promise<({ value: ResolvedPrincipalHistoryProof } | { error: unknown })[]> {\n const nodes = new Map<string, PrincipalHistoryIndexNode | null>();\n const results: (\n | { value: ResolvedPrincipalHistoryProof }\n | { error: unknown }\n )[] = [];\n let pending = input.versions.map((_, index) => index);\n while (pending.length > 0) {\n const needed = new Set<string>();\n const unfinished: number[] = [];\n for (const index of pending) {\n try {\n results[index] = {\n value: await resolvePrincipalHistoryIndexProof({\n rootHash: input.history.indexRootHash,\n treeSize: input.history.currentEntry.state.version,\n version: input.versions[index] ?? 0,\n readNode: async (hash) => {\n const node = nodes.get(hash);\n if (node === undefined)\n throw new PrincipalHistoryNodeNotLoaded(hash);\n return node;\n },\n }),\n };\n } catch (error) {\n if (!(error instanceof PrincipalHistoryNodeNotLoaded)) {\n results[index] = { error };\n continue;\n }\n needed.add(error.hash);\n unfinished.push(index);\n }\n }\n await loadStoredPrincipalHistoryNodes(db, input.scopeId, needed, nodes);\n pending = unfinished;\n }\n return results;\n}\n\nasync function loadPrincipalHistoryEntryJson(\n db: ClientSQLiteDatabase,\n scopeId: string,\n leafHashes: readonly string[],\n): Promise<Map<string, string>> {\n const entries = new Map<string, string>();\n for (const batch of hashBatches([...new Set(leafHashes)])) {\n const rows = await db\n .select({\n leafHash: principalHistoryEntries.leafHash,\n entryJson: principalHistoryEntries.entryJson,\n })\n .from(principalHistoryEntries)\n .where(\n and(\n eq(principalHistoryEntries.scopeId, scopeId),\n inArray(principalHistoryEntries.leafHash, batch),\n ),\n );\n for (const row of rows) entries.set(row.leafHash, row.entryJson);\n }\n return entries;\n}\n\nfunction parsePrincipalHistoryEntry(\n entryJson: string | undefined,\n): PrincipalPolicyStateChainEntryResponse {\n let entry: unknown;\n try {\n entry = entryJson === undefined ? null : JSON.parse(entryJson);\n } catch {\n entry = null;\n }\n if (!isPrincipalPolicyStateChainEntryResponse(entry))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history entry is missing or corrupt\",\n );\n return entry;\n}\n\n/**\n * Returns untrusted material, in `versions` order. The caller must verify it\n * against the issued root. Index nodes are read one level at a time for every\n * version and entries in one set read; the first version that fails, in\n * order, throws the error loading it alone would.\n */\nexport async function readPrincipalHistoryReferences(\n db: ClientSQLiteDatabase,\n input: {\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly versions: readonly number[];\n },\n): Promise<PrincipalPolicyHistoryReferenceProof[]> {\n const resolved = await resolvePrincipalHistoryProofs(db, input);\n const entries = await loadPrincipalHistoryEntryJson(\n db,\n input.scopeId,\n resolved.flatMap((result) =>\n \"value\" in result ? [result.value.leafHash] : [],\n ),\n );\n return resolved.map((result) => {\n if (!(\"value\" in result)) throw result.error;\n const entry = parsePrincipalHistoryEntry(\n entries.get(result.value.leafHash),\n );\n return {\n reference: {\n principalType: entry.state.principalType,\n principalId: entry.state.principalId,\n version: entry.state.version,\n keyEpoch: entry.state.keyEpoch,\n stateHash: entry.state.stateHash,\n keyFingerprint: entry.state.keyFingerprint,\n },\n entry,\n proof: result.value.proof,\n };\n });\n}\n"]}
|
|
@@ -1,22 +1,126 @@
|
|
|
1
1
|
import { principalHistoryPrefixes } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
|
|
2
|
-
import {
|
|
2
|
+
import type { ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
3
3
|
export type PrincipalHistoryPrefix = Omit<typeof principalHistoryPrefixes.$inferSelect, "rootHash" | "identityBundleFormat">;
|
|
4
|
-
export declare
|
|
4
|
+
export declare const principalHistoryPrefixColumns: {
|
|
5
|
+
scopeId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
6
|
+
name: "scope_id";
|
|
7
|
+
tableName: "principal_history_prefixes";
|
|
8
|
+
dataType: "string";
|
|
9
|
+
columnType: "SQLiteText";
|
|
10
|
+
data: string;
|
|
11
|
+
driverParam: string;
|
|
12
|
+
notNull: true;
|
|
13
|
+
hasDefault: false;
|
|
14
|
+
isPrimaryKey: true;
|
|
15
|
+
isAutoincrement: false;
|
|
16
|
+
hasRuntimeDefault: false;
|
|
17
|
+
enumValues: [string, ...string[]];
|
|
18
|
+
baseColumn: never;
|
|
19
|
+
identity: undefined;
|
|
20
|
+
generated: undefined;
|
|
21
|
+
}, {}, {
|
|
22
|
+
length: number | undefined;
|
|
23
|
+
}>;
|
|
24
|
+
organizationId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
25
|
+
name: "organization_id";
|
|
26
|
+
tableName: "principal_history_prefixes";
|
|
27
|
+
dataType: "string";
|
|
28
|
+
columnType: "SQLiteText";
|
|
29
|
+
data: string;
|
|
30
|
+
driverParam: string;
|
|
31
|
+
notNull: true;
|
|
32
|
+
hasDefault: false;
|
|
33
|
+
isPrimaryKey: false;
|
|
34
|
+
isAutoincrement: false;
|
|
35
|
+
hasRuntimeDefault: false;
|
|
36
|
+
enumValues: [string, ...string[]];
|
|
37
|
+
baseColumn: never;
|
|
38
|
+
identity: undefined;
|
|
39
|
+
generated: undefined;
|
|
40
|
+
}, {}, {
|
|
41
|
+
length: number | undefined;
|
|
42
|
+
}>;
|
|
43
|
+
version: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
44
|
+
name: "version";
|
|
45
|
+
tableName: "principal_history_prefixes";
|
|
46
|
+
dataType: "number";
|
|
47
|
+
columnType: "SQLiteInteger";
|
|
48
|
+
data: number;
|
|
49
|
+
driverParam: number;
|
|
50
|
+
notNull: true;
|
|
51
|
+
hasDefault: false;
|
|
52
|
+
isPrimaryKey: false;
|
|
53
|
+
isAutoincrement: false;
|
|
54
|
+
hasRuntimeDefault: false;
|
|
55
|
+
enumValues: undefined;
|
|
56
|
+
baseColumn: never;
|
|
57
|
+
identity: undefined;
|
|
58
|
+
generated: undefined;
|
|
59
|
+
}, {}, {}>;
|
|
60
|
+
headJson: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
61
|
+
name: "head_json";
|
|
62
|
+
tableName: "principal_history_prefixes";
|
|
63
|
+
dataType: "string";
|
|
64
|
+
columnType: "SQLiteText";
|
|
65
|
+
data: string;
|
|
66
|
+
driverParam: string;
|
|
67
|
+
notNull: true;
|
|
68
|
+
hasDefault: false;
|
|
69
|
+
isPrimaryKey: false;
|
|
70
|
+
isAutoincrement: false;
|
|
71
|
+
hasRuntimeDefault: false;
|
|
72
|
+
enumValues: [string, ...string[]];
|
|
73
|
+
baseColumn: never;
|
|
74
|
+
identity: undefined;
|
|
75
|
+
generated: undefined;
|
|
76
|
+
}, {}, {
|
|
77
|
+
length: number | undefined;
|
|
78
|
+
}>;
|
|
79
|
+
currentJson: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
80
|
+
name: "current_json";
|
|
81
|
+
tableName: "principal_history_prefixes";
|
|
82
|
+
dataType: "string";
|
|
83
|
+
columnType: "SQLiteText";
|
|
84
|
+
data: string;
|
|
85
|
+
driverParam: string;
|
|
86
|
+
notNull: true;
|
|
87
|
+
hasDefault: false;
|
|
88
|
+
isPrimaryKey: false;
|
|
89
|
+
isAutoincrement: false;
|
|
90
|
+
hasRuntimeDefault: false;
|
|
91
|
+
enumValues: [string, ...string[]];
|
|
92
|
+
baseColumn: never;
|
|
93
|
+
identity: undefined;
|
|
94
|
+
generated: undefined;
|
|
95
|
+
}, {}, {
|
|
96
|
+
length: number | undefined;
|
|
97
|
+
}>;
|
|
98
|
+
progress: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
99
|
+
name: "progress";
|
|
100
|
+
tableName: "principal_history_prefixes";
|
|
101
|
+
dataType: "string";
|
|
102
|
+
columnType: "SQLiteText";
|
|
103
|
+
data: string;
|
|
104
|
+
driverParam: string;
|
|
105
|
+
notNull: true;
|
|
106
|
+
hasDefault: false;
|
|
107
|
+
isPrimaryKey: false;
|
|
108
|
+
isAutoincrement: false;
|
|
109
|
+
hasRuntimeDefault: false;
|
|
110
|
+
enumValues: [string, ...string[]];
|
|
111
|
+
baseColumn: never;
|
|
112
|
+
identity: undefined;
|
|
113
|
+
generated: undefined;
|
|
114
|
+
}, {}, {
|
|
115
|
+
length: number | undefined;
|
|
116
|
+
}>;
|
|
117
|
+
};
|
|
5
118
|
/**
|
|
6
119
|
* Preserve identical completed progress; this sink does not authenticate hints.
|
|
7
120
|
* Callers must discard an unreadable prefix or identify it with rejectedPrefix
|
|
8
|
-
* before publishing a repair of the same head and current artifacts.
|
|
121
|
+
* before publishing a repair of the same head and current artifacts. Updates
|
|
122
|
+
* the owned `prefix` copy's progress when it reuses the stored progress.
|
|
9
123
|
*/
|
|
10
|
-
export declare function
|
|
11
|
-
readonly execSql: ExecSql;
|
|
12
|
-
readonly prefix: PrincipalHistoryPrefix;
|
|
13
|
-
readonly indexRootHash: string;
|
|
14
|
-
readonly stillCurrent: () => boolean;
|
|
15
|
-
readonly rejectedPrefix?: PrincipalHistoryPrefix | null;
|
|
16
|
-
}): Promise<void>;
|
|
124
|
+
export declare function savePrincipalHistoryPrefixInTransaction(tx: ClientSQLiteTransactionScope, prefix: PrincipalHistoryPrefix, indexRootHash: string, rejected: PrincipalHistoryPrefix | null): Promise<void>;
|
|
17
125
|
/** Invalid hints are disposable, but a losing reader must preserve a newer hint. */
|
|
18
|
-
export declare function
|
|
19
|
-
readonly execSql: ExecSql;
|
|
20
|
-
readonly prefix: PrincipalHistoryPrefix;
|
|
21
|
-
readonly stillCurrent: () => boolean;
|
|
22
|
-
}): Promise<void>;
|
|
126
|
+
export declare function discardPrincipalHistoryPrefixInTransaction(tx: ClientSQLiteTransactionScope, prefix: PrincipalHistoryPrefix): Promise<void>;
|