@tearleads/client-sdk 0.1.199 → 0.1.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/principalKeys/principalKeyEnvelopeCandidates.js +4 -16
- package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -1
- package/data/persistence/principalMutationJournalPersistence.d.ts +20 -13
- package/data/persistence/principalMutationJournalPersistence.js +54 -43
- package/data/persistence/principalMutationJournalPersistence.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/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/principalMutations/principalMutationJournalManagement.js +5 -7
- package/workflows/organizations/principalMutations/principalMutationJournalManagement.js.map +1 -1
- package/workflows/organizations/principalMutations/principalMutationJournalSession.js +4 -6
- package/workflows/organizations/principalMutations/principalMutationJournalSession.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/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"heldPrincipalState.js","sourceRoot":"","sources":["heldPrincipalState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,wBAAwB,GAEzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,uBAAuB,EACvB,kCAAkC,GACnC,MAAM,oDAAoD,CAAC;
|
|
1
|
+
{"version":3,"file":"heldPrincipalState.js","sourceRoot":"","sources":["heldPrincipalState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,wBAAwB,GAEzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,uBAAuB,EACvB,kCAAkC,GACnC,MAAM,oDAAoD,CAAC;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BAAsB,CAAC,kBAAkB;KAC9D,CAAC;SACD,IAAI,CAAC,sBAAsB,CAAC;SAC5B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,sBAAsB,CAAC,aAAa,EAAE,IAAI,CAAC,aAAa,CAAC,EAC5D,EAAE,CAAC,sBAAsB,CAAC,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC,EACxD,EAAE,CACA,EAAE,CAAC,sBAAsB,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,EACpD,OAAO,CAAC,sBAAsB,CAAC,SAAS,EAAE,OAAO,CAAC,CACnD,CACF,CACF,CAAC;IACJ,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,KAAK,GAAG,UAAU,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;QAC1D,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;IAC1B,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,EAAwB,EACxB,IAA6B;IAE7B,OAAO,CAAC,MAAM,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,IAAI,WAAW,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;AAClE,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n isPrincipalStateResponse,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport { principalHeadMatchesReference } from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n} from \"../../sqlite/schema\";\nimport {\n principalHistoryEntries,\n principalHistoryEntryStateHashJson,\n} from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\n\n/** Candidate rows per source; equal hashes rarely repeat across scopes. */\nconst HELD_STATE_CANDIDATES = 8;\n\nfunction parsedJson(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\nfunction stateOf(entry: unknown): unknown {\n return entry && typeof entry === \"object\"\n ? Reflect.get(entry, \"state\")\n : null;\n}\n\nfunction exactState(\n state: unknown,\n head: ReferencedPrincipalHead,\n): PrincipalStateResponse | null {\n return isPrincipalStateResponse(state) &&\n principalHeadMatchesReference(state, head)\n ? state\n : null;\n}\n\n/** States this device stored as signed history evidence, by state hash. */\nasync function evidenceState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n const rows = await db\n .select({ entryJson: principalHistoryEntries.entryJson })\n .from(principalHistoryEntries)\n .where(\n eq(\n principalHistoryEntryStateHashJson(principalHistoryEntries.entryJson),\n head.stateHash,\n ),\n )\n .limit(HELD_STATE_CANDIDATES);\n for (const { entryJson } of rows) {\n const state = exactState(stateOf(parsedJson(entryJson)), head);\n if (state) return state;\n }\n return null;\n}\n\n/** A bundle row holds the head itself, or a predecessor at its version index. */\nfunction bundleRowState(\n row: {\n readonly stateHash: string;\n readonly currentStateJson: string;\n readonly previousStatesJson: string;\n },\n head: ReferencedPrincipalHead,\n): unknown {\n if (row.stateHash === head.stateHash) return parsedJson(row.currentStateJson);\n const previous = parsedJson(row.previousStatesJson);\n return Array.isArray(previous) ? stateOf(previous[head.version - 1]) : null;\n}\n\n/**\n * States in a cached policy bundle chain, current or retained: its head, or a\n * predecessor the reference index names.\n */\nasync function bundleState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n const indexed = db\n .selectDistinct({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(principalPolicyBundleReferences.principalType, head.principalType),\n eq(principalPolicyBundleReferences.principalId, head.principalId),\n eq(principalPolicyBundleReferences.version, head.version),\n eq(principalPolicyBundleReferences.stateHash, head.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, head.keyEpoch),\n eq(principalPolicyBundleReferences.keyFingerprint, head.keyFingerprint),\n ),\n )\n .limit(HELD_STATE_CANDIDATES);\n const rows = await db\n .select({\n stateHash: principalPolicyBundles.stateHash,\n currentStateJson: principalPolicyBundles.currentStateJson,\n previousStatesJson: principalPolicyBundles.previousStatesJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(principalPolicyBundles.principalType, head.principalType),\n eq(principalPolicyBundles.principalId, head.principalId),\n or(\n eq(principalPolicyBundles.stateHash, head.stateHash),\n inArray(principalPolicyBundles.stateHash, indexed),\n ),\n ),\n );\n for (const row of rows) {\n const state = exactState(bundleRowState(row, head), head);\n if (state) return state;\n }\n return null;\n}\n\n/** History evidence first, then cached bundle chains; tables already ensured. */\nexport async function selectHeldPrincipalState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n return (await evidenceState(db, head)) ?? bundleState(db, head);\n}\n"]}
|
|
@@ -1,8 +1,4 @@
|
|
|
1
1
|
import { KeyingVerificationError, verifyPrincipalPolicyCheckpoint, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { keyingCheckpointTables } from "../../sqlite/schema/keyingCheckpointSchema.js";
|
|
3
|
-
import { principalPolicyTables } from "../../sqlite/schema/principalPolicySchema.js";
|
|
4
|
-
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
5
|
-
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
6
2
|
import { assertPrincipalPolicyCheckpointShape, loadPrincipalPolicyCheckpointRows, principalPolicyKey, storedPrincipalPolicyPin, upsertPrincipalPolicyCheckpointsInTransaction, } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
|
|
7
3
|
import { storePrincipalGrantRetirements, } from "../principalKeys/principalGrantRetirementPersistence.js";
|
|
8
4
|
import { retainPrincipalPolicyBundleInTransaction, writePrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
|
|
@@ -32,7 +28,8 @@ function validateAcknowledgedPolicy(policy, checkpoint, genesis) {
|
|
|
32
28
|
}
|
|
33
29
|
return true;
|
|
34
30
|
}
|
|
35
|
-
|
|
31
|
+
/** Rejects a batch that repeats a principal or mismatches its verified policy. */
|
|
32
|
+
export async function assertLocallyAcknowledgedPrincipalPolicyBundles(entries) {
|
|
36
33
|
const seen = new Set();
|
|
37
34
|
for (const { policy } of entries) {
|
|
38
35
|
const key = principalPolicyKey(policy);
|
|
@@ -41,6 +38,7 @@ function assertUniqueAcknowledgedPolicies(entries) {
|
|
|
41
38
|
}
|
|
42
39
|
seen.add(key);
|
|
43
40
|
}
|
|
41
|
+
await Promise.all(entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)));
|
|
44
42
|
}
|
|
45
43
|
async function loadValidatedAcknowledgedCheckpoints(tx, entries, genesis) {
|
|
46
44
|
const stored = await loadPrincipalPolicyCheckpointRows(tx, entries.map(({ policy }) => policy));
|
|
@@ -52,67 +50,18 @@ async function loadValidatedAcknowledgedCheckpoints(tx, entries, genesis) {
|
|
|
52
50
|
}
|
|
53
51
|
return checkpoints;
|
|
54
52
|
}
|
|
55
|
-
async function
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
if (input.retiredContainers)
|
|
66
|
-
await storePrincipalGrantRetirements(tx, input.retiredContainers, input.entries.map(({ policy }) => policy), input.organizationId);
|
|
67
|
-
for (const entry of input.entries) {
|
|
68
|
-
if (input.placement !== "history") {
|
|
69
|
-
await writePrincipalPolicyBundleInTransaction(tx, entry.bundle, input.updatedAt, input.organizationId);
|
|
70
|
-
}
|
|
71
|
-
else {
|
|
72
|
-
await retainPrincipalPolicyBundleInTransaction(tx, entry.bundle, input.updatedAt, input.organizationId);
|
|
73
|
-
}
|
|
53
|
+
export async function storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(tx, input, updatedAt) {
|
|
54
|
+
const checkpoints = await loadValidatedAcknowledgedCheckpoints(tx, input.entries, input.placement === "genesis");
|
|
55
|
+
if (input.retiredContainers)
|
|
56
|
+
await storePrincipalGrantRetirements(tx, input.retiredContainers, input.entries.map(({ policy }) => policy), input.organizationId);
|
|
57
|
+
for (const entry of input.entries) {
|
|
58
|
+
if (input.placement !== "history") {
|
|
59
|
+
await writePrincipalPolicyBundleInTransaction(tx, entry.bundle, updatedAt, input.organizationId);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
await retainPrincipalPolicyBundleInTransaction(tx, entry.bundle, updatedAt, input.organizationId);
|
|
74
63
|
}
|
|
75
|
-
await upsertPrincipalPolicyCheckpointsInTransaction(tx, checkpoints, input.updatedAt, input.organizationId);
|
|
76
|
-
};
|
|
77
|
-
if (input.stillCurrent) {
|
|
78
|
-
await runtime.guardedTransaction(store, input.stillCurrent, {
|
|
79
|
-
behavior: "immediate",
|
|
80
|
-
});
|
|
81
|
-
return;
|
|
82
64
|
}
|
|
83
|
-
await
|
|
84
|
-
}
|
|
85
|
-
/** Atomically pins and caches exact full policy bundles acknowledged by the API. */
|
|
86
|
-
export function persistLocallyAcknowledgedPrincipalPolicyBundles(input) {
|
|
87
|
-
return storeAcknowledgedPrincipalPolicyBundles({
|
|
88
|
-
...input,
|
|
89
|
-
placement: "current",
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
export function persistLocallyAcknowledgedPrincipalPolicyBundle(input) {
|
|
93
|
-
return persistLocallyAcknowledgedPrincipalPolicyBundles({
|
|
94
|
-
entries: [input],
|
|
95
|
-
execSql: input.execSql,
|
|
96
|
-
organizationId: input.organizationId,
|
|
97
|
-
stillCurrent: input.stillCurrent,
|
|
98
|
-
updatedAt: input.updatedAt,
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* Seed a provisioning acknowledgement without making genesis current again.
|
|
103
|
-
* The cache writer still checks ownership, equal-version forks and retained
|
|
104
|
-
* same-hash bundle integrity, and preserves any newer cached policy head.
|
|
105
|
-
*/
|
|
106
|
-
export function seedLocallyAcknowledgedPrincipalPolicyBundles(input) {
|
|
107
|
-
return storeAcknowledgedPrincipalPolicyBundles({
|
|
108
|
-
...input,
|
|
109
|
-
placement: "genesis",
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
export function retainLocallyAcknowledgedPrincipalPolicyBundles(input) {
|
|
113
|
-
return storeAcknowledgedPrincipalPolicyBundles({
|
|
114
|
-
...input,
|
|
115
|
-
placement: "history",
|
|
116
|
-
});
|
|
65
|
+
await upsertPrincipalPolicyCheckpointsInTransaction(tx, checkpoints, updatedAt, input.organizationId);
|
|
117
66
|
}
|
|
118
67
|
//# sourceMappingURL=locallyAcknowledgedPrincipalPolicyPersistence.js.map
|
package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"locallyAcknowledgedPrincipalPolicyPersistence.js","sourceRoot":"","sources":["locallyAcknowledgedPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,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,EACL,oCAAoC,EACpC,iCAAiC,EACjC,kBAAkB,EAClB,wBAAwB,EACxB,6CAA6C,GAC9C,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAEL,8BAA8B,GAC/B,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EACL,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OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC9D,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,gDAAgD,CAAC,KAMhE;IACC,OAAO,uCAAuC,CAAC;QAC7C,GAAG,KAAK;QACR,SAAS,EAAE,SAAS;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,+CAA+C,CAC7D,KAKC;IAED,OAAO,gDAAgD,CAAC;QACtD,OAAO,EAAE,CAAC,KAAK,CAAC;QAChB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,6CAA6C,CAC3D,KAA6E;IAE7E,OAAO,uCAAuC,CAAC;QAC7C,GAAG,KAAK;QACR,SAAS,EAAE,SAAS;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,+CAA+C,CAAC,KAS/D;IACC,OAAO,uCAAuC,CAAC;QAC7C,GAAG,KAAK;QACR,SAAS,EAAE,SAAS;KACrB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\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 {\n assertPrincipalPolicyCheckpointShape,\n loadPrincipalPolicyCheckpointRows,\n principalPolicyKey,\n storedPrincipalPolicyPin,\n upsertPrincipalPolicyCheckpointsInTransaction,\n} from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n type AcknowledgedPrincipalGrantRetirements,\n storePrincipalGrantRetirements,\n} from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n retainPrincipalPolicyBundleInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nfunction validateAcknowledgedPolicy(\n policy: VerifiedPrincipalPolicy,\n checkpoint: PrincipalPolicyCheckpoint | null,\n genesis: boolean,\n): boolean {\n if (genesis) {\n if (policy.version !== 1 || policy.state.prevStateHash !== null) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"registration policy must begin at version 1\",\n );\n }\n if (checkpoint) assertPrincipalPolicyCheckpointShape(checkpoint, policy);\n // Adoption never advances a newer pin back to genesis. Equal versions\n // still pass through the normal fork check below.\n if (checkpoint && checkpoint.version > policy.version) return false;\n }\n verifyPrincipalPolicyCheckpoint({\n chain: policy.history ?? [],\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n if (!checkpoint && policy.version !== 1) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged principal policy does not begin at version 1\",\n );\n }\n if (checkpoint && policy.version > checkpoint.version + 1) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged principal policy does not directly extend the durable checkpoint\",\n );\n }\n return true;\n}\n\ninterface LocallyAcknowledgedPrincipalPolicyBundle {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nfunction assertUniqueAcknowledgedPolicies(\n entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[],\n): void {\n const seen = new Set<string>();\n for (const { policy } of entries) {\n const key = principalPolicyKey(policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `locally acknowledged policy batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n}\n\nasync function loadValidatedAcknowledgedCheckpoints(\n tx: ClientSQLiteTransactionScope,\n entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[],\n genesis: boolean,\n): Promise<PrincipalPolicyCheckpoint[]> {\n const stored = await loadPrincipalPolicyCheckpointRows(\n tx,\n entries.map(({ policy }) => policy),\n );\n const checkpoints: PrincipalPolicyCheckpoint[] = [];\n for (const { policy } of entries) {\n const pin = storedPrincipalPolicyPin(\n stored.get(principalPolicyKey(policy)),\n );\n if (\n validateAcknowledgedPolicy(\n policy,\n pin ? { ...policy.checkpoint, ...pin } : null,\n genesis,\n )\n )\n checkpoints.push(policy.checkpoint);\n }\n return checkpoints;\n}\n\nasync function storeAcknowledgedPrincipalPolicyBundles(input: {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly placement: \"current\" | \"history\" | \"genesis\";\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n assertUniqueAcknowledgedPolicies(input.entries);\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const store = async (tx: ClientSQLiteTransactionScope) => {\n const checkpoints = await loadValidatedAcknowledgedCheckpoints(\n tx,\n input.entries,\n input.placement === \"genesis\",\n );\n if (input.retiredContainers)\n await storePrincipalGrantRetirements(\n tx,\n input.retiredContainers,\n input.entries.map(({ policy }) => policy),\n input.organizationId,\n );\n for (const entry of input.entries) {\n if (input.placement !== \"history\") {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n } else {\n await retainPrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n }\n }\n await upsertPrincipalPolicyCheckpointsInTransaction(\n tx,\n checkpoints,\n input.updatedAt,\n input.organizationId,\n );\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(store, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(store, { behavior: \"immediate\" });\n}\n\n/** Atomically pins and caches exact full policy bundles acknowledged by the API. */\nexport function persistLocallyAcknowledgedPrincipalPolicyBundles(input: {\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n return storeAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n}\n\nexport function persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n },\n): Promise<void> {\n return persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: input.updatedAt,\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 */\nexport function seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: Parameters<typeof persistLocallyAcknowledgedPrincipalPolicyBundles>[0],\n): Promise<void> {\n return storeAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n}\n\nexport function retainLocallyAcknowledgedPrincipalPolicyBundles(input: {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n return storeAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"locallyAcknowledgedPrincipalPolicyPersistence.js","sourceRoot":"","sources":["locallyAcknowledgedPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,oCAAoC,EACpC,iCAAiC,EACjC,kBAAkB,EAClB,wBAAwB,EACxB,6CAA6C,GAC9C,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAEL,8BAA8B,GAC/B,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EACL,wCAAwC,EACxC,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAEpF,SAAS,0BAA0B,CACjC,MAA+B,EAC/B,UAA4C,EAC5C,OAAgB;IAEhB,IAAI,OAAO,EAAE,CAAC;QACZ,IAAI,MAAM,CAAC,OAAO,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,aAAa,KAAK,IAAI,EAAE,CAAC;YAChE,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,6CAA6C,CAC9C,CAAC;QACJ,CAAC;QACD,IAAI,UAAU;YAAE,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QACzE,sEAAsE;QACtE,kDAAkD;QAClD,IAAI,UAAU,IAAI,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;YAAE,OAAO,KAAK,CAAC;IACtE,CAAC;IACD,+BAA+B,CAAC;QAC9B,KAAK,EAAE,MAAM,CAAC,OAAO,IAAI,EAAE;QAC3B,YAAY,EAAE,MAAM,CAAC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AC;IACD,MAAM,6CAA6C,CACjD,EAAE,EACF,WAAW,EACX,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n assertPrincipalPolicyCheckpointShape,\n loadPrincipalPolicyCheckpointRows,\n principalPolicyKey,\n storedPrincipalPolicyPin,\n upsertPrincipalPolicyCheckpointsInTransaction,\n} from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n type AcknowledgedPrincipalGrantRetirements,\n storePrincipalGrantRetirements,\n} from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n retainPrincipalPolicyBundleInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nfunction validateAcknowledgedPolicy(\n policy: VerifiedPrincipalPolicy,\n checkpoint: PrincipalPolicyCheckpoint | null,\n genesis: boolean,\n): boolean {\n if (genesis) {\n if (policy.version !== 1 || policy.state.prevStateHash !== null) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"registration policy must begin at version 1\",\n );\n }\n if (checkpoint) assertPrincipalPolicyCheckpointShape(checkpoint, policy);\n // Adoption never advances a newer pin back to genesis. Equal versions\n // still pass through the normal fork check below.\n if (checkpoint && checkpoint.version > policy.version) return false;\n }\n verifyPrincipalPolicyCheckpoint({\n chain: policy.history ?? [],\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n if (!checkpoint && policy.version !== 1) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged principal policy does not begin at version 1\",\n );\n }\n if (checkpoint && policy.version > checkpoint.version + 1) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged principal policy does not directly extend the durable checkpoint\",\n );\n }\n return true;\n}\n\nexport interface LocallyAcknowledgedPrincipalPolicyBundle {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/** An acknowledged batch; a false `stillCurrent` refuses its commit. */\nexport interface LocallyAcknowledgedPrincipalPolicyBundles {\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/**\n * Where a batch lands: `current` and `genesis` write heads, `history` only\n * retains them; `genesis` never moves a newer pin back to version 1.\n */\nexport interface LocallyAcknowledgedPrincipalPolicyStore {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly organizationId?: string | undefined;\n readonly placement: \"current\" | \"history\" | \"genesis\";\n}\n\n/** Rejects a batch that repeats a principal or mismatches its verified policy. */\nexport async function assertLocallyAcknowledgedPrincipalPolicyBundles(\n entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[],\n): Promise<void> {\n const seen = new Set<string>();\n for (const { policy } of entries) {\n const key = principalPolicyKey(policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `locally acknowledged policy batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n}\n\nasync function loadValidatedAcknowledgedCheckpoints(\n tx: ClientSQLiteTransactionScope,\n entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[],\n genesis: boolean,\n): Promise<PrincipalPolicyCheckpoint[]> {\n const stored = await loadPrincipalPolicyCheckpointRows(\n tx,\n entries.map(({ policy }) => policy),\n );\n const checkpoints: PrincipalPolicyCheckpoint[] = [];\n for (const { policy } of entries) {\n const pin = storedPrincipalPolicyPin(\n stored.get(principalPolicyKey(policy)),\n );\n if (\n validateAcknowledgedPolicy(\n policy,\n pin ? { ...policy.checkpoint, ...pin } : null,\n genesis,\n )\n )\n checkpoints.push(policy.checkpoint);\n }\n return checkpoints;\n}\n\nexport async function storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: LocallyAcknowledgedPrincipalPolicyStore,\n updatedAt: string,\n): Promise<void> {\n const checkpoints = await loadValidatedAcknowledgedCheckpoints(\n tx,\n input.entries,\n input.placement === \"genesis\",\n );\n if (input.retiredContainers)\n await storePrincipalGrantRetirements(\n tx,\n input.retiredContainers,\n input.entries.map(({ policy }) => policy),\n input.organizationId,\n );\n for (const entry of input.entries) {\n if (input.placement !== \"history\") {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n updatedAt,\n input.organizationId,\n );\n } else {\n await retainPrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n updatedAt,\n input.organizationId,\n );\n }\n }\n await upsertPrincipalPolicyCheckpointsInTransaction(\n tx,\n checkpoints,\n updatedAt,\n input.organizationId,\n );\n}\n"]}
|
|
@@ -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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AI,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
|