@tearleads/client-sdk 0.1.14 → 0.1.15
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/client/containerContents.js +2 -1
- package/client/containerContents.js.map +1 -1
- package/data/documents/blob/shared/types.d.ts +4 -0
- package/data/documents/blob/shared/types.js.map +1 -1
- package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +2 -0
- package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpointContext.d.ts +2 -1
- package/data/keyingProjectionVerification/checkpointContext.js +22 -0
- package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/containerDestinationVerification.js +11 -1
- package/data/keyingProjectionVerification/containerDestinationVerification.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 +3 -2
- package/data/keyingProjectionVerification/containerProjectionVerification.js +10 -11
- 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 +2 -3
- package/data/keyingProjectionVerification/documentProjectionVerification.js +4 -0
- package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js +14 -12
- package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
- package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js +33 -6
- package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/projectionLifetimes.js +13 -0
- package/data/keyingProjectionVerification/projectionLifetimes.js.map +1 -0
- package/data/keyingProjectionVerification/projectionPolicyEvidence.js +19 -66
- package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/types.d.ts +13 -2
- package/data/keyingProjectionVerification/types.js +15 -0
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/persistence/keyingCheckpointAdvancePersistence.js +4 -1
- package/data/persistence/keyingCheckpointAdvancePersistence.js.map +1 -1
- package/data/persistence/organizationFounderPersistence.js +2 -2
- package/data/persistence/organizationFounderPersistence.js.map +1 -1
- package/data/persistence/principalAuthorizationCheckpoints.js +29 -0
- package/data/persistence/principalAuthorizationCheckpoints.js.map +1 -0
- package/data/persistence/principalHistoryEvidencePersistence.d.ts +30 -0
- package/data/persistence/principalHistoryPrefixPersistence.d.ts +24 -0
- package/data/persistence/principalHistoryPrefixPersistence.js +6 -2
- package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
- package/data/persistence/principalHistoryStagePersistence.d.ts +21 -0
- package/data/principals/principalHistoryRuntime.js +12 -0
- package/data/principals/principalHistoryRuntime.js.map +1 -0
- package/data/principals/principalHistoryStageProtection.js +2 -12
- package/data/principals/principalHistoryStageProtection.js.map +1 -1
- package/data/principals/principalPolicyEvidence.d.ts +2 -2
- package/data/principals/principalPolicyEvidence.js.map +1 -1
- package/data/sqlite/principalHistoryEvidenceSchema.d.ts +308 -0
- package/data/sqlite/principalHistoryStageSchema.d.ts +119 -0
- package/index.d.ts +2 -2
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/api-client/ApiCache.d.ts +54 -0
- package/internal/api-client/ApiClient.d.ts +255 -309
- package/internal/api-client/ApiClient.js +15 -6
- package/internal/api-client/ApiClient.js.map +1 -1
- package/internal/api-client/index.d.ts +1 -0
- package/internal/api-client/index.js.map +1 -1
- package/internal/api-client/principalHistoryDeadline.js +20 -0
- package/internal/api-client/principalHistoryDeadline.js.map +1 -0
- package/internal/api-client/principalHistoryRequest.js +59 -22
- package/internal/api-client/principalHistoryRequest.js.map +1 -1
- package/internal/api-client/principalHistoryRequestContext.js +18 -5
- package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
- package/internal/api-client/principalPolicyRequests.d.ts +799 -0
- package/internal/api-client/principalPolicyRequests.js +9 -4
- package/internal/api-client/principalPolicyRequests.js.map +1 -1
- package/internal/api-client/projectionPolicyHistoryPages.d.ts +9 -0
- package/internal/api-client/projectionPolicyHistoryPages.js +88 -0
- package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -0
- package/internal/api-client/writerProjectionRequests.js +26 -0
- package/internal/api-client/writerProjectionRequests.js.map +1 -0
- package/internal/crypto/keying/principalPolicyHistory.js +4 -0
- package/internal/crypto/keying/principalPolicyHistory.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryTypes.d.ts +2 -0
- package/internal/crypto/keying/principalPolicyHistoryTypes.js.map +1 -1
- package/internal/crypto/projectionHistorySlots.js +0 -4
- package/internal/crypto/projectionHistorySlots.js.map +1 -1
- package/internal/validators/operation/index.d.ts +1 -0
- package/internal/validators/operation/index.js +1 -0
- package/internal/validators/operation/index.js.map +1 -1
- package/internal/validators/operation/principals.d.ts +38 -16
- package/internal/validators/operation/principals.js +11 -5
- package/internal/validators/operation/principals.js.map +1 -1
- package/internal/validators/operation/projectionPolicyHistory.d.ts +512 -0
- package/internal/validators/operation/projectionPolicyHistory.js +37 -0
- package/internal/validators/operation/projectionPolicyHistory.js.map +1 -0
- package/internal/validators/operation/registry.d.ts +2 -0
- package/internal/validators/operation/registry.js +2 -0
- package/internal/validators/operation/registry.js.map +1 -1
- package/internal/validators/operation/writerProjections.d.ts +178 -1224
- package/internal/validators/operation/writerProjections.js +9 -2
- package/internal/validators/operation/writerProjections.js.map +1 -1
- package/internal/validators/response/container.d.ts +84 -612
- package/internal/validators/response/documentMutation.d.ts +84 -612
- package/internal/validators/response/index.d.ts +1 -0
- package/internal/validators/response/index.js +1 -0
- package/internal/validators/response/index.js.map +1 -1
- package/internal/validators/response/organizationBilling.d.ts +1 -0
- package/internal/validators/response/organizationBilling.js +1 -1
- package/internal/validators/response/organizationBilling.js.map +1 -1
- package/internal/validators/response/principalHistoryPreparation.js +28 -1
- package/internal/validators/response/principalHistoryPreparation.js.map +1 -1
- package/internal/validators/response/principalPolicySnapshotPage.d.ts +388 -0
- package/internal/validators/response/principalPolicySnapshotPage.js +24 -0
- package/internal/validators/response/principalPolicySnapshotPage.js.map +1 -0
- package/internal/validators/response/projectionPolicyEvidence.d.ts +85 -613
- package/internal/validators/response/projectionPolicyEvidence.js +10 -5
- package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/attachmentHydration.js +3 -0
- package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
- package/stores/documents/documentStore/syncDetachedAttachments.js +3 -0
- package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
- package/workflows/blobs/decrypt.d.ts +1 -1
- package/workflows/blobs/decrypt.js +3 -1
- package/workflows/blobs/decrypt.js.map +1 -1
- package/workflows/blobs/detach.js +6 -1
- package/workflows/blobs/detach.js.map +1 -1
- package/workflows/blobs/hydrate.d.ts +3 -1
- package/workflows/blobs/hydrate.js +2 -0
- package/workflows/blobs/hydrate.js.map +1 -1
- package/workflows/blobs/retainedAttachmentVerification.js +2 -0
- package/workflows/blobs/retainedAttachmentVerification.js.map +1 -1
- package/workflows/container-contents/container-state/createAdoption.js +2 -0
- package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
- package/workflows/container-contents/container-state/createWithMetadata.js +7 -39
- package/workflows/container-contents/container-state/createWithMetadata.js.map +1 -1
- package/workflows/container-contents/container-state/createWithMetadataPlan.js +68 -0
- package/workflows/container-contents/container-state/createWithMetadataPlan.js.map +1 -0
- package/workflows/container-contents/remoteContainerState.js +3 -1
- package/workflows/container-contents/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/verifiedDestination.js +3 -0
- package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
- package/workflows/container-contents/runtime.d.ts +3 -0
- package/workflows/container-contents/runtime.js +7 -6
- package/workflows/container-contents/runtime.js.map +1 -1
- package/workflows/documents/create.d.ts +2 -15
- package/workflows/documents/create.js +9 -64
- package/workflows/documents/create.js.map +1 -1
- package/workflows/documents/createProjection.d.ts +14 -0
- package/workflows/documents/createProjection.js +26 -0
- package/workflows/documents/createProjection.js.map +1 -0
- package/workflows/documents/createResponse.js +49 -0
- package/workflows/documents/createResponse.js.map +1 -0
- package/workflows/documents/linkSetBlobRewraps.js +2 -0
- package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/runtime.d.ts +3 -0
- package/workflows/documents/runtime.js +3 -2
- package/workflows/documents/runtime.js.map +1 -1
- package/workflows/documents/syncFailureClassification.js +3 -1
- package/workflows/documents/syncFailureClassification.js.map +1 -1
- package/workflows/principals/index.d.ts +2 -0
- package/workflows/principals/index.js +1 -0
- package/workflows/principals/index.js.map +1 -1
- package/workflows/principals/policyVerification.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryAuthority.js +20 -0
- package/workflows/principals/principalHistoryRecoveryAuthority.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryStage.js +1 -1
- package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryTypes.d.ts +3 -3
- package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryVerification.js +6 -1
- package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -1
- package/workflows/principals/principalRecoveryOutage.js +1 -1
- package/workflows/principals/principalRecoveryOutage.js.map +1 -1
- package/workflows/principals/publicPrincipalHistoryAuthority.js +60 -0
- package/workflows/principals/publicPrincipalHistoryAuthority.js.map +1 -0
- package/workflows/principals/publicPrincipalHistoryPage.js +87 -0
- package/workflows/principals/publicPrincipalHistoryPage.js.map +1 -0
- package/workflows/principals/publicPrincipalHistoryProgress.js +178 -0
- package/workflows/principals/publicPrincipalHistoryProgress.js.map +1 -0
- package/workflows/principals/publicPrincipalHistoryTypes.d.ts +39 -0
- package/workflows/principals/publicPrincipalHistoryTypes.js +2 -0
- package/workflows/principals/publicPrincipalHistoryTypes.js.map +1 -0
- package/workflows/principals/publicProjectionDirectory.js +40 -0
- package/workflows/principals/publicProjectionDirectory.js.map +1 -0
- package/workflows/principals/publicProjectionPrincipal.js +53 -0
- package/workflows/principals/publicProjectionPrincipal.js.map +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.js +4 -1
- package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/recoverProjectionPolicyHistory.d.ts +9 -0
- package/workflows/principals/recoverProjectionPolicyHistory.js +98 -0
- package/workflows/principals/recoverProjectionPolicyHistory.js.map +1 -0
- package/workflows/principals/recoverPublicPrincipalHistory.js +176 -0
- package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +2 -5
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +2 -1
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimePolicyWarmer.js +2 -0
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js +56 -0
- package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -0
- package/workflows/principals/selectPublicPrincipalHistory.js +90 -0
- package/workflows/principals/selectPublicPrincipalHistory.js.map +1 -0
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +21 -153
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projectionAuthorizationEvidence.js","sourceRoot":"","sources":["projectionAuthorizationEvidence.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"projectionAuthorizationEvidence.js","sourceRoot":"","sources":["projectionAuthorizationEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EAC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AAK,CAAC,cAAc;QACpC,UAAU;QACV,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,cAAc,CAAC,YAAY;QACnC,yBAAyB,CAAC,KAAK,CAAC,iBAAiB,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;IAC7E,KAAK,CAAC,iBAAiB,CAAC,qBAAqB,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;IAC1E,OAAO,sCAAsC,CAAC;QAC5C,GAAG,KAAK;QACR,QAAQ,EAAE,SAAS,CAAC,QAAQ;KAC7B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n KeyingVerificationError,\n principalPolicyMatchesReference,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ProjectionPolicyEvidenceResponse,\n} from \"@tearleads/validators/response\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport { collectReferencedPrincipalPolicies } from \"./principalPolicyVerification\";\nimport { observeProjectionLifetime } from \"./projectionLifetimes\";\nimport { verifyProjectionPolicyEvidence } from \"./projectionPolicyEvidence\";\nimport { readAccessManifest } from \"./readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\n\n/** Locally planned successors may cite an already verified, uncommitted policy. */\nasync function resolveProjectionAuthorizationEvidence(input: {\n readonly bundles: readonly AccessManifestBundleWireResponse[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly evidence: readonly PrincipalPolicyAuthorization[];\n readonly organizationId: string;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<PrincipalPolicyAuthorization[]> {\n const references = input.bundles\n .flatMap(\n (bundle) =>\n readAccessManifest(bundle.manifest, \"Projection manifest\")\n .referencedPrincipalHeads,\n )\n .filter(\n (reference) =>\n !input.evidence.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n ),\n );\n const known = [...input.principalPolicyCache.values()];\n if (\n references.some(\n (reference) =>\n !known.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required principal policy evidence\",\n );\n return [\n ...input.evidence,\n ...(await collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n })),\n ];\n}\n\nexport async function verifyProjectionAuthorizationEvidence(\n input: Omit<\n Parameters<typeof resolveProjectionAuthorizationEvidence>[0],\n \"evidence\"\n > & { readonly policyEvidence: ProjectionPolicyEvidenceResponse },\n) {\n const sources = [\n input.policyEvidence.organization,\n ...input.policyEvidence.groups,\n ];\n const known = [...input.principalPolicyCache.values()];\n const references = input.bundles\n .flatMap(\n (bundle) =>\n readAccessManifest(bundle.manifest, \"Projection manifest\")\n .referencedPrincipalHeads,\n )\n .filter((reference) => {\n if (\n sources.some(\n (source) =>\n source &&\n source.head.principalType === reference.principalType &&\n source.head.principalId === reference.principalId &&\n source.head.version >= reference.version,\n )\n )\n return true;\n // Locally planned successors are verified below through the current-policy path.\n if (\n known.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n )\n )\n return false;\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required principal policy evidence\",\n );\n });\n const recovered = await verifyProjectionPolicyEvidence({\n evidence: input.policyEvidence,\n organizationId: input.organizationId,\n references,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (input.policyEvidence.organization)\n observeProjectionLifetime(input.checkpointContext, recovered.stillCurrent);\n input.checkpointContext.authorizationPolicies.push(...recovered.policies);\n return resolveProjectionAuthorizationEvidence({\n ...input,\n evidence: recovered.policies,\n });\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const lifetimes = new WeakMap();
|
|
2
|
+
export function observeProjectionLifetime(context, current) {
|
|
3
|
+
const guards = lifetimes.get(context) ?? [];
|
|
4
|
+
guards.push(current);
|
|
5
|
+
lifetimes.set(context, guards);
|
|
6
|
+
}
|
|
7
|
+
export function projectionLifetimeGuard(context, current) {
|
|
8
|
+
if (!lifetimes.has(context))
|
|
9
|
+
return current;
|
|
10
|
+
return () => current?.() !== false &&
|
|
11
|
+
(lifetimes.get(context)?.every((guard) => guard()) ?? true);
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=projectionLifetimes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"projectionLifetimes.js","sourceRoot":"","sources":["projectionLifetimes.ts"],"names":[],"mappings":"AAAA,MAAM,SAAS,GAAG,IAAI,OAAO,EAA6B,CAAC;AAE3D,MAAM,UAAU,yBAAyB,CACvC,OAAe,EACf,OAAsB;IAEtB,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;IAC5C,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACrB,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,OAAe,EACf,OAAqC;IAErC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,OAAO,OAAO,CAAC;IAC5C,OAAO,GAAG,EAAE,CACV,OAAO,EAAE,EAAE,KAAK,KAAK;QACrB,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC;AAChE,CAAC","sourcesContent":["const lifetimes = new WeakMap<object, (() => boolean)[]>();\n\nexport function observeProjectionLifetime(\n context: object,\n current: () => boolean,\n): void {\n const guards = lifetimes.get(context) ?? [];\n guards.push(current);\n lifetimes.set(context, guards);\n}\n\nexport function projectionLifetimeGuard(\n context: object,\n current?: (() => boolean) | undefined,\n): (() => boolean) | undefined {\n if (!lifetimes.has(context)) return current;\n return () =>\n current?.() !== false &&\n (lifetimes.get(context)?.every((guard) => guard()) ?? true);\n}\n"]}
|
|
@@ -1,70 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
throw new KeyingVerificationError("object_mismatch", `Projection policy evidence: ${message}`);
|
|
6
|
-
}
|
|
7
|
-
async function verifyDirectories(input) {
|
|
8
|
-
const states = new Map(input.organization.history.map(({ state }) => [state.stateHash, state]));
|
|
9
|
-
const descriptors = [];
|
|
10
|
-
for (const payload of input.evidence.organizationPayloads) {
|
|
11
|
-
const state = states.get(payload.stateHash);
|
|
12
|
-
if (!state ||
|
|
13
|
-
payload.principalType !== "organization" ||
|
|
14
|
-
payload.principalId !== input.organizationId)
|
|
15
|
-
reject("directory payload scope is invalid");
|
|
16
|
-
const hash = await computePrincipalStatePayloadCiphertextHash(payload.ciphertext);
|
|
17
|
-
if (hash !== state.payloadCiphertextHash || hash !== payload.ciphertextHash)
|
|
18
|
-
reject("directory payload does not match its signed hash");
|
|
19
|
-
const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);
|
|
20
|
-
if (descriptor.organizationId !== input.organizationId)
|
|
21
|
-
reject("directory belongs to another organization");
|
|
22
|
-
descriptors.push(descriptor);
|
|
23
|
-
states.delete(payload.stateHash);
|
|
24
|
-
}
|
|
25
|
-
// Only directory payloads needed to bind the supplied group heads are
|
|
26
|
-
// required. The organization's complete signed state chain is verified above;
|
|
27
|
-
// unrelated payload bodies add no authority and need not be disclosed.
|
|
28
|
-
return descriptors;
|
|
29
|
-
}
|
|
30
|
-
/** Evidence authenticates signed citations only; it never becomes current policy. */
|
|
1
|
+
import { KeyingVerificationError, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "./dependencyUnavailable.js";
|
|
3
|
+
import { assertProjectionVerificationCurrent, } from "./types.js";
|
|
4
|
+
/** Recover public authorization without admitting historical heads as current policy. */
|
|
31
5
|
export async function verifyProjectionPolicyEvidence(input) {
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
evidence.groups.some((group) => group.currentState.principalType !== "group"))
|
|
41
|
-
reject("principal scope is invalid");
|
|
42
|
-
const policies = await verifyPrincipalPolicySnapshots({
|
|
43
|
-
resolveUserKey: input.resolveUserKey,
|
|
44
|
-
snapshots: [evidence.organization, ...evidence.groups],
|
|
45
|
-
});
|
|
46
|
-
const organization = policies.find((policy) => policy.principalType === "organization");
|
|
47
|
-
if (!organization)
|
|
48
|
-
reject("organization snapshot is missing");
|
|
49
|
-
const directories = await verifyDirectories({ ...input, organization });
|
|
50
|
-
for (const group of policies.filter((policy) => policy.principalType === "group")) {
|
|
51
|
-
const directory = directories.find((candidate) => candidate.groupHeads.some((reference) => principalHeadMatchesReference(group.state, reference)));
|
|
52
|
-
if (!directory)
|
|
53
|
-
reject("group state is absent from signed directory history");
|
|
54
|
-
// The snapshot's authenticated predecessor chain supplies older states;
|
|
55
|
-
// only its bound head needs to appear in a directory payload.
|
|
56
|
-
for (const { state } of group.history) {
|
|
57
|
-
if (state.externalAuthority &&
|
|
58
|
-
state.externalAuthority.principalId !== directory.adminGroupId)
|
|
59
|
-
reject("group authority is not the organization's Admins group");
|
|
60
|
-
}
|
|
6
|
+
const stillCurrent = () => input.stillCurrent?.() !== false;
|
|
7
|
+
assertProjectionVerificationCurrent(stillCurrent);
|
|
8
|
+
if (!input.evidence.organization) {
|
|
9
|
+
if (input.evidence.groups.length ||
|
|
10
|
+
input.evidence.organizationPayloads.length ||
|
|
11
|
+
input.references.length)
|
|
12
|
+
throw new KeyingVerificationError("missing_dependency", "Projection omits required organization history");
|
|
13
|
+
return { policies: [], stillCurrent };
|
|
61
14
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
return
|
|
15
|
+
const resolve = input.warmReferencedPrincipalPolicies?.resolveProjectionHistory;
|
|
16
|
+
if (!resolve)
|
|
17
|
+
throw new ProjectionDependencyUnavailableError("Private projection history recovery is unavailable");
|
|
18
|
+
const result = await resolve({ ...input, stillCurrent });
|
|
19
|
+
assertProjectionVerificationCurrent(stillCurrent);
|
|
20
|
+
assertProjectionVerificationCurrent(result.stillCurrent);
|
|
21
|
+
return result;
|
|
69
22
|
}
|
|
70
23
|
//# sourceMappingURL=projectionPolicyEvidence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projectionPolicyEvidence.js","sourceRoot":"","sources":["projectionPolicyEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,
|
|
1
|
+
{"version":3,"file":"projectionPolicyEvidence.js","sourceRoot":"","sources":["projectionPolicyEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,EACL,mCAAmC,GAGpC,MAAM,SAAS,CAAC;AAEjB,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAQpD;IACC,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,CAAC;IAC5D,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC;QACjC,IACE,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM;YAC5B,KAAK,CAAC,QAAQ,CAAC,oBAAoB,CAAC,MAAM;YAC1C,KAAK,CAAC,UAAU,CAAC,MAAM;YAEvB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,gDAAgD,CACjD,CAAC;QACJ,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,YAAY,EAAE,CAAC;IACxC,CAAC;IACD,MAAM,OAAO,GACX,KAAK,CAAC,+BAA+B,EAAE,wBAAwB,CAAC;IAClE,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,oDAAoD,CACrD,CAAC;IACJ,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;IACzD,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,mCAAmC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IACzD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedProjectionPolicyHistory,\n} from \"./types\";\n\n/** Recover public authorization without admitting historical heads as current policy. */\nexport async function verifyProjectionPolicyEvidence(input: {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<ResolvedProjectionPolicyHistory> {\n const stillCurrent = () => input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n if (!input.evidence.organization) {\n if (\n input.evidence.groups.length ||\n input.evidence.organizationPayloads.length ||\n input.references.length\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required organization history\",\n );\n return { policies: [], stillCurrent };\n }\n const resolve =\n input.warmReferencedPrincipalPolicies?.resolveProjectionHistory;\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Private projection history recovery is unavailable\",\n );\n const result = await resolve({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(result.stillCurrent);\n return result;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
|
|
2
|
-
import type { PrincipalPolicyBundleResponse } from "../../internal/validators/response/index.js";
|
|
1
|
+
import type { ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent, VerifiedPrincipalPolicySelection } from "../../internal/crypto/index.js";
|
|
2
|
+
import type { PrincipalPolicyBundleResponse, ProjectionPolicyEvidenceResponse } from "../../internal/validators/response/index.js";
|
|
3
3
|
import type { PrincipalPolicyCurrentEvidence } from "../principals/principalPolicyEvidence.js";
|
|
4
4
|
import type { TrustedUserIdentity } from "../trustedUserIdentity/index.js";
|
|
5
5
|
export type ProjectionUserKey = TrustedUserIdentity;
|
|
@@ -28,9 +28,20 @@ export interface PrincipalPolicyBundleCacheRequest {
|
|
|
28
28
|
readonly organizationId: string;
|
|
29
29
|
readonly stillCurrent?: (() => boolean) | undefined;
|
|
30
30
|
}
|
|
31
|
+
export interface ProjectionPolicyHistoryResolveRequest {
|
|
32
|
+
readonly organizationId: string;
|
|
33
|
+
readonly evidence: ProjectionPolicyEvidenceResponse;
|
|
34
|
+
readonly references: readonly ReferencedPrincipalHead[];
|
|
35
|
+
readonly stillCurrent?: (() => boolean) | undefined;
|
|
36
|
+
}
|
|
37
|
+
export interface ResolvedProjectionPolicyHistory {
|
|
38
|
+
readonly policies: readonly VerifiedPrincipalPolicySelection[];
|
|
39
|
+
readonly stillCurrent: () => boolean;
|
|
40
|
+
}
|
|
31
41
|
export type PrincipalPolicyBundleCacher = (input: PrincipalPolicyBundleCacheRequest) => Promise<void>;
|
|
32
42
|
export type ReferencedPrincipalPolicyWarmer = ((input: ReferencedPrincipalPolicyWarmRequest) => Promise<void>) & {
|
|
33
43
|
readonly cacheBundles?: PrincipalPolicyBundleCacher | undefined;
|
|
44
|
+
readonly resolveProjectionHistory?: ((input: ProjectionPolicyHistoryResolveRequest) => Promise<ResolvedProjectionPolicyHistory>) | undefined;
|
|
34
45
|
readonly resolveReference?: ((input: PrincipalPolicyResolveRequest) => Promise<ResolvedPrincipalPolicyEvidence>) | undefined;
|
|
35
46
|
};
|
|
36
47
|
export declare class ProjectionVerificationCancelledError extends Error {
|
|
@@ -38,7 +38,22 @@ export function generationGuardedPrincipalPolicyWarmer(warmer, stillCurrent) {
|
|
|
38
38
|
const guardWithCapabilities = (operation) => {
|
|
39
39
|
const guarded = guard(operation);
|
|
40
40
|
const resolve = operation.resolveReference;
|
|
41
|
+
const resolveProjectionHistory = operation.resolveProjectionHistory;
|
|
41
42
|
return Object.assign(guarded, {
|
|
43
|
+
...(resolveProjectionHistory
|
|
44
|
+
? {
|
|
45
|
+
resolveProjectionHistory: async (input) => {
|
|
46
|
+
const current = () => stillCurrent() && input.stillCurrent?.() !== false;
|
|
47
|
+
assertProjectionVerificationCurrent(current);
|
|
48
|
+
const result = await resolveProjectionHistory({
|
|
49
|
+
...input,
|
|
50
|
+
stillCurrent: current,
|
|
51
|
+
});
|
|
52
|
+
assertProjectionVerificationCurrent(current);
|
|
53
|
+
return result;
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
: {}),
|
|
42
57
|
...(resolve
|
|
43
58
|
? {
|
|
44
59
|
resolveReference: async (input) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA+EA,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D;QACE,KAAK,CAAC,4CAA4C,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,MAAM,kCAAkC,GACtC,IAAI,oCAAoC,EAAE,CAAC;AAE7C,MAAM,UAAU,sCAAsC,CACpD,KAAc;IAEd,OAAO,KAAK,KAAK,kCAAkC,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,sCAAsC,CAAC,KAAc;IACnE,IAAI,sCAAsC,CAAC,KAAK,CAAC;QAAE,MAAM,KAAK,CAAC;AACjE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,SAA2B;IAE3B,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,sCAAsC,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC/D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,YAAyC;IAEzC,IAAI,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QAC/B,MAAM,kCAAkC,CAAC;IAC3C,CAAC;AACH,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,MAAmD,EACnD,YAAyC;IAEzC,IAAI,CAAC,MAAM,IAAI,CAAC,YAAY;QAAE,OAAO,MAAM,CAAC;IAC5C,MAAM,KAAK,GACT,CAAC,SAA0C,EAAE,EAAE,CAC/C,KAAK,EAAE,KAA2C,EAAE,EAAE;QACpD,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,MAAM,SAAS,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAA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;gBACH,CAAC,CAAC,EAAE,CAAC;YACP,GAAG,CAAC,SAAS,CAAC,YAAY;gBACxB,CAAC,CAAC;oBACE,YAAY,EAAE,KAAK,EAAE,KAAwC,EAAE,EAAE;wBAC/D,mCAAmC,CAAC,YAAY,CAAC,CAAC;wBAClD,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;wBAC3D,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBACpD,CAAC;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC;SACR,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAO/C,KAAY;IACZ,OAAO;QACL,GAAG,KAAK;QACR,+BAA+B,EAAE,sCAAsC,CACrE,KAAK,CAAC,+BAA+B,EACrC,KAAK,CAAC,YAAY,CACnB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyCurrent,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ProjectionPolicyEvidenceResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\n\nexport type ProjectionUserKey = TrustedUserIdentity;\n\nexport type ProjectionUserKeyResolver = (\n userId: string,\n) => Promise<ProjectionUserKey | null>;\n\nexport type PrincipalPolicyCache = Map<string, PrincipalPolicyCurrentEvidence>;\n\nexport interface PrincipalPolicyResolveRequest {\n /** Identity of one projection collection, never caller-supplied evidence. */\n readonly recoveryBatch?: object | undefined;\n readonly organizationId: string;\n readonly reference: ReferencedPrincipalHead;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedPrincipalPolicyEvidence {\n readonly stillCurrent: () => boolean;\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nexport interface ReferencedPrincipalPolicyWarmRequest {\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface PrincipalPolicyBundleCacheRequest {\n readonly bundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ProjectionPolicyHistoryResolveRequest {\n readonly organizationId: string;\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedProjectionPolicyHistory {\n readonly policies: readonly VerifiedPrincipalPolicySelection[];\n readonly stillCurrent: () => boolean;\n}\n\nexport type PrincipalPolicyBundleCacher = (\n input: PrincipalPolicyBundleCacheRequest,\n) => Promise<void>;\n\nexport type ReferencedPrincipalPolicyWarmer = ((\n input: ReferencedPrincipalPolicyWarmRequest,\n) => Promise<void>) & {\n readonly cacheBundles?: PrincipalPolicyBundleCacher | undefined;\n readonly resolveProjectionHistory?:\n | ((\n input: ProjectionPolicyHistoryResolveRequest,\n ) => Promise<ResolvedProjectionPolicyHistory>)\n | undefined;\n readonly resolveReference?:\n | ((\n input: PrincipalPolicyResolveRequest,\n ) => Promise<ResolvedPrincipalPolicyEvidence>)\n | undefined;\n};\n\nexport class ProjectionVerificationCancelledError extends Error {\n constructor() {\n super(\"Projection verification generation expired\");\n this.name = \"ProjectionVerificationCancelledError\";\n }\n}\n\nconst projectionVerificationCancellation =\n new ProjectionVerificationCancelledError();\n\nexport function isProjectionVerificationCancelledError(\n error: unknown,\n): error is ProjectionVerificationCancelledError {\n return error === projectionVerificationCancellation;\n}\n\nexport function rethrowProjectionVerificationCancelled(error: unknown): void {\n if (isProjectionVerificationCancelledError(error)) throw error;\n}\n\nexport async function nullOnProjectionVerificationCancellation<T>(\n operation: () => Promise<T>,\n): Promise<T | null> {\n try {\n return await operation();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n throw error;\n }\n}\n\nexport function assertProjectionVerificationCurrent(\n stillCurrent: (() => boolean) | undefined,\n): void {\n if (stillCurrent?.() === false) {\n throw projectionVerificationCancellation;\n }\n}\n\nexport function generationGuardedPrincipalPolicyWarmer(\n warmer: ReferencedPrincipalPolicyWarmer | undefined,\n stillCurrent: (() => boolean) | undefined,\n): ReferencedPrincipalPolicyWarmer | undefined {\n if (!warmer || !stillCurrent) return warmer;\n const guard =\n (operation: ReferencedPrincipalPolicyWarmer) =>\n async (input: ReferencedPrincipalPolicyWarmRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n };\n const guardWithCapabilities = (\n operation: ReferencedPrincipalPolicyWarmer,\n ): ReferencedPrincipalPolicyWarmer => {\n const guarded = guard(operation);\n const resolve = operation.resolveReference;\n const resolveProjectionHistory = operation.resolveProjectionHistory;\n return Object.assign(guarded, {\n ...(resolveProjectionHistory\n ? {\n resolveProjectionHistory: async (\n input: ProjectionPolicyHistoryResolveRequest,\n ) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolveProjectionHistory({\n ...input,\n stillCurrent: current,\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n ...(resolve\n ? {\n resolveReference: async (input: PrincipalPolicyResolveRequest) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolve({ ...input, stillCurrent: current });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n ...(operation.cacheBundles\n ? {\n cacheBundles: async (input: PrincipalPolicyBundleCacheRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation.cacheBundles?.({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n },\n }\n : {}),\n });\n };\n return guardWithCapabilities(warmer);\n}\n\nexport function withGenerationGuardedPolicyWarmer<\n Input extends {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n },\n>(input: Input): Input {\n return {\n ...input,\n warmReferencedPrincipalPolicies: generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n ),\n };\n}\n"]}
|
|
@@ -5,6 +5,7 @@ import { ensureSqlTables } from "../sqlite/sqlSchema.js";
|
|
|
5
5
|
import { storeDocumentPurgeCheckpointInTransaction, } from "./documentPurgeCheckpointPersistence.js";
|
|
6
6
|
import { validateAccessManifestCheckpointEvidence } from "./keyingCheckpointEvidence.js";
|
|
7
7
|
import { accessManifestObjectKey, loadStoredAccessManifestCheckpoint, loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertAccessManifestCheckpointInTransaction, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpointPersistence.js";
|
|
8
|
+
import { validatePrincipalAuthorizationCheckpoints } from "./principalAuthorizationCheckpoints.js";
|
|
8
9
|
import { assertContainerNotRetired } from "./principalGrantRetirementPersistence.js";
|
|
9
10
|
import { assertPrincipalPolicyBundleStoredInTransaction, writePrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
|
|
10
11
|
import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
|
|
@@ -106,7 +107,7 @@ async function writePolicyCheckpoints(tx, pending, updatedAt, organizationId) {
|
|
|
106
107
|
}
|
|
107
108
|
}
|
|
108
109
|
async function ensureKeyingCheckpointValidationTables(input) {
|
|
109
|
-
await ensureSqlTables(input.execSql, input.policies.length > 0
|
|
110
|
+
await ensureSqlTables(input.execSql, input.policies.length > 0 || (input.authorizationPolicies?.length ?? 0) > 0
|
|
110
111
|
? [...principalPolicyTables, ...keyingCheckpointTables]
|
|
111
112
|
: keyingCheckpointTables);
|
|
112
113
|
}
|
|
@@ -116,6 +117,7 @@ export async function validateKeyingCheckpointsAtomically(input) {
|
|
|
116
117
|
const validate = async (tx) => {
|
|
117
118
|
await validateAccessAdvances(tx, input.access);
|
|
118
119
|
await validatePolicyAdvances(tx, input.policies);
|
|
120
|
+
await validatePrincipalAuthorizationCheckpoints(tx, input.authorizationPolicies ?? []);
|
|
119
121
|
};
|
|
120
122
|
const runtime = getClientSQLitePersistenceRuntime(input.execSql);
|
|
121
123
|
if (input.stillCurrent) {
|
|
@@ -139,6 +141,7 @@ export async function advanceKeyingCheckpointsAtomically(input) {
|
|
|
139
141
|
const advance = async (tx) => {
|
|
140
142
|
const access = await validateAccessAdvances(tx, input.access);
|
|
141
143
|
const policies = await validatePolicyAdvances(tx, input.policies);
|
|
144
|
+
await validatePrincipalAuthorizationCheckpoints(tx, input.authorizationPolicies ?? []);
|
|
142
145
|
await writeAccessCheckpoints(tx, access, updatedAt);
|
|
143
146
|
await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);
|
|
144
147
|
if (input.documentPurgeCheckpoint) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAIvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,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D,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { assertContainerNotRetired } from \"./principalGrantRetirementPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ninterface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\nasync function validatePolicyAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\nasync function writePolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\nasync function ensureKeyingCheckpointValidationTables(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureSqlTables(\n input.execSql,\n input.policies.length > 0\n ? [...principalPolicyTables, ...keyingCheckpointTables]\n : keyingCheckpointTables,\n );\n}\n\n/** Re-checks verified candidates against durable pins without advancing them. */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePolicyAdvances(tx, input.policies);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(input: {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly policies: readonly CheckpointPolicy[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePolicyAdvances(tx, input.policies);\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n\n/**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n const seen = new Set<string>();\n for (const entry of input.entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const persist = async (tx: ClientSQLiteTransactionScope) => {\n const policies = await validatePolicyAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePolicyCheckpoints(\n tx,\n policies,\n input.updatedAt,\n input.organizationId,\n );\n for (const policy of policies.values()) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\n \"Verified principal policy checkpoint was not persisted\",\n );\n }\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(persist, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(persist, { behavior: \"immediate\" });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAKvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAClC,mCAAmC,EACnC,kBAAkB,EAClB,2CAA2C,EAC3C,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAChG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,MAAM,CAAC,OAAO;gBACrC,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EACzC,CAAC;gBACD,MAAM,IAAI,KAAK,CACb,wDAAwD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\nimport { assertContainerNotRetired } from \"./principalGrantRetirementPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ninterface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\nasync function validatePolicyAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\nasync function writePolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\nasync function ensureKeyingCheckpointValidationTables(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureSqlTables(\n input.execSql,\n input.policies.length > 0 || (input.authorizationPolicies?.length ?? 0) > 0\n ? [...principalPolicyTables, ...keyingCheckpointTables]\n : keyingCheckpointTables,\n );\n}\n\n/** Re-checks verified candidates against durable pins without advancing them. */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(input: {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n\n/**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n const seen = new Set<string>();\n for (const entry of input.entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const persist = async (tx: ClientSQLiteTransactionScope) => {\n const policies = await validatePolicyAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePolicyCheckpoints(\n tx,\n policies,\n input.updatedAt,\n input.organizationId,\n );\n for (const policy of policies.values()) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\n \"Verified principal policy checkpoint was not persisted\",\n );\n }\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(persist, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(persist, { behavior: \"immediate\" });\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
1
|
+
import { KeyingVerificationError, } from "../../internal/crypto/index.js";
|
|
2
2
|
import { eq } from "drizzle-orm";
|
|
3
|
-
import { principalPolicyEvidenceEntries
|
|
3
|
+
import { principalPolicyEvidenceEntries } from "../principals/principalPolicyEvidence.js";
|
|
4
4
|
import { organizationFounders } from "../sqlite/organizationFounderSchema.js";
|
|
5
5
|
import { keyingCheckpointTables } from "../sqlite/schema.js";
|
|
6
6
|
import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationFounderPersistence.js","sourceRoot":"","sources":["organizationFounderPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"organizationFounderPersistence.js","sourceRoot":"","sources":["organizationFounderPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEpE,SAAS,iBAAiB,CACxB,MAAgD,EAChD,OAAiD;IAEjD,IACE,MAAM,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM;QAChC,MAAM,CAAC,qBAAqB,KAAK,OAAO,CAAC,qBAAqB;QAC9D,MAAM,CAAC,gBAAgB,KAAK,OAAO,CAAC,gBAAgB;QAEpD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,iEAAiE,CAClE,CAAC;AACN,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,OAAgB,EAChB,cAAsB;IAEtB,MAAM,eAAe,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,iCAAiC,CAAC,OAAO,C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AAE;aACtB,MAAM,EAAE;aACR,IAAI,CAAC,oBAAoB,CAAC;aAC1B,KAAK,CAAC,EAAE,CAAC,oBAAoB,CAAC,cAAc,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;aACtE,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,IAAI,MAAM,EAAE,CAAC;YACX,iBAAiB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACnC,OAAO;QACT,CAAC;QACD,MAAM,EAAE;aACL,MAAM,CAAC,oBAAoB,CAAC;aAC5B,MAAM,CAAC,OAAO,CAAC;aACf,mBAAmB,EAAE;aACrB,GAAG,EAAE,CAAC;IACX,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { principalPolicyEvidenceEntries } from \"../principals/principalPolicyEvidence\";\nimport { organizationFounders } from \"../sqlite/organizationFounderSchema\";\nimport { keyingCheckpointTables } from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nfunction assertSameFounder(\n stored: typeof organizationFounders.$inferSelect,\n founder: typeof organizationFounders.$inferInsert,\n): void {\n if (\n stored.userId !== founder.userId ||\n stored.signingKeyFingerprint !== founder.signingKeyFingerprint ||\n stored.genesisStateHash !== founder.genesisStateHash\n )\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Organization founder conflicts with its durable genesis binding\",\n );\n}\n\nexport async function loadOrganizationFounder(\n execSql: ExecSql,\n organizationId: string,\n): Promise<typeof organizationFounders.$inferSelect | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const [stored] = await runtime.db\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, organizationId))\n .limit(1);\n return stored ?? null;\n}\n\n/** Pin verified genesis, never a later administrator or a folder's creator. */\nexport async function rememberOrganizationFounder(input: {\n readonly execSql: ExecSql;\n readonly organization: PrincipalPolicyAuthorization;\n}): Promise<void> {\n const genesis = principalPolicyEvidenceEntries(input.organization).find(\n ({ state }) => state.version === 1,\n )?.state;\n if (\n genesis?.principalType !== \"organization\" ||\n genesis.prevStateHash !== null\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization founder requires verified genesis\",\n );\n const founder = {\n organizationId: genesis.principalId,\n userId: genesis.signerUserId,\n signingKeyFingerprint: genesis.signerUserKeyFingerprint,\n genesisStateHash: genesis.stateHash,\n };\n const held = await loadOrganizationFounder(\n input.execSql,\n founder.organizationId,\n );\n if (held) {\n assertSameFounder(held, founder);\n return;\n }\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n await runtime.transaction(\n async (tx) => {\n const [stored] = await tx\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, founder.organizationId))\n .limit(1);\n if (stored) {\n assertSameFounder(stored, founder);\n return;\n }\n await tx\n .insert(organizationFounders)\n .values(founder)\n .onConflictDoNothing()\n .run();\n },\n { behavior: \"immediate\" },\n );\n}\n"]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { KeyingVerificationError, verifyPrincipalPolicyCheckpoint, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { loadStoredPrincipalPolicyCheckpoint } from "./keyingCheckpointPersistence.js";
|
|
3
|
+
export class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {
|
|
4
|
+
constructor() {
|
|
5
|
+
super("missing_dependency", "Public authorization cannot connect to the latest durable checkpoint");
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
/** Historical capabilities validate trust but never advance current-policy pins. */
|
|
9
|
+
export async function validatePrincipalAuthorizationCheckpoints(tx, policies) {
|
|
10
|
+
for (const policy of policies) {
|
|
11
|
+
const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);
|
|
12
|
+
if (!checkpoint)
|
|
13
|
+
continue;
|
|
14
|
+
const matchingHead = policies.filter((other) => other.principalType === policy.principalType &&
|
|
15
|
+
other.principalId === policy.principalId &&
|
|
16
|
+
other.stateHash === policy.stateHash);
|
|
17
|
+
const chain = matchingHead.flatMap((other) => other.retainedHistory);
|
|
18
|
+
if (checkpoint.version > policy.version ||
|
|
19
|
+
(checkpoint.version < policy.version &&
|
|
20
|
+
!chain.some(({ state }) => state.version === checkpoint.version)))
|
|
21
|
+
throw new PrincipalAuthorizationCheckpointUnavailableError();
|
|
22
|
+
verifyPrincipalPolicyCheckpoint({
|
|
23
|
+
chain,
|
|
24
|
+
currentState: policy.state,
|
|
25
|
+
localCheckpoint: checkpoint,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=principalAuthorizationCheckpoints.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalAuthorizationCheckpoints.js","sourceRoot":"","sources":["principalAuthorizationCheckpoints.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAEpF,MAAM,OAAO,gDAAiD,SAAQ,uBAAuB;IAC3F;QACE,KAAK,CACH,oBAAoB,EACpB,sEAAsE,CACvE,CAAC;IACJ,CAAC;CACF;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,QAAqD;IAErD,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;QACzE,IAAI,CAAC,UAAU;YAAE,SAAS;QAC1B,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAClC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,MAAM,CAAC,aAAa;YAC5C,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;YACxC,KAAK,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,CACvC,CAAC;QACF,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;QACrE,IACE,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;YACnC,CAAC,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;gBAClC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAAC,CAAC;YAEnE,MAAM,IAAI,gDAAgD,EAAE,CAAC;QAC/D,+BAA+B,CAAC;YAC9B,KAAK;YACL,YAAY,EAAE,MAAM,CAAC,KAAK;YAC1B,eAAe,EAAE,UAAU;SAC5B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { loadStoredPrincipalPolicyCheckpoint } from \"./keyingCheckpointPersistence\";\n\nexport class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {\n constructor() {\n super(\n \"missing_dependency\",\n \"Public authorization cannot connect to the latest durable checkpoint\",\n );\n }\n}\n\n/** Historical capabilities validate trust but never advance current-policy pins. */\nexport async function validatePrincipalAuthorizationCheckpoints(\n tx: ClientSQLiteTransactionScope,\n policies: readonly VerifiedPrincipalPolicySelection[],\n): Promise<void> {\n for (const policy of policies) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (!checkpoint) continue;\n const matchingHead = policies.filter(\n (other) =>\n other.principalType === policy.principalType &&\n other.principalId === policy.principalId &&\n other.stateHash === policy.stateHash,\n );\n const chain = matchingHead.flatMap((other) => other.retainedHistory);\n if (\n checkpoint.version > policy.version ||\n (checkpoint.version < policy.version &&\n !chain.some(({ state }) => state.version === checkpoint.version))\n )\n throw new PrincipalAuthorizationCheckpointUnavailableError();\n verifyPrincipalPolicyCheckpoint({\n chain,\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n }\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type PrincipalHistoryIndexNode, type PrincipalPolicyHistoryReferenceProof, type ReferencedPrincipalHead, type VerifiedPrincipalPolicyHistory } from "../../internal/crypto/index.js";
|
|
2
|
+
import { type PrincipalPolicyStateChainEntryResponse } from "../../internal/validators/response/index.js";
|
|
3
|
+
import { type ClientSQLiteTransactionScope } from "../sqlite/sqlitePersistenceRuntime.js";
|
|
4
|
+
import { type ExecSql } from "../sqlite/sqlSchema.js";
|
|
5
|
+
export interface PrincipalHistoryEvidencePage {
|
|
6
|
+
readonly scopeId: string;
|
|
7
|
+
readonly organizationId: string;
|
|
8
|
+
readonly entries: readonly {
|
|
9
|
+
readonly leafHash: string;
|
|
10
|
+
readonly entryJson: string;
|
|
11
|
+
}[];
|
|
12
|
+
readonly nodes: readonly PrincipalHistoryIndexNode[];
|
|
13
|
+
}
|
|
14
|
+
/** Prepare only a page accepted by the signature/authorization verifier. */
|
|
15
|
+
export declare function preparePrincipalHistoryEvidencePage(input: {
|
|
16
|
+
readonly scopeId: string;
|
|
17
|
+
readonly organizationId: string;
|
|
18
|
+
readonly entries: readonly PrincipalPolicyStateChainEntryResponse[];
|
|
19
|
+
readonly nodes: readonly PrincipalHistoryIndexNode[];
|
|
20
|
+
}): Promise<PrincipalHistoryEvidencePage>;
|
|
21
|
+
/** Publish in the same guarded transaction as the accepted page's progress. */
|
|
22
|
+
export declare function writePrincipalHistoryEvidencePage(tx: ClientSQLiteTransactionScope, page: PrincipalHistoryEvidencePage): Promise<void>;
|
|
23
|
+
/** Returns untrusted material. The caller must verify it against the issued root. */
|
|
24
|
+
export declare function loadPrincipalHistoryReference(input: {
|
|
25
|
+
readonly execSql: ExecSql;
|
|
26
|
+
readonly scopeId: string;
|
|
27
|
+
readonly history: VerifiedPrincipalPolicyHistory;
|
|
28
|
+
readonly version: number;
|
|
29
|
+
readonly expectedReference?: ReferencedPrincipalHead | undefined;
|
|
30
|
+
}): Promise<PrincipalPolicyHistoryReferenceProof>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { principalHistoryPrefixes } from "../sqlite/principalHistoryEvidenceSchema.js";
|
|
2
|
+
import { type ExecSql } from "../sqlite/sqlSchema.js";
|
|
3
|
+
export type PrincipalHistoryPrefix = typeof principalHistoryPrefixes.$inferSelect;
|
|
4
|
+
export declare function loadPrincipalHistoryPrefix(execSql: ExecSql, scopeId: string): Promise<{
|
|
5
|
+
scopeId: string;
|
|
6
|
+
organizationId: string;
|
|
7
|
+
version: number;
|
|
8
|
+
headJson: string;
|
|
9
|
+
currentJson: string;
|
|
10
|
+
progress: string;
|
|
11
|
+
} | null>;
|
|
12
|
+
/** Keep the newest prefix unless replay replaces the exact rejected candidate. */
|
|
13
|
+
export declare function savePrincipalHistoryPrefix(input: {
|
|
14
|
+
readonly execSql: ExecSql;
|
|
15
|
+
readonly prefix: PrincipalHistoryPrefix;
|
|
16
|
+
readonly stillCurrent: () => boolean;
|
|
17
|
+
readonly rejectedPrefix?: PrincipalHistoryPrefix | null;
|
|
18
|
+
}): Promise<void>;
|
|
19
|
+
/** Invalid hints are disposable, but a losing reader must preserve a newer hint. */
|
|
20
|
+
export declare function discardPrincipalHistoryPrefix(input: {
|
|
21
|
+
readonly execSql: ExecSql;
|
|
22
|
+
readonly prefix: PrincipalHistoryPrefix;
|
|
23
|
+
readonly stillCurrent: () => boolean;
|
|
24
|
+
}): Promise<void>;
|
|
@@ -13,9 +13,10 @@ export async function loadPrincipalHistoryPrefix(execSql, scopeId) {
|
|
|
13
13
|
.limit(1);
|
|
14
14
|
return prefix ?? null;
|
|
15
15
|
}
|
|
16
|
-
/** Keep
|
|
16
|
+
/** Keep the newest prefix unless replay replaces the exact rejected candidate. */
|
|
17
17
|
export async function savePrincipalHistoryPrefix(input) {
|
|
18
18
|
const prefix = { ...input.prefix };
|
|
19
|
+
const rejected = input.rejectedPrefix ? { ...input.rejectedPrefix } : null;
|
|
19
20
|
await ensureSqlTables(input.execSql, principalHistoryEvidenceTables);
|
|
20
21
|
const runtime = getClientSQLitePersistenceRuntime(input.execSql);
|
|
21
22
|
const result = await runtime.guardedTransaction(async (tx) => {
|
|
@@ -24,7 +25,10 @@ export async function savePrincipalHistoryPrefix(input) {
|
|
|
24
25
|
.from(principalHistoryPrefixes)
|
|
25
26
|
.where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))
|
|
26
27
|
.limit(1);
|
|
27
|
-
if (previous &&
|
|
28
|
+
if (previous &&
|
|
29
|
+
previous.version > prefix.version &&
|
|
30
|
+
!(rejected?.scopeId === previous.scopeId &&
|
|
31
|
+
rejected.progress === previous.progress))
|
|
28
32
|
return;
|
|
29
33
|
await tx
|
|
30
34
|
.insert(principalHistoryPrefixes)
|