@tearleads/client-sdk 0.1.11 → 0.1.13
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/README.md +18 -2
- package/client/Tearleads.d.ts +4 -0
- package/client/Tearleads.js +5 -0
- package/client/Tearleads.js.map +1 -1
- package/client/index.d.ts +1 -0
- package/client/index.js.map +1 -1
- package/client/principalHistoryProtection.d.ts +19 -0
- package/client/principalHistoryProtection.js +76 -0
- package/client/principalHistoryProtection.js.map +1 -0
- package/client/workflowRuntime.d.ts +5 -0
- package/client/workflowRuntime.js +34 -5
- package/client/workflowRuntime.js.map +1 -1
- package/data/containers/shared/authorAccess.d.ts +2 -2
- package/data/containers/shared/authorAccess.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +1 -1
- package/data/containers/shared/principalPolicies.js.map +1 -1
- package/data/containers/shared/types.d.ts +3 -2
- package/data/containers/shared/types.js.map +1 -1
- package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpointContext.d.ts +4 -3
- package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +4 -3
- package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +3 -2
- package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/organizationFounderBinding.js +9 -4
- package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyCache.js +3 -4
- package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js +12 -2
- package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +70 -0
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -0
- package/data/keyingProjectionVerification/types.d.ts +17 -2
- package/data/keyingProjectionVerification/types.js +12 -0
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/persistence/organizationFounderPersistence.js +3 -2
- package/data/persistence/organizationFounderPersistence.js.map +1 -1
- package/data/persistence/principalHistoryEvidencePersistence.js +91 -0
- package/data/persistence/principalHistoryEvidencePersistence.js.map +1 -0
- package/data/persistence/principalHistoryPrefixPersistence.js +52 -0
- package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -0
- package/data/persistence/principalHistoryStagePersistence.js +9 -2
- package/data/persistence/principalHistoryStagePersistence.js.map +1 -1
- package/data/persistence/principalKeyEnvelopeCandidates.js +67 -0
- package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -0
- package/data/principals/principalHistoryPrefixProtection.js +29 -0
- package/data/principals/principalHistoryPrefixProtection.js.map +1 -0
- package/data/principals/principalHistoryProtection.d.ts +10 -0
- package/data/principals/principalHistoryProtection.js +14 -0
- package/data/principals/principalHistoryProtection.js.map +1 -0
- package/data/principals/principalHistoryStageProtection.js.map +1 -1
- package/data/principals/principalPolicyCrypto.js +11 -21
- package/data/principals/principalPolicyCrypto.js.map +1 -1
- package/data/principals/principalPolicyEvidence.d.ts +4 -0
- package/data/principals/principalPolicyEvidence.js +12 -0
- package/data/principals/principalPolicyEvidence.js.map +1 -0
- package/data/sqlite/principalHistoryEvidenceSchema.js +46 -0
- package/data/sqlite/principalHistoryEvidenceSchema.js.map +1 -0
- package/data/sqlite/principalKeyFingerprintJson.js +9 -0
- package/data/sqlite/principalKeyFingerprintJson.js.map +1 -0
- package/data/sqlite/principalPolicySchema.js +4 -0
- package/data/sqlite/principalPolicySchema.js.map +1 -1
- package/data/sqlite/schema.d.ts +304 -0
- package/data/sqlite/schema.js +5 -0
- package/data/sqlite/schema.js.map +1 -1
- package/data/sqlite/sqlTableSchema.js +1 -1
- package/data/sqlite/sqlTableSchema.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/api-client/principalPolicyPages.d.ts +2 -0
- package/internal/api-client/principalPolicyPages.js +11 -2
- package/internal/api-client/principalPolicyPages.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/index.d.ts +1 -1
- package/internal/crypto/keying/index.js +1 -1
- package/internal/crypto/keying/index.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryIndex.d.ts +6 -2
- package/internal/crypto/keying/principalPolicyHistoryIndex.js +11 -5
- package/internal/crypto/keying/principalPolicyHistoryIndex.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryReferences.d.ts +2 -0
- package/internal/crypto/keying/principalPolicyHistoryReferences.js +19 -2
- package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
- package/package.json +1 -1
- package/workflows/containers/child/create.js.map +1 -1
- package/workflows/containers/child/move.js.map +1 -1
- package/workflows/containers/child/moveWraps.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/child/rekey.d.ts +3 -2
- package/workflows/containers/child/rekey.js.map +1 -1
- package/workflows/containers/child/revoke.d.ts +2 -2
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/rotationPrincipalPolicies.js.map +1 -1
- package/workflows/containers/child/rotationWraps.js.map +1 -1
- package/workflows/containers/child/sharePlanCore.d.ts +11 -10
- package/workflows/containers/child/sharePlanCore.js.map +1 -1
- package/workflows/documents/linkSetAuthority.js.map +1 -1
- package/workflows/principals/index.d.ts +1 -0
- package/workflows/principals/index.js +1 -0
- package/workflows/principals/index.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryPrefix.js +65 -0
- package/workflows/principals/principalHistoryRecoveryPrefix.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js +60 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryStage.js +38 -2
- package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryTypes.d.ts +9 -1
- package/workflows/principals/principalHistoryRecoveryTypes.js +7 -0
- package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryVerification.js +24 -0
- package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -0
- package/workflows/principals/principalRecoveryDirectory.d.ts +10 -0
- package/workflows/principals/principalRecoveryDirectory.js +107 -0
- package/workflows/principals/principalRecoveryDirectory.js.map +1 -0
- package/workflows/principals/principalRecoveryMemo.js +46 -0
- package/workflows/principals/principalRecoveryMemo.js.map +1 -0
- package/workflows/principals/principalRecoveryOutage.js +40 -0
- package/workflows/principals/principalRecoveryOutage.js.map +1 -0
- package/workflows/principals/principalRecoveryQueue.js +22 -0
- package/workflows/principals/principalRecoveryQueue.js.map +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.js +108 -36
- package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +13 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +150 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -0
- package/workflows/principals/runtimePolicyRecovery.js +65 -0
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -0
- package/workflows/principals/runtimePolicyWarmer.js +5 -1
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
- package/workflows/sync/remoteResetPrincipalScope.js +10 -0
- package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type ReferencedPrincipalHead, type VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
|
|
2
|
+
import { type RecoveredPrincipalPolicyHistory } from "./principalHistoryRecoveryTypes.js";
|
|
3
|
+
import { type PrincipalRecoveryContext } from "./principalRecoveryDirectory.js";
|
|
4
|
+
export interface RecoverScopedPrincipalPolicyHistoryOptions extends PrincipalRecoveryContext {
|
|
5
|
+
readonly reference: ReferencedPrincipalHead;
|
|
6
|
+
}
|
|
7
|
+
export interface RecoveredScopedPrincipalPolicyHistory extends RecoveredPrincipalPolicyHistory {
|
|
8
|
+
/** Submit these with policy when atomically admitting its organization scope. */
|
|
9
|
+
readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];
|
|
10
|
+
}
|
|
11
|
+
export declare function recoverScopedPrincipalPolicyHistory(options: RecoverScopedPrincipalPolicyHistoryOptions): Promise<RecoveredScopedPrincipalPolicyHistory>;
|
|
12
|
+
/** Internal runtime batch: shared results never outlive one caller's collection. */
|
|
13
|
+
export declare function createScopedPrincipalPolicyHistoryBatch(): typeof recoverScopedPrincipalPolicyHistory;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { createPrincipalPolicyHistoryVerifier, KeyingVerificationError, serializeKeyingCanonicalJson, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
3
|
+
import { ownPrincipalHistoryProtection } from "../../data/principals/principalHistoryProtection.js";
|
|
4
|
+
import { PrincipalHistoryRecoveryRaceError, } from "./principalHistoryRecoveryTypes.js";
|
|
5
|
+
import { PrincipalRecoveryDirectoryAdvanced, } from "./principalRecoveryDirectory.js";
|
|
6
|
+
import { createPrincipalRecoveryReader, } from "./principalRecoveryMemo.js";
|
|
7
|
+
import { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
|
|
8
|
+
function groupHead(directory, principalId) {
|
|
9
|
+
const head = directory.descriptor.groupHeads.find((entry) => entry.principalId === principalId);
|
|
10
|
+
if (!head)
|
|
11
|
+
throw new KeyingVerificationError("missing_dependency", "Group is absent from the signed organization directory");
|
|
12
|
+
return head;
|
|
13
|
+
}
|
|
14
|
+
function authorityHead(state) {
|
|
15
|
+
return {
|
|
16
|
+
principalType: "group",
|
|
17
|
+
principalId: state.principalId,
|
|
18
|
+
version: state.version,
|
|
19
|
+
stateHash: state.stateHash,
|
|
20
|
+
keyEpoch: state.keyEpoch,
|
|
21
|
+
keyFingerprint: state.keyFingerprint,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function scopedGroupProtection(input, adminHead) {
|
|
25
|
+
return {
|
|
26
|
+
localKey: input.protection.localKey,
|
|
27
|
+
context: serializeKeyingCanonicalJson([
|
|
28
|
+
"tearleads.sdk.principal-history.scoped-group.v1",
|
|
29
|
+
input.protection.context,
|
|
30
|
+
input.organizationId,
|
|
31
|
+
adminHead.principalId,
|
|
32
|
+
]),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
async function recoverScopedPolicy(input, memo) {
|
|
36
|
+
if (input.reference.principalType === "organization" &&
|
|
37
|
+
input.reference.principalId !== input.organizationId)
|
|
38
|
+
throw new KeyingVerificationError("object_mismatch", "Requested organization policy is outside its scope");
|
|
39
|
+
const read = createPrincipalRecoveryReader(input, memo);
|
|
40
|
+
const directory = await read.directory(input.reference.principalType === "organization" ? [input.reference] : []);
|
|
41
|
+
if (input.reference.principalType === "organization")
|
|
42
|
+
return {
|
|
43
|
+
current: directory.current,
|
|
44
|
+
policy: directory.policy,
|
|
45
|
+
dependencies: [],
|
|
46
|
+
};
|
|
47
|
+
const expectedHead = groupHead(directory, input.reference.principalId);
|
|
48
|
+
if (input.reference.version > expectedHead.version)
|
|
49
|
+
throw new PrincipalRecoveryDirectoryAdvanced();
|
|
50
|
+
const adminHead = groupHead(directory, directory.descriptor.adminGroupId);
|
|
51
|
+
const isAdmins = expectedHead.principalId === adminHead.principalId;
|
|
52
|
+
let admins = null;
|
|
53
|
+
if (!isAdmins) {
|
|
54
|
+
admins = (await read.admins(adminHead)).policy;
|
|
55
|
+
}
|
|
56
|
+
const loadExternalAuthority = async (entries) => {
|
|
57
|
+
const references = new Map();
|
|
58
|
+
for (const { state } of entries) {
|
|
59
|
+
const citation = state.externalAuthority;
|
|
60
|
+
if (!citation)
|
|
61
|
+
continue;
|
|
62
|
+
if (citation.principalId !== adminHead.principalId)
|
|
63
|
+
throw new KeyingVerificationError("object_mismatch", "Group cites another organization's Admins authority");
|
|
64
|
+
if (citation.version > adminHead.version)
|
|
65
|
+
throw new PrincipalRecoveryDirectoryAdvanced();
|
|
66
|
+
references.set(`${citation.version}:${citation.stateHash}`, citation);
|
|
67
|
+
}
|
|
68
|
+
if (!references.size)
|
|
69
|
+
return undefined;
|
|
70
|
+
const recovered = await read.admins(adminHead, [...references.values()]);
|
|
71
|
+
return {
|
|
72
|
+
currentHead: adminHead,
|
|
73
|
+
states: recovered.policy.retainedHistory.map(({ state, projection }) => ({
|
|
74
|
+
head: authorityHead(state),
|
|
75
|
+
projection,
|
|
76
|
+
})),
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
const recovered = await recoverPrincipalPolicyHistory({
|
|
80
|
+
...input,
|
|
81
|
+
expectedHead,
|
|
82
|
+
retainedReferences: [input.reference],
|
|
83
|
+
historyVerification: isAdmins ? "direct-admins" : "standard",
|
|
84
|
+
...(isAdmins
|
|
85
|
+
? {}
|
|
86
|
+
: { protection: scopedGroupProtection(input, adminHead) }),
|
|
87
|
+
...(isAdmins ? {} : { loadExternalAuthority }),
|
|
88
|
+
});
|
|
89
|
+
return {
|
|
90
|
+
...recovered,
|
|
91
|
+
dependencies: admins ? [directory.policy, admins] : [directory.policy],
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** Recover signed directory and strict Admins dependencies without full histories. */
|
|
95
|
+
async function recoverScopedPrincipalPolicyHistoryInBatch(options, memo) {
|
|
96
|
+
if (options.offline !== undefined && typeof options.offline !== "boolean")
|
|
97
|
+
throw new KeyingVerificationError("invalid_shape", "Invalid principal history transport mode");
|
|
98
|
+
if (!options.organizationId)
|
|
99
|
+
throw new KeyingVerificationError("object_mismatch", "Principal recovery requires an organization scope");
|
|
100
|
+
const input = {
|
|
101
|
+
apiClient: options.apiClient,
|
|
102
|
+
execSql: options.execSql,
|
|
103
|
+
organizationId: options.organizationId,
|
|
104
|
+
offline: options.offline,
|
|
105
|
+
resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,
|
|
106
|
+
signal: options.signal,
|
|
107
|
+
stillCurrent: options.stillCurrent,
|
|
108
|
+
reference: structuredClone(options.reference),
|
|
109
|
+
protection: ownPrincipalHistoryProtection(options.protection),
|
|
110
|
+
};
|
|
111
|
+
try {
|
|
112
|
+
// Reject malformed exact citations before any discovery or disposable writes.
|
|
113
|
+
createPrincipalPolicyHistoryVerifier({
|
|
114
|
+
principalId: input.reference.principalId,
|
|
115
|
+
principalType: input.reference.principalType,
|
|
116
|
+
retainedReferences: [input.reference],
|
|
117
|
+
});
|
|
118
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
119
|
+
try {
|
|
120
|
+
const recovered = await recoverScopedPolicy(input, memo);
|
|
121
|
+
assertProjectionVerificationCurrent(() => !input.signal?.aborted && input.stillCurrent());
|
|
122
|
+
return recovered;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (!(error instanceof PrincipalRecoveryDirectoryAdvanced))
|
|
126
|
+
throw error;
|
|
127
|
+
memo?.directories.clear();
|
|
128
|
+
memo?.admins.clear();
|
|
129
|
+
if (input.offline)
|
|
130
|
+
throw new KeyingVerificationError("missing_dependency", "Requested principal evidence is newer than the offline directory");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
throw new PrincipalHistoryRecoveryRaceError("Organization directory remains behind the requested policy evidence");
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
input.protection.localKey.fill(0);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
export function recoverScopedPrincipalPolicyHistory(options) {
|
|
140
|
+
return recoverScopedPrincipalPolicyHistoryInBatch(options);
|
|
141
|
+
}
|
|
142
|
+
/** Internal runtime batch: shared results never outlive one caller's collection. */
|
|
143
|
+
export function createScopedPrincipalPolicyHistoryBatch() {
|
|
144
|
+
const memo = {
|
|
145
|
+
directories: new Map(),
|
|
146
|
+
admins: new Map(),
|
|
147
|
+
};
|
|
148
|
+
return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=recoverScopedPrincipalPolicyHistory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recoverScopedPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverScopedPrincipalPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAIvB,4BAA4B,GAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EACL,iCAAiC,GAElC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,kCAAkC,GAEnC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,6BAA6B,GAE9B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAahF,SAAS,SAAS,CAAC,SAAmC,EAAE,WAAmB;IACzE,MAAM,IAAI,GAAG,SAAS,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAC/C,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,KAAK,WAAW,CAC7C,CAAC;IACF,IAAI,CAAC,IAAI;QACP,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AI,EAAE,WAAW,CAAC,KAAK,EAAE,CAAC;gBAC1B,IAAI,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;gBACrB,IAAI,KAAK,CAAC,OAAO;oBACf,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,kEAAkE,CACnE,CAAC;YACN,CAAC;QACH,CAAC;QACD,MAAM,IAAI,iCAAiC,CACzC,qEAAqE,CACtE,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,OAAmD;IAEnD,OAAO,0CAA0C,CAAC,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,uCAAuC;IACrD,MAAM,IAAI,GAA0B;QAClC,WAAW,EAAE,IAAI,GAAG,EAAE;QACtB,MAAM,EAAE,IAAI,GAAG,EAAE;KAClB,CAAC;IACF,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicyStateChainEntry,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoveredPrincipalPolicyHistory,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n type PrincipalRecoveryContext,\n PrincipalRecoveryDirectoryAdvanced,\n type RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n createPrincipalRecoveryReader,\n type PrincipalRecoveryMemo,\n} from \"./principalRecoveryMemo\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport interface RecoverScopedPrincipalPolicyHistoryOptions\n extends PrincipalRecoveryContext {\n readonly reference: ReferencedPrincipalHead;\n}\n\nexport interface RecoveredScopedPrincipalPolicyHistory\n extends RecoveredPrincipalPolicyHistory {\n /** Submit these with policy when atomically admitting its organization scope. */\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nfunction groupHead(directory: RecoveredPolicyDirectory, principalId: string) {\n const head = directory.descriptor.groupHeads.find(\n (entry) => entry.principalId === principalId,\n );\n if (!head)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Group is absent from the signed organization directory\",\n );\n return head;\n}\n\nfunction authorityHead(state: ReferencedPrincipalHead) {\n return {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\nfunction scopedGroupProtection(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n adminHead: ReferencedPrincipalHead,\n) {\n return {\n localKey: input.protection.localKey,\n context: serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.scoped-group.v1\",\n input.protection.context,\n input.organizationId,\n adminHead.principalId,\n ]),\n };\n}\n\nasync function recoverScopedPolicy(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n if (\n input.reference.principalType === \"organization\" &&\n input.reference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested organization policy is outside its scope\",\n );\n const read = createPrincipalRecoveryReader(input, memo);\n const directory = await read.directory(\n input.reference.principalType === \"organization\" ? [input.reference] : [],\n );\n if (input.reference.principalType === \"organization\")\n return {\n current: directory.current,\n policy: directory.policy,\n dependencies: [],\n };\n const expectedHead = groupHead(directory, input.reference.principalId);\n if (input.reference.version > expectedHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n const adminHead = groupHead(directory, directory.descriptor.adminGroupId);\n const isAdmins = expectedHead.principalId === adminHead.principalId;\n let admins: VerifiedPrincipalPolicyCurrent | null = null;\n if (!isAdmins) {\n admins = (await read.admins(adminHead)).policy;\n }\n const loadExternalAuthority = async (\n entries: readonly PrincipalPolicyStateChainEntry[],\n ): Promise<PrincipalPolicyExternalAuthority | undefined> => {\n const references = new Map<string, ReferencedPrincipalHead>();\n for (const { state } of entries) {\n const citation = state.externalAuthority;\n if (!citation) continue;\n if (citation.principalId !== adminHead.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Group cites another organization's Admins authority\",\n );\n if (citation.version > adminHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n references.set(`${citation.version}:${citation.stateHash}`, citation);\n }\n if (!references.size) return undefined;\n const recovered = await read.admins(adminHead, [...references.values()]);\n return {\n currentHead: adminHead,\n states: recovered.policy.retainedHistory.map(({ state, projection }) => ({\n head: authorityHead(state),\n projection,\n })),\n };\n };\n const recovered = await recoverPrincipalPolicyHistory({\n ...input,\n expectedHead,\n retainedReferences: [input.reference],\n historyVerification: isAdmins ? \"direct-admins\" : \"standard\",\n ...(isAdmins\n ? {}\n : { protection: scopedGroupProtection(input, adminHead) }),\n ...(isAdmins ? {} : { loadExternalAuthority }),\n });\n return {\n ...recovered,\n dependencies: admins ? [directory.policy, admins] : [directory.policy],\n };\n}\n\n/** Recover signed directory and strict Admins dependencies without full histories. */\nasync function recoverScopedPrincipalPolicyHistoryInBatch(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (!options.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal recovery requires an organization scope\",\n );\n const input = {\n apiClient: options.apiClient,\n execSql: options.execSql,\n organizationId: options.organizationId,\n offline: options.offline,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n signal: options.signal,\n stillCurrent: options.stillCurrent,\n reference: structuredClone(options.reference),\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n // Reject malformed exact citations before any discovery or disposable writes.\n createPrincipalPolicyHistoryVerifier({\n principalId: input.reference.principalId,\n principalType: input.reference.principalType,\n retainedReferences: [input.reference],\n });\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const recovered = await recoverScopedPolicy(input, memo);\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n return recovered;\n } catch (error) {\n if (!(error instanceof PrincipalRecoveryDirectoryAdvanced)) throw error;\n memo?.directories.clear();\n memo?.admins.clear();\n if (input.offline)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested principal evidence is newer than the offline directory\",\n );\n }\n }\n throw new PrincipalHistoryRecoveryRaceError(\n \"Organization directory remains behind the requested policy evidence\",\n );\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n\nexport function recoverScopedPrincipalPolicyHistory(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n return recoverScopedPrincipalPolicyHistoryInBatch(options);\n}\n\n/** Internal runtime batch: shared results never outlive one caller's collection. */\nexport function createScopedPrincipalPolicyHistoryBatch(): typeof recoverScopedPrincipalPolicyHistory {\n const memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n };\n return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);\n}\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
|
+
import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
|
|
4
|
+
import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
|
|
5
|
+
import { PrincipalHistoryRecoveryRaceError, PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
|
|
6
|
+
import { recoverWithPrincipalOutageFallback } from "./principalRecoveryOutage.js";
|
|
7
|
+
import { queuePrincipalRecovery } from "./principalRecoveryQueue.js";
|
|
8
|
+
import { createScopedPrincipalPolicyHistoryBatch, recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
|
|
9
|
+
/** Keep the private recovery key inside its runtime lease throughout verification. */
|
|
10
|
+
export function createRuntimePrincipalPolicyResolver(runtime) {
|
|
11
|
+
const lease = runtime.withPrincipalHistoryProtection;
|
|
12
|
+
const readPages = runtime.apiClient.getPrincipalPolicyPages?.bind(runtime.apiClient);
|
|
13
|
+
if (!lease || !readPages)
|
|
14
|
+
return undefined;
|
|
15
|
+
const batches = new WeakMap();
|
|
16
|
+
const recoverFor = (batch) => {
|
|
17
|
+
if (!batch)
|
|
18
|
+
return recoverScopedPrincipalPolicyHistory;
|
|
19
|
+
let recover = batches.get(batch);
|
|
20
|
+
if (!recover) {
|
|
21
|
+
recover = createScopedPrincipalPolicyHistoryBatch();
|
|
22
|
+
batches.set(batch, recover);
|
|
23
|
+
}
|
|
24
|
+
return recover;
|
|
25
|
+
};
|
|
26
|
+
return (input) => queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
|
|
27
|
+
objectId: input.reference.principalId,
|
|
28
|
+
objectKind: "principal",
|
|
29
|
+
operation: "principal.policy.recover",
|
|
30
|
+
organizationId: input.organizationId,
|
|
31
|
+
}, () => lease(async ({ protection, stillCurrent: leaseCurrent }) => {
|
|
32
|
+
const stillCurrent = () => leaseCurrent() && input.stillCurrent?.() !== false;
|
|
33
|
+
assertProjectionVerificationCurrent(stillCurrent);
|
|
34
|
+
const offline = runtime.state?.online === false;
|
|
35
|
+
try {
|
|
36
|
+
const options = {
|
|
37
|
+
apiClient: { getPrincipalPolicyPages: readPages },
|
|
38
|
+
execSql: runtime.infra.execSql,
|
|
39
|
+
offline,
|
|
40
|
+
organizationId: input.organizationId,
|
|
41
|
+
protection,
|
|
42
|
+
reference: input.reference,
|
|
43
|
+
resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
|
|
44
|
+
stillCurrent,
|
|
45
|
+
};
|
|
46
|
+
const result = await recoverWithPrincipalOutageFallback(recoverFor(input.recoveryBatch), options);
|
|
47
|
+
return {
|
|
48
|
+
organizationId: input.organizationId,
|
|
49
|
+
policy: result.policy,
|
|
50
|
+
dependencies: result.dependencies,
|
|
51
|
+
stillCurrent,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
assertProjectionVerificationCurrent(stillCurrent);
|
|
56
|
+
if (error instanceof PrincipalPolicyHistoryReadError ||
|
|
57
|
+
error instanceof PrincipalHistoryRecoveryRaceError ||
|
|
58
|
+
(error instanceof KeyingVerificationError &&
|
|
59
|
+
error.code === "missing_dependency"))
|
|
60
|
+
throw new ProjectionDependencyUnavailableError(error.message);
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
})));
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=runtimePolicyRecovery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAEpC,MAAM,+CAA+C,CAAC;AAKvD,OAAO,EACL,iCAAiC,EACjC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ent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport {\n createScopedPrincipalPolicyHistoryBatch,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<Pick<ApiClient, \"getPrincipalPolicyPages\">>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease throughout verification. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const lease = runtime.withPrincipalHistoryProtection;\n const readPages = runtime.apiClient.getPrincipalPolicyPages?.bind(\n runtime.apiClient,\n );\n if (!lease || !readPages) return undefined;\n const batches = new WeakMap<\n object,\n typeof recoverScopedPrincipalPolicyHistory\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return recoverScopedPrincipalPolicyHistory;\n let recover = batches.get(batch);\n if (!recover) {\n recover = createScopedPrincipalPolicyHistoryBatch();\n batches.set(batch, recover);\n }\n return recover;\n };\n return (input) =>\n queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference.principalId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n apiClient: { getPrincipalPolicyPages: readPages },\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n reference: input.reference,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const result = await recoverWithPrincipalOutageFallback(\n recoverFor(input.recoveryBatch),\n options,\n );\n return {\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n stillCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
|
|
2
|
+
import { createRuntimePrincipalPolicyResolver, } from "./runtimePolicyRecovery.js";
|
|
2
3
|
export function createRuntimePrincipalPolicyWarmer(runtime) {
|
|
3
4
|
const policyInput = ({ organizationId, references, stillCurrent, }) => {
|
|
4
5
|
const input = {
|
|
@@ -24,6 +25,9 @@ export function createRuntimePrincipalPolicyWarmer(runtime) {
|
|
|
24
25
|
resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
|
|
25
26
|
stillCurrent: input.stillCurrent,
|
|
26
27
|
});
|
|
27
|
-
return Object.assign(warmer, {
|
|
28
|
+
return Object.assign(warmer, {
|
|
29
|
+
cacheBundles,
|
|
30
|
+
resolveReference: createRuntimePrincipalPolicyResolver(runtime),
|
|
31
|
+
});
|
|
28
32
|
}
|
|
29
33
|
//# sourceMappingURL=runtimePolicyWarmer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimePolicyWarmer.js","sourceRoot":"","sources":["runtimePolicyWarmer.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"runtimePolicyWarmer.js","sourceRoot":"","sources":["runtimePolicyWarmer.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,oCAAoC,GAErC,MAAM,yBAAyB,CAAC;AAiBjC,MAAM,UAAU,kCAAkC,CAChD,OAAmC;IAEnC,MAAM,WAAW,GAAG,CAAC,EACnB,cAAc,EACd,UAAU,EACV,YAAY,GACmC,EAAE,EAAE;QACnD,MAAM,KAAK,GAA2D;YACpE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,yBAAyB,EAAE,CAAC,aAAa,EAAE,WAAW,EAAE,EAAE,CACxD,OAAO,CAAC,SAAS,CAAC,yBAAyB,CAAC,aAAa,EAAE,WAAW,CAAC;YACzE,GAAG,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG;YACrB,cAAc;YACd,sBAAsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;YAC3D,UAAU;YACV,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;YAC9D,YAAY;SACb,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IACF,MAAM,MAAM,GAAG,KAAK,EAClB,KAAqD,EACrD,EAAE,CAAC,gCAAgC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1D,MAAM,YAAY,GAAG,CAAC,KAAwC,EAAE,EAAE,CAChE,2BAA2B,CAAC;QAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,yBAAyB,EAAE,CAAC,aAAa,EAAE,WAAW,EAAE,EAAE,CACxD,OAAO,CAAC,SAAS,CAAC,yBAAyB,CAAC,aAAa,EAAE,WAAW,CAAC;QACzE,GAAG,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG;QACrB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;QAC3D,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACL,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE;QAC3B,YAAY;QACZ,gBAAgB,EAAE,oCAAoC,CAAC,OAAO,CAAC;KAChE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type {\n PrincipalPolicyBundleCacheRequest,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nimport {\n createRuntimePrincipalPolicyResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"./runtimePolicyRecovery\";\n\ninterface PrincipalPolicyWarmRuntime extends PrincipalPolicyRecoveryRuntime {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] & {\n getCurrentPrincipalPolicy(\n principalType: \"group\" | \"organization\",\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null>;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport function createRuntimePrincipalPolicyWarmer(\n runtime: PrincipalPolicyWarmRuntime,\n): ReferencedPrincipalPolicyWarmer {\n const policyInput = ({\n organizationId,\n references,\n stillCurrent,\n }: Parameters<ReferencedPrincipalPolicyWarmer>[0]) => {\n const input: Parameters<typeof cacheReferencedPrincipalPolicies>[0] = {\n execSql: runtime.infra.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n runtime.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n log: runtime.util.log,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n references,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n return input;\n };\n const warmer = async (\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n ) => cacheReferencedPrincipalPolicies(policyInput(input));\n const cacheBundles = (input: PrincipalPolicyBundleCacheRequest) =>\n cachePrincipalPolicyBundles({\n bundles: input.bundles,\n execSql: runtime.infra.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n runtime.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n log: runtime.util.log,\n organizationId: input.organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return Object.assign(warmer, {\n cacheBundles,\n resolveReference: createRuntimePrincipalPolicyResolver(runtime),\n });\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { and, eq, or } from "drizzle-orm";
|
|
2
|
+
import { principalHistoryEntries, principalHistoryNodes, principalHistoryPrefixes, } from "../../data/sqlite/principalHistoryEvidenceSchema.js";
|
|
2
3
|
import { principalHistoryStages } from "../../data/sqlite/principalHistoryStageSchema.js";
|
|
3
4
|
import { principalPolicies, principalPolicyBundleHistory, principalPolicyBundleReferences, principalPolicyCheckpoints, principalPolicyOrganizations, } from "../../data/sqlite/schema.js";
|
|
4
5
|
import { remoteResetBatches } from "./remoteResetBatches.js";
|
|
@@ -68,6 +69,15 @@ export async function loadRemoteResetPrincipalScope(tx, organizationId) {
|
|
|
68
69
|
// Trust checkpoints and their ownership survive reset. Clearing cached bundles
|
|
69
70
|
// must not turn a previously observed principal or object into first sight.
|
|
70
71
|
export async function clearRemoteResetPrincipalRows(input) {
|
|
72
|
+
for (const table of [
|
|
73
|
+
principalHistoryEntries,
|
|
74
|
+
principalHistoryNodes,
|
|
75
|
+
principalHistoryPrefixes,
|
|
76
|
+
])
|
|
77
|
+
await input.tx
|
|
78
|
+
.delete(table)
|
|
79
|
+
.where(eq(table.organizationId, input.organizationId))
|
|
80
|
+
.run();
|
|
71
81
|
await input.tx
|
|
72
82
|
.delete(principalHistoryStages)
|
|
73
83
|
.where(eq(principalHistoryStages.organizationId, input.organizationId))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remoteResetPrincipalScope.js","sourceRoot":"","sources":["remoteResetPrincipalScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,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AE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;AAC3D,CAAC;AAED,+EAA+E;AAC/E,4EAA4E;AAC5E,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAInD;IACC,MAAM,KAAK,CAAC,EAAE;SACX,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;SACtE,GAAG,EAAE,CAAC;IACT,KAAK,MAAM,cAAc,IAAI,kBAAkB,CAC7C,KAAK,CAAC,QAAQ,CAAC,aAAa,CAC7B,EAAE,CAAC;QACF,KAAK,MAAM,KAAK,IAAI;YAClB,iBAAiB;YACjB,4BAA4B;YAC5B,+BAA+B;SACvB,EAAE,CAAC;YACX,MAAM,KAAK,CAAC,EAAE;iBACX,MAAM,CAAC,KAAK,CAAC;iBACb,KAAK,CACJ,EAAE,CACA,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAClC,GAAG,CACD,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,SAAS,CAAC,aAAa,CAAC,EAChD,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,SAAS,CAAC,WAAW,CAAC,CAC7C,CACF,CACF,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport { principalHistoryStages } from \"../../data/sqlite/principalHistoryStageSchema\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"../../data/sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface RemoteResetPrincipalKey {\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n}\n\ninterface PrincipalRow {\n readonly id: string;\n readonly type: string;\n}\n\n/** Current cache writes atomically pin ownership; reset never backfills it. */\nexport async function loadRemoteResetPrincipalScope(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<{\n readonly policyRows: readonly PrincipalRow[];\n readonly principalKeys: readonly RemoteResetPrincipalKey[];\n}> {\n const [policyRows, retainedRows, ownershipRows] = await Promise.all([\n tx\n .select({\n id: principalPolicies.principalId,\n type: principalPolicies.principalType,\n })\n .from(principalPolicies),\n Promise.all(\n [\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n ].map((table) =>\n tx\n .selectDistinct({ id: table.principalId, type: table.principalType })\n .from(table),\n ),\n ),\n tx\n .select({\n organizationId: principalPolicyOrganizations.organizationId,\n principalId: principalPolicyOrganizations.principalId,\n principalType: principalPolicyOrganizations.principalType,\n })\n .from(principalPolicyOrganizations),\n ]);\n const owners = new Map(\n ownershipRows.map((row) => [\n `${row.principalType}\\0${row.principalId}`,\n row.organizationId,\n ]),\n );\n for (const row of [...policyRows, ...retainedRows.flat()]) {\n const owner = owners.get(`${row.type}\\0${row.id}`);\n if (row.type === \"group\" && !owner) {\n throw new Error(\n \"Unowned group policy cache requires a local database reset before organization purge\",\n );\n }\n if (row.type !== \"group\" && row.type !== \"organization\") {\n throw new Error(\"Principal policy cache has an invalid principal type\");\n }\n if (\n row.type === \"organization\" &&\n owner !== undefined &&\n owner !== row.id\n ) {\n throw new Error(\n \"Organization policy cache ownership does not match its identity\",\n );\n }\n }\n const keys = new Map<string, RemoteResetPrincipalKey>();\n keys.set(`organization\\0${organizationId}`, {\n principalId: organizationId,\n principalType: \"organization\",\n });\n for (const row of ownershipRows) {\n if (row.principalType !== \"group\" && row.principalType !== \"organization\") {\n throw new Error(\n \"Principal policy cache ownership has an invalid principal type\",\n );\n }\n if (!row.organizationId) {\n throw new Error(\n \"Principal policy cache ownership requires a local database reset\",\n );\n }\n if (row.organizationId !== organizationId) continue;\n keys.set(`${row.principalType}\\0${row.principalId}`, {\n principalId: row.principalId,\n principalType: row.principalType,\n });\n }\n return { policyRows, principalKeys: [...keys.values()] };\n}\n\n// Trust checkpoints and their ownership survive reset. Clearing cached bundles\n// must not turn a previously observed principal or object into first sight.\nexport async function clearRemoteResetPrincipalRows(input: {\n organizationId: string;\n snapshot: { principalKeys: readonly RemoteResetPrincipalKey[] };\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n await input.tx\n .delete(principalHistoryStages)\n .where(eq(principalHistoryStages.organizationId, input.organizationId))\n .run();\n for (const principalBatch of remoteResetBatches(\n input.snapshot.principalKeys,\n )) {\n for (const table of [\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n ] as const) {\n await input.tx\n .delete(table)\n .where(\n or(\n ...principalBatch.map((principal) =>\n and(\n eq(table.principalType, principal.principalType),\n eq(table.principalId, principal.principalId),\n ),\n ),\n ),\n )\n .run();\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remoteResetPrincipalScope.js","sourceRoot":"","sources":["remoteResetPrincipalScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAY1D,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,EAAgC,EAChC,cAAsB;IAKtB,MAAM,CAAC,UAAU,EAAE,YAAY,EAAE,aAAa,CAAC,GAAG,MAAM,OAAO,CAAC,GA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AAK,IAAI;QAClB,uBAAuB;QACvB,qBAAqB;QACrB,wBAAwB;KACzB;QACC,MAAM,KAAK,CAAC,EAAE;aACX,MAAM,CAAC,KAAK,CAAC;aACb,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;aACrD,GAAG,EAAE,CAAC;IACX,MAAM,KAAK,CAAC,EAAE;SACX,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;SACtE,GAAG,EAAE,CAAC;IACT,KAAK,MAAM,cAAc,IAAI,kBAAkB,CAC7C,KAAK,CAAC,QAAQ,CAAC,aAAa,CAC7B,EAAE,CAAC;QACF,KAAK,MAAM,KAAK,IAAI;YAClB,iBAAiB;YACjB,4BAA4B;YAC5B,+BAA+B;SACvB,EAAE,CAAC;YACX,MAAM,KAAK,CAAC,EAAE;iBACX,MAAM,CAAC,KAAK,CAAC;iBACb,KAAK,CACJ,EAAE,CACA,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAClC,GAAG,CACD,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,SAAS,CAAC,aAAa,CAAC,EAChD,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,SAAS,CAAC,WAAW,CAAC,CAC7C,CACF,CACF,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport {\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n} from \"../../data/sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../../data/sqlite/principalHistoryStageSchema\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"../../data/sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface RemoteResetPrincipalKey {\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n}\n\ninterface PrincipalRow {\n readonly id: string;\n readonly type: string;\n}\n\n/** Current cache writes atomically pin ownership; reset never backfills it. */\nexport async function loadRemoteResetPrincipalScope(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<{\n readonly policyRows: readonly PrincipalRow[];\n readonly principalKeys: readonly RemoteResetPrincipalKey[];\n}> {\n const [policyRows, retainedRows, ownershipRows] = await Promise.all([\n tx\n .select({\n id: principalPolicies.principalId,\n type: principalPolicies.principalType,\n })\n .from(principalPolicies),\n Promise.all(\n [\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n ].map((table) =>\n tx\n .selectDistinct({ id: table.principalId, type: table.principalType })\n .from(table),\n ),\n ),\n tx\n .select({\n organizationId: principalPolicyOrganizations.organizationId,\n principalId: principalPolicyOrganizations.principalId,\n principalType: principalPolicyOrganizations.principalType,\n })\n .from(principalPolicyOrganizations),\n ]);\n const owners = new Map(\n ownershipRows.map((row) => [\n `${row.principalType}\\0${row.principalId}`,\n row.organizationId,\n ]),\n );\n for (const row of [...policyRows, ...retainedRows.flat()]) {\n const owner = owners.get(`${row.type}\\0${row.id}`);\n if (row.type === \"group\" && !owner) {\n throw new Error(\n \"Unowned group policy cache requires a local database reset before organization purge\",\n );\n }\n if (row.type !== \"group\" && row.type !== \"organization\") {\n throw new Error(\"Principal policy cache has an invalid principal type\");\n }\n if (\n row.type === \"organization\" &&\n owner !== undefined &&\n owner !== row.id\n ) {\n throw new Error(\n \"Organization policy cache ownership does not match its identity\",\n );\n }\n }\n const keys = new Map<string, RemoteResetPrincipalKey>();\n keys.set(`organization\\0${organizationId}`, {\n principalId: organizationId,\n principalType: \"organization\",\n });\n for (const row of ownershipRows) {\n if (row.principalType !== \"group\" && row.principalType !== \"organization\") {\n throw new Error(\n \"Principal policy cache ownership has an invalid principal type\",\n );\n }\n if (!row.organizationId) {\n throw new Error(\n \"Principal policy cache ownership requires a local database reset\",\n );\n }\n if (row.organizationId !== organizationId) continue;\n keys.set(`${row.principalType}\\0${row.principalId}`, {\n principalId: row.principalId,\n principalType: row.principalType,\n });\n }\n return { policyRows, principalKeys: [...keys.values()] };\n}\n\n// Trust checkpoints and their ownership survive reset. Clearing cached bundles\n// must not turn a previously observed principal or object into first sight.\nexport async function clearRemoteResetPrincipalRows(input: {\n organizationId: string;\n snapshot: { principalKeys: readonly RemoteResetPrincipalKey[] };\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const table of [\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n ])\n await input.tx\n .delete(table)\n .where(eq(table.organizationId, input.organizationId))\n .run();\n await input.tx\n .delete(principalHistoryStages)\n .where(eq(principalHistoryStages.organizationId, input.organizationId))\n .run();\n for (const principalBatch of remoteResetBatches(\n input.snapshot.principalKeys,\n )) {\n for (const table of [\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n ] as const) {\n await input.tx\n .delete(table)\n .where(\n or(\n ...principalBatch.map((principal) =>\n and(\n eq(table.principalType, principal.principalType),\n eq(table.principalId, principal.principalId),\n ),\n ),\n ),\n )\n .run();\n }\n }\n}\n"]}
|