@tearleads/client-sdk 0.1.198 → 0.1.200
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/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +2 -2
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +6 -7
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
- package/data/persistence/identity/trustedUserIdentityPinModel.d.ts +4 -0
- package/data/persistence/identity/trustedUserIdentityPinModel.js +113 -0
- package/data/persistence/identity/trustedUserIdentityPinModel.js.map +1 -1
- package/data/persistence/identity/trustedUserIdentityPinRepository.js +196 -0
- package/data/persistence/identity/trustedUserIdentityPinRepository.js.map +1 -0
- package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js +4 -16
- package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -1
- package/data/persistence/principalPolicy/heldPrincipalState.js +2 -11
- package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +14 -65
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +180 -0
- package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -0
- package/data/persistence/principalPolicy/principalPolicyPersistence.js +6 -62
- package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +11 -12
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +24 -40
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -1
- package/data/principals/organizationGroupRoles.js +2 -2
- package/data/principals/organizationGroupRoles.js.map +1 -1
- package/data/principals/principalPolicyCrypto.js +2 -2
- package/data/principals/principalPolicyCrypto.js.map +1 -1
- package/data/trustedUserIdentity/pinnedIdentity.d.ts +1 -1
- package/data/trustedUserIdentity/pinnedIdentity.js +2 -2
- package/data/trustedUserIdentity/pinnedIdentity.js.map +1 -1
- package/data/trustedUserIdentity/pinnedResolution.js +4 -5
- package/data/trustedUserIdentity/pinnedResolution.js.map +1 -1
- package/data/trustedUserIdentity/service.js +12 -13
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/package.json +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -5
- package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +4 -11
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js +7 -9
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/shareWithGroup.js +2 -2
- package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
- package/workflows/organizations/groups/deleteOrganizationGroup.js +2 -4
- package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js +2 -4
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js +3 -3
- package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
- package/workflows/principals/externalAdminPolicy.js +2 -4
- package/workflows/principals/externalAdminPolicy.js.map +1 -1
- package/workflows/principals/policyCache/index.js +3 -5
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +3 -2
- package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/registration/registrationPrincipalPolicyPersistence.js +2 -4
- package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
- package/data/persistence/identity/trustedUserIdentityPinBatch.js +0 -36
- package/data/persistence/identity/trustedUserIdentityPinBatch.js.map +0 -1
- package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js +0 -18
- package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js.map +0 -1
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
- package/data/persistence/trustedUserIdentityPinPersistence.d.ts +0 -37
- package/data/persistence/trustedUserIdentityPinPersistence.js +0 -258
- package/data/persistence/trustedUserIdentityPinPersistence.js.map +0 -1
- /package/data/persistence/{trustedUserIdentityPinTransaction.js → identity/trustedUserIdentityPinTransaction.js} +0 -0
- /package/data/persistence/{trustedUserIdentityPinTransaction.js.map → identity/trustedUserIdentityPinTransaction.js.map} +0 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { asc, desc } from "drizzle-orm";
|
|
2
|
+
import { keyingCheckpointTables } from "../../sqlite/schema/keyingCheckpointSchema.js";
|
|
3
|
+
import { principalHistoryEvidenceTables } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
|
|
4
|
+
import { principalPolicyBundles, principalPolicyTables, } from "../../sqlite/schema/principalPolicySchema.js";
|
|
5
|
+
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
|
+
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
7
|
+
import { selectPrincipalKeyEnvelopeCandidates, } from "../principalKeys/principalKeyEnvelopeCandidates.js";
|
|
8
|
+
import { selectHeldPrincipalState } from "./heldPrincipalState.js";
|
|
9
|
+
import { assertLocallyAcknowledgedPrincipalPolicyBundles, storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction, } from "./locallyAcknowledgedPrincipalPolicyPersistence.js";
|
|
10
|
+
import { parseSelectedPrincipalPolicyBundle, principalPolicyBundleSelection, retainPrincipalPolicyBundleInTransaction, wherePrincipalPolicyCurrent, writePrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
|
|
11
|
+
import { assertReferenceShape, selectReferencedPrincipalPolicyBundle, } from "./principalPolicyReferencePersistence.js";
|
|
12
|
+
import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
|
|
13
|
+
import { assertVerifiedPrincipalPolicyBundles, persistVerifiedPrincipalPolicyBundlesInTransaction, } from "./verifiedPrincipalPolicyBundlePersistence.js";
|
|
14
|
+
/**
|
|
15
|
+
* The cached principal policy bundles, current heads and retained epochs, and
|
|
16
|
+
* the member key envelopes they carry, bound to one executor and clock. Each
|
|
17
|
+
* method ensures its tables; each writer runs its own immediate transaction
|
|
18
|
+
* and silently skips a commit its `stillCurrent` refuses. Work inside a
|
|
19
|
+
* caller's transaction takes the locked handle per call through the
|
|
20
|
+
* `*InTransaction` functions instead.
|
|
21
|
+
*/
|
|
22
|
+
export class PrincipalPolicyBundleRepository {
|
|
23
|
+
execSql;
|
|
24
|
+
now;
|
|
25
|
+
constructor(execSql, now = () => new Date()) {
|
|
26
|
+
this.execSql = execSql;
|
|
27
|
+
this.now = now;
|
|
28
|
+
}
|
|
29
|
+
async ensurePrincipalPolicyTables() {
|
|
30
|
+
await ensureSqlTables(this.execSql, principalPolicyTables);
|
|
31
|
+
}
|
|
32
|
+
async loadPrincipalPolicyBundle(principalType, principalId) {
|
|
33
|
+
await this.ensurePrincipalPolicyTables();
|
|
34
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
35
|
+
const [row] = await db
|
|
36
|
+
.select(principalPolicyBundleSelection)
|
|
37
|
+
.from(principalPolicyBundles)
|
|
38
|
+
.where(wherePrincipalPolicyCurrent({ principalType, principalId }))
|
|
39
|
+
.limit(1);
|
|
40
|
+
return row ? parseSelectedPrincipalPolicyBundle(row) : null;
|
|
41
|
+
}
|
|
42
|
+
/** Current heads first, then retained bundles. */
|
|
43
|
+
async loadAllPrincipalPolicyBundles() {
|
|
44
|
+
await this.ensurePrincipalPolicyTables();
|
|
45
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
46
|
+
const rows = await db
|
|
47
|
+
.select(principalPolicyBundleSelection)
|
|
48
|
+
.from(principalPolicyBundles)
|
|
49
|
+
.orderBy(desc(principalPolicyBundles.isCurrent), asc(principalPolicyBundles.principalType), asc(principalPolicyBundles.principalId), asc(principalPolicyBundles.stateHash));
|
|
50
|
+
const bundles = [];
|
|
51
|
+
for (const row of rows) {
|
|
52
|
+
const bundle = parseSelectedPrincipalPolicyBundle(row);
|
|
53
|
+
if (bundle)
|
|
54
|
+
bundles.push(bundle);
|
|
55
|
+
}
|
|
56
|
+
return bundles;
|
|
57
|
+
}
|
|
58
|
+
async loadPrincipalPolicyStateHash(principalType, principalId) {
|
|
59
|
+
await this.ensurePrincipalPolicyTables();
|
|
60
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
61
|
+
const [row] = await db
|
|
62
|
+
.select({ stateHash: principalPolicyBundles.stateHash })
|
|
63
|
+
.from(principalPolicyBundles)
|
|
64
|
+
.where(wherePrincipalPolicyCurrent({ principalType, principalId }))
|
|
65
|
+
.limit(1);
|
|
66
|
+
return row?.stateHash ?? null;
|
|
67
|
+
}
|
|
68
|
+
/** The newest stored bundle containing exactly `reference`, never a guess. */
|
|
69
|
+
async loadPrincipalPolicyBundleForReference(reference, checkpoint) {
|
|
70
|
+
assertReferenceShape(reference);
|
|
71
|
+
await this.ensurePrincipalPolicyTables();
|
|
72
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
73
|
+
return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* A signed state this device stored for exactly `head`: history evidence it
|
|
77
|
+
* verified or acknowledged, or a cached policy bundle chain. It is untrusted;
|
|
78
|
+
* the caller verifies it as it would a served copy, and a miss only means the
|
|
79
|
+
* server sends one.
|
|
80
|
+
*/
|
|
81
|
+
async loadHeldPrincipalState(head) {
|
|
82
|
+
await this.ensurePrincipalPolicyTables();
|
|
83
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
84
|
+
return selectHeldPrincipalState(db, head);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Untrusted encrypted key candidates, never authorization evidence. The actual
|
|
88
|
+
* private key must open the requested recipient wrap; the projection verifier
|
|
89
|
+
* separately checks the signed KEK material identity and all policy authority.
|
|
90
|
+
* Read only envelopes for the requested fingerprints, never signed histories.
|
|
91
|
+
*/
|
|
92
|
+
async loadPrincipalKeyEnvelopeCandidates(fingerprints) {
|
|
93
|
+
await ensureSqlTables(this.execSql, [
|
|
94
|
+
...principalPolicyTables,
|
|
95
|
+
...principalHistoryEvidenceTables,
|
|
96
|
+
]);
|
|
97
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
98
|
+
return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);
|
|
99
|
+
}
|
|
100
|
+
async savePrincipalPolicyBundle(bundle, organizationId, options) {
|
|
101
|
+
await ensureSqlTables(this.execSql, [
|
|
102
|
+
...principalPolicyTables,
|
|
103
|
+
...keyingCheckpointTables,
|
|
104
|
+
]);
|
|
105
|
+
await this.runImmediate((tx) => writePrincipalPolicyBundleInTransaction(tx, bundle, this.now().toISOString(), organizationId), options?.stillCurrent);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Persists each verified full policy bundle together with its durable head.
|
|
109
|
+
* This prevents a crash or bundle-write failure from leaving a checkpoint
|
|
110
|
+
* without the exact same-head payload and member-envelope evidence.
|
|
111
|
+
*/
|
|
112
|
+
async persistVerifiedPrincipalPolicyBundlesAtomically(input) {
|
|
113
|
+
await assertVerifiedPrincipalPolicyBundles(input.entries);
|
|
114
|
+
await ensureSqlTables(this.execSql, [
|
|
115
|
+
...principalPolicyTables,
|
|
116
|
+
...keyingCheckpointTables,
|
|
117
|
+
]);
|
|
118
|
+
await this.runImmediate((tx) => persistVerifiedPrincipalPolicyBundlesInTransaction(tx, input, this.now().toISOString()), input.stillCurrent);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Retains a just-verified epoch without promoting it to the mutable head.
|
|
122
|
+
* `updatedAt` stays explicit: callers stamp a whole retention walk at once.
|
|
123
|
+
*/
|
|
124
|
+
async retainVerifiedPrincipalPolicyBundle(input) {
|
|
125
|
+
await assertBundleMatchesVerifiedPolicy(input);
|
|
126
|
+
await this.ensurePrincipalPolicyTables();
|
|
127
|
+
await this.runImmediate((tx) => retainPrincipalPolicyBundleInTransaction(tx, input.bundle, input.updatedAt, input.organizationId), input.stillCurrent);
|
|
128
|
+
}
|
|
129
|
+
/** Atomically pins and caches exact full policy bundles acknowledged by the API. */
|
|
130
|
+
persistLocallyAcknowledgedPrincipalPolicyBundles(input) {
|
|
131
|
+
return this.storeLocallyAcknowledgedPrincipalPolicyBundles({
|
|
132
|
+
...input,
|
|
133
|
+
placement: "current",
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
persistLocallyAcknowledgedPrincipalPolicyBundle(input) {
|
|
137
|
+
return this.persistLocallyAcknowledgedPrincipalPolicyBundles({
|
|
138
|
+
entries: [input],
|
|
139
|
+
organizationId: input.organizationId,
|
|
140
|
+
stillCurrent: input.stillCurrent,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Seed a provisioning acknowledgement without making genesis current again.
|
|
145
|
+
* The cache writer still checks ownership, equal-version forks and retained
|
|
146
|
+
* same-hash bundle integrity, and preserves any newer cached policy head.
|
|
147
|
+
*/
|
|
148
|
+
seedLocallyAcknowledgedPrincipalPolicyBundles(input) {
|
|
149
|
+
return this.storeLocallyAcknowledgedPrincipalPolicyBundles({
|
|
150
|
+
...input,
|
|
151
|
+
placement: "genesis",
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
retainLocallyAcknowledgedPrincipalPolicyBundles(input) {
|
|
155
|
+
return this.storeLocallyAcknowledgedPrincipalPolicyBundles({
|
|
156
|
+
...input,
|
|
157
|
+
placement: "history",
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
async storeLocallyAcknowledgedPrincipalPolicyBundles(input) {
|
|
161
|
+
await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);
|
|
162
|
+
await ensureSqlTables(this.execSql, [
|
|
163
|
+
...principalPolicyTables,
|
|
164
|
+
...keyingCheckpointTables,
|
|
165
|
+
]);
|
|
166
|
+
await this.runImmediate((tx) => storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(tx, input, this.now().toISOString()), input.stillCurrent);
|
|
167
|
+
}
|
|
168
|
+
/** Guarded when `stillCurrent` is given; a refused commit is not an error. */
|
|
169
|
+
async runImmediate(body, stillCurrent) {
|
|
170
|
+
const runtime = getClientSQLitePersistenceRuntime(this.execSql);
|
|
171
|
+
if (stillCurrent) {
|
|
172
|
+
await runtime.guardedTransaction(body, stillCurrent, {
|
|
173
|
+
behavior: "immediate",
|
|
174
|
+
});
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
await runtime.transaction(body, { behavior: "immediate" });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
//# sourceMappingURL=principalPolicyBundleRepository.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalPolicyBundleRepository.js","sourceRoot":"","sources":["principalPolicyBundleRepository.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAEL,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,+CAA+C,EAI/C,2DAA2D,GAC5D,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,wCAAwC,EACxC,2BAA2B,EAC3B,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EACL,oCAAoC,EACpC,kDAAkD,GAEnD,MAAM,4CAA4C,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,OAAO,+BAA+B;IACzB,OAAO,CAAU;IACjB,GAAG,CAAa;IAEjC,YAAY,OAAgB,EAAE,MAAkB,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE;QAC9D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,2B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B,IAAyD,EACzD,YAAyC;QAEzC,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE;gBACnD,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { asc, desc } from \"drizzle-orm\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalGrantRetirements } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type PrincipalKeyEnvelopeCandidate,\n selectPrincipalKeyEnvelopeCandidates,\n} from \"../principalKeys/principalKeyEnvelopeCandidates\";\nimport { selectHeldPrincipalState } from \"./heldPrincipalState\";\nimport {\n assertLocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyBundle,\n type LocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyStore,\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction,\n} from \"./locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n parseSelectedPrincipalPolicyBundle,\n principalPolicyBundleSelection,\n retainPrincipalPolicyBundleInTransaction,\n wherePrincipalPolicyCurrent,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n assertReferenceShape,\n selectReferencedPrincipalPolicyBundle,\n} from \"./principalPolicyReferencePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\nimport {\n assertVerifiedPrincipalPolicyBundles,\n persistVerifiedPrincipalPolicyBundlesInTransaction,\n type VerifiedPrincipalPolicyBundleEntry,\n} from \"./verifiedPrincipalPolicyBundlePersistence\";\n\n/**\n * The cached principal policy bundles, current heads and retained epochs, and\n * the member key envelopes they carry, bound to one executor and clock. Each\n * method ensures its tables; each writer runs its own immediate transaction\n * and silently skips a commit its `stillCurrent` refuses. Work inside a\n * caller's transaction takes the locked handle per call through the\n * `*InTransaction` functions instead.\n */\nexport class PrincipalPolicyBundleRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensurePrincipalPolicyTables(): Promise<void> {\n await ensureSqlTables(this.execSql, principalPolicyTables);\n }\n\n async loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row ? parseSelectedPrincipalPolicyBundle(row) : null;\n }\n\n /** Current heads first, then retained bundles. */\n async loadAllPrincipalPolicyBundles(): Promise<\n PrincipalPolicyBundleResponse[]\n > {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n const bundles: PrincipalPolicyBundleResponse[] = [];\n for (const row of rows) {\n const bundle = parseSelectedPrincipalPolicyBundle(row);\n if (bundle) bundles.push(bundle);\n }\n return bundles;\n }\n\n async loadPrincipalPolicyStateHash(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<string | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row?.stateHash ?? null;\n }\n\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n async loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);\n }\n\n /**\n * A signed state this device stored for exactly `head`: history evidence it\n * verified or acknowledged, or a cached policy bundle chain. It is untrusted;\n * the caller verifies it as it would a served copy, and a miss only means the\n * server sends one.\n */\n async loadHeldPrincipalState(\n head: ReferencedPrincipalHead,\n ): Promise<PrincipalStateResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHeldPrincipalState(db, head);\n }\n\n /**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\n async loadPrincipalKeyEnvelopeCandidates(\n fingerprints: readonly string[],\n ): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);\n }\n\n async savePrincipalPolicyBundle(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n ): Promise<void> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n this.now().toISOString(),\n organizationId,\n ),\n options?.stillCurrent,\n );\n }\n\n /**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\n async persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<void> {\n await assertVerifiedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /**\n * Retains a just-verified epoch without promoting it to the mutable head.\n * `updatedAt` stays explicit: callers stamp a whole retention walk at once.\n */\n async retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n }): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await this.ensurePrincipalPolicyTables();\n await this.runImmediate(\n (tx) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n ),\n input.stillCurrent,\n );\n }\n\n /** Atomically pins and caches exact full policy bundles acknowledged by the API. */\n persistLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n }\n\n persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n return this.persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n }\n\n /**\n * Seed a provisioning acknowledgement without making genesis current again.\n * The cache writer still checks ownership, equal-version forks and retained\n * same-hash bundle integrity, and preserves any newer cached policy head.\n */\n seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n }\n\n retainLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles & {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n },\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n }\n\n private async storeLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyStore & {\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /** Guarded when `stillCurrent` is given; a refused commit is not an error. */\n private async runImmediate(\n body: (tx: ClientSQLiteTransactionScope) => Promise<void>,\n stillCurrent: (() => boolean) | undefined,\n ): Promise<void> {\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (stillCurrent) {\n await runtime.guardedTransaction(body, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(body, { behavior: \"immediate\" });\n }\n}\n"]}
|
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { isPrincipalPolicyBundleResponse } from "../../../internal/validators/response/index.js";
|
|
3
|
-
import { and,
|
|
3
|
+
import { and, eq, or } from "drizzle-orm";
|
|
4
4
|
import { principalPolicyBundles } from "../../sqlite/schema/index.js";
|
|
5
|
-
import { keyingCheckpointTables } from "../../sqlite/schema/keyingCheckpointSchema.js";
|
|
6
|
-
import { principalPolicyTables } from "../../sqlite/schema/principalPolicySchema.js";
|
|
7
|
-
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
8
|
-
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
9
5
|
import { storedPrincipalPolicyPin } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
|
|
10
6
|
import { recordPrincipalPolicyBundleOrganizationInTransaction, recordPrincipalPolicyOrganizationInTransaction, } from "../keyingCheckpoints/principalPolicyOrganizationPersistence.js";
|
|
11
7
|
import { assertSameHeadPrincipalPolicyBundle } from "./principalPolicyBundleIntegrity.js";
|
|
@@ -54,8 +50,10 @@ function parsePrincipalPolicyBundle(row) {
|
|
|
54
50
|
}
|
|
55
51
|
return bundle;
|
|
56
52
|
}
|
|
57
|
-
|
|
58
|
-
|
|
53
|
+
/** A selected row's bundle; null when the row is not a managed principal. */
|
|
54
|
+
export function parseSelectedPrincipalPolicyBundle(row) {
|
|
55
|
+
const parsed = parsePrincipalPolicyRow(row);
|
|
56
|
+
return parsed ? parsePrincipalPolicyBundle(parsed) : null;
|
|
59
57
|
}
|
|
60
58
|
/** The ONE select shape for a stored principal-policy bundle row. */
|
|
61
59
|
export const principalPolicyBundleSelection = {
|
|
@@ -76,7 +74,7 @@ export function wherePrincipalPolicyBundlePrincipal(principal) {
|
|
|
76
74
|
return and(eq(principalPolicyBundles.principalType, principal.principalType), eq(principalPolicyBundles.principalId, principal.principalId));
|
|
77
75
|
}
|
|
78
76
|
/** The one current head of a principal. */
|
|
79
|
-
function wherePrincipalPolicyCurrent(principal) {
|
|
77
|
+
export function wherePrincipalPolicyCurrent(principal) {
|
|
80
78
|
return and(wherePrincipalPolicyBundlePrincipal(principal), eq(principalPolicyBundles.isCurrent, true));
|
|
81
79
|
}
|
|
82
80
|
function wherePrincipalPolicyBundle(row) {
|
|
@@ -93,45 +91,6 @@ async function loadCurrentAndRetainedPolicyBundles(tx, row) {
|
|
|
93
91
|
retained: rows.find((stored) => !stored.isCurrent && stored.stateHash === row.stateHash),
|
|
94
92
|
};
|
|
95
93
|
}
|
|
96
|
-
export async function loadPrincipalPolicyBundle(execSql, principalType, principalId) {
|
|
97
|
-
await ensurePrincipalPolicyTables(execSql);
|
|
98
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
99
|
-
const rows = await db
|
|
100
|
-
.select(principalPolicyBundleSelection)
|
|
101
|
-
.from(principalPolicyBundles)
|
|
102
|
-
.where(wherePrincipalPolicyCurrent({ principalType, principalId }))
|
|
103
|
-
.limit(1);
|
|
104
|
-
const row = rows[0] ? parsePrincipalPolicyRow(rows[0]) : null;
|
|
105
|
-
return row ? parsePrincipalPolicyBundle(row) : null;
|
|
106
|
-
}
|
|
107
|
-
/** Current heads first, then retained bundles. */
|
|
108
|
-
export async function loadAllPrincipalPolicyBundles(execSql) {
|
|
109
|
-
await ensurePrincipalPolicyTables(execSql);
|
|
110
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
111
|
-
const rows = await db
|
|
112
|
-
.select(principalPolicyBundleSelection)
|
|
113
|
-
.from(principalPolicyBundles)
|
|
114
|
-
.orderBy(desc(principalPolicyBundles.isCurrent), asc(principalPolicyBundles.principalType), asc(principalPolicyBundles.principalId), asc(principalPolicyBundles.stateHash));
|
|
115
|
-
const bundles = [];
|
|
116
|
-
for (const rawRow of rows) {
|
|
117
|
-
const row = parsePrincipalPolicyRow(rawRow);
|
|
118
|
-
if (!row) {
|
|
119
|
-
continue;
|
|
120
|
-
}
|
|
121
|
-
bundles.push(parsePrincipalPolicyBundle(row));
|
|
122
|
-
}
|
|
123
|
-
return bundles;
|
|
124
|
-
}
|
|
125
|
-
export async function loadPrincipalPolicyStateHash(execSql, principalType, principalId) {
|
|
126
|
-
await ensurePrincipalPolicyTables(execSql);
|
|
127
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
128
|
-
const rows = await db
|
|
129
|
-
.select({ stateHash: principalPolicyBundles.stateHash })
|
|
130
|
-
.from(principalPolicyBundles)
|
|
131
|
-
.where(wherePrincipalPolicyCurrent({ principalType, principalId }))
|
|
132
|
-
.limit(1);
|
|
133
|
-
return rows[0]?.stateHash ?? null;
|
|
134
|
-
}
|
|
135
94
|
function policyBundleRow(bundle, updatedAt) {
|
|
136
95
|
return {
|
|
137
96
|
principalType: bundle.currentState.principalType,
|
|
@@ -269,19 +228,4 @@ export async function retainPrincipalPolicyBundleInTransaction(tx, bundle, updat
|
|
|
269
228
|
.run();
|
|
270
229
|
await indexPrincipalPolicyBundleInTransaction(tx, bundle);
|
|
271
230
|
}
|
|
272
|
-
export async function savePrincipalPolicyBundle(execSql, bundle, updatedAt, organizationId, options) {
|
|
273
|
-
await ensureSqlTables(execSql, [
|
|
274
|
-
...principalPolicyTables,
|
|
275
|
-
...keyingCheckpointTables,
|
|
276
|
-
]);
|
|
277
|
-
const runtime = getClientSQLitePersistenceRuntime(execSql);
|
|
278
|
-
const save = (tx) => writePrincipalPolicyBundleInTransaction(tx, bundle, updatedAt, organizationId);
|
|
279
|
-
if (options?.stillCurrent) {
|
|
280
|
-
await runtime.guardedTransaction(save, options.stillCurrent, {
|
|
281
|
-
behavior: "immediate",
|
|
282
|
-
});
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
await runtime.transaction(save, { behavior: "immediate" });
|
|
286
|
-
}
|
|
287
231
|
//# sourceMappingURL=principalPolicyPersistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyPersistence.js","sourceRoot":"","sources":["principalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EACL,oDAAoD,EACpD,8CAA8C,GAC/C,MAAM,6DAA6D,CAAC;AACrE,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EAAE,uCAAuC,EAAE,MAAM,4CAA4C,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAkCpF,SAAS,sBAAsB,CAC7B,KAAa;IAE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,EAAgC,EAAE,EAAE,CAChD,uCAAuC,CACrC,EAAE,EACF,MAAM,EACN,SAAS,EACT,cAAc,CACf,CAAC;IACJ,IAAI,OAAO,EAAE,YAAY,EAAE,CAAC;QAC1B,MAAM,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,OAAO,CAAC,YAAY,EAAE;YAC3D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, asc, desc, eq, or } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalPolicyTables } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { storedPrincipalPolicyPin } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n recordPrincipalPolicyBundleOrganizationInTransaction,\n recordPrincipalPolicyOrganizationInTransaction,\n} from \"../keyingCheckpoints/principalPolicyOrganizationPersistence\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport { indexPrincipalPolicyBundleInTransaction } from \"./principalPolicyReferenceIndexPersistence\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface PrincipalPolicyRow {\n principalType: \"group\" | \"organization\";\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\nexport interface SelectedPrincipalPolicyRow {\n principalType: string;\n principalId: string;\n stateHash: string;\n isCurrent: boolean;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\ninterface StoredPrincipalPolicyHead {\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isManagedPrincipalType(\n value: string,\n): value is PrincipalStateResponse[\"principalType\"] {\n return value === \"group\" || value === \"organization\";\n}\n\nfunction parsePrincipalPolicyRow(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyRow | null {\n if (!isManagedPrincipalType(row.principalType)) {\n return null;\n }\n\n return {\n principalType: row.principalType,\n principalId: row.principalId,\n stateHash: row.stateHash,\n currentStateJson: row.currentStateJson,\n currentPayloadJson: row.currentPayloadJson,\n currentProjectionJson: row.currentProjectionJson,\n currentGrantsJson: row.currentGrantsJson,\n currentMemberEnvelopesJson: row.currentMemberEnvelopesJson,\n previousStatesJson: row.previousStatesJson,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction parseStoredPrincipalPolicyHead(\n currentStateJson: string,\n): StoredPrincipalPolicyHead | null {\n try {\n const value: unknown = JSON.parse(currentStateJson);\n if (!value || typeof value !== \"object\") {\n return null;\n }\n const stateHash = Reflect.get(value, \"stateHash\");\n const version = Reflect.get(value, \"version\");\n return typeof stateHash === \"string\" && typeof version === \"number\"\n ? { stateHash, version }\n : null;\n } catch {\n return null;\n }\n}\n\nfunction parsePrincipalPolicyBundle(\n row: PrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n\n return bundle;\n}\n\nexport async function ensurePrincipalPolicyTables(\n execSql: ExecSql,\n): Promise<void> {\n await ensureSqlTables(execSql, principalPolicyTables);\n}\n\n/** The ONE select shape for a stored principal-policy bundle row. */\nexport const principalPolicyBundleSelection = {\n principalType: principalPolicyBundles.principalType,\n principalId: principalPolicyBundles.principalId,\n stateHash: principalPolicyBundles.stateHash,\n isCurrent: principalPolicyBundles.isCurrent,\n currentStateJson: principalPolicyBundles.currentStateJson,\n currentPayloadJson: principalPolicyBundles.currentPayloadJson,\n currentProjectionJson: principalPolicyBundles.currentProjectionJson,\n currentGrantsJson: principalPolicyBundles.currentGrantsJson,\n currentMemberEnvelopesJson: principalPolicyBundles.currentMemberEnvelopesJson,\n previousStatesJson: principalPolicyBundles.previousStatesJson,\n updatedAt: principalPolicyBundles.updatedAt,\n};\n\n/** Every stored bundle of one principal. */\nexport function wherePrincipalPolicyBundlePrincipal(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n eq(principalPolicyBundles.principalType, principal.principalType),\n eq(principalPolicyBundles.principalId, principal.principalId),\n );\n}\n\n/** The one current head of a principal. */\nfunction wherePrincipalPolicyCurrent(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(principal),\n eq(principalPolicyBundles.isCurrent, true),\n );\n}\n\nfunction wherePrincipalPolicyBundle(row: {\n readonly principalType: string;\n readonly principalId: string;\n readonly stateHash: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(row),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n );\n}\n\n/** A principal's current head and its retained bundle at `row`'s exact hash, in one read. */\nasync function loadCurrentAndRetainedPolicyBundles(\n tx: ClientSQLiteTransactionScope,\n row: PrincipalPolicyRow,\n) {\n const rows = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(row),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n ),\n ),\n );\n return {\n current: rows.find((stored) => stored.isCurrent),\n retained: rows.find(\n (stored) => !stored.isCurrent && stored.stateHash === row.stateHash,\n ),\n };\n}\n\nexport async function loadPrincipalPolicyBundle(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<PrincipalPolicyBundleResponse | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n\n const row = rows[0] ? parsePrincipalPolicyRow(rows[0]) : null;\n return row ? parsePrincipalPolicyBundle(row) : null;\n}\n\n/** Current heads first, then retained bundles. */\nexport async function loadAllPrincipalPolicyBundles(\n execSql: ExecSql,\n): Promise<PrincipalPolicyBundleResponse[]> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n\n const bundles: PrincipalPolicyBundleResponse[] = [];\n\n for (const rawRow of rows) {\n const row = parsePrincipalPolicyRow(rawRow);\n\n if (!row) {\n continue;\n }\n\n bundles.push(parsePrincipalPolicyBundle(row));\n }\n\n return bundles;\n}\n\nexport async function loadPrincipalPolicyStateHash(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<string | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n\n return rows[0]?.stateHash ?? null;\n}\n\nfunction policyBundleRow(\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n): PrincipalPolicyRow {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n stateHash: bundle.currentState.stateHash,\n currentStateJson: JSON.stringify(bundle.currentState),\n currentPayloadJson: JSON.stringify(bundle.currentPayload),\n currentProjectionJson: JSON.stringify(bundle.currentProjection),\n currentGrantsJson: JSON.stringify(bundle.currentGrants),\n currentMemberEnvelopesJson: JSON.stringify(bundle.currentMemberEnvelopes),\n previousStatesJson: JSON.stringify(bundle.previousStates),\n updatedAt,\n };\n}\n\nfunction assertNoHeadConflict(\n incoming: StoredPrincipalPolicyHead,\n checkpoint: StoredPrincipalPolicyHead | null,\n): void {\n if (\n checkpoint &&\n incoming.version === checkpoint.version &&\n incoming.stateHash !== checkpoint.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle conflicts with the cached head at one version\",\n );\n }\n}\n\n/**\n * The replaced head stays as a retained bundle when it is an older valid\n * bundle; a corrupt cache row is dropped, never retained as key material.\n */\nasync function retirePrincipalPolicyHead(\n tx: ClientSQLiteTransactionScope,\n storedPolicy: SelectedPrincipalPolicyRow | undefined,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n if (!storedPolicy) {\n return;\n }\n const where = wherePrincipalPolicyBundle(storedPolicy);\n if (isRetainablePolicyHead(storedPolicy, storedHead, incomingHead)) {\n await tx\n .update(principalPolicyBundles)\n .set({ isCurrent: false })\n .where(where)\n .run();\n return;\n }\n await tx.delete(principalPolicyBundles).where(where).run();\n}\n\nfunction isRetainablePolicyHead(\n storedPolicy: SelectedPrincipalPolicyRow,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): boolean {\n if (!storedHead || storedHead.version >= incomingHead.version) {\n return false;\n }\n const row = parsePrincipalPolicyRow(storedPolicy);\n if (!row) {\n return false;\n }\n try {\n parsePrincipalPolicyBundle(row);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function writePrincipalPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n nextRow: PrincipalPolicyRow,\n incomingHead: StoredPrincipalPolicyHead,\n durablePin: Awaited<\n ReturnType<typeof recordPrincipalPolicyBundleOrganizationInTransaction>\n >,\n): Promise<void> {\n const { current: storedPolicy, retained: retainedPolicy } =\n await loadCurrentAndRetainedPolicyBundles(tx, nextRow);\n const durableCheckpoint = durablePin\n ? storedPrincipalPolicyPin(durablePin)\n : null;\n const storedHead = storedPolicy\n ? parseStoredPrincipalPolicyHead(storedPolicy.currentStateJson)\n : null;\n if (\n storedPolicy &&\n storedHead?.version === incomingHead.version &&\n storedHead.stateHash === incomingHead.stateHash\n ) {\n assertSameHeadPrincipalPolicyBundle(storedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n if (retainedPolicy) {\n assertSameHeadPrincipalPolicyBundle(retainedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n }\n const effectiveHead =\n durableCheckpoint &&\n (!storedHead || durableCheckpoint.version >= storedHead.version)\n ? durableCheckpoint\n : storedHead;\n assertNoHeadConflict(incomingHead, storedHead);\n assertNoHeadConflict(incomingHead, durableCheckpoint ?? null);\n if (effectiveHead && incomingHead.version < effectiveHead.version) {\n return;\n }\n\n // Promotion flips the head flag; a retained row at this hash becomes current.\n await retirePrincipalPolicyHead(tx, storedPolicy, storedHead, incomingHead);\n const currentRow = { ...nextRow, isCurrent: true };\n await tx\n .insert(principalPolicyBundles)\n .values(currentRow)\n .onConflictDoUpdate({\n target: [\n principalPolicyBundles.principalType,\n principalPolicyBundles.principalId,\n principalPolicyBundles.stateHash,\n ],\n set: currentRow,\n })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function writePrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const durableCheckpoint =\n await recordPrincipalPolicyBundleOrganizationInTransaction(\n tx,\n bundle,\n organizationId,\n );\n await writePrincipalPolicyBundle(\n tx,\n bundle,\n policyBundleRow(bundle, updatedAt),\n bundle.currentState,\n durableCheckpoint,\n );\n}\n\nexport async function assertPrincipalPolicyBundleStoredInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const expected = policyBundleRow(bundle, bundle.currentState.createdAt);\n const [stored] = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent(expected))\n .limit(1);\n if (!stored) {\n throw new Error(\"Verified principal policy bundle was not persisted\");\n }\n assertSameHeadPrincipalPolicyBundle(stored, expected);\n}\n\nexport async function retainPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const row = policyBundleRow(bundle, updatedAt);\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: row.principalId,\n principalType: row.principalType,\n });\n const { current, retained } = await loadCurrentAndRetainedPolicyBundles(\n tx,\n row,\n );\n const stored = current?.stateHash === row.stateHash ? current : retained;\n if (stored) {\n assertSameHeadPrincipalPolicyBundle(stored, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n await tx\n .insert(principalPolicyBundles)\n .values({ ...row, isCurrent: false })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function savePrincipalPolicyBundle(\n execSql: ExecSql,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n): Promise<void> {\n await ensureSqlTables(execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const save = (tx: ClientSQLiteTransactionScope) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n updatedAt,\n organizationId,\n );\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(save, options.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(save, { behavior: \"immediate\" });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyPersistence.js","sourceRoot":"","sources":["principalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EACL,oDAAoD,EACpD,8CAA8C,GAC/C,MAAM,6DAA6D,CAAC;AACrE,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EAAE,uCAAuC,EAAE,MAAM,4CAA4C,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAkCpF,SAAS,sBAAsB,CAC7B,KAAa;IAEb,OAAO,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,cAAc,CAAC;AACvD,CAAC;AAED,SAAS,uBAAuB,CAC9B,GAA+B;IAE/B,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;QAC/C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,aAAa,EAAE,GAAG,CAAC,aAAa;QAChC,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,gBA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\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, eq, or } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { storedPrincipalPolicyPin } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n recordPrincipalPolicyBundleOrganizationInTransaction,\n recordPrincipalPolicyOrganizationInTransaction,\n} from \"../keyingCheckpoints/principalPolicyOrganizationPersistence\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport { indexPrincipalPolicyBundleInTransaction } from \"./principalPolicyReferenceIndexPersistence\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface PrincipalPolicyRow {\n principalType: \"group\" | \"organization\";\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\nexport interface SelectedPrincipalPolicyRow {\n principalType: string;\n principalId: string;\n stateHash: string;\n isCurrent: boolean;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\ninterface StoredPrincipalPolicyHead {\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isManagedPrincipalType(\n value: string,\n): value is PrincipalStateResponse[\"principalType\"] {\n return value === \"group\" || value === \"organization\";\n}\n\nfunction parsePrincipalPolicyRow(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyRow | null {\n if (!isManagedPrincipalType(row.principalType)) {\n return null;\n }\n\n return {\n principalType: row.principalType,\n principalId: row.principalId,\n stateHash: row.stateHash,\n currentStateJson: row.currentStateJson,\n currentPayloadJson: row.currentPayloadJson,\n currentProjectionJson: row.currentProjectionJson,\n currentGrantsJson: row.currentGrantsJson,\n currentMemberEnvelopesJson: row.currentMemberEnvelopesJson,\n previousStatesJson: row.previousStatesJson,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction parseStoredPrincipalPolicyHead(\n currentStateJson: string,\n): StoredPrincipalPolicyHead | null {\n try {\n const value: unknown = JSON.parse(currentStateJson);\n if (!value || typeof value !== \"object\") {\n return null;\n }\n const stateHash = Reflect.get(value, \"stateHash\");\n const version = Reflect.get(value, \"version\");\n return typeof stateHash === \"string\" && typeof version === \"number\"\n ? { stateHash, version }\n : null;\n } catch {\n return null;\n }\n}\n\nfunction parsePrincipalPolicyBundle(\n row: PrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n\n return bundle;\n}\n\n/** A selected row's bundle; null when the row is not a managed principal. */\nexport function parseSelectedPrincipalPolicyBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse | null {\n const parsed = parsePrincipalPolicyRow(row);\n return parsed ? parsePrincipalPolicyBundle(parsed) : null;\n}\n\n/** The ONE select shape for a stored principal-policy bundle row. */\nexport const principalPolicyBundleSelection = {\n principalType: principalPolicyBundles.principalType,\n principalId: principalPolicyBundles.principalId,\n stateHash: principalPolicyBundles.stateHash,\n isCurrent: principalPolicyBundles.isCurrent,\n currentStateJson: principalPolicyBundles.currentStateJson,\n currentPayloadJson: principalPolicyBundles.currentPayloadJson,\n currentProjectionJson: principalPolicyBundles.currentProjectionJson,\n currentGrantsJson: principalPolicyBundles.currentGrantsJson,\n currentMemberEnvelopesJson: principalPolicyBundles.currentMemberEnvelopesJson,\n previousStatesJson: principalPolicyBundles.previousStatesJson,\n updatedAt: principalPolicyBundles.updatedAt,\n};\n\n/** Every stored bundle of one principal. */\nexport function wherePrincipalPolicyBundlePrincipal(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n eq(principalPolicyBundles.principalType, principal.principalType),\n eq(principalPolicyBundles.principalId, principal.principalId),\n );\n}\n\n/** The one current head of a principal. */\nexport function wherePrincipalPolicyCurrent(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(principal),\n eq(principalPolicyBundles.isCurrent, true),\n );\n}\n\nfunction wherePrincipalPolicyBundle(row: {\n readonly principalType: string;\n readonly principalId: string;\n readonly stateHash: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(row),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n );\n}\n\n/** A principal's current head and its retained bundle at `row`'s exact hash, in one read. */\nasync function loadCurrentAndRetainedPolicyBundles(\n tx: ClientSQLiteTransactionScope,\n row: PrincipalPolicyRow,\n) {\n const rows = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(row),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n ),\n ),\n );\n return {\n current: rows.find((stored) => stored.isCurrent),\n retained: rows.find(\n (stored) => !stored.isCurrent && stored.stateHash === row.stateHash,\n ),\n };\n}\n\nfunction policyBundleRow(\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n): PrincipalPolicyRow {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n stateHash: bundle.currentState.stateHash,\n currentStateJson: JSON.stringify(bundle.currentState),\n currentPayloadJson: JSON.stringify(bundle.currentPayload),\n currentProjectionJson: JSON.stringify(bundle.currentProjection),\n currentGrantsJson: JSON.stringify(bundle.currentGrants),\n currentMemberEnvelopesJson: JSON.stringify(bundle.currentMemberEnvelopes),\n previousStatesJson: JSON.stringify(bundle.previousStates),\n updatedAt,\n };\n}\n\nfunction assertNoHeadConflict(\n incoming: StoredPrincipalPolicyHead,\n checkpoint: StoredPrincipalPolicyHead | null,\n): void {\n if (\n checkpoint &&\n incoming.version === checkpoint.version &&\n incoming.stateHash !== checkpoint.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle conflicts with the cached head at one version\",\n );\n }\n}\n\n/**\n * The replaced head stays as a retained bundle when it is an older valid\n * bundle; a corrupt cache row is dropped, never retained as key material.\n */\nasync function retirePrincipalPolicyHead(\n tx: ClientSQLiteTransactionScope,\n storedPolicy: SelectedPrincipalPolicyRow | undefined,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n if (!storedPolicy) {\n return;\n }\n const where = wherePrincipalPolicyBundle(storedPolicy);\n if (isRetainablePolicyHead(storedPolicy, storedHead, incomingHead)) {\n await tx\n .update(principalPolicyBundles)\n .set({ isCurrent: false })\n .where(where)\n .run();\n return;\n }\n await tx.delete(principalPolicyBundles).where(where).run();\n}\n\nfunction isRetainablePolicyHead(\n storedPolicy: SelectedPrincipalPolicyRow,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): boolean {\n if (!storedHead || storedHead.version >= incomingHead.version) {\n return false;\n }\n const row = parsePrincipalPolicyRow(storedPolicy);\n if (!row) {\n return false;\n }\n try {\n parsePrincipalPolicyBundle(row);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function writePrincipalPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n nextRow: PrincipalPolicyRow,\n incomingHead: StoredPrincipalPolicyHead,\n durablePin: Awaited<\n ReturnType<typeof recordPrincipalPolicyBundleOrganizationInTransaction>\n >,\n): Promise<void> {\n const { current: storedPolicy, retained: retainedPolicy } =\n await loadCurrentAndRetainedPolicyBundles(tx, nextRow);\n const durableCheckpoint = durablePin\n ? storedPrincipalPolicyPin(durablePin)\n : null;\n const storedHead = storedPolicy\n ? parseStoredPrincipalPolicyHead(storedPolicy.currentStateJson)\n : null;\n if (\n storedPolicy &&\n storedHead?.version === incomingHead.version &&\n storedHead.stateHash === incomingHead.stateHash\n ) {\n assertSameHeadPrincipalPolicyBundle(storedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n if (retainedPolicy) {\n assertSameHeadPrincipalPolicyBundle(retainedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n }\n const effectiveHead =\n durableCheckpoint &&\n (!storedHead || durableCheckpoint.version >= storedHead.version)\n ? durableCheckpoint\n : storedHead;\n assertNoHeadConflict(incomingHead, storedHead);\n assertNoHeadConflict(incomingHead, durableCheckpoint ?? null);\n if (effectiveHead && incomingHead.version < effectiveHead.version) {\n return;\n }\n\n // Promotion flips the head flag; a retained row at this hash becomes current.\n await retirePrincipalPolicyHead(tx, storedPolicy, storedHead, incomingHead);\n const currentRow = { ...nextRow, isCurrent: true };\n await tx\n .insert(principalPolicyBundles)\n .values(currentRow)\n .onConflictDoUpdate({\n target: [\n principalPolicyBundles.principalType,\n principalPolicyBundles.principalId,\n principalPolicyBundles.stateHash,\n ],\n set: currentRow,\n })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function writePrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const durableCheckpoint =\n await recordPrincipalPolicyBundleOrganizationInTransaction(\n tx,\n bundle,\n organizationId,\n );\n await writePrincipalPolicyBundle(\n tx,\n bundle,\n policyBundleRow(bundle, updatedAt),\n bundle.currentState,\n durableCheckpoint,\n );\n}\n\nexport async function assertPrincipalPolicyBundleStoredInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const expected = policyBundleRow(bundle, bundle.currentState.createdAt);\n const [stored] = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent(expected))\n .limit(1);\n if (!stored) {\n throw new Error(\"Verified principal policy bundle was not persisted\");\n }\n assertSameHeadPrincipalPolicyBundle(stored, expected);\n}\n\nexport async function retainPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const row = policyBundleRow(bundle, updatedAt);\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: row.principalId,\n principalType: row.principalType,\n });\n const { current, retained } = await loadCurrentAndRetainedPolicyBundles(\n tx,\n row,\n );\n const stored = current?.stateHash === row.stateHash ? current : retained;\n if (stored) {\n assertSameHeadPrincipalPolicyBundle(stored, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n await tx\n .insert(principalPolicyBundles)\n .values({ ...row, isCurrent: false })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n"]}
|
|
@@ -3,9 +3,8 @@ import { isPrincipalPolicyBundleResponse, isReferencedPrincipalStateResponse, }
|
|
|
3
3
|
import { and, eq, inArray, or } from "drizzle-orm";
|
|
4
4
|
import { principalPolicyBundleContainsReference, principalPolicyBundleStates, } from "../../principals/principalPolicyStates.js";
|
|
5
5
|
import { principalPolicyBundleReferences, principalPolicyBundles, } from "../../sqlite/schema/index.js";
|
|
6
|
-
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
7
6
|
import { assertSameHeadPrincipalPolicyBundle } from "./principalPolicyBundleIntegrity.js";
|
|
8
|
-
import {
|
|
7
|
+
import { principalPolicyBundleSelection, wherePrincipalPolicyBundlePrincipal, } from "./principalPolicyPersistence.js";
|
|
9
8
|
import { applyPrincipalPolicyReferenceCheckpoint } from "./principalPolicyReferenceCheckpoint.js";
|
|
10
9
|
import { storedPrincipalPolicyBundleFromJson } from "./storedPrincipalPolicyBundle.js";
|
|
11
10
|
function assertUnambiguousBundleChain(bundle) {
|
|
@@ -103,7 +102,7 @@ function selectNewestCandidate(candidates) {
|
|
|
103
102
|
}
|
|
104
103
|
return selected;
|
|
105
104
|
}
|
|
106
|
-
function assertReferenceShape(reference) {
|
|
105
|
+
export function assertReferenceShape(reference) {
|
|
107
106
|
if (!isReferencedPrincipalStateResponse(reference)) {
|
|
108
107
|
throw new KeyingVerificationError("invalid_shape", "principal policy reference is malformed");
|
|
109
108
|
}
|
|
@@ -117,8 +116,7 @@ function assertReferenceShape(reference) {
|
|
|
117
116
|
throw new KeyingVerificationError("invalid_shape", "principal policy reference is malformed");
|
|
118
117
|
}
|
|
119
118
|
}
|
|
120
|
-
async function loadIndexedHeads(
|
|
121
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
119
|
+
async function loadIndexedHeads(db, reference) {
|
|
122
120
|
return db
|
|
123
121
|
.select({
|
|
124
122
|
bundleStateHash: principalPolicyBundleReferences.bundleStateHash,
|
|
@@ -144,11 +142,10 @@ function indexHeadsByHash(heads) {
|
|
|
144
142
|
return new Map(heads.map((head) => [head.bundleStateHash, head]));
|
|
145
143
|
}
|
|
146
144
|
/** The current head and the retained bundles at the referenced or indexed hashes, in one read. */
|
|
147
|
-
async function loadReferencedRows(
|
|
145
|
+
async function loadReferencedRows(db, reference, indexedByHash) {
|
|
148
146
|
// Remote reset deliberately clears mutable heads while retaining historical
|
|
149
147
|
// key material, so an index target can outlive its bundle row. Such a target
|
|
150
148
|
// is only a selection hint; rows that still exist remain authoritative.
|
|
151
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
152
149
|
const rows = await db
|
|
153
150
|
.select(principalPolicyBundleSelection)
|
|
154
151
|
.from(principalPolicyBundles)
|
|
@@ -188,11 +185,13 @@ function collectCandidates(currentRow, retainedRows, indexedByHash, reference) {
|
|
|
188
185
|
}
|
|
189
186
|
return candidates;
|
|
190
187
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
188
|
+
/**
|
|
189
|
+
* The newest stored bundle containing the exact reference, read after the
|
|
190
|
+
* caller checked its shape and ensured the principal policy tables.
|
|
191
|
+
*/
|
|
192
|
+
export async function selectReferencedPrincipalPolicyBundle(db, reference, checkpoint) {
|
|
193
|
+
const indexedByHash = indexHeadsByHash(await loadIndexedHeads(db, reference));
|
|
194
|
+
const { currentRow, retainedRows } = await loadReferencedRows(db, reference, indexedByHash);
|
|
196
195
|
const candidates = collectCandidates(currentRow, retainedRows, indexedByHash, reference);
|
|
197
196
|
const selected = selectNewestCandidate(candidates);
|
|
198
197
|
return selected
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACL,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAE9B,mCAAmC,GACpC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAC/F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAOpF,SAAS,4BAA4B,CACnC,MAAqC;IAErC,MAAM,MAA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IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,OAAgB,EAChB,SAAkC,EAClC,UAA4C;IAE5C,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,aAAa,GAAG,gBAAgB,CACpC,MAAM,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,CAC3C,CAAC;IACF,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,MAAM,kBAAkB,CAC3D,OAAO,EACP,SAAS,EACT,aAAa,CACd,CAAC;IACF,MAAM,UAAU,GAAG,iBAAiB,CAClC,UAAU,EACV,YAAY,EACZ,aAAa,EACb,SAAS,CACV,CAAC;IACF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,OAAO,QAAQ;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../../principals/principalPolicyStates\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n} from \"../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n ensurePrincipalPolicyTables,\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n wherePrincipalPolicyBundlePrincipal,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nfunction assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadIndexedHeads(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\n/** The current head and the retained bundles at the referenced or indexed hashes, in one read. */\nasync function loadReferencedRows(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<{\n currentRow: SelectedPrincipalPolicyRow | undefined;\n retainedRows: SelectedPrincipalPolicyRow[];\n}> {\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(reference),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n inArray(principalPolicyBundles.stateHash, [\n ...new Set([reference.stateHash, ...indexedByHash.keys()]),\n ]),\n ),\n ),\n );\n return {\n currentRow: rows.find((row) => row.isCurrent),\n retainedRows: rows.filter((row) => !row.isCurrent),\n };\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\nexport async function loadPrincipalPolicyBundleForReference(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await ensurePrincipalPolicyTables(execSql);\n const indexedByHash = indexHeadsByHash(\n await loadIndexedHeads(execSql, reference),\n );\n const { currentRow, retainedRows } = await loadReferencedRows(\n execSql,\n reference,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,O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CAAC,GAAG,CAAC,CAAC;QACrC,MAAM,OAAO,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,OAAO,EAAE,CAAC;YACZ,mBAAmB,CAAC,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;QAClD,CAAC;aAAM,IAAI,CAAC,sCAAsC,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,CAAC;YACtE,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,wEAAwE,CACzE,CAAC;QACJ,CAAC;QACD,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IACxC,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,EAAwB,EACxB,SAAkC,EAClC,UAA4C;IAE5C,MAAM,aAAa,GAAG,gBAAgB,CAAC,MAAM,gBAAgB,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC;IAC9E,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,MAAM,kBAAkB,CAC3D,EAAE,EACF,SAAS,EACT,aAAa,CACd,CAAC;IACF,MAAM,UAAU,GAAG,iBAAiB,CAClC,UAAU,EACV,YAAY,EACZ,aAAa,EACb,SAAS,CACV,CAAC;IACF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,OAAO,QAAQ;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../../principals/principalPolicyStates\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n wherePrincipalPolicyBundlePrincipal,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nexport function assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadIndexedHeads(\n db: ClientSQLiteDatabase,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\n/** The current head and the retained bundles at the referenced or indexed hashes, in one read. */\nasync function loadReferencedRows(\n db: ClientSQLiteDatabase,\n reference: ReferencedPrincipalHead,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<{\n currentRow: SelectedPrincipalPolicyRow | undefined;\n retainedRows: SelectedPrincipalPolicyRow[];\n}> {\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(reference),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n inArray(principalPolicyBundles.stateHash, [\n ...new Set([reference.stateHash, ...indexedByHash.keys()]),\n ]),\n ),\n ),\n );\n return {\n currentRow: rows.find((row) => row.isCurrent),\n retainedRows: rows.filter((row) => !row.isCurrent),\n };\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\n/**\n * The newest stored bundle containing the exact reference, read after the\n * caller checked its shape and ensured the principal policy tables.\n */\nexport async function selectReferencedPrincipalPolicyBundle(\n db: ClientSQLiteDatabase,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n const indexedByHash = indexHeadsByHash(await loadIndexedHeads(db, reference));\n const { currentRow, retainedRows } = await loadReferencedRows(\n db,\n reference,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
|