@tearleads/client-sdk 0.1.18 → 0.1.20
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/organizations/index.js +2 -2
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationHistory.js +66 -0
- package/client/organizations/organizationHistory.js.map +1 -0
- package/client/organizations/organizationReadModels.d.ts +1 -1
- package/client/organizations/organizationReadModels.js +7 -27
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +1 -1
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/data/containers/shared/types.d.ts +2 -2
- package/data/containers/shared/types.js.map +1 -1
- package/data/documents/shared/syncSubmitFailure.d.ts +2 -2
- package/data/documents/shared/syncSubmitFailure.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurgeCheckpointCurrency.js +34 -8
- package/data/keyingProjectionVerification/documentPurgeCheckpointCurrency.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurgePolicyCheckpoints.js +17 -0
- package/data/keyingProjectionVerification/documentPurgePolicyCheckpoints.js.map +1 -0
- package/data/keyingProjectionVerification/documentPurgePolicyCurrency.js +55 -0
- package/data/keyingProjectionVerification/documentPurgePolicyCurrency.js.map +1 -0
- package/data/keyingProjectionVerification/documentPurgePrincipalEvidence.js +25 -13
- package/data/keyingProjectionVerification/documentPurgePrincipalEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurgeProofVerification.d.ts +5 -3
- package/data/keyingProjectionVerification/documentPurgeProofVerification.js +52 -8
- package/data/keyingProjectionVerification/documentPurgeProofVerification.js.map +1 -1
- package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/types.d.ts +4 -0
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
- package/data/persistence/principalAuthorizationCheckpoints.js +1 -1
- package/data/persistence/principalAuthorizationCheckpoints.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +1 -0
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +58 -12
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/persistence/principalHistoryEvidencePersistence.d.ts +2 -0
- package/data/persistence/principalHistoryEvidencePersistence.js +2 -0
- package/data/persistence/principalHistoryEvidencePersistence.js.map +1 -1
- package/data/persistence/principalHistoryIncompleteRetention.js +32 -0
- package/data/persistence/principalHistoryIncompleteRetention.js.map +1 -0
- package/data/persistence/principalHistoryNodeRetention.js +76 -0
- package/data/persistence/principalHistoryNodeRetention.js.map +1 -0
- package/data/persistence/principalHistoryPrefixPersistence.d.ts +1 -0
- package/data/persistence/principalHistoryPrefixPersistence.js +30 -1
- package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
- package/data/persistence/principalHistoryRootOwnership.js +71 -0
- package/data/persistence/principalHistoryRootOwnership.js.map +1 -0
- package/data/persistence/principalHistoryStagePersistence.js +45 -0
- package/data/persistence/principalHistoryStagePersistence.js.map +1 -1
- package/data/persistence/principalHistoryStageRetention.js +44 -0
- package/data/persistence/principalHistoryStageRetention.js.map +1 -0
- package/data/persistence/principalHistoryUnpublishedRetention.js +71 -0
- package/data/persistence/principalHistoryUnpublishedRetention.js.map +1 -0
- package/data/persistence/principalKeyEnvelopeArchivePersistence.js +63 -0
- package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +1 -0
- package/data/persistence/principalKeyEnvelopeCandidates.js +10 -1
- package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -1
- package/data/sqlite/principalHistoryEvidenceSchema.js +2 -0
- package/data/sqlite/principalHistoryEvidenceSchema.js.map +1 -1
- package/data/sqlite/principalHistoryNodeRetentionSchema.js +30 -0
- package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +1 -0
- package/data/sqlite/principalHistoryRetentionSchema.js +40 -0
- package/data/sqlite/principalHistoryRetentionSchema.js.map +1 -0
- package/data/sqlite/principalHistoryStageSchema.js +2 -0
- package/data/sqlite/principalHistoryStageSchema.js.map +1 -1
- package/data/sqlite/schema.d.ts +453 -0
- package/data/sqlite/schema.js +6 -0
- package/data/sqlite/schema.js.map +1 -1
- package/data/sqlite/sqliteCommitGuards.js +49 -0
- package/data/sqlite/sqliteCommitGuards.js.map +1 -0
- package/data/sqlite/sqlitePersistenceRuntime.js +14 -2
- package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
- package/index.d.ts +3 -1
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +60 -137
- package/internal/api-client/ApiClient.js +7 -5
- package/internal/api-client/ApiClient.js.map +1 -1
- package/internal/api-client/apiRequestRuntime.js +7 -7
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/documentPurge.js +25 -0
- package/internal/api-client/documentPurge.js.map +1 -0
- package/internal/api-client/organizationPolicyHistory.d.ts +53 -0
- package/internal/api-client/organizationPolicyHistory.js +15 -0
- package/internal/api-client/organizationPolicyHistory.js.map +1 -0
- package/internal/api-client/requestInternals.js +4 -4
- package/internal/api-client/requestInternals.js.map +1 -1
- package/internal/api-client/types.d.ts +2 -2
- package/internal/api-client/types.js.map +1 -1
- 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/loro/document.js +8 -11
- package/internal/loro/document.js.map +1 -1
- package/internal/validators/operation/containerMutations.d.ts +448 -6528
- package/internal/validators/operation/documentMutations.d.ts +323 -579
- package/internal/validators/operation/documentMutations.js +22 -4
- package/internal/validators/operation/documentMutations.js.map +1 -1
- package/internal/validators/operation/documentSync.d.ts +26 -406
- package/internal/validators/operation/organizationPolicyHistory.d.ts +188 -310
- package/internal/validators/operation/organizationPolicyHistory.js +17 -3
- package/internal/validators/operation/organizationPolicyHistory.js.map +1 -1
- package/internal/validators/response/containerMutationError.d.ts +28 -408
- package/internal/validators/response/documentMutation.d.ts +232 -544
- package/internal/validators/response/documentMutation.js +1 -2
- package/internal/validators/response/documentMutation.js.map +1 -1
- package/internal/validators/response/documentSyncError.d.ts +26 -406
- package/internal/validators/response/documentSyncError.js +4 -3
- package/internal/validators/response/documentSyncError.js.map +1 -1
- package/internal/validators/response/index.d.ts +1 -1
- package/internal/validators/response/index.js +1 -1
- package/internal/validators/response/index.js.map +1 -1
- package/internal/validators/response/organizationPolicyHistory.d.ts +127 -309
- package/internal/validators/response/organizationPolicyHistory.js +10 -4
- package/internal/validators/response/organizationPolicyHistory.js.map +1 -1
- package/internal/validators/response/principal.d.ts +28 -408
- package/internal/validators/response/principal.js +3 -1
- package/internal/validators/response/principal.js.map +1 -1
- package/internal/validators/util/index.d.ts +1 -1
- package/internal/validators/util/index.js +1 -1
- package/internal/validators/util/index.js.map +1 -1
- package/internal/validators/util/principalHistoryWire.d.ts +2 -0
- package/internal/validators/util/principalHistoryWire.js +2 -0
- package/internal/validators/util/principalHistoryWire.js.map +1 -1
- package/package.json +4 -4
- package/workflows/container-contents/container-state/createWithMetadata.js +19 -49
- package/workflows/container-contents/container-state/createWithMetadata.js.map +1 -1
- package/workflows/container-contents/container-state/groupGrantVerification.js +29 -0
- package/workflows/container-contents/container-state/groupGrantVerification.js.map +1 -1
- package/workflows/container-contents/container-state/groupShareEpoch.js +33 -0
- package/workflows/container-contents/container-state/groupShareEpoch.js.map +1 -0
- package/workflows/container-contents/container-state/remote.js +4 -1
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/share.js +2 -24
- package/workflows/container-contents/container-state/share.js.map +1 -1
- package/workflows/container-contents/documentTombstoneEvidence.js +23 -12
- package/workflows/container-contents/documentTombstoneEvidence.js.map +1 -1
- package/workflows/containers/child/create.js +1 -3
- package/workflows/containers/child/create.js.map +1 -1
- package/workflows/containers/child/createSubmission.d.ts +1 -3
- package/workflows/containers/child/createSubmission.js +13 -15
- package/workflows/containers/child/createSubmission.js.map +1 -1
- package/workflows/containers/child/currentShareGrantMutation.js +82 -0
- package/workflows/containers/child/currentShareGrantMutation.js.map +1 -0
- package/workflows/containers/child/currentSharePrincipalPolicy.js +83 -0
- package/workflows/containers/child/currentSharePrincipalPolicy.js.map +1 -0
- package/workflows/containers/child/mutationSubmit.js +1 -1
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js +82 -0
- package/workflows/containers/child/runtimeCurrentGroupShare.js.map +1 -0
- package/workflows/containers/child/share.js +1 -14
- package/workflows/containers/child/share.js.map +1 -1
- package/workflows/containers/child/shareProjection.js +15 -0
- package/workflows/containers/child/shareProjection.js.map +1 -0
- package/workflows/documents/purge.d.ts +3 -0
- package/workflows/documents/purge.js +13 -0
- package/workflows/documents/purge.js.map +1 -1
- package/workflows/documents/sync.js +2 -0
- package/workflows/documents/sync.js.map +1 -1
- package/workflows/documents/syncFailures.js +2 -2
- package/workflows/documents/syncFailures.js.map +1 -1
- package/workflows/documents/syncPolicyRepair.js +15 -13
- package/workflows/documents/syncPolicyRepair.js.map +1 -1
- package/workflows/organizations/initialPrincipalCurrentPublication.js +2 -0
- package/workflows/organizations/initialPrincipalCurrentPublication.js.map +1 -1
- package/workflows/organizations/loadPolicyHistoryDetails.js +31 -32
- package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/organizationPolicyHistoryDetails.js +37 -15
- package/workflows/organizations/organizationPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/organizationPolicyHistoryVerification.js +56 -69
- package/workflows/organizations/organizationPolicyHistoryVerification.js.map +1 -1
- package/workflows/organizations/policyHistoryCache.js +5 -2
- package/workflows/organizations/policyHistoryCache.js.map +1 -1
- package/workflows/organizations/policyHistoryTypes.d.ts +1 -0
- package/workflows/organizations/policyHistoryTypes.js.map +1 -1
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +4 -1
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/principals/loadRecoveredPrincipalHistoryPage.d.ts +0 -1
- package/workflows/principals/loadRecoveredPrincipalHistoryPage.js +1 -2
- package/workflows/principals/loadRecoveredPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/policyRepair.js +38 -0
- package/workflows/principals/policyRepair.js.map +1 -0
- package/workflows/principals/policyRepairBudget.d.ts +2 -2
- package/workflows/principals/policyRepairBudget.js +3 -3
- package/workflows/principals/policyRepairBudget.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryPrefix.js +4 -0
- package/workflows/principals/principalHistoryRecoveryPrefix.js.map +1 -1
- package/workflows/principals/principalRecoveryLocalPreference.js +3 -2
- package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -1
- package/workflows/principals/publicPrincipalHistoryPage.js +1 -0
- package/workflows/principals/publicPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/publicPrincipalHistoryProgress.js +1 -0
- package/workflows/principals/publicPrincipalHistoryProgress.js.map +1 -1
- package/workflows/principals/publicPrincipalHistoryTypes.d.ts +2 -0
- package/workflows/principals/publicPrincipalHistoryTypes.js.map +1 -1
- package/workflows/principals/publicProjectionPrincipal.js +1 -0
- package/workflows/principals/publicProjectionPrincipal.js.map +1 -1
- package/workflows/principals/recoverPrincipalHistoryPage.js +2 -1
- package/workflows/principals/recoverPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/recoverPrincipalPolicyHistory.js +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/recoverPublicPrincipalHistory.js +2 -0
- package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +2 -1
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/selectPublicPrincipalHistory.js +21 -15
- package/workflows/principals/selectPublicPrincipalHistory.js.map +1 -1
- package/workflows/sync/remoteResetPrincipalScope.js +6 -0
- package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicySnapshotVerification.js +0 -208
- package/data/keyingProjectionVerification/principalPolicySnapshotVerification.js.map +0 -1
- package/data/keyingProjectionVerification/snapshotVerificationCache.js +0 -39
- package/data/keyingProjectionVerification/snapshotVerificationCache.js.map +0 -1
- package/workflows/containers/child/policyRepair.js +0 -23
- package/workflows/containers/child/policyRepair.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recoverPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverPrincipalPolicyHistory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,kCAAkC,EAGlC,+BAA+B,EAC/B,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AACxG,OAAO,EAAE,sCAAsC,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAChG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAGhC,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AAI,uBAAuB,CAC/B,eAAe,EACf,0CAA0C,CAC3C,CAAC;IACJ,IACE,CAAC,OAAO,CAAC,cAAc;QACvB,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,cAAc;YACpD,OAAO,CAAC,YAAY,CAAC,WAAW,KAAK,OAAO,CAAC,cAAc,CAAC;QAE9D,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,iDAAiD,CAClD,CAAC;IACJ,IACE,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAC9B,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,OAAO,CAChE;QAED,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,yDAAyD,CAC1D,CAAC;IACJ,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,IAAI,UAAU;QAC9D,YAAY,EAAE,eAAe,CAAC,OAAO,CAAC,YAAY,CAAC;QACnD,kBAAkB,EAAE,eAAe,CAAC,OAAO,CAAC,kBAAkB,IAAI,EAAE,CAAC;QACrE,gBAAgB,EAAE,CAAC,GAAG,gBAAgB,CAAC;QACvC,UAAU,EAAE,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC;KAC9D,CAAC;IACF,IAAI,CAAC;QACH,KAAK,CAAC,UAAU,CAAC,OAAO,GAAG,mCAAmC,CAAC,KAAK,CAAC,CAAC;QACtE,OAAO,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryInput,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n discardPrincipalHistoryStage,\n savePrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { principalHistoryStageProtection } from \"../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport { validatePrincipalHistoryRecoveryAuthority } from \"./principalHistoryRecoveryAuthority\";\nimport { publishReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalHistoryEvidenceUnavailableError,\n type PrincipalHistorySelectionOptions,\n selectRecoveredPrincipalHistory,\n} from \"./principalHistoryRecoveryReferences\";\nimport {\n type PrincipalHistoryRecoveryStage,\n restorePrincipalHistoryRecoveryStage,\n} from \"./principalHistoryRecoveryStage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\nclass PrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction currentArtifacts(\n page: PrincipalPolicyPageResponse,\n): PrincipalPolicyPageCurrent {\n return {\n currentState: page.currentState,\n currentPayload: page.currentPayload,\n currentProjection: page.currentProjection,\n currentGrants: page.currentGrants,\n currentMemberEnvelopes: page.currentMemberEnvelopes,\n };\n}\n\nfunction recoveryIsCurrent(\n input: RecoverPrincipalPolicyHistoryOptions,\n): boolean {\n return !input.signal?.aborted && input.stillCurrent();\n}\n\nfunction assertCurrent(input: RecoverPrincipalPolicyHistoryOptions): void {\n assertProjectionVerificationCurrent(() => recoveryIsCurrent(input));\n}\n\nfunction assertExpectedHead(\n current: PrincipalPolicyPageCurrent,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): void {\n for (const field of [\n \"principalType\",\n \"principalId\",\n \"version\",\n \"stateHash\",\n \"keyEpoch\",\n \"keyFingerprint\",\n ] as const) {\n if (current.currentState[field] !== expectedHead[field])\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history page does not match its requested head\",\n );\n }\n}\n\nasync function acceptPage(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n response: PrincipalPolicyPageResponse,\n): Promise<void> {\n const page = structuredClone(response);\n assertCurrent(input);\n assertExpectedHead(page, input.expectedHead);\n if (stage.complete) {\n if (\n page.previousStates.length !== 0 ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed history returned additional entries\",\n );\n stage.current = currentArtifacts(page);\n return;\n }\n const complete = page.historyPage.nextAfterVersion === null;\n const current = currentArtifacts(page);\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n });\n assertPrincipalHistoryVerificationMode(input, entries);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: page.previousStates },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n ),\n );\n const appended = await stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n const next = {\n id: stage.id,\n organizationId: input.organizationId,\n currentJson: JSON.stringify(current),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const protectedProgress = await stage.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n next,\n ),\n );\n if (!protectedProgress.ok) throw protectedProgress.error;\n const saved = { ...next, progress: protectedProgress.value };\n await savePrincipalHistoryStage({\n execSql: input.execSql,\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n scopeId: stage.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: stage.saved?.progress ?? null,\n stillCurrent: () => recoveryIsCurrent(input),\n });\n stage.current = current;\n stage.saved = saved;\n stage.complete = complete;\n}\n\nasync function finishRecovery(\n input: PrincipalHistorySelectionOptions,\n stage: PrincipalHistoryRecoveryStage,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (!stage.current || !stage.complete)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history ended before its pinned head\",\n );\n const history = stage.verifier.finish(input.expectedHead);\n if (!history.ok) throw history.error;\n const selected = await selectRecoveredPrincipalHistory({\n options: input,\n scopeId: stage.scopeId,\n history: history.value,\n checkpoint,\n });\n const current = await verifyPrincipalPolicyCurrent({\n current: stage.current,\n history: selected,\n });\n if (!current.ok) throw current.error;\n verifyPrincipalPolicyCheckpoint({\n chain: current.value.retainedHistory,\n currentState: current.value.state,\n localCheckpoint: checkpoint,\n });\n const latest = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (\n latest?.version !== checkpoint?.version ||\n latest?.stateHash !== checkpoint?.stateHash\n )\n throw new PrincipalHistoryRecoveryRaceError(\n \"Local principal checkpoint changed during history recovery\",\n );\n assertCurrent(input);\n if (!input.offline)\n await publishReusablePrincipalHistoryPrefix(\n input,\n stage.scopeId,\n stage.verifier,\n stage.current,\n );\n assertCurrent(input);\n return { current: stage.current, policy: current.value };\n}\n\nasync function readRecoveryPages(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n): Promise<void> {\n if (input.offline) {\n if (!stage.complete || !stage.current)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed principal history is unavailable offline\",\n );\n assertExpectedHead(stage.current, input.expectedHead);\n return;\n }\n let receivedFinalPage = false;\n for await (const result of input.apiClient.getPrincipalPolicyPages(\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n {\n signal: input.signal,\n stateHash: input.expectedHead.stateHash,\n ...(stage.saved && stage.current\n ? {\n resume: {\n current: stage.current,\n afterVersion: stage.saved.afterVersion,\n },\n }\n : { afterVersion: stage.initialAfterVersion }),\n },\n )) {\n if (!result.ok) {\n // A rejected transport pin cannot justify skipping history on retry.\n // Discard only this operation's progress, then let a new call replay it.\n if (result.kind === \"shape\" && stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n throw new PrincipalPolicyHistoryReadError(result);\n }\n await acceptPage(input, stage, result.data);\n receivedFinalPage = result.data.historyPage.nextAfterVersion === null;\n }\n if (!receivedFinalPage)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history transport did not complete\",\n );\n}\n\nasync function recover(\n input: PrincipalHistorySelectionOptions,\n allowEvidenceRebuild = true,\n): Promise<RecoveredPrincipalPolicyHistory> {\n assertCurrent(input);\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (checkpoint && input.expectedHead.version < checkpoint.version)\n throw new KeyingVerificationError(\n input.offline ? \"missing_dependency\" : \"rollback\",\n \"Requested principal history predates the local checkpoint\",\n );\n // Validate the requested pin/selection before creating any disposable caches.\n createPrincipalPolicyHistoryVerifier({\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n localCheckpoint: checkpoint,\n retainedReferences: input.retainedReferences ?? [],\n });\n const historyInput: PrincipalPolicyHistoryInput = {\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n };\n const stage = await restorePrincipalHistoryRecoveryStage(\n input,\n historyInput,\n allowEvidenceRebuild,\n );\n try {\n if (stage.fromCache)\n await validatePrincipalHistoryRecoveryAuthority(input, stage.verifier);\n await readRecoveryPages(input, stage);\n return await finishRecovery(input, stage, checkpoint);\n } catch (error) {\n const lostEvidence =\n error instanceof PrincipalHistoryEvidenceUnavailableError;\n const disconnected =\n error instanceof PrincipalHistoryPrefixDisconnectedError;\n if (!lostEvidence && !disconnected) throw error;\n if (stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n if (\n !input.offline &&\n allowEvidenceRebuild &&\n (lostEvidence || stage.fromCache)\n )\n return recover(input, false);\n throw lostEvidence || disconnected ? error.verificationError : error;\n }\n}\n\n/**\n * Recover one exact head with bounded retained history and durable checked progress.\n * The result is a sparse current-policy capability; this does not advance app checkpoints.\n * Retain organization version 1 when the result will establish founder binding.\n */\nexport function recoverPrincipalPolicyHistory(\n options: RecoverPrincipalPolicyHistoryOptions,\n): Promise<RecoveredPrincipalPolicyHistory> {\n return recoverPrincipalPolicyHistoryWithVersions(options, []);\n}\n\n/** Internal bounded display selection; missing proof rows use the normal single rebuild. */\nexport async function recoverPrincipalPolicyHistoryWithVersions(\n options: RecoverPrincipalPolicyHistoryOptions,\n retainedVersions: readonly number[],\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (\n !Array.isArray(retainedVersions) ||\n retainedVersions.length + (options.retainedReferences?.length ?? 0) >\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT ||\n retainedVersions.some(\n (version) =>\n !Number.isSafeInteger(version) ||\n version < 1 ||\n version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal display history selection exceeds its bounded range\",\n );\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 (\n !options.organizationId ||\n (options.expectedHead.principalType === \"organization\" &&\n options.expectedHead.principalId !== options.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history organization scope is invalid\",\n );\n if (\n options.retainedReferences?.some(\n (reference) => reference.version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested history reference is beyond the recovery head\",\n );\n const input = {\n ...options,\n historyVerification: options.historyVerification ?? \"standard\",\n expectedHead: structuredClone(options.expectedHead),\n retainedReferences: structuredClone(options.retainedReferences ?? []),\n retainedVersions: [...retainedVersions],\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n input.protection.context = principalHistoryVerificationContext(input);\n return await recover(input);\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recoverPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverPrincipalPolicyHistory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,kCAAkC,EAGlC,+BAA+B,EAC/B,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA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AAO,CAAC,kBAAkB,IAAI,EAAE,CAAC;QACrE,gBAAgB,EAAE,CAAC,GAAG,gBAAgB,CAAC;QACvC,UAAU,EAAE,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC;KAC9D,CAAC;IACF,IAAI,CAAC;QACH,KAAK,CAAC,UAAU,CAAC,OAAO,GAAG,mCAAmC,CAAC,KAAK,CAAC,CAAC;QACtE,OAAO,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryInput,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n discardPrincipalHistoryStage,\n savePrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { principalHistoryStageProtection } from \"../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport { validatePrincipalHistoryRecoveryAuthority } from \"./principalHistoryRecoveryAuthority\";\nimport { publishReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalHistoryEvidenceUnavailableError,\n type PrincipalHistorySelectionOptions,\n selectRecoveredPrincipalHistory,\n} from \"./principalHistoryRecoveryReferences\";\nimport {\n type PrincipalHistoryRecoveryStage,\n restorePrincipalHistoryRecoveryStage,\n} from \"./principalHistoryRecoveryStage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\nclass PrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction currentArtifacts(\n page: PrincipalPolicyPageResponse,\n): PrincipalPolicyPageCurrent {\n return {\n currentState: page.currentState,\n currentPayload: page.currentPayload,\n currentProjection: page.currentProjection,\n currentGrants: page.currentGrants,\n currentMemberEnvelopes: page.currentMemberEnvelopes,\n };\n}\n\nfunction recoveryIsCurrent(\n input: RecoverPrincipalPolicyHistoryOptions,\n): boolean {\n return !input.signal?.aborted && input.stillCurrent();\n}\n\nfunction assertCurrent(input: RecoverPrincipalPolicyHistoryOptions): void {\n assertProjectionVerificationCurrent(() => recoveryIsCurrent(input));\n}\n\nfunction assertExpectedHead(\n current: PrincipalPolicyPageCurrent,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): void {\n for (const field of [\n \"principalType\",\n \"principalId\",\n \"version\",\n \"stateHash\",\n \"keyEpoch\",\n \"keyFingerprint\",\n ] as const) {\n if (current.currentState[field] !== expectedHead[field])\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history page does not match its requested head\",\n );\n }\n}\n\nasync function acceptPage(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n response: PrincipalPolicyPageResponse,\n): Promise<void> {\n const page = structuredClone(response);\n assertCurrent(input);\n assertExpectedHead(page, input.expectedHead);\n if (stage.complete) {\n if (\n page.previousStates.length !== 0 ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed history returned additional entries\",\n );\n stage.current = currentArtifacts(page);\n return;\n }\n const complete = page.historyPage.nextAfterVersion === null;\n const current = currentArtifacts(page);\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n });\n assertPrincipalHistoryVerificationMode(input, entries);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: page.previousStates },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n ),\n );\n const appended = await stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n const next = {\n id: stage.id,\n organizationId: input.organizationId,\n currentJson: JSON.stringify(current),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const protectedProgress = await stage.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n next,\n ),\n );\n if (!protectedProgress.ok) throw protectedProgress.error;\n const saved = { ...next, progress: protectedProgress.value };\n await savePrincipalHistoryStage({\n execSql: input.execSql,\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId: stage.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: stage.saved?.progress ?? null,\n stillCurrent: () => recoveryIsCurrent(input),\n });\n stage.current = current;\n stage.saved = saved;\n stage.complete = complete;\n}\n\nasync function finishRecovery(\n input: PrincipalHistorySelectionOptions,\n stage: PrincipalHistoryRecoveryStage,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (!stage.current || !stage.complete)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history ended before its pinned head\",\n );\n const history = stage.verifier.finish(input.expectedHead);\n if (!history.ok) throw history.error;\n const selected = await selectRecoveredPrincipalHistory({\n options: input,\n scopeId: stage.scopeId,\n history: history.value,\n checkpoint,\n });\n const current = await verifyPrincipalPolicyCurrent({\n current: stage.current,\n history: selected,\n });\n if (!current.ok) throw current.error;\n verifyPrincipalPolicyCheckpoint({\n chain: current.value.retainedHistory,\n currentState: current.value.state,\n localCheckpoint: checkpoint,\n });\n const latest = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (\n latest?.version !== checkpoint?.version ||\n latest?.stateHash !== checkpoint?.stateHash\n )\n throw new PrincipalHistoryRecoveryRaceError(\n \"Local principal checkpoint changed during history recovery\",\n );\n assertCurrent(input);\n if (!input.offline)\n await publishReusablePrincipalHistoryPrefix(\n input,\n stage.scopeId,\n stage.verifier,\n stage.current,\n );\n assertCurrent(input);\n return { current: stage.current, policy: current.value };\n}\n\nasync function readRecoveryPages(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n): Promise<void> {\n if (input.offline) {\n if (!stage.complete || !stage.current)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed principal history is unavailable offline\",\n );\n assertExpectedHead(stage.current, input.expectedHead);\n return;\n }\n let receivedFinalPage = false;\n for await (const result of input.apiClient.getPrincipalPolicyPages(\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n {\n signal: input.signal,\n stateHash: input.expectedHead.stateHash,\n ...(stage.saved && stage.current\n ? {\n resume: {\n current: stage.current,\n afterVersion: stage.saved.afterVersion,\n },\n }\n : { afterVersion: stage.initialAfterVersion }),\n },\n )) {\n if (!result.ok) {\n // A rejected transport pin cannot justify skipping history on retry.\n // Discard only this operation's progress, then let a new call replay it.\n if (result.kind === \"shape\" && stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n throw new PrincipalPolicyHistoryReadError(result);\n }\n await acceptPage(input, stage, result.data);\n receivedFinalPage = result.data.historyPage.nextAfterVersion === null;\n }\n if (!receivedFinalPage)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history transport did not complete\",\n );\n}\n\nasync function recover(\n input: PrincipalHistorySelectionOptions,\n allowEvidenceRebuild = true,\n): Promise<RecoveredPrincipalPolicyHistory> {\n assertCurrent(input);\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (checkpoint && input.expectedHead.version < checkpoint.version)\n throw new KeyingVerificationError(\n input.offline ? \"missing_dependency\" : \"rollback\",\n \"Requested principal history predates the local checkpoint\",\n );\n // Validate the requested pin/selection before creating any disposable caches.\n createPrincipalPolicyHistoryVerifier({\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n localCheckpoint: checkpoint,\n retainedReferences: input.retainedReferences ?? [],\n });\n const historyInput: PrincipalPolicyHistoryInput = {\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n };\n const stage = await restorePrincipalHistoryRecoveryStage(\n input,\n historyInput,\n allowEvidenceRebuild,\n );\n try {\n if (stage.fromCache)\n await validatePrincipalHistoryRecoveryAuthority(input, stage.verifier);\n await readRecoveryPages(input, stage);\n return await finishRecovery(input, stage, checkpoint);\n } catch (error) {\n const lostEvidence =\n error instanceof PrincipalHistoryEvidenceUnavailableError;\n const disconnected =\n error instanceof PrincipalHistoryPrefixDisconnectedError;\n if (!lostEvidence && !disconnected) throw error;\n if (stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n if (\n !input.offline &&\n allowEvidenceRebuild &&\n (lostEvidence || stage.fromCache)\n )\n return recover(input, false);\n throw lostEvidence || disconnected ? error.verificationError : error;\n }\n}\n\n/**\n * Recover one exact head with bounded retained history and durable checked progress.\n * The result is a sparse current-policy capability; this does not advance app checkpoints.\n * Retain organization version 1 when the result will establish founder binding.\n */\nexport function recoverPrincipalPolicyHistory(\n options: RecoverPrincipalPolicyHistoryOptions,\n): Promise<RecoveredPrincipalPolicyHistory> {\n return recoverPrincipalPolicyHistoryWithVersions(options, []);\n}\n\n/** Internal bounded display selection; missing proof rows use the normal single rebuild. */\nexport async function recoverPrincipalPolicyHistoryWithVersions(\n options: RecoverPrincipalPolicyHistoryOptions,\n retainedVersions: readonly number[],\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (\n !Array.isArray(retainedVersions) ||\n retainedVersions.length + (options.retainedReferences?.length ?? 0) >\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT ||\n retainedVersions.some(\n (version) =>\n !Number.isSafeInteger(version) ||\n version < 1 ||\n version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal display history selection exceeds its bounded range\",\n );\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 (\n !options.organizationId ||\n (options.expectedHead.principalType === \"organization\" &&\n options.expectedHead.principalId !== options.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history organization scope is invalid\",\n );\n if (\n options.retainedReferences?.some(\n (reference) => reference.version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested history reference is beyond the recovery head\",\n );\n const input = {\n ...options,\n historyVerification: options.historyVerification ?? \"standard\",\n expectedHead: structuredClone(options.expectedHead),\n retainedReferences: structuredClone(options.retainedReferences ?? []),\n retainedVersions: [...retainedVersions],\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n input.protection.context = principalHistoryVerificationContext(input);\n return await recover(input);\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n"]}
|
|
@@ -138,6 +138,8 @@ async function recover(input, allowReuse = true, rejectedPrefix = null) {
|
|
|
138
138
|
/** Private-key-backed public history recovery; never admits a current policy pin. */
|
|
139
139
|
export async function recoverPublicPrincipalHistory(options) {
|
|
140
140
|
if (!options.organizationId ||
|
|
141
|
+
(options.historicalProof !== undefined &&
|
|
142
|
+
typeof options.historicalProof !== "boolean") ||
|
|
141
143
|
(options.offline !== undefined && typeof options.offline !== "boolean") ||
|
|
142
144
|
(options.strictAdmins !== undefined &&
|
|
143
145
|
typeof options.strictAdmins !== "boolean") ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,qCAAqC,GAEtC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAE3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,sCAAsC,EAAE,MAAM,mCAAmC,CAAC;AAC3F,OAAO,EACL,gCAAgC,EAChC,6CAA6C,GAC9C,MAAM,8BAA8B,CA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AAC;IACJ,IACE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,KAAK,cAAc;QACpD,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,KAAK,OAAO,CAAC,cAAc;QAE1D,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kDAAkD,CACnD,CAAC;IACJ,0EAA0E;IAC1E,oCAAoC,CAAC;QACnC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa;QAChD,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;QAC5C,kBAAkB,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrE,UAAU,CAAC,OAAO,GAAG,4BAA4B,CAAC;QAChD,2CAA2C;QAC3C,UAAU,CAAC,OAAO;QAClB,OAAO,CAAC,YAAY,KAAK,IAAI;QAC7B,OAAO,CAAC,gBAAgB,IAAI,IAAI;KACjC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPageResponse,\n type PrincipalPolicySnapshotPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPageResponse,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPageResponse(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPageResponse | undefined;\n if (!input.offline) {\n for await (const result of input.apiClient.getProjectionPolicyHistoryPages(\n input.source,\n { afterVersion: progress.afterVersion, signal: input.signal },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (!progress.completedHead)\n progress = await appendPublicPrincipalHistoryPage(\n input,\n progress,\n page,\n );\n else if (\n page.previousStates.length ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n // A signed cached candidate need not belong to this requested chain. Only\n // reused progress permits one replay; a fresh disconnected chain fails.\n if (mayReplay && initial.afterVersion > 0)\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n if (lastPage) {\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n }\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix);\n } catch (error) {\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix);\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,qCAAqC,GAEtC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAE3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,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n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPageResponse,\n type PrincipalPolicySnapshotPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPageResponse,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPageResponse(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPageResponse | undefined;\n if (!input.offline) {\n for await (const result of input.apiClient.getProjectionPolicyHistoryPages(\n input.source,\n { afterVersion: progress.afterVersion, signal: input.signal },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (!progress.completedHead)\n progress = await appendPublicPrincipalHistoryPage(\n input,\n progress,\n page,\n );\n else if (\n page.previousStates.length ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n // A signed cached candidate need not belong to this requested chain. Only\n // reused progress permits one replay; a fresh disconnected chain fails.\n if (mayReplay && initial.afterVersion > 0)\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n if (lastPage) {\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n }\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix);\n } catch (error) {\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix);\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
|
|
@@ -57,7 +57,8 @@ export function createRuntimePrincipalPolicyCurrentResolver(runtime) {
|
|
|
57
57
|
...options,
|
|
58
58
|
reference: input.reference,
|
|
59
59
|
historyPage: input.historyPage,
|
|
60
|
-
}, input.preferLocalCurrent === true
|
|
60
|
+
}, input.preferLocalCurrent === true ||
|
|
61
|
+
input.preferLocalHistory === true, input.preferLocalHistory === true)
|
|
61
62
|
: await batch.discover(options);
|
|
62
63
|
return {
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AAK,CAAC,WAAW,CAAC,aAAa,CAAC;IAC/C,IACE,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,MAAM,KAAK,SAAS;YACnB,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;gBAC5B,MAAM,IAAI,CAAC;gBACX,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,iEAAiE,CAClE,CAAC;AACN,CAAC","sourcesContent":["import type {\n ApiClient,\n PrincipalPolicyPageCurrent,\n} 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 PrincipalPolicyResolveRequest,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./principalCurrentRecoveryBatch\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport type { RecoveredScopedPrincipalPolicyHistory } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<\n Pick<\n ApiClient,\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >\n >;\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 while resolving cited evidence. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);\n return resolve\n ? (input) =>\n resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })\n : undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\ninterface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\n/** Keep current artifacts with their verified evidence and private runtime lifetime. */\nexport function createRuntimePrincipalPolicyCurrentResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n):\n | ((\n input: PrincipalPolicyCurrentRequest,\n ) => Promise<ResolvedPrincipalPolicyCurrent>)\n | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\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 ReturnType<typeof createPrincipalCurrentRecoveryBatch>\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return createPrincipalCurrentRecoveryBatch();\n let recover = batches.get(batch);\n if (!recover) {\n recover = createPrincipalCurrentRecoveryBatch();\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 ?? input.organizationId,\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 assertHistoryPageRequest(input);\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 resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const batch = recoverFor(input.recoveryBatch);\n const result: RecoveredScopedPrincipalPolicyHistory =\n input.reference\n ? await recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true,\n )\n : await batch.discover(options);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\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\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AAIA,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,GAIpC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAK/F,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,mCAAmC,EAAE,MAAM,oCAAoC,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAmBlE,6FAA6F;AAC7F,MAAM,UAAU,oCAAoC,CAClD,OAAuC,EACvC,UAAqD,EAAE;IAEvD,MAAM,OAAO,GAAG,2CAA2C,CAAC,OAAO,CAAC,CAAC;IACrE,OAAO,OAAO;QACZ,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CACR,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,EAAE,CAAC;QACzE,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAiBD,wFAAwF;AACxF,MAAM,UAAU,2CAA2C,CACzD,OAAuC;IAMvC,MAAM,KAAK,GAAG,8BAA8B,CAAC,OAAO,CA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B,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC;AAED,SAAS,wBAAwB,CAAC,KAAoC;IACpE,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO;IAC/B,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC;IAC/C,IACE,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,MAAM,KAAK,SAAS;YACnB,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;gBAC5B,MAAM,IAAI,CAAC;gBACX,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,iEAAiE,CAClE,CAAC;AACN,CAAC","sourcesContent":["import type {\n ApiClient,\n PrincipalPolicyPageCurrent,\n} 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 PrincipalPolicyResolveRequest,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./principalCurrentRecoveryBatch\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport type { RecoveredScopedPrincipalPolicyHistory } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<\n Pick<\n ApiClient,\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >\n >;\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 while resolving cited evidence. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);\n return resolve\n ? (input) =>\n resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })\n : undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\ninterface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\n/** Keep current artifacts with their verified evidence and private runtime lifetime. */\nexport function createRuntimePrincipalPolicyCurrentResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n):\n | ((\n input: PrincipalPolicyCurrentRequest,\n ) => Promise<ResolvedPrincipalPolicyCurrent>)\n | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\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 ReturnType<typeof createPrincipalCurrentRecoveryBatch>\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return createPrincipalCurrentRecoveryBatch();\n let recover = batches.get(batch);\n if (!recover) {\n recover = createPrincipalCurrentRecoveryBatch();\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 ?? input.organizationId,\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 assertHistoryPageRequest(input);\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 resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const batch = recoverFor(input.recoveryBatch);\n const result: RecoveredScopedPrincipalPolicyHistory =\n input.reference\n ? await recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true ||\n input.preferLocalHistory === true,\n input.preferLocalHistory === true,\n )\n : await batch.discover(options);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\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\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
|
|
@@ -39,12 +39,30 @@ async function loadCheckpointProof(input, checkpoint) {
|
|
|
39
39
|
}
|
|
40
40
|
return checkpointReference;
|
|
41
41
|
}
|
|
42
|
+
function checkSelectedReferences(input, references, batch, selected, checkpoint) {
|
|
43
|
+
// Authenticate the disposable proof before comparing caller citations or pins.
|
|
44
|
+
for (const reference of references.filter(({ version }) => batch.includes(version)))
|
|
45
|
+
if (!selected.retainedEntries.some(({ state }) => principalHeadMatchesReference(state, reference)))
|
|
46
|
+
throw new KeyingVerificationError("object_mismatch", "Public history citation differs from its verified entry");
|
|
47
|
+
if (!input.deferCheckpointCheck)
|
|
48
|
+
verifyPrincipalPolicyCheckpoint({
|
|
49
|
+
chain: selected.retainedEntries.map((entry) => ({
|
|
50
|
+
...entry,
|
|
51
|
+
projection: [...entry.projection],
|
|
52
|
+
grants: [...entry.grants],
|
|
53
|
+
})),
|
|
54
|
+
currentState: selected.currentEntry.state,
|
|
55
|
+
localCheckpoint: checkpoint,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
42
58
|
/** Select bounded proof batches without admitting or advancing durable pins. */
|
|
43
59
|
export async function selectPublicPrincipalHistory(input) {
|
|
44
60
|
const references = structuredClone(input.references);
|
|
45
61
|
const checkpoint = input.checkpoint && { ...input.checkpoint };
|
|
46
62
|
const head = input.recovered.history.currentEntry.state;
|
|
47
|
-
if (
|
|
63
|
+
if (!input.deferCheckpointCheck &&
|
|
64
|
+
checkpoint &&
|
|
65
|
+
checkpoint.version > head.version)
|
|
48
66
|
throw new KeyingVerificationError("missing_dependency", "Public history cannot connect to the newer durable checkpoint");
|
|
49
67
|
if (references.some((reference) => reference.principalType !== head.principalType ||
|
|
50
68
|
reference.principalId !== head.principalId ||
|
|
@@ -58,7 +76,7 @@ export async function selectPublicPrincipalHistory(input) {
|
|
|
58
76
|
]),
|
|
59
77
|
];
|
|
60
78
|
const policies = [];
|
|
61
|
-
const checkpointReference = await loadCheckpointProof(input, checkpoint);
|
|
79
|
+
const checkpointReference = await loadCheckpointProof(input, checkpoint && checkpoint.version <= head.version ? checkpoint : null);
|
|
62
80
|
for (let offset = 0; offset < versions.length; offset += PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT) {
|
|
63
81
|
const batch = versions.slice(offset, offset + PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT);
|
|
64
82
|
const selected = await selectBatch(input, batch, checkpointReference).catch((error) => {
|
|
@@ -66,19 +84,7 @@ export async function selectPublicPrincipalHistory(input) {
|
|
|
66
84
|
throw new PrincipalHistoryEvidenceUnavailableError(error);
|
|
67
85
|
throw error;
|
|
68
86
|
});
|
|
69
|
-
|
|
70
|
-
for (const reference of references.filter(({ version }) => batch.includes(version)))
|
|
71
|
-
if (!selected.retainedEntries.some(({ state }) => principalHeadMatchesReference(state, reference)))
|
|
72
|
-
throw new KeyingVerificationError("object_mismatch", "Public history citation differs from its verified entry");
|
|
73
|
-
verifyPrincipalPolicyCheckpoint({
|
|
74
|
-
chain: selected.retainedEntries.map((entry) => ({
|
|
75
|
-
...entry,
|
|
76
|
-
projection: [...entry.projection],
|
|
77
|
-
grants: [...entry.grants],
|
|
78
|
-
})),
|
|
79
|
-
currentState: selected.currentEntry.state,
|
|
80
|
-
localCheckpoint: checkpoint,
|
|
81
|
-
});
|
|
87
|
+
checkSelectedReferences(input, references, batch, selected, checkpoint);
|
|
82
88
|
const policy = await selectPrincipalPolicyAuthorization(selected);
|
|
83
89
|
if (!policy.ok)
|
|
84
90
|
throw policy.error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectPublicPrincipalHistory.js","sourceRoot":"","sources":["selectPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAIlC,kCAAkC,EAElC,+BAA+B,EAC/B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAEtG,OAAO,EAAE,wCAAwC,EAAE,MAAM,sCAAsC,CAAC;
|
|
1
|
+
{"version":3,"file":"selectPublicPrincipalHistory.js","sourceRoot":"","sources":["selectPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAIlC,kCAAkC,EAElC,+BAA+B,EAC/B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAEtG,OAAO,EAAE,wCAAwC,EAAE,MAAM,sCAAsC,CAAC;AAahG,KAAK,UAAU,WAAW,CACxB,KAAkC,EAClC,QAA2B,EAC3B,mBAAqE;IAErE,MAAM,MAAM,GAA2C,EAAE,CAAC;IAC1D,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,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,MAAM,CAAC,EAAE;YAAE,MAAM,MAAM,CAAC,KAAK,CAAC;QACnC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IACD,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryReferenceProof,\n type ReferencedPrincipalHead,\n selectPrincipalPolicyAuthorization,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"./principalHistoryRecoveryReferences\";\nimport type { RecoveredPublicPrincipalHistory } from \"./publicPrincipalHistoryTypes\";\n\ninterface PublicHistorySelectionInput {\n readonly execSql: ExecSql;\n readonly recovered: RecoveredPublicPrincipalHistory;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly checkpoint: PrincipalPolicyCheckpoint | null;\n readonly deferCheckpointCheck?: boolean | undefined;\n readonly includeGenesis?: boolean;\n readonly stillCurrent: () => boolean;\n}\n\nasync function selectBatch(\n input: PublicHistorySelectionInput,\n versions: readonly number[],\n checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined,\n) {\n const proofs: PrincipalPolicyHistoryReferenceProof[] = [];\n for (const version of versions) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n proofs.push(\n await loadPrincipalHistoryReference({\n execSql: input.execSql,\n ...input.recovered,\n version,\n }),\n );\n }\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: input.recovered.history,\n references: proofs,\n checkpointReference,\n });\n if (!selected.ok) throw selected.error;\n return selected.value;\n}\n\nasync function loadCheckpointProof(\n input: PublicHistorySelectionInput,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyHistoryReferenceProof | undefined> {\n let checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined;\n try {\n if (checkpoint)\n checkpointReference = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n ...input.recovered,\n version: checkpoint.version,\n });\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n return checkpointReference;\n}\n\nfunction checkSelectedReferences(\n input: PublicHistorySelectionInput,\n references: readonly ReferencedPrincipalHead[],\n batch: readonly number[],\n selected: Awaited<ReturnType<typeof selectBatch>>,\n checkpoint: PrincipalPolicyCheckpoint | null,\n) {\n // Authenticate the disposable proof before comparing caller citations or pins.\n for (const reference of references.filter(({ version }) =>\n batch.includes(version),\n ))\n if (\n !selected.retainedEntries.some(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history citation differs from its verified entry\",\n );\n if (!input.deferCheckpointCheck)\n verifyPrincipalPolicyCheckpoint({\n chain: selected.retainedEntries.map((entry) => ({\n ...entry,\n projection: [...entry.projection],\n grants: [...entry.grants],\n })),\n currentState: selected.currentEntry.state,\n localCheckpoint: checkpoint,\n });\n}\n\n/** Select bounded proof batches without admitting or advancing durable pins. */\nexport async function selectPublicPrincipalHistory(\n input: PublicHistorySelectionInput,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n const references = structuredClone(input.references);\n const checkpoint = input.checkpoint && { ...input.checkpoint };\n const head = input.recovered.history.currentEntry.state;\n if (\n !input.deferCheckpointCheck &&\n checkpoint &&\n checkpoint.version > head.version\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history cannot connect to the newer durable checkpoint\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalType !== head.principalType ||\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history reference is outside the verified prefix\",\n );\n const versions = [\n ...new Set([\n ...(input.includeGenesis ? [1] : []),\n ...references.map(({ version }) => version),\n head.version,\n ]),\n ];\n const policies: VerifiedPrincipalPolicySelection[] = [];\n const checkpointReference = await loadCheckpointProof(\n input,\n checkpoint && checkpoint.version <= head.version ? checkpoint : null,\n );\n for (\n let offset = 0;\n offset < versions.length;\n offset += PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n ) {\n const batch = versions.slice(\n offset,\n offset + PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n );\n const selected = await selectBatch(input, batch, checkpointReference).catch(\n (error: unknown) => {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n },\n );\n checkSelectedReferences(input, references, batch, selected, checkpoint);\n const policy = await selectPrincipalPolicyAuthorization(selected);\n if (!policy.ok) throw policy.error;\n policies.push(policy.value);\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n}\n"]}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { and, eq, or } from "drizzle-orm";
|
|
2
2
|
import { principalHistoryEntries, principalHistoryNodes, principalHistoryPrefixes, } from "../../data/sqlite/principalHistoryEvidenceSchema.js";
|
|
3
|
+
import { principalHistoryNodeReferences, principalHistoryRootOwners, } from "../../data/sqlite/principalHistoryNodeRetentionSchema.js";
|
|
4
|
+
import { principalHistoryStageScopes, principalKeyEnvelopeArchive, } from "../../data/sqlite/principalHistoryRetentionSchema.js";
|
|
3
5
|
import { principalHistoryStages } from "../../data/sqlite/principalHistoryStageSchema.js";
|
|
4
6
|
import { principalPolicies, principalPolicyBundleHistory, principalPolicyBundleReferences, principalPolicyCheckpoints, principalPolicyOrganizations, } from "../../data/sqlite/schema.js";
|
|
5
7
|
import { remoteResetBatches } from "./remoteResetBatches.js";
|
|
@@ -70,9 +72,13 @@ export async function loadRemoteResetPrincipalScope(tx, organizationId) {
|
|
|
70
72
|
// must not turn a previously observed principal or object into first sight.
|
|
71
73
|
export async function clearRemoteResetPrincipalRows(input) {
|
|
72
74
|
for (const table of [
|
|
75
|
+
principalHistoryNodeReferences,
|
|
76
|
+
principalHistoryRootOwners,
|
|
73
77
|
principalHistoryEntries,
|
|
74
78
|
principalHistoryNodes,
|
|
75
79
|
principalHistoryPrefixes,
|
|
80
|
+
principalHistoryStageScopes,
|
|
81
|
+
principalKeyEnvelopeArchive,
|
|
76
82
|
])
|
|
77
83
|
await input.tx
|
|
78
84
|
.delete(table)
|
|
@@ -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,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,GAAG,CAAC;QAClE,EAAE;aACC,MAAM,CAAC;YACN,EAAE,EAAE,iBAAiB,CAAC,WAAW;YACjC,IAAI,EAAE,iBAAiB,CAAC,a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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 {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n} from \"../../data/sqlite/principalHistoryNodeRetentionSchema\";\nimport {\n principalHistoryStageScopes,\n principalKeyEnvelopeArchive,\n} from \"../../data/sqlite/principalHistoryRetentionSchema\";\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 principalHistoryNodeReferences,\n principalHistoryRootOwners,\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n principalHistoryStageScopes,\n principalKeyEnvelopeArchive,\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"]}
|