@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,196 @@
|
|
|
1
|
+
import { and, eq, inArray, or } from "drizzle-orm";
|
|
2
|
+
import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../../sqlite/schema/trustedUserIdentityPinSchema.js";
|
|
3
|
+
import { sqliteRowsPerStatement } from "../../sqlite/sqliteBindBudget.js";
|
|
4
|
+
import { registerClientSQLiteCommitGuard } from "../../sqlite/sqliteCommitGuards.js";
|
|
5
|
+
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
|
+
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
7
|
+
import { assertCandidatePin, differingPinFields, parseStoredPin, provenanceRank, TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, validationFailure, } from "./trustedUserIdentityPinModel.js";
|
|
8
|
+
import { runTrustedUserIdentityPinTransaction } from "./trustedUserIdentityPinTransaction.js";
|
|
9
|
+
const pins = trustedUserIdentityPins;
|
|
10
|
+
// Each member binds one ID; the trust domain binds once per statement.
|
|
11
|
+
const PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);
|
|
12
|
+
/**
|
|
13
|
+
* Durable trusted identity pins on one SQLite executor. Callers build it from
|
|
14
|
+
* the executor in hand at each call; it holds no other state.
|
|
15
|
+
*/
|
|
16
|
+
export class TrustedUserIdentityPinRepository {
|
|
17
|
+
execSql;
|
|
18
|
+
constructor(execSql) {
|
|
19
|
+
this.execSql = execSql;
|
|
20
|
+
}
|
|
21
|
+
async loadTrustedUserIdentityPin(input) {
|
|
22
|
+
const scope = {
|
|
23
|
+
identityTrustDomain: input.identityTrustDomain,
|
|
24
|
+
userId: input.userId,
|
|
25
|
+
};
|
|
26
|
+
await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
|
|
27
|
+
return selectStoredPin(getClientSQLitePersistenceRuntime(this.execSql).db, scope);
|
|
28
|
+
}
|
|
29
|
+
/** Read immutable pins together, never exposing another adapter's uncommitted rows. */
|
|
30
|
+
async loadTrustedUserIdentityPins(input) {
|
|
31
|
+
const userIds = [...new Set(input.userIds)];
|
|
32
|
+
if (userIds.length === 0)
|
|
33
|
+
return new Map();
|
|
34
|
+
await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
|
|
35
|
+
const runtime = getClientSQLitePersistenceRuntime(this.execSql);
|
|
36
|
+
return runTrustedUserIdentityPinTransaction(() => runtime.transaction(async (tx) => {
|
|
37
|
+
const loaded = new Map();
|
|
38
|
+
for (let start = 0; start < userIds.length; start += PIN_READ_BATCH_SIZE) {
|
|
39
|
+
const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);
|
|
40
|
+
const rows = await tx
|
|
41
|
+
.select()
|
|
42
|
+
.from(pins)
|
|
43
|
+
.where(and(eq(pins.identityTrustDomain, input.identityTrustDomain), inArray(pins.userId, batch)));
|
|
44
|
+
for (const row of rows) {
|
|
45
|
+
const pin = parseStoredPin(row, {
|
|
46
|
+
identityTrustDomain: input.identityTrustDomain,
|
|
47
|
+
userId: row.userId,
|
|
48
|
+
});
|
|
49
|
+
loaded.set(pin.userId, pin);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return loaded;
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The user a signing key is already bound to in this trust domain, if any.
|
|
57
|
+
* Each key has at most one such user: the reverse binding is unique.
|
|
58
|
+
*/
|
|
59
|
+
async loadTrustedUserIdForSigningKey(input) {
|
|
60
|
+
await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
|
|
61
|
+
const rows = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
62
|
+
.db.select({ userId: pins.userId })
|
|
63
|
+
.from(pins)
|
|
64
|
+
.where(and(eq(pins.identityTrustDomain, input.identityTrustDomain), eq(pins.signingKeyFingerprint, input.signingKeyFingerprint)))
|
|
65
|
+
.limit(1);
|
|
66
|
+
return rows[0]?.userId ?? null;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Atomically establishes or verifies a durable identity pin.
|
|
70
|
+
*
|
|
71
|
+
* The immediate transaction serializes first contact across SDK instances that
|
|
72
|
+
* share the SQLite database. Conflict handling never replaces the existing
|
|
73
|
+
* keys: the winning pin is re-read and every identity field is compared before
|
|
74
|
+
* this method returns. When the keys match and the candidate's provenance
|
|
75
|
+
* ranks higher (an identity link confirming an observed pin), only the
|
|
76
|
+
* provenance is raised; it is never lowered.
|
|
77
|
+
*
|
|
78
|
+
* `assertCurrent` is the caller's lifetime check. It guards the write
|
|
79
|
+
* transaction's COMMIT, so an operation whose account or database changed
|
|
80
|
+
* while it awaited SQLite rolls its pin back instead of committing it.
|
|
81
|
+
*/
|
|
82
|
+
async compareOrInsertTrustedUserIdentityPin(input) {
|
|
83
|
+
const [stored] = await this.compareOrInsertTrustedUserIdentityPins({
|
|
84
|
+
assertCurrent: input.assertCurrent,
|
|
85
|
+
pins: [input.pin],
|
|
86
|
+
});
|
|
87
|
+
if (!stored)
|
|
88
|
+
throw new TrustedUserIdentityPinCorruptError(input.pin, "pin not stored");
|
|
89
|
+
return stored;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Compare-or-insert a set of pins in one write transaction: a conflict on any
|
|
93
|
+
* pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.
|
|
94
|
+
*/
|
|
95
|
+
async compareOrInsertTrustedUserIdentityPins(input) {
|
|
96
|
+
const { assertCurrent = () => { } } = input;
|
|
97
|
+
for (const pin of input.pins)
|
|
98
|
+
assertCandidatePin(pin);
|
|
99
|
+
const runtime = getClientSQLitePersistenceRuntime(this.execSql);
|
|
100
|
+
return runTrustedUserIdentityPinTransaction(async () => {
|
|
101
|
+
await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
|
|
102
|
+
// Like the write path's BEGIN, this read's BEGIN retries while any adapter
|
|
103
|
+
// holds the connection's transaction, so it never sees uncommitted pins.
|
|
104
|
+
const pinned = await runtime.transaction(async (tx) => {
|
|
105
|
+
const matched = [];
|
|
106
|
+
for (const pin of input.pins) {
|
|
107
|
+
const stored = await matchingPin(tx, pin);
|
|
108
|
+
if (!stored)
|
|
109
|
+
return null;
|
|
110
|
+
matched.push(stored);
|
|
111
|
+
}
|
|
112
|
+
return matched;
|
|
113
|
+
});
|
|
114
|
+
if (pinned)
|
|
115
|
+
return pinned;
|
|
116
|
+
return runtime.transaction(async (tx) => {
|
|
117
|
+
registerClientSQLiteCommitGuard(this.execSql, assertCurrent);
|
|
118
|
+
const stored = [];
|
|
119
|
+
for (const pin of input.pins)
|
|
120
|
+
stored.push(await writePin(tx, pin));
|
|
121
|
+
return stored;
|
|
122
|
+
}, { behavior: "immediate" });
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
async function selectStoredPin(db, scope) {
|
|
127
|
+
const rows = await db
|
|
128
|
+
.select()
|
|
129
|
+
.from(pins)
|
|
130
|
+
.where(and(eq(pins.identityTrustDomain, scope.identityTrustDomain), eq(pins.userId, scope.userId)))
|
|
131
|
+
.limit(1);
|
|
132
|
+
const row = rows[0];
|
|
133
|
+
return row ? parseStoredPin(row, scope) : null;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* One read answers an exact repeat of a pin that alone holds its
|
|
137
|
+
* key and ranks at or above the candidate; anything else returns null for the
|
|
138
|
+
* write transaction. Pins are never deleted, keys never change, and
|
|
139
|
+
* provenance only rises, so a match is what the transaction would return.
|
|
140
|
+
*/
|
|
141
|
+
async function matchingPin(db, pin) {
|
|
142
|
+
const [row, other] = await db
|
|
143
|
+
.select()
|
|
144
|
+
.from(pins)
|
|
145
|
+
.where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), or(eq(pins.userId, pin.userId), eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint))))
|
|
146
|
+
.limit(2);
|
|
147
|
+
if (other || row?.userId !== pin.userId || validationFailure(row))
|
|
148
|
+
return null;
|
|
149
|
+
const stored = parseStoredPin(row, pin);
|
|
150
|
+
const rank = provenanceRank;
|
|
151
|
+
if (differingPinFields(stored, pin).length > 0)
|
|
152
|
+
return null;
|
|
153
|
+
return rank[pin.provenance] <= rank[stored.provenance] ? stored : null;
|
|
154
|
+
}
|
|
155
|
+
async function writePin(tx, pin) {
|
|
156
|
+
const aliases = await tx
|
|
157
|
+
.select()
|
|
158
|
+
.from(pins)
|
|
159
|
+
.where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint)))
|
|
160
|
+
.limit(1);
|
|
161
|
+
const alias = aliases[0];
|
|
162
|
+
if (alias && alias.userId !== pin.userId) {
|
|
163
|
+
throw new TrustedUserIdentityPinMismatchError(parseStoredPin(alias, {
|
|
164
|
+
identityTrustDomain: pin.identityTrustDomain,
|
|
165
|
+
userId: alias.userId,
|
|
166
|
+
}), pin, ["userId"]);
|
|
167
|
+
}
|
|
168
|
+
// Targets the primary key only: re-pinning the same user is a no-op,
|
|
169
|
+
// but a write that would bind this key to a second user must fail at
|
|
170
|
+
// the unique index rather than be silently skipped.
|
|
171
|
+
await tx
|
|
172
|
+
.insert(pins)
|
|
173
|
+
.values(pin)
|
|
174
|
+
.onConflictDoNothing({
|
|
175
|
+
target: [pins.identityTrustDomain, pins.userId],
|
|
176
|
+
})
|
|
177
|
+
.run();
|
|
178
|
+
const stored = await selectStoredPin(tx, pin);
|
|
179
|
+
if (!stored) {
|
|
180
|
+
throw new TrustedUserIdentityPinCorruptError(pin, "row is missing after compare-or-insert");
|
|
181
|
+
}
|
|
182
|
+
const differingFields = differingPinFields(stored, pin);
|
|
183
|
+
if (differingFields.length > 0) {
|
|
184
|
+
throw new TrustedUserIdentityPinMismatchError(stored, pin, differingFields);
|
|
185
|
+
}
|
|
186
|
+
if (provenanceRank[pin.provenance] <= provenanceRank[stored.provenance]) {
|
|
187
|
+
return stored;
|
|
188
|
+
}
|
|
189
|
+
await tx
|
|
190
|
+
.update(pins)
|
|
191
|
+
.set({ provenance: pin.provenance })
|
|
192
|
+
.where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), eq(pins.userId, pin.userId)))
|
|
193
|
+
.run();
|
|
194
|
+
return { ...stored, provenance: pin.provenance };
|
|
195
|
+
}
|
|
196
|
+
//# sourceMappingURL=trustedUserIdentityPinRepository.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trustedUserIdentityPinRepository.js","sourceRoot":"","sources":["trustedUserIdentityPinRepository.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAGL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAElB,cAAc,EACd,cAAc,EAEd,kCAAkC,EAClC,mCAAmC,EACnC,iBAAiB,GAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,oCAAoC,EAAE,MAAM,qCAAqC,CAAC;AAE3F,MAAM,IAAI,GAAG,uBAAuB,CAAC;AAErC,uEAAuE;AACvE,MAAM,mBAAmB,GAAG,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAEzD;;;GAGG;AACH,MAAM,OAAO,gCAAgC;IAC1B,OAAO,CAAU;IAElC,YAAY,OAAgB;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,0BAA0B,CAC9B,KAAe;QAEf,MAAM,KAAK,GAAa;YACtB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM,EAAE,KAAK,CAAC,MAAM;SACrB,CAAC;QACF,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE,4BAA4B,CAAC,CAAC;QAClE,OAAO,eAAe,CACpB,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,EAClD,KAAK,CACN,CAAC;IACJ,CAAC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zC,CAAC;IACJ,CAAC;IAED,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACxD,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,mCAAmC,CAAC,MAAM,EAAE,GAAG,EAAE,eAAe,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,cAAc,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;QACxE,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,IAAI,CAAC;SACZ,GAAG,CAAC,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC;SACnC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,IAAI,CAAC,mBAAmB,EAAE,GAAG,CAAC,mBAAmB,CAAC,EACrD,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAC5B,CACF;SACA,GAAG,EAAE,CAAC;IACT,OAAO,EAAE,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC;AACnD,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../../sqlite/schema/trustedUserIdentityPinSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n assertCandidatePin,\n differingPinFields,\n type PinScope,\n parseStoredPin,\n provenanceRank,\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n validationFailure,\n} from \"./trustedUserIdentityPinModel\";\nimport { runTrustedUserIdentityPinTransaction } from \"./trustedUserIdentityPinTransaction\";\n\nconst pins = trustedUserIdentityPins;\n\n// Each member binds one ID; the trust domain binds once per statement.\nconst PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\n/**\n * Durable trusted identity pins on one SQLite executor. Callers build it from\n * the executor in hand at each call; it holds no other state.\n */\nexport class TrustedUserIdentityPinRepository {\n private readonly execSql: ExecSql;\n\n constructor(execSql: ExecSql) {\n this.execSql = execSql;\n }\n\n async loadTrustedUserIdentityPin(\n input: PinScope,\n ): Promise<TrustedUserIdentityPin | null> {\n const scope: PinScope = {\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n };\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n return selectStoredPin(\n getClientSQLitePersistenceRuntime(this.execSql).db,\n scope,\n );\n }\n\n /** Read immutable pins together, never exposing another adapter's uncommitted rows. */\n async loadTrustedUserIdentityPins(input: {\n readonly identityTrustDomain: string;\n readonly userIds: readonly string[];\n }): Promise<ReadonlyMap<string, TrustedUserIdentityPin>> {\n const userIds = [...new Set(input.userIds)];\n if (userIds.length === 0) return new Map();\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n return runTrustedUserIdentityPinTransaction(() =>\n runtime.transaction(async (tx) => {\n const loaded = new Map<string, TrustedUserIdentityPin>();\n for (\n let start = 0;\n start < userIds.length;\n start += PIN_READ_BATCH_SIZE\n ) {\n const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);\n const rows = await tx\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, input.identityTrustDomain),\n inArray(pins.userId, batch),\n ),\n );\n for (const row of rows) {\n const pin = parseStoredPin(row, {\n identityTrustDomain: input.identityTrustDomain,\n userId: row.userId,\n });\n loaded.set(pin.userId, pin);\n }\n }\n return loaded;\n }),\n );\n }\n\n /**\n * The user a signing key is already bound to in this trust domain, if any.\n * Each key has at most one such user: the reverse binding is unique.\n */\n async loadTrustedUserIdForSigningKey(input: {\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ userId: pins.userId })\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, input.identityTrustDomain),\n eq(pins.signingKeyFingerprint, input.signingKeyFingerprint),\n ),\n )\n .limit(1);\n return rows[0]?.userId ?? null;\n }\n\n /**\n * Atomically establishes or verifies a durable identity pin.\n *\n * The immediate transaction serializes first contact across SDK instances that\n * share the SQLite database. Conflict handling never replaces the existing\n * keys: the winning pin is re-read and every identity field is compared before\n * this method returns. When the keys match and the candidate's provenance\n * ranks higher (an identity link confirming an observed pin), only the\n * provenance is raised; it is never lowered.\n *\n * `assertCurrent` is the caller's lifetime check. It guards the write\n * transaction's COMMIT, so an operation whose account or database changed\n * while it awaited SQLite rolls its pin back instead of committing it.\n */\n async compareOrInsertTrustedUserIdentityPin(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly pin: TrustedUserIdentityPin;\n }): Promise<TrustedUserIdentityPin> {\n const [stored] = await this.compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: [input.pin],\n });\n if (!stored)\n throw new TrustedUserIdentityPinCorruptError(input.pin, \"pin not stored\");\n return stored;\n }\n\n /**\n * Compare-or-insert a set of pins in one write transaction: a conflict on any\n * pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.\n */\n async compareOrInsertTrustedUserIdentityPins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly pins: readonly TrustedUserIdentityPin[];\n }): Promise<TrustedUserIdentityPin[]> {\n const { assertCurrent = () => {} } = input;\n for (const pin of input.pins) assertCandidatePin(pin);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n return runTrustedUserIdentityPinTransaction(async () => {\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n // Like the write path's BEGIN, this read's BEGIN retries while any adapter\n // holds the connection's transaction, so it never sees uncommitted pins.\n const pinned = await runtime.transaction(async (tx) => {\n const matched: TrustedUserIdentityPin[] = [];\n for (const pin of input.pins) {\n const stored = await matchingPin(tx, pin);\n if (!stored) return null;\n matched.push(stored);\n }\n return matched;\n });\n if (pinned) return pinned;\n return runtime.transaction(\n async (tx) => {\n registerClientSQLiteCommitGuard(this.execSql, assertCurrent);\n const stored: TrustedUserIdentityPin[] = [];\n for (const pin of input.pins) stored.push(await writePin(tx, pin));\n return stored;\n },\n { behavior: \"immediate\" },\n );\n });\n }\n}\n\nasync function selectStoredPin(\n db: ClientSQLiteDatabase | ClientSQLiteTransactionScope,\n scope: PinScope,\n): Promise<TrustedUserIdentityPin | null> {\n const rows = await db\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, scope.identityTrustDomain),\n eq(pins.userId, scope.userId),\n ),\n )\n .limit(1);\n const row = rows[0];\n return row ? parseStoredPin(row, scope) : null;\n}\n\n/**\n * One read answers an exact repeat of a pin that alone holds its\n * key and ranks at or above the candidate; anything else returns null for the\n * write transaction. Pins are never deleted, keys never change, and\n * provenance only rises, so a match is what the transaction would return.\n */\nasync function matchingPin(\n db: ClientSQLiteTransactionScope,\n pin: TrustedUserIdentityPin,\n): Promise<TrustedUserIdentityPin | null> {\n const [row, other] = await db\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n or(\n eq(pins.userId, pin.userId),\n eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint),\n ),\n ),\n )\n .limit(2);\n if (other || row?.userId !== pin.userId || validationFailure(row))\n return null;\n const stored = parseStoredPin(row, pin);\n const rank = provenanceRank;\n if (differingPinFields(stored, pin).length > 0) return null;\n return rank[pin.provenance] <= rank[stored.provenance] ? stored : null;\n}\n\nasync function writePin(\n tx: ClientSQLiteTransactionScope,\n pin: TrustedUserIdentityPin,\n): Promise<TrustedUserIdentityPin> {\n const aliases = await tx\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint),\n ),\n )\n .limit(1);\n const alias = aliases[0];\n if (alias && alias.userId !== pin.userId) {\n throw new TrustedUserIdentityPinMismatchError(\n parseStoredPin(alias, {\n identityTrustDomain: pin.identityTrustDomain,\n userId: alias.userId,\n }),\n pin,\n [\"userId\"],\n );\n }\n // Targets the primary key only: re-pinning the same user is a no-op,\n // but a write that would bind this key to a second user must fail at\n // the unique index rather than be silently skipped.\n await tx\n .insert(pins)\n .values(pin)\n .onConflictDoNothing({\n target: [pins.identityTrustDomain, pins.userId],\n })\n .run();\n\n const stored = await selectStoredPin(tx, pin);\n if (!stored) {\n throw new TrustedUserIdentityPinCorruptError(\n pin,\n \"row is missing after compare-or-insert\",\n );\n }\n\n const differingFields = differingPinFields(stored, pin);\n if (differingFields.length > 0) {\n throw new TrustedUserIdentityPinMismatchError(stored, pin, differingFields);\n }\n if (provenanceRank[pin.provenance] <= provenanceRank[stored.provenance]) {\n return stored;\n }\n await tx\n .update(pins)\n .set({ provenance: pin.provenance })\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n eq(pins.userId, pin.userId),\n ),\n )\n .run();\n return { ...stored, provenance: pin.provenance };\n}\n"]}
|
|
@@ -1,24 +1,12 @@
|
|
|
1
1
|
import { isCurrentPrincipalMemberEnvelopesResponse, } from "../../../internal/validators/response/index.js";
|
|
2
2
|
import { and, desc, eq, sql } from "drizzle-orm";
|
|
3
3
|
import { principalCurrentFingerprintJson, principalStateFingerprintJson, } from "../../sqlite/principalKeyFingerprintJson.js";
|
|
4
|
-
import {
|
|
4
|
+
import { principalHistoryPrefixes } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
|
|
5
5
|
import { principalKeyEnvelopeArchive } from "../../sqlite/schema/principalHistoryRetentionSchema.js";
|
|
6
6
|
import { principalHistoryStages } from "../../sqlite/schema/principalHistoryStageSchema.js";
|
|
7
|
-
import { principalPolicyBundles
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Untrusted encrypted key candidates, never authorization evidence. The actual
|
|
12
|
-
* private key must open the requested recipient wrap; the projection verifier
|
|
13
|
-
* separately checks the signed KEK material identity and all policy authority.
|
|
14
|
-
* Read only envelopes for the requested fingerprints, never signed histories.
|
|
15
|
-
*/
|
|
16
|
-
export async function loadPrincipalKeyEnvelopeCandidates(execSql, fingerprints) {
|
|
17
|
-
await ensureSqlTables(execSql, [
|
|
18
|
-
...principalPolicyTables,
|
|
19
|
-
...principalHistoryEvidenceTables,
|
|
20
|
-
]);
|
|
21
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
7
|
+
import { principalPolicyBundles } from "../../sqlite/schema/principalPolicySchema.js";
|
|
8
|
+
/** Each source's newest envelopes per fingerprint; tables already ensured. */
|
|
9
|
+
export async function selectPrincipalKeyEnvelopeCandidates(db, fingerprints) {
|
|
22
10
|
const candidates = [];
|
|
23
11
|
for (const fingerprint of new Set(fingerprints)) {
|
|
24
12
|
const encoded = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalKeyEnvelopeCandidates.js","sourceRoot":"","sources":["principalKeyEnvelopeCandidates.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,yCAAyC,GAC1C,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,+BAA+B,EAC/B,6BAA6B,GAC9B,MAAM,0CAA0C,CAAC;AAClD,OAAO,
|
|
1
|
+
{"version":3,"file":"principalKeyEnvelopeCandidates.js","sourceRoot":"","sources":["principalKeyEnvelopeCandidates.ts"],"names":[],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AAO,CAAC,IAAI,CAAC,sBAAsB,CAAC,YAAY,CAAC,CAAC;aAClD,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,IAAI,KAAK;YAAE,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACzC,UAAU,CAAC,IAAI,CAAC,GAAG,wBAAwB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA0B,EAC1B,WAAmB;IAEnB,MAAM,UAAU,GAAoC,EAAE,CAAC;IACvD,KAAK,MAAM,IAAI,IAAI,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QACpC,IAAI,SAAkB,CAAC;QACvB,IAAI,CAAC;YACH,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;QACD,IAAI,CAAC,yCAAyC,CAAC,SAAS,CAAC;YAAE,SAAS;QACpE,UAAU,CAAC,IAAI,CAAC;YACd,YAAY,EAAE;gBACZ,aAAa,EAAE,SAAS,CAAC,aAAa;gBACtC,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,SAAS,EAAE,SAAS,CAAC,SAAS;gBAC9B,cAAc,EAAE,WAAW;aAC5B;YACD,sBAAsB,EAAE,SAAS;SAClC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import {\n type CurrentPrincipalMemberEnvelopesResponse,\n isCurrentPrincipalMemberEnvelopesResponse,\n} from \"@tearleads/validators/response\";\nimport { and, desc, eq, sql } from \"drizzle-orm\";\nimport {\n principalCurrentFingerprintJson,\n principalStateFingerprintJson,\n} from \"../../sqlite/principalKeyFingerprintJson\";\nimport { principalHistoryPrefixes } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport { principalKeyEnvelopeArchive } from \"../../sqlite/schema/principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"../../sqlite/schema/principalHistoryStageSchema\";\nimport { principalPolicyBundles } from \"../../sqlite/schema/principalPolicySchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\n\nexport interface PrincipalKeyEnvelopeCandidate {\n readonly currentState: {\n readonly principalType: \"group\" | \"organization\";\n readonly principalId: string;\n readonly stateHash: string;\n readonly keyFingerprint: string;\n };\n readonly currentMemberEnvelopes: CurrentPrincipalMemberEnvelopesResponse;\n}\n\n/** Each source's newest envelopes per fingerprint; tables already ensured. */\nexport async function selectPrincipalKeyEnvelopeCandidates(\n db: ClientSQLiteDatabase,\n fingerprints: readonly string[],\n): Promise<PrincipalKeyEnvelopeCandidate[]> {\n const candidates: PrincipalKeyEnvelopeCandidate[] = [];\n for (const fingerprint of new Set(fingerprints)) {\n const encoded: string[] = [];\n const [archived] = await db\n .select({ envelopes: principalKeyEnvelopeArchive.envelopesJson })\n .from(principalKeyEnvelopeArchive)\n .where(eq(principalKeyEnvelopeArchive.keyFingerprint, fingerprint))\n .orderBy(desc(principalKeyEnvelopeArchive.version))\n .limit(1);\n if (archived) encoded.push(archived.envelopes);\n // The newest current head and the newest retained bundle each offer one.\n for (const isCurrent of [true, false]) {\n const [row] = await db\n .select({\n envelopes: principalPolicyBundles.currentMemberEnvelopesJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(\n principalStateFingerprintJson(\n principalPolicyBundles.currentStateJson,\n ),\n fingerprint,\n ),\n eq(principalPolicyBundles.isCurrent, isCurrent),\n ),\n )\n .orderBy(desc(principalPolicyBundles.updatedAt))\n .limit(1);\n if (row) encoded.push(row.envelopes);\n }\n const [prefix] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryPrefixes.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryPrefixes)\n .where(\n eq(\n principalCurrentFingerprintJson(principalHistoryPrefixes.currentJson),\n fingerprint,\n ),\n )\n .orderBy(desc(principalHistoryPrefixes.version))\n .limit(1);\n if (prefix) encoded.push(prefix.envelopes);\n const [stage] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryStages.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryStages)\n .where(\n and(\n eq(\n principalCurrentFingerprintJson(principalHistoryStages.currentJson),\n fingerprint,\n ),\n eq(principalHistoryStages.complete, true),\n ),\n )\n .orderBy(desc(principalHistoryStages.afterVersion))\n .limit(1);\n if (stage) encoded.push(stage.envelopes);\n candidates.push(...decodeEnvelopeCandidates(encoded, fingerprint));\n }\n return candidates;\n}\n\n/** Distinct, well-formed envelope sets; malformed JSON is skipped. */\nfunction decodeEnvelopeCandidates(\n encoded: readonly string[],\n fingerprint: string,\n): PrincipalKeyEnvelopeCandidate[] {\n const candidates: PrincipalKeyEnvelopeCandidate[] = [];\n for (const json of new Set(encoded)) {\n let envelopes: unknown;\n try {\n envelopes = JSON.parse(json);\n } catch {\n continue;\n }\n if (!isCurrentPrincipalMemberEnvelopesResponse(envelopes)) continue;\n candidates.push({\n currentState: {\n principalType: envelopes.principalType,\n principalId: envelopes.principalId,\n stateHash: envelopes.stateHash,\n keyFingerprint: fingerprint,\n },\n currentMemberEnvelopes: envelopes,\n });\n }\n return candidates;\n}\n"]}
|
|
@@ -3,8 +3,6 @@ import { and, eq, inArray, or } from "drizzle-orm";
|
|
|
3
3
|
import { principalHeadMatchesReference } from "../../principals/organizationAuthorityDescriptor.js";
|
|
4
4
|
import { principalPolicyBundleReferences, principalPolicyBundles, } from "../../sqlite/schema/index.js";
|
|
5
5
|
import { principalHistoryEntries, principalHistoryEntryStateHashJson, } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
|
|
6
|
-
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
7
|
-
import { ensurePrincipalPolicyTables } from "./principalPolicyPersistence.js";
|
|
8
6
|
/** Candidate rows per source; equal hashes rarely repeat across scopes. */
|
|
9
7
|
const HELD_STATE_CANDIDATES = 8;
|
|
10
8
|
function parsedJson(json) {
|
|
@@ -74,15 +72,8 @@ async function bundleState(db, head) {
|
|
|
74
72
|
}
|
|
75
73
|
return null;
|
|
76
74
|
}
|
|
77
|
-
/**
|
|
78
|
-
|
|
79
|
-
* verified or acknowledged, or a cached policy bundle chain. It is untrusted;
|
|
80
|
-
* the caller verifies it as it would a served copy, and a miss only means the
|
|
81
|
-
* server sends one.
|
|
82
|
-
*/
|
|
83
|
-
export async function loadHeldPrincipalState(execSql, head) {
|
|
84
|
-
await ensurePrincipalPolicyTables(execSql);
|
|
85
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
75
|
+
/** History evidence first, then cached bundle chains; tables already ensured. */
|
|
76
|
+
export async function selectHeldPrincipalState(db, head) {
|
|
86
77
|
return (await evidenceState(db, head)) ?? bundleState(db, head);
|
|
87
78
|
}
|
|
88
79
|
//# sourceMappingURL=heldPrincipalState.js.map
|
|
@@ -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,EAA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C,cAAc,EAAE,IAAI,CAAC,cAAc,CAAC,CACxE,CACF;SACA,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAChC,MAAM,IAAI,GAAG,MAAM,EAAE;SAClB,MAAM,CAAC;QACN,SAAS,EAAE,sBAAsB,CAAC,SAAS;QAC3C,gBAAgB,EAAE,sBAAsB,CAAC,gBAAgB;QACzD,kBAAkB,EAAE,sBAAsB,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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ACf,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAC,YAAY,EAAE;YAC1D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,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,MAA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,MAAM,uCAAuC,CAC3C,EAAE,EACF,KAAK,CAAC,MAAM,EACZ,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,MAAM,wCAAwC,CAC5C,EAAE,EACF,KAAK,CAAC,MAAM,EACZ,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;QACJ,CAAC;IACH,CAAC;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"]}
|