@tearleads/client-sdk 0.1.56 → 0.1.58

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.
Files changed (59) hide show
  1. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +2 -2
  2. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  3. package/data/persistence/organizations/organizationReadModelPersistence.js +2 -2
  4. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  5. package/data/principals/principalPolicyCoordinator.js +40 -0
  6. package/data/principals/principalPolicyCoordinator.js.map +1 -0
  7. package/index.d.ts +4 -4
  8. package/index.js +2 -2
  9. package/index.js.map +1 -1
  10. package/package.json +1 -1
  11. package/workflows/organizations/currentOrganizationMutationRetention.js +1 -1
  12. package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -1
  13. package/workflows/organizations/index.d.ts +0 -1
  14. package/workflows/organizations/index.js +0 -1
  15. package/workflows/organizations/index.js.map +1 -1
  16. package/workflows/organizations/principalMutationJournalManagement.js +3 -3
  17. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
  18. package/workflows/organizations/principalMutationJournalSession.js +3 -3
  19. package/workflows/organizations/principalMutationJournalSession.js.map +1 -1
  20. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +4 -24
  21. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +13 -133
  22. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
  23. package/workflows/organizations/runtimeCurrentGroupMutation.js +1 -1
  24. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -1
  25. package/workflows/principals/acknowledgedPrincipalCurrents.d.ts +33 -0
  26. package/workflows/principals/acknowledgedPrincipalCurrents.js +140 -0
  27. package/workflows/principals/acknowledgedPrincipalCurrents.js.map +1 -0
  28. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.d.ts +1 -1
  29. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.js +1 -1
  30. package/workflows/principals/acknowledgedPrincipalPredecessor.js.map +1 -0
  31. package/workflows/principals/index.d.ts +1 -0
  32. package/workflows/principals/index.js +1 -0
  33. package/workflows/principals/index.js.map +1 -1
  34. package/workflows/{organizations → principals}/initialPrincipalCurrentPublication.js +5 -7
  35. package/workflows/principals/initialPrincipalCurrentPublication.js.map +1 -0
  36. package/workflows/principals/principalAcknowledgementChecks.d.ts +30 -0
  37. package/workflows/principals/principalAcknowledgementChecks.js +2 -0
  38. package/workflows/principals/principalAcknowledgementChecks.js.map +1 -0
  39. package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js.map +1 -1
  40. package/workflows/principals/principalRecoveryMemoValidity.js +2 -2
  41. package/workflows/principals/principalRecoveryMemoValidity.js.map +1 -1
  42. package/workflows/{organizations → principals}/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  43. package/workflows/principals/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
  44. package/workflows/principals/runtimePolicyRecovery.js +2 -2
  45. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  46. package/workflows/principals/runtimeProjectionPolicyRecovery.js +2 -2
  47. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  48. package/workflows/registration/provisionedPrincipalHistory.js +2 -2
  49. package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
  50. package/data/principals/principalRecoveryEpoch.js +0 -18
  51. package/data/principals/principalRecoveryEpoch.js.map +0 -1
  52. package/workflows/organizations/acknowledgedPrincipalPredecessor.js.map +0 -1
  53. package/workflows/organizations/initialPrincipalCurrentPublication.js.map +0 -1
  54. package/workflows/organizations/principalMutationJournalLane.js +0 -26
  55. package/workflows/organizations/principalMutationJournalLane.js.map +0 -1
  56. package/workflows/organizations/reconcileAcknowledgedPrincipalCurrent.js.map +0 -1
  57. package/workflows/principals/principalRecoveryQueue.js +0 -22
  58. package/workflows/principals/principalRecoveryQueue.js.map +0 -1
  59. /package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"acknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["acknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAGL,oCAAoC,EACpC,oCAAoC,GACrC,MAAM,mEAAmE,CAAC;AAC3E,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AAEjG,OAAO,EAEL,uCAAuC,GACxC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAC7F,OAAO,EAAE,sCAAsC,EAAE,MAAM,sBAAsB,CAAC;AAE9E,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,GAC1B,MAAM,mCAAmC,CAAC;AAE3C,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,qCAAqC,EAAE,MAAM,yCAAyC,CAAC;AAgBhG,KAAK,UAAU,kBAAkB,CAC/B,OAA6C,EAC7C,OAAkC,EAClC,QAAyC,EACzC,WAAoD,EACpD,MAAsC;IAEtC,OAAO,GAAG;QACR,GAAG,OAAO;QACV,UAAU,EAAE;YACV,GAAG,OAAO,CAAC,UAAU;YACrB,OAAO,EAAE,mCAAmC,CAAC,OAAO,CAAC;SACtD;KACF,CAAC;IACF,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IACzE,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,MAAM,EACJ,OAAO,EACP,KAAK,EACL,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,wBA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ads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n PrincipalAcknowledgementChangedError,\n persistAcknowledgedPrincipalCurrents,\n} from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type AcknowledgedPrincipalPredecessor,\n restoreAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\nimport { reconcileAcknowledgedPrincipalCurrent } from \"./reconcileAcknowledgedPrincipalCurrent\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Capture before submitting the mutation; null only for a new group. */\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const {\n scopeId,\n saved,\n artifacts,\n verifier,\n previous,\n predecessorIndexRootHash,\n } = await restoreAcknowledgedPrincipalPredecessor(options, predecessor);\n const expectedHead = await checks.authoredHead(request);\n checks.assertReceipt({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(current);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const policy = await checks.acknowledgeSuccessor({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: response.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent: current,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n predecessorIndexRootHash,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** The acknowledged currents of one mutation, recorded together. */\nexport interface AcknowledgedPrincipalCurrentBatch {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * Extend authenticated local progress and retain exact acknowledged artifacts\n * atomically with pins, once `checks` accept each acknowledgement.\n */\nexport async function recordAcknowledgedPrincipalCurrents(\n input: AcknowledgedPrincipalCurrentBatch & {\n readonly checks: PrincipalAcknowledgementChecks;\n },\n): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const checks = input.checks;\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: {\n initialGroup: boolean;\n request: PutPrincipalPolicyRequest;\n response: PrincipalPolicyMutationResponse;\n options: RecoverPrincipalPolicyHistoryOptions;\n predecessor: AcknowledgedPrincipalPredecessor | null;\n }[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n predecessor: structuredClone(entry.predecessor),\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const entry of entries)\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(\n entry.options,\n entry.request,\n entry.response,\n entry.predecessor,\n checks,\n ),\n );\n checks.assertDirectoryBindings(\n organizationId,\n entries.map(({ response }) => response),\n );\n for (let attempt = 0; ; attempt += 1) {\n const reconciled = [];\n for (const [index, publication] of publications.entries()) {\n const entry = entries[index];\n if (!entry) throw new Error(\"Missing acknowledgement entry\");\n reconciled.push(\n await reconcileAcknowledgedPrincipalCurrent(\n entry.options,\n publication,\n ),\n );\n }\n try {\n await persistAcknowledgedPrincipalCurrents({\n execSql,\n organizationId,\n entries: reconciled,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n break;\n } catch (error) {\n if (\n !(error instanceof PrincipalAcknowledgementChangedError) ||\n attempt >= 7\n )\n throw error;\n }\n }\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { type PrincipalHistoryPrefix } from "../../data/persistence/principalHistoryPrefixPersistence.js";
2
- import type { RecoverPrincipalPolicyHistoryOptions } from "../principals/principalHistoryRecoveryTypes.js";
2
+ import type { RecoverPrincipalPolicyHistoryOptions } from "./principalHistoryRecoveryTypes.js";
3
3
  /** Sealed predecessor evidence, owned by a mutation before its request is sent. */
4
4
  export type AcknowledgedPrincipalPredecessor = Readonly<PrincipalHistoryPrefix>;
5
5
  /** Authenticate the entire prefix, including its scope and current artifacts. */
@@ -6,7 +6,7 @@ import { principalHistoryEvidenceScopeId, principalHistoryPrefixProtection, } fr
6
6
  import { ownPrincipalHistoryProtection } from "../../data/principals/principalHistoryProtection.js";
7
7
  import { parsePrincipalHistoryStageCurrent } from "../../data/principals/principalHistoryStageProtection.js";
8
8
  import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
9
- import { principalHistoryVerificationContext } from "../principals/principalHistoryRecoveryVerification.js";
9
+ import { principalHistoryVerificationContext } from "./principalHistoryRecoveryVerification.js";
10
10
  /** Authenticate the entire prefix, including its scope and current artifacts. */
11
11
  export async function restoreAcknowledgedPrincipalPrefix(options, saved) {
12
12
  const scopeId = await principalHistoryEvidenceScopeId({
@@ -0,0 +1 @@
1
+ {"version":3,"file":"acknowledgedPrincipalPredecessor.js","sourceRoot":"","sources":["acknowledgedPrincipalPredecessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,0BAA0B,GAE3B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,iCAAiC,EAAE,MAAM,uDAAuD,CAAC;AAC1G,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAEvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,wCAAwC,CAAC;AAK7F,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAA6C,EAC7C,KAA8C;IAE9C,MAAM,OAAO,GAAG,MAAM,+BAA+B,CAAC;QACpD,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,IAAI,EAAE,OAAO,CAAC,YAAY;QAC1B,UAAU,EAAE,OAAO,CAAC,UAAU;KAC/B,CAAC,CAAC;IACH,IACE,CAAC,KAAK;QACN,KAAK,CAAC,OAAO,KAAK,OAAO;QACzB,KAAK,CAAC,cAAc,KAAK,OAAO,CAAC,cAAc;QAE/C,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,+DAA+D,CAChE,CAAC;IAC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AAQ,CAAC,QAAQ,CAAC,KAAK,EACvB,OAAO,CAAC,YAAY,CACrB;QAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,iEAAiE,CAClE,CAAC;IACJ,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n loadPrincipalHistoryPrefix,\n type PrincipalHistoryPrefix,\n} from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\nimport { principalHistoryVerificationContext } from \"./principalHistoryRecoveryVerification\";\n\n/** Sealed predecessor evidence, owned by a mutation before its request is sent. */\nexport type AcknowledgedPrincipalPredecessor = Readonly<PrincipalHistoryPrefix>;\n\n/** Authenticate the entire prefix, including its scope and current artifacts. */\nexport async function restoreAcknowledgedPrincipalPrefix(\n options: RecoverPrincipalPolicyHistoryOptions,\n saved: AcknowledgedPrincipalPredecessor | null,\n) {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n if (\n !saved ||\n saved.scopeId !== scopeId ||\n saved.organizationId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledgement requires its authenticated predecessor prefix\",\n );\n const restored = await restorePrincipalPolicyHistoryVerifier(\n {\n principalId: options.expectedHead.principalId,\n principalType: options.expectedHead.principalType,\n },\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n if (!restored.ok) throw restored.error;\n const artifacts = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (!artifacts)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Acknowledged predecessor artifacts are malformed\",\n );\n const history = restored.value.finish(\n principalPolicyReferenceFromBundle(artifacts),\n );\n if (!history.ok) throw history.error;\n const previous = await verifyPrincipalPolicyCurrent({\n current: artifacts,\n history: history.value,\n });\n if (!previous.ok) throw previous.error;\n return {\n scopeId,\n saved,\n artifacts,\n verifier: restored.value,\n previous: previous.value,\n history: history.value,\n predecessorIndexRootHash: history.value.indexRootHash,\n };\n}\n\n/** Capture exact predecessor evidence while authoring, before HTTP can commit. */\nexport async function captureAcknowledgedPrincipalPredecessor(\n input: RecoverPrincipalPolicyHistoryOptions,\n): Promise<AcknowledgedPrincipalPredecessor> {\n const protection = ownPrincipalHistoryProtection(input.protection);\n const options = {\n ...input,\n expectedHead: structuredClone(input.expectedHead),\n protection: {\n ...protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n try {\n assertProjectionVerificationCurrent(current);\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n const restored = await restoreAcknowledgedPrincipalPrefix(\n options,\n await loadPrincipalHistoryPrefix(options.execSql, scopeId),\n );\n assertProjectionVerificationCurrent(current);\n if (\n !principalHeadMatchesReference(\n restored.previous.state,\n options.expectedHead,\n )\n )\n throw new Error(\n \"Principal policy changed before submission; retry the mutation\",\n );\n return structuredClone(restored.saved);\n } finally {\n protection.localKey.fill(0);\n }\n}\n\nexport async function restoreAcknowledgedPrincipalPredecessor(\n options: RecoverPrincipalPolicyHistoryOptions,\n saved: AcknowledgedPrincipalPredecessor | null,\n) {\n const restored = await restoreAcknowledgedPrincipalPrefix(options, saved);\n if (\n !principalHeadMatchesReference(\n restored.previous.state,\n options.expectedHead,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledgement predecessor does not match the authored request\",\n );\n return restored;\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
2
+ export { type AcknowledgedPrincipalPredecessor, captureAcknowledgedPrincipalPredecessor, } from "./acknowledgedPrincipalPredecessor.js";
2
3
  export { type CachePrincipalPolicyBundlesOptions, type CacheReferencedPrincipalPoliciesOptions, cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
3
4
  export { PrincipalPolicyHistoryReadError, type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions, } from "./principalHistoryRecoveryTypes.js";
4
5
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
@@ -1,3 +1,4 @@
1
+ export { captureAcknowledgedPrincipalPredecessor, } from "./acknowledgedPrincipalPredecessor.js";
1
2
  export { cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
2
3
  export { PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
3
4
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nexport {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,uCAAuC,GACxC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nexport {\n type AcknowledgedPrincipalPredecessor,\n captureAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nexport {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
@@ -3,23 +3,21 @@ import { assertProjectionVerificationCurrent } from "../../data/keyingProjection
3
3
  import { preparePrincipalHistoryEvidencePage } from "../../data/persistence/principalHistoryEvidencePersistence.js";
4
4
  import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
5
5
  import { principalHistoryEvidenceScopeId } from "../../data/principals/principalHistoryPrefixProtection.js";
6
- import { collectPrincipalPolicySignerPublicKeys } from "../principals/policyVerification.js";
7
- import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "../principals/principalHistoryRecoveryVerification.js";
8
- import { groupPolicyMutationHead } from "./groupPolicyMutationHead.js";
6
+ import { collectPrincipalPolicySignerPublicKeys } from "./policyVerification.js";
9
7
  import { sealPrincipalCurrentPublication } from "./principalCurrentPublicationSeal.js";
10
- import { assertPrincipalPolicyReceiptArtifacts } from "./principalPolicyReceiptArtifacts.js";
8
+ import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "./principalHistoryRecoveryVerification.js";
11
9
  /** Verify a newly authored group from genesis before its atomic directory publication. */
12
- export async function prepareInitialGroupCurrentPublication(input, request, response, predecessor) {
10
+ export async function prepareInitialGroupCurrentPublication(input, request, response, predecessor, checks) {
13
11
  const current = () => !input.signal?.aborted && input.stillCurrent();
14
12
  assertProjectionVerificationCurrent(current);
15
- const expectedHead = await groupPolicyMutationHead(request);
13
+ const expectedHead = await checks.authoredHead(request);
16
14
  if (predecessor !== null ||
17
15
  request.state.principalType !== "group" ||
18
16
  request.state.version !== 1 ||
19
17
  request.state.prevStateHash !== null ||
20
18
  !principalHeadMatchesReference(expectedHead, input.expectedHead))
21
19
  throw new KeyingVerificationError("object_mismatch", "Initial group publication must begin at its exact genesis");
22
- assertPrincipalPolicyReceiptArtifacts({ expectedHead, request, response });
20
+ checks.assertReceipt({ expectedHead, request, response });
23
21
  const keys = await collectPrincipalPolicySignerPublicKeys({
24
22
  bundle: { currentState: response.currentState, previousStates: [] },
25
23
  resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initialPrincipalCurrentPublication.js","sourceRoot":"","sources":["initialPrincipalCurrentPublication.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,+BAA+B,EAAE,MAAM,wDAAwD,CAAC;AAEzG,OAAO,EAAE,sCAAsC,EAAE,MAAM,sBAAsB,CAAC;AAE9E,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAEpF,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,wCAAwC,CAAC;AAEhD,0FAA0F;AAC1F,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,KAA2C,EAC3C,OAAkC,EAClC,QAAyC,EACzC,WAAoD,EACpD,MAAsC;IAEtC,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;IACrE,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,M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AE,MAAM,CAAC,KAAK;QACpB,gBAAgB,EAAE,IAAI;QACtB,wBAAwB,EAAE,IAAI;QAC9B,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO,EAAE,CAAC,KAAK,CAAC;YAChB,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { AcknowledgedPrincipalCurrentPublication } from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport type { AcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport { sealPrincipalCurrentPublication } from \"./principalCurrentPublicationSeal\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\n/** Verify a newly authored group from genesis before its atomic directory publication. */\nexport async function prepareInitialGroupCurrentPublication(\n input: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const expectedHead = await checks.authoredHead(request);\n if (\n predecessor !== null ||\n request.state.principalType !== \"group\" ||\n request.state.version !== 1 ||\n request.state.prevStateHash !== null ||\n !principalHeadMatchesReference(expectedHead, input.expectedHead)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Initial group publication must begin at its exact genesis\",\n );\n checks.assertReceipt({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Initial group signer could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const verifier = createPrincipalPolicyHistoryVerifier({\n principalType: \"group\",\n principalId: expectedHead.principalId,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(input, [entry]);\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const history = verifier.finish(expectedHead);\n if (!history.ok) throw history.error;\n const policy = await verifyPrincipalPolicyCurrent({\n current: response,\n history: history.value,\n });\n if (!policy.ok) throw policy.error;\n const options = {\n ...input,\n protection: {\n ...input.protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: expectedHead,\n protection: options.protection,\n });\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n ...sealed,\n policy: policy.value,\n predecessorStage: null,\n predecessorIndexRootHash: null,\n previousPrefixProgress: null,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: input.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n"]}
@@ -0,0 +1,30 @@
1
+ import type { PrincipalPolicyExternalAuthority, PrincipalPolicySignerPublicKey, ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
2
+ import type { PutPrincipalPolicyRequest } from "../../internal/validators/request/index.js";
3
+ import type { PrincipalPolicyMutationResponse } from "../../internal/validators/response/index.js";
4
+ /**
5
+ * The checks the code that authored a principal mutation makes on the
6
+ * server's acknowledgement of it. Recovery records an acknowledged current
7
+ * only after these accept it; the organization mutation workflows supply them.
8
+ */
9
+ export interface PrincipalAcknowledgementChecks {
10
+ /** The head an authored request commits to. */
11
+ readonly authoredHead: (request: PutPrincipalPolicyRequest) => Promise<ReferencedPrincipalHead>;
12
+ /** The receipt carries exactly the authored state and artifacts. */
13
+ readonly assertReceipt: (input: {
14
+ readonly expectedHead: ReferencedPrincipalHead;
15
+ readonly request: PutPrincipalPolicyRequest;
16
+ readonly response: PrincipalPolicyMutationResponse;
17
+ }) => void;
18
+ /** The acknowledged state is the authored successor of the verified predecessor. */
19
+ readonly acknowledgeSuccessor: (input: {
20
+ readonly verifiedCurrentPolicy: VerifiedPrincipalPolicyCurrent;
21
+ readonly expectedHead: ReferencedPrincipalHead;
22
+ readonly request: PutPrincipalPolicyRequest;
23
+ readonly response: PrincipalPolicyMutationResponse["currentState"];
24
+ readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];
25
+ readonly externalAuthority?: PrincipalPolicyExternalAuthority | undefined;
26
+ readonly stillCurrent: () => boolean;
27
+ }) => Promise<VerifiedPrincipalPolicyCurrent>;
28
+ /** Acknowledged directory and group heads cite each other. */
29
+ readonly assertDirectoryBindings: (organizationId: string, responses: readonly PrincipalPolicyMutationResponse[]) => void;
30
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=principalAcknowledgementChecks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalAcknowledgementChecks.js","sourceRoot":"","sources":["principalAcknowledgementChecks.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n PrincipalPolicyExternalAuthority,\n PrincipalPolicySignerPublicKey,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\n\n/**\n * The checks the code that authored a principal mutation makes on the\n * server's acknowledgement of it. Recovery records an acknowledged current\n * only after these accept it; the organization mutation workflows supply them.\n */\nexport interface PrincipalAcknowledgementChecks {\n /** The head an authored request commits to. */\n readonly authoredHead: (\n request: PutPrincipalPolicyRequest,\n ) => Promise<ReferencedPrincipalHead>;\n /** The receipt carries exactly the authored state and artifacts. */\n readonly assertReceipt: (input: {\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n }) => void;\n /** The acknowledged state is the authored successor of the verified predecessor. */\n readonly acknowledgeSuccessor: (input: {\n readonly verifiedCurrentPolicy: VerifiedPrincipalPolicyCurrent;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse[\"currentState\"];\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n readonly externalAuthority?: PrincipalPolicyExternalAuthority | undefined;\n readonly stillCurrent: () => boolean;\n }) => Promise<VerifiedPrincipalPolicyCurrent>;\n /** Acknowledged directory and group heads cite each other. */\n readonly assertDirectoryBindings: (\n organizationId: string,\n responses: readonly PrincipalPolicyMutationResponse[],\n ) => void;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"principalCurrentPublicationSeal.js","sourceRoot":"","sources":["principalCurrentPublicationSeal.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAC;AAC1G,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,uDAAuD,CAAC;AAG/D,SAAS,SAAS,CAAC,IAA6B;IAC9C,OAAO;QACL,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,cAAc,EAAE,IAAI,CAAC,cAAc;KACpC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,OAA6C,EAC7C,YAAqC,EACrC,QAAwC,EACxC,QAAoC;IAEpC,+EAA+E;IAC/E,YAAY,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC;IACvC,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC;QACjC,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;QAC7C,aAAa,EAAE,QAAQ,CAAC,aAAa;QACrC,cAAc,EAAE,QAAQ,CAAC,cAAc;QACvC,sBAAsB,EAAE,QAAQ,CAAC,sBAAsB;KACxD,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,EAAE,EAAE,MAAM,uBAAuB,CAC/B,OAAO,CAAC,cAAc,EACtB,YAAY,EACZ,OAAO,CAAC,UAAU,CAAC,OAAO,CAC3B;QACD,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,YAAY,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\nimport {\n type PrincipalPolicyHistoryVerifier,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { principalHistoryPrefixProtection } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport {\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../data/principals/principalHistoryStageProtection\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../principals/principalHistoryRecoveryTypes\";\n\nfunction exactHead(head: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\n principalType: head.principalType,\n principalId: head.principalId,\n version: head.version,\n keyEpoch: head.keyEpoch,\n stateHash: head.stateHash,\n keyFingerprint: head.keyFingerprint,\n };\n}\n\nexport async function sealPrincipalCurrentStage(\n options: RecoverPrincipalPolicyHistoryOptions,\n expectedHead: ReferencedPrincipalHead,\n verifier: PrincipalPolicyHistoryVerifier,\n response: PrincipalPolicyPageCurrent,\n) {\n // Authentication uses the reference contract, never extra signed-state fields.\n expectedHead = exactHead(expectedHead);\n const currentJson = JSON.stringify({\n currentState: response.currentState,\n currentProjection: response.currentProjection,\n currentGrants: response.currentGrants,\n currentPayload: response.currentPayload,\n currentMemberEnvelopes: response.currentMemberEnvelopes,\n });\n const stage = {\n id: await principalHistoryStageId(\n options.organizationId,\n expectedHead,\n options.protection.context,\n ),\n organizationId: options.organizationId,\n afterVersion: expectedHead.version - 1,\n complete: true,\n currentJson,\n };\n const progress = await verifier.exportProgress(\n await principalHistoryStageProtection(\n options.protection,\n expectedHead,\n stage,\n ),\n );\n if (!progress.ok) throw progress.error;\n return { ...stage, progress: progress.value };\n}\n\nexport async function sealPrincipalCurrentPublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n scopeId: string,\n expectedHead: ReferencedPrincipalHead,\n verifier: PrincipalPolicyHistoryVerifier,\n response: PrincipalPolicyPageCurrent,\n) {\n expectedHead = exactHead(expectedHead);\n const stage = await sealPrincipalCurrentStage(\n options,\n expectedHead,\n verifier,\n response,\n );\n const prefix = {\n scopeId,\n organizationId: options.organizationId,\n version: expectedHead.version,\n headJson: serializeKeyingCanonicalJson({ ...expectedHead }),\n currentJson: stage.currentJson,\n };\n const progress = await verifier.exportProgress(\n await principalHistoryPrefixProtection(options.protection, prefix),\n );\n if (!progress.ok) throw progress.error;\n return { prefix: { ...prefix, progress: progress.value }, stage };\n}\n"]}
1
+ {"version":3,"file":"principalCurrentPublicationSeal.js","sourceRoot":"","sources":["principalCurrentPublicationSeal.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAC;AAC1G,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,uDAAuD,CAAC;AAG/D,SAAS,SAAS,CAAC,IAA6B;IAC9C,OAAO;QACL,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,cAAc,EAAE,IAAI,CAAC,cAAc;KACpC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,OAA6C,EAC7C,YAAqC,EACrC,QAAwC,EACxC,QAAoC;IAEpC,+EAA+E;IAC/E,YAAY,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC;IACvC,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC;QACjC,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;QAC7C,aAAa,EAAE,QAAQ,CAAC,aAAa;QACrC,cAAc,EAAE,QAAQ,CAAC,cAAc;QACvC,sBAAsB,EAAE,QAAQ,CAAC,sBAAsB;KACxD,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,EAAE,EAAE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,GAAG,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,CAAC;AACpE,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n type PrincipalPolicyHistoryVerifier,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { principalHistoryPrefixProtection } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport {\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../data/principals/principalHistoryStageProtection\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nfunction exactHead(head: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\n principalType: head.principalType,\n principalId: head.principalId,\n version: head.version,\n keyEpoch: head.keyEpoch,\n stateHash: head.stateHash,\n keyFingerprint: head.keyFingerprint,\n };\n}\n\nexport async function sealPrincipalCurrentStage(\n options: RecoverPrincipalPolicyHistoryOptions,\n expectedHead: ReferencedPrincipalHead,\n verifier: PrincipalPolicyHistoryVerifier,\n response: PrincipalPolicyPageCurrent,\n) {\n // Authentication uses the reference contract, never extra signed-state fields.\n expectedHead = exactHead(expectedHead);\n const currentJson = JSON.stringify({\n currentState: response.currentState,\n currentProjection: response.currentProjection,\n currentGrants: response.currentGrants,\n currentPayload: response.currentPayload,\n currentMemberEnvelopes: response.currentMemberEnvelopes,\n });\n const stage = {\n id: await principalHistoryStageId(\n options.organizationId,\n expectedHead,\n options.protection.context,\n ),\n organizationId: options.organizationId,\n afterVersion: expectedHead.version - 1,\n complete: true,\n currentJson,\n };\n const progress = await verifier.exportProgress(\n await principalHistoryStageProtection(\n options.protection,\n expectedHead,\n stage,\n ),\n );\n if (!progress.ok) throw progress.error;\n return { ...stage, progress: progress.value };\n}\n\nexport async function sealPrincipalCurrentPublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n scopeId: string,\n expectedHead: ReferencedPrincipalHead,\n verifier: PrincipalPolicyHistoryVerifier,\n response: PrincipalPolicyPageCurrent,\n) {\n expectedHead = exactHead(expectedHead);\n const stage = await sealPrincipalCurrentStage(\n options,\n expectedHead,\n verifier,\n response,\n );\n const prefix = {\n scopeId,\n organizationId: options.organizationId,\n version: expectedHead.version,\n headJson: serializeKeyingCanonicalJson({ ...expectedHead }),\n currentJson: stage.currentJson,\n };\n const progress = await verifier.exportProgress(\n await principalHistoryPrefixProtection(options.protection, prefix),\n );\n if (!progress.ok) throw progress.error;\n return { prefix: { ...prefix, progress: progress.value }, stage };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { loadPrincipalPolicyCheckpoint } from "../../data/persistence/keyingCheckpointPersistence.js";
2
- import { principalRecoveryEpoch } from "../../data/principals/principalRecoveryEpoch.js";
2
+ import { getOrCreatePrincipalPolicyCoordinator } from "../../data/principals/principalPolicyCoordinator.js";
3
3
  async function pinCovers(input, head) {
4
4
  const pin = await loadPrincipalPolicyCheckpoint(input.execSql, head.principalType, head.principalId);
5
5
  return (!pin ||
@@ -7,7 +7,7 @@ async function pinCovers(input, head) {
7
7
  (pin.version === head.version && pin.stateHash === head.stateHash));
8
8
  }
9
9
  function organizationEpoch(input) {
10
- return () => principalRecoveryEpoch(input.execSql, input.organizationId);
10
+ return () => getOrCreatePrincipalPolicyCoordinator(input.execSql).recoveryEpoch(input.organizationId);
11
11
  }
12
12
  /** A directory names every group head; a newer pin on any of them evicts it. */
13
13
  export function directoryMemoValidity(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalRecoveryMemoValidity.js","sourceRoot":"","sources":["principalRecoveryMemoValidity.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AAoBtF,KAAK,UAAU,SAAS,CACtB,KAA+B,EAC/B,IAAgB;IAEhB,MAAM,GAAG,GAAG,MAAM,6BAA6B,CAC7C,KAAK,CAAC,OAAO,EACb,IAAI,CAAC,aAAa,EAClB,IAAI,CAAC,WAAW,CACjB,CAAC;IACF,OAAO,CACL,CAAC,GAAG;QACJ,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO;QAC1B,CAAC,GAAG,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO,IAAI,GAAG,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,CAAC,CACnE,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,KAA+B;IACxD,OAAO,GAAG,EAAE,CAAC,sBAAsB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;AAC3E,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,qBAAqB,CACnC,KAA+B;IAE/B,OAAO;QACL,KAAK,EAAE,iBAAiB,CAAC,KAAK,CAAC;QAC/B,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE;YAC1B,KAAK,MAAM,IAAI,IAAI;gBACjB,SAAS,CAAC,MAAM,CAAC,KAAK;gBACtB,GAAG,SAAS,CAAC,UAAU,CAAC,UAAU;aACnC;gBACC,IAAI,CAAC,CAAC,MAAM,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;oBAAE,OAAO,KAAK,CAAC;YACpD,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,KAA+B,EAC/B,YAAwB;IAExB,OAAO;QACL,KAAK,EAAE,iBAAiB,CAAC,KAAK,CAAC;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,YAAY,CAAC;KAC7C,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { principalRecoveryEpoch } from \"../../data/principals/principalRecoveryEpoch\";\nimport type { RecoveredPrincipalPolicyHistory } from \"./principalHistoryRecoveryTypes\";\nimport type {\n PrincipalRecoveryContext,\n RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\n\n/** What keeps a memo entry valid beyond its producer's lease. */\nexport interface PrincipalRecoveryMemoValidity<T> {\n /** Organization hint epoch; production records it before its reads. */\n readonly epoch: () => number;\n /** No durable pin has moved past or forked from a memoized head. */\n readonly covers: (value: T) => Promise<boolean>;\n}\n\ntype PinnedHead = Pick<\n ReferencedPrincipalHead,\n \"principalType\" | \"principalId\" | \"version\" | \"stateHash\"\n>;\n\nasync function pinCovers(\n input: PrincipalRecoveryContext,\n head: PinnedHead,\n): Promise<boolean> {\n const pin = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n head.principalType,\n head.principalId,\n );\n return (\n !pin ||\n pin.version < head.version ||\n (pin.version === head.version && pin.stateHash === head.stateHash)\n );\n}\n\nfunction organizationEpoch(input: PrincipalRecoveryContext) {\n return () => principalRecoveryEpoch(input.execSql, input.organizationId);\n}\n\n/** A directory names every group head; a newer pin on any of them evicts it. */\nexport function directoryMemoValidity(\n input: PrincipalRecoveryContext,\n): PrincipalRecoveryMemoValidity<RecoveredPolicyDirectory> {\n return {\n epoch: organizationEpoch(input),\n covers: async (directory) => {\n for (const head of [\n directory.policy.state,\n ...directory.descriptor.groupHeads,\n ])\n if (!(await pinCovers(input, head))) return false;\n return true;\n },\n };\n}\n\nexport function adminsMemoValidity(\n input: PrincipalRecoveryContext,\n expectedHead: PinnedHead,\n): PrincipalRecoveryMemoValidity<RecoveredPrincipalPolicyHistory> {\n return {\n epoch: organizationEpoch(input),\n covers: () => pinCovers(input, expectedHead),\n };\n}\n"]}
1
+ {"version":3,"file":"principalRecoveryMemoValidity.js","sourceRoot":"","sources":["principalRecoveryMemoValidity.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;A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import { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport type { RecoveredPrincipalPolicyHistory } from \"./principalHistoryRecoveryTypes\";\nimport type {\n PrincipalRecoveryContext,\n RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\n\n/** What keeps a memo entry valid beyond its producer's lease. */\nexport interface PrincipalRecoveryMemoValidity<T> {\n /** Organization hint epoch; production records it before its reads. */\n readonly epoch: () => number;\n /** No durable pin has moved past or forked from a memoized head. */\n readonly covers: (value: T) => Promise<boolean>;\n}\n\ntype PinnedHead = Pick<\n ReferencedPrincipalHead,\n \"principalType\" | \"principalId\" | \"version\" | \"stateHash\"\n>;\n\nasync function pinCovers(\n input: PrincipalRecoveryContext,\n head: PinnedHead,\n): Promise<boolean> {\n const pin = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n head.principalType,\n head.principalId,\n );\n return (\n !pin ||\n pin.version < head.version ||\n (pin.version === head.version && pin.stateHash === head.stateHash)\n );\n}\n\nfunction organizationEpoch(input: PrincipalRecoveryContext) {\n return () =>\n getOrCreatePrincipalPolicyCoordinator(input.execSql).recoveryEpoch(\n input.organizationId,\n );\n}\n\n/** A directory names every group head; a newer pin on any of them evicts it. */\nexport function directoryMemoValidity(\n input: PrincipalRecoveryContext,\n): PrincipalRecoveryMemoValidity<RecoveredPolicyDirectory> {\n return {\n epoch: organizationEpoch(input),\n covers: async (directory) => {\n for (const head of [\n directory.policy.state,\n ...directory.descriptor.groupHeads,\n ])\n if (!(await pinCovers(input, head))) return false;\n return true;\n },\n };\n}\n\nexport function adminsMemoValidity(\n input: PrincipalRecoveryContext,\n expectedHead: PinnedHead,\n): PrincipalRecoveryMemoValidity<RecoveredPrincipalPolicyHistory> {\n return {\n epoch: organizationEpoch(input),\n covers: () => pinCovers(input, expectedHead),\n };\n}\n"]}
@@ -2,9 +2,9 @@ import { KeyingVerificationError, verifyPrincipalPolicyCurrent, } from "../../in
2
2
  import { loadPrincipalPolicyCheckpoint } from "../../data/persistence/keyingCheckpointPersistence.js";
3
3
  import { loadPrincipalHistoryPrefix } from "../../data/persistence/principalHistoryPrefixPersistence.js";
4
4
  import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
5
- import { PrincipalHistoryEvidenceUnavailableError, selectRecoveredPrincipalHistory, } from "../principals/principalHistoryRecoveryReferences.js";
6
- import { principalHistoryVerificationContext } from "../principals/principalHistoryRecoveryVerification.js";
7
5
  import { restoreAcknowledgedPrincipalPrefix } from "./acknowledgedPrincipalPredecessor.js";
6
+ import { PrincipalHistoryEvidenceUnavailableError, selectRecoveredPrincipalHistory, } from "./principalHistoryRecoveryReferences.js";
7
+ import { principalHistoryVerificationContext } from "./principalHistoryRecoveryVerification.js";
8
8
  /** Only the receipt is proven; a newer local pin needs scoped history covering it. */
9
9
  function reconcileReceiptOnly(publication, observedPrefixProgress, checkpoint) {
10
10
  // Other verified evidence, such as a document purge proof, can pin a newer
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcileAcknowledgedPrincipalCurrent.js","sourceRoot":"","sources":["reconcileAcknowledgedPrincipalCurrent.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AAKnG,OAAO,EAAE,0BAA0B,EAAE,MAAM,0DAA0D,CAAC;AACtG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAC;AACxF,OAAO,EACL,wCAAwC,EACxC,+BAA+B,GAChC,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,mCAAmC,EAAE,MAAM,wCAAwC,CAAC;AAE7F,sFAAsF;AACtF,SAAS,oBAAoB,CAC3B,WAAoD,EACpD,s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Q,CAAC,QAAQ,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAC3D,IACE,CAAC,6BAA6B,CAC5B,QAAQ,CAAC,QAAQ,CAAC,KAAK,EACvB,OAAO,CAAC,YAAY,CACrB;YAED,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,kEAAkE,CACnE,CAAC;QACJ,OAAO,oBAAoB,CACzB,WAAW,EACX,sBAAsB,EACtB,UAAU,CACX,CAAC;IACJ,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,+BAA+B,CAAC;QACpD,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,kBAAkB,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;QACvE,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,OAAO;QACnC,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,UAAU;KACX,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,4BAA4B,CAAC;QAChD,OAAO,EAAE,QAAQ,CAAC,SAAS;QAC3B,OAAO;KACR,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,OAAO;QACL,GAAG,WAAW;QACd,cAAc,EAAE,IAAI;QACpB,sBAAsB;QACtB,kBAAkB,EAAE,UAAU;QAC9B,cAAc,EAAE,QAAQ,CAAC,KAAK;QAC9B,gBAAgB,EAAE,MAAM,CAAC,KAAK;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport type {\n AcknowledgedPrincipalCurrentPublication,\n ReconciledPrincipalCurrentPublication,\n} from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { loadPrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { restoreAcknowledgedPrincipalPrefix } from \"./acknowledgedPrincipalPredecessor\";\nimport {\n PrincipalHistoryEvidenceUnavailableError,\n selectRecoveredPrincipalHistory,\n} from \"./principalHistoryRecoveryReferences\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\nimport { principalHistoryVerificationContext } from \"./principalHistoryRecoveryVerification\";\n\n/** Only the receipt is proven; a newer local pin needs scoped history covering it. */\nfunction reconcileReceiptOnly(\n publication: AcknowledgedPrincipalCurrentPublication,\n observedPrefixProgress: string | null,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): ReconciledPrincipalCurrentPublication {\n // Other verified evidence, such as a document purge proof, can pin a newer\n // head without advancing this scope's prefix. That is honest progress this\n // receipt cannot prove membership in: retry after recovery, not a rollback.\n // A genesis receipt has no predecessor, so any existing pin stays a conflict.\n if (\n publication.predecessorStage &&\n checkpoint &&\n checkpoint.version > publication.policy.version\n )\n throw new PrincipalHistoryEvidenceUnavailableError(\n new KeyingVerificationError(\n \"missing_dependency\",\n \"A newer local principal pin is not covered by scoped history\",\n ),\n );\n return {\n ...publication,\n preservePrefix: false,\n observedPrefixProgress,\n observedCheckpoint: checkpoint,\n retainedPrefix: publication.prefix,\n checkpointPolicy: publication.policy,\n };\n}\n\n/** Prove an already observed successor contains this receipt before preserving it. */\nexport async function reconcileAcknowledgedPrincipalCurrent(\n input: RecoverPrincipalPolicyHistoryOptions,\n publication: AcknowledgedPrincipalCurrentPublication,\n): Promise<ReconciledPrincipalCurrentPublication> {\n const options = {\n ...input,\n protection: {\n ...input.protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n options.execSql,\n publication.policy.principalType,\n publication.policy.principalId,\n );\n const saved = await loadPrincipalHistoryPrefix(\n options.execSql,\n publication.prefix.scopeId,\n );\n const observedPrefixProgress = saved?.progress ?? null;\n if (observedPrefixProgress === publication.previousPrefixProgress)\n return reconcileReceiptOnly(\n publication,\n observedPrefixProgress,\n checkpoint,\n );\n const restored = await restoreAcknowledgedPrincipalPrefix(options, saved);\n if (restored.previous.version < publication.policy.version) {\n if (\n !principalHeadMatchesReference(\n restored.previous.state,\n options.expectedHead,\n )\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledgement does not extend the authenticated current prefix\",\n );\n return reconcileReceiptOnly(\n publication,\n observedPrefixProgress,\n checkpoint,\n );\n }\n const history = await selectRecoveredPrincipalHistory({\n options: { ...options, retainedReferences: [publication.policy.state] },\n scopeId: publication.prefix.scopeId,\n history: restored.history,\n checkpoint,\n });\n const policy = await verifyPrincipalPolicyCurrent({\n current: restored.artifacts,\n history,\n });\n if (!policy.ok) throw policy.error;\n return {\n ...publication,\n preservePrefix: true,\n observedPrefixProgress,\n observedCheckpoint: checkpoint,\n retainedPrefix: restored.saved,\n checkpointPolicy: policy.value,\n };\n}\n"]}
@@ -3,11 +3,11 @@ import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectio
3
3
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
4
4
  import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
5
5
  import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
6
+ import { getOrCreatePrincipalPolicyCoordinator } from "../../data/principals/principalPolicyCoordinator.js";
6
7
  import { createPrincipalCurrentRecoveryBatch } from "./principalCurrentRecoveryBatch.js";
7
8
  import { PrincipalHistoryRecoveryRaceError, PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
8
9
  import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
9
10
  import { recoverWithPrincipalLocalPreference } from "./principalRecoveryLocalPreference.js";
10
- import { queuePrincipalRecovery } from "./principalRecoveryQueue.js";
11
11
  /** Keep the private recovery key inside its runtime lease while resolving cited evidence. */
12
12
  export function createRuntimePrincipalPolicyResolver(runtime, options = {}) {
13
13
  const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);
@@ -32,7 +32,7 @@ export function createRuntimePrincipalPolicyCurrentResolver(runtime) {
32
32
  }
33
33
  return recover;
34
34
  };
35
- return (input) => queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
35
+ return (input) => getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql).queueRecovery(input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
36
36
  objectId: input.reference?.principalId ?? input.organizationId,
37
37
  objectKind: "principal",
38
38
  operation: "principal.policy.recover",
@@ -1 +1 @@
1
- {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,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,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,oCAAoC,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAclE,6FAA6F;AAC7F,MAAM,UAAU,oCAAoC,CAClD,OAAuC,EACvC,UAAqD,EAAE;IAEvD,MAAM,OAAO,GAAG,2CAA2C,CAAC,OAAO,CAA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cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,WAAW,EAAE,MAAM,CAAC,WAAW;gBAC/B,YAAY,EAAE,aAAa;aAC5B,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,KAAK,YAAY,iCAAiC;gBAClD,CAAC,KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,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 { PrincipalPolicyPageCurrent } 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 {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyHistoryReader,\n} from \"./principalPolicyHistoryReader\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\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 historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);\n if (!lease || !historyReader) 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 historyReader,\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: ScopedPrincipalPolicyRecovery = 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 // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\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":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,m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AChB,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 { PrincipalPolicyPageCurrent } 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 { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\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 {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyHistoryReader,\n} from \"./principalPolicyHistoryReader\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\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 historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);\n if (!lease || !historyReader) 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 getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql).queueRecovery(\n input.organizationId,\n () =>\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 historyReader,\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity:\n runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const batch = recoverFor(input.recoveryBatch);\n const result: ScopedPrincipalPolicyRecovery = 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 // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\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"]}
@@ -3,10 +3,10 @@ import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectio
3
3
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
4
4
  import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
5
5
  import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
6
+ import { getOrCreatePrincipalPolicyCoordinator } from "../../data/principals/principalPolicyCoordinator.js";
6
7
  import { PrincipalPolicyHistoryReadError } from "./principalHistoryRecoveryTypes.js";
7
8
  import { apiProjectionPolicyHistoryReader } from "./principalPolicyHistoryReader.js";
8
9
  import { isPrincipalRecoveryOutage } from "./principalRecoveryOutage.js";
9
- import { queuePrincipalRecovery } from "./principalRecoveryQueue.js";
10
10
  import { recoverProjectionPolicyHistory, } from "./recoverProjectionPolicyHistory.js";
11
11
  async function recoverWithOutageFallback(options) {
12
12
  try {
@@ -24,7 +24,7 @@ export function createRuntimeProjectionPolicyResolver(runtime) {
24
24
  const historyReader = apiProjectionPolicyHistoryReader(runtime.apiClient);
25
25
  if (!lease || !historyReader)
26
26
  return undefined;
27
- return (input) => queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
27
+ return (input) => getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql).queueRecovery(input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
28
28
  objectId: input.organizationId,
29
29
  objectKind: "principal",
30
30
  operation: "principal.projection.recover",
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeProjectionPolicyRecovery.js","sourceRoot":"","sources":["runtimeProjectionPolicyRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAEpC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAG1C,KAAK,UAAU,yBAAyB,CACtC,OAA+C;IAE/C,IAAI,CAAC;QACH,OAAO,MAAM,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC1D,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;QACtE,OAAO,8BAA8B,CAAC,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACvE,CAAC;AACH,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,OAAuC;IAEvC,MAAM,KAAK,GAAG,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,aAAa,GAAG,gCAAgC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1E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M,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { apiProjectionPolicyHistoryReader } from \"./principalPolicyHistoryReader\";\nimport { isPrincipalRecoveryOutage } from \"./principalRecoveryOutage\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"./runtimePolicyRecovery\";\n\nasync function recoverWithOutageFallback(\n options: ProjectionPolicyHistoryRecoveryOptions,\n) {\n try {\n return await recoverProjectionPolicyHistory(options);\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (options.offline || !isPrincipalRecoveryOutage(error)) throw error;\n return recoverProjectionPolicyHistory({ ...options, offline: true });\n }\n}\n\nexport function createRuntimeProjectionPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n const lease = readPrincipalHistoryProtection(runtime);\n const historyReader = apiProjectionPolicyHistoryReader(runtime.apiClient);\n if (!lease || !historyReader) return undefined;\n return (input) =>\n queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.projection.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 try {\n const policies = await recoverWithOutageFallback({\n ...input,\n historyReader,\n execSql: runtime.infra.execSql,\n protection,\n stillCurrent,\n offline: runtime.state?.online === false,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n });\n return { policies, stillCurrent };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"runtimeProjectionPolicyRecovery.js","sourceRoot":"","sources":["runtimeProjectionPolicyRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAEpC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AACzG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAG1C,KAAK,UAAU,yBAAyB,CACtC,OAA+C;IAE/C,IAAI,CAAC;QACH,OAAO,MAAM,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;IAAC,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O;gBAC9B,UAAU;gBACV,YAAY;gBACZ,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM,KAAK,KAAK;gBACxC,0BAA0B,EACxB,OAAO,CAAC,0BAA0B;aACrC,CAAC,CAAC;YACH,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;QACpC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,CAAC,KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACJ,CAAC;AACN,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { apiProjectionPolicyHistoryReader } from \"./principalPolicyHistoryReader\";\nimport { isPrincipalRecoveryOutage } from \"./principalRecoveryOutage\";\nimport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"./runtimePolicyRecovery\";\n\nasync function recoverWithOutageFallback(\n options: ProjectionPolicyHistoryRecoveryOptions,\n) {\n try {\n return await recoverProjectionPolicyHistory(options);\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (options.offline || !isPrincipalRecoveryOutage(error)) throw error;\n return recoverProjectionPolicyHistory({ ...options, offline: true });\n }\n}\n\nexport function createRuntimeProjectionPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n const lease = readPrincipalHistoryProtection(runtime);\n const historyReader = apiProjectionPolicyHistoryReader(runtime.apiClient);\n if (!lease || !historyReader) return undefined;\n return (input) =>\n getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql).queueRecovery(\n input.organizationId,\n () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.projection.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 try {\n const policies = await recoverWithOutageFallback({\n ...input,\n historyReader,\n execSql: runtime.infra.execSql,\n protection,\n stillCurrent,\n offline: runtime.state?.online === false,\n resolveTrustedUserIdentity:\n runtime.resolveTrustedUserIdentity,\n });\n return { policies, stillCurrent };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
2
2
  import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
3
+ import { getOrCreatePrincipalPolicyCoordinator } from "../../data/principals/principalPolicyCoordinator.js";
3
4
  import { createPrincipalCurrentRecoveryBatch } from "../principals/principalCurrentRecoveryBatch.js";
4
- import { queuePrincipalRecovery } from "../principals/principalRecoveryQueue.js";
5
5
  /**
6
6
  * Serves only the acknowledged initial heads, each complete in one page. The
7
7
  * ordinary verifier still checks every signature, the directory binding and
@@ -91,7 +91,7 @@ async function primeInProvisioningScope(runtime, input) {
91
91
  ? identity
92
92
  : null;
93
93
  };
94
- await queuePrincipalRecovery(execSql, input.organizationId, () => lease(({ protection, stillCurrent }) => primeProvisionedPrincipalHistory({
94
+ await getOrCreatePrincipalPolicyCoordinator(execSql).queueRecovery(input.organizationId, () => lease(({ protection, stillCurrent }) => primeProvisionedPrincipalHistory({
95
95
  execSql,
96
96
  organizationId: input.organizationId,
97
97
  policies: input.policies,
@@ -1 +1 @@
1
- {"version":3,"file":"provisionedPrincipalHistory.js","sourceRoot":"","sources":["provisionedPrincipalHistory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAMvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAElG,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAyB9E;;;;GAIG;AACH,SAAS,sBAAsB,CAC7B,QAAsC;IAEtC,MAAM,OAAO,GAAG;QACd,QAAQ,CAAC,YAAY;QACrB,QAAQ,CAAC,UAAU;QACnB,QAAQ,CAAC,WAAW;KACrB,CAAC;IACF,OAAO;QACL,KAAK,CAAC,CAAC,uBAAuB,CAAC,aAAa,EAAE,WAAW,EAAE,OAAO,GAAG,EAAE;YACrE,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CACzB,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CACnB,YAAY,CAAC,aAAa,KAAK,aAAa;gBAC5C,YAAY,CAAC,WAAW,KAAK,WAAW,CAC3C,CAAC;YACF,IACE,CAAC,MAAM;gBACP,OAAO,CAAC,MAAM,KAAK,SAAS;gBAC5B,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sB,CAAC,OAAO,EAAE,KAAK,CAAC,cAAc,EAAE,GAAG,EAAE,CAC/D,KAAK,CAAC,CAAC,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,EAAE,CACrC,gCAAgC,CAAC;QAC/B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,UAAU;QACV,0BAA0B;QAC1B,wDAAwD;QACxD,YAAY,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,YAAY,EAAE;KACrD,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport { createPrincipalCurrentRecoveryBatch } from \"../principals/principalCurrentRecoveryBatch\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport { queuePrincipalRecovery } from \"../principals/principalRecoveryQueue\";\n\n/** The version-1 policies a provisioning request signed and its response acknowledged. */\ninterface ProvisionedPrincipalPolicies {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}\n\n/**\n * Records verified recovery progress for an organization's founding policy\n * heads, so the device's first scoped recovery of them needs no history read.\n * It is bound to the provisioning scope: the database the bootstrap committed\n * to and the identity that signed it. Failure leaves the online path.\n */\nexport type ProvisionedPrincipalHistoryPrimer = (input: {\n /** The database client the provisioning bootstrap committed to. */\n readonly database: ExecSqlClientLike;\n /** Whether the identity that provisioned is still the active one. */\n readonly isCurrent: () => boolean;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly userId: string;\n}) => Promise<void>;\n\n/**\n * Serves only the acknowledged initial heads, each complete in one page. The\n * ordinary verifier still checks every signature, the directory binding and\n * strict Admins rules before any progress is saved.\n */\nfunction provisionedPolicyPages(\n policies: ProvisionedPrincipalPolicies,\n): PrincipalPolicyPageReader {\n const bundles = [\n policies.organization,\n policies.adminGroup,\n policies.memberGroup,\n ];\n return {\n async *getPrincipalPolicyPages(principalType, principalId, options = {}) {\n const bundle = bundles.find(\n ({ currentState }) =>\n currentState.principalType === principalType &&\n currentState.principalId === principalId,\n );\n if (\n !bundle ||\n options.resume !== undefined ||\n (options.afterVersion ?? 0) !== 0 ||\n (options.stateHash !== undefined &&\n options.stateHash !== bundle.currentState.stateHash)\n )\n throw new Error(\n \"Provisioned principal history holds only the acknowledged initial heads\",\n );\n yield {\n ok: true,\n data: {\n ...structuredClone(bundle),\n historyPage: { afterVersion: 0, nextAfterVersion: null },\n },\n };\n },\n };\n}\n\nasync function primeProvisionedPrincipalHistory(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const { recover } = createPrincipalCurrentRecoveryBatch();\n const options = {\n historyReader: provisionedPolicyPages(input.policies),\n execSql: input.execSql,\n offline: false,\n organizationId: input.organizationId,\n protection: input.protection,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n };\n // Scoped recovery of each group also completes the directory and strict\n // Admins stages; Members reuses them through the shared batch.\n for (const group of [input.policies.adminGroup, input.policies.memberGroup])\n await recover({\n ...options,\n reference: principalPolicyReferenceFromBundle(group),\n });\n}\n\n/** The runtime seams priming reads; none of them writes durable state. */\ninterface ProvisionedPrincipalHistoryRuntime {\n readonly bindLease: () => PrincipalHistoryProtectionLease | undefined;\n /** The runtime executor, only while `database` is its ready database. */\n readonly execSqlFor: (database: ExecSqlClientLike) => ExecSql | null;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n /** Read-only: the identity the trust store already pins for a user. */\n readonly loadPinnedIdentity: (\n execSql: ExecSql,\n userId: string,\n ) => Promise<TrustedUserIdentity | null>;\n readonly signingFingerprint: () => string | null;\n}\n\n/**\n * Binds priming to the exact provisioning scope, captured before any await:\n * the bootstrap's database and runtime executor, the identity whose key signed\n * the founding states, and a protection lease for that identity. Every later\n * step, and every progress write inside its transaction, rechecks that scope,\n * so a switched identity or database aborts priming without a durable write.\n * Priming never writes a trust pin; it only reads the founder's existing one.\n */\nexport function createProvisionedPrincipalHistoryPrimer(\n runtime: ProvisionedPrincipalHistoryRuntime,\n): ProvisionedPrincipalHistoryPrimer {\n return async (input) => {\n try {\n await primeInProvisioningScope(runtime, input);\n } catch (error) {\n runtime.logError(\n \"Provisioned principal history was not primed; recovery reads it online\",\n error,\n );\n }\n };\n}\n\nasync function primeInProvisioningScope(\n runtime: ProvisionedPrincipalHistoryRuntime,\n input: Parameters<ProvisionedPrincipalHistoryPrimer>[0],\n): Promise<void> {\n // Everything below is captured synchronously, before the first await.\n const founderFingerprint =\n input.policies.organization.currentState.signerUserKeyFingerprint;\n const execSql = runtime.execSqlFor(input.database);\n const scopeCurrent = () =>\n execSql !== null &&\n input.isCurrent() &&\n runtime.execSqlFor(input.database) === execSql &&\n runtime.signingFingerprint() === founderFingerprint;\n const lease = scopeCurrent() ? runtime.bindLease() : undefined;\n if (!execSql || !lease) return;\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = async (\n signerUserId,\n ) => {\n if (signerUserId !== input.userId) return null;\n assertProjectionVerificationCurrent(scopeCurrent);\n const identity = await runtime.loadPinnedIdentity(execSql, input.userId);\n assertProjectionVerificationCurrent(scopeCurrent);\n return identity?.signingKeyFingerprint === founderFingerprint\n ? identity\n : null;\n };\n await queuePrincipalRecovery(execSql, input.organizationId, () =>\n lease(({ protection, stillCurrent }) =>\n primeProvisionedPrincipalHistory({\n execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n protection,\n resolveTrustedUserIdentity,\n // Progress writes check this inside their transactions.\n stillCurrent: () => stillCurrent() && scopeCurrent(),\n }),\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"provisionedPrincipalHistory.js","sourceRoot":"","sources":["provisionedPrincipalHistory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAMzG,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AA0BlG;;;;GAIG;AACH,SAAS,sBAAsB,CAC7B,QAAsC;IAEtC,MAAM,OAAO,GAAG;QACd,QAAQ,CAAC,YAAY;QACrB,QAAQ,CAAC,UAAU;QACnB,QAAQ,CAAC,WAAW;KACrB,CAAC;IACF,OAAO;QACL,KAAK,CAAC,CAAC,uBAAuB,CAAC,aAAa,EAAE,WAAW,EAAE,OAAO,GAAG,EAAE;YACrE,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CACzB,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CACnB,YAAY,CAAC,aAAa,KAAK,aAAa;gBAC5C,YAAY,CAAC,WAAW,KAAK,WAAW,CAC3C,CAAC;YACF,IACE,CAAC,MAAM;gBACP,OAAO,CAAC,MAAM,KAAK,SAAS;gBAC5B,CAAC,OAAO,CAAC,YAAY,IAAI,CAAC,CAAC,KAAK,CAAC;gBACjC,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS;oBAC9B,OAAO,CAAC,SAAS,KAAK,MAAM,CAAC,YAAY,CAAC,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,CAAC;QAC/B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,UAAU;QACV,0BAA0B;QAC1B,wDAAwD;QACxD,YAAY,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,YAAY,EAAE;KACrD,CAAC,CACH,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport { createPrincipalCurrentRecoveryBatch } from \"../principals/principalCurrentRecoveryBatch\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\n\n/** The version-1 policies a provisioning request signed and its response acknowledged. */\ninterface ProvisionedPrincipalPolicies {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}\n\n/**\n * Records verified recovery progress for an organization's founding policy\n * heads, so the device's first scoped recovery of them needs no history read.\n * It is bound to the provisioning scope: the database the bootstrap committed\n * to and the identity that signed it. Failure leaves the online path.\n */\nexport type ProvisionedPrincipalHistoryPrimer = (input: {\n /** The database client the provisioning bootstrap committed to. */\n readonly database: ExecSqlClientLike;\n /** Whether the identity that provisioned is still the active one. */\n readonly isCurrent: () => boolean;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly userId: string;\n}) => Promise<void>;\n\n/**\n * Serves only the acknowledged initial heads, each complete in one page. The\n * ordinary verifier still checks every signature, the directory binding and\n * strict Admins rules before any progress is saved.\n */\nfunction provisionedPolicyPages(\n policies: ProvisionedPrincipalPolicies,\n): PrincipalPolicyPageReader {\n const bundles = [\n policies.organization,\n policies.adminGroup,\n policies.memberGroup,\n ];\n return {\n async *getPrincipalPolicyPages(principalType, principalId, options = {}) {\n const bundle = bundles.find(\n ({ currentState }) =>\n currentState.principalType === principalType &&\n currentState.principalId === principalId,\n );\n if (\n !bundle ||\n options.resume !== undefined ||\n (options.afterVersion ?? 0) !== 0 ||\n (options.stateHash !== undefined &&\n options.stateHash !== bundle.currentState.stateHash)\n )\n throw new Error(\n \"Provisioned principal history holds only the acknowledged initial heads\",\n );\n yield {\n ok: true,\n data: {\n ...structuredClone(bundle),\n historyPage: { afterVersion: 0, nextAfterVersion: null },\n },\n };\n },\n };\n}\n\nasync function primeProvisionedPrincipalHistory(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const { recover } = createPrincipalCurrentRecoveryBatch();\n const options = {\n historyReader: provisionedPolicyPages(input.policies),\n execSql: input.execSql,\n offline: false,\n organizationId: input.organizationId,\n protection: input.protection,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n };\n // Scoped recovery of each group also completes the directory and strict\n // Admins stages; Members reuses them through the shared batch.\n for (const group of [input.policies.adminGroup, input.policies.memberGroup])\n await recover({\n ...options,\n reference: principalPolicyReferenceFromBundle(group),\n });\n}\n\n/** The runtime seams priming reads; none of them writes durable state. */\ninterface ProvisionedPrincipalHistoryRuntime {\n readonly bindLease: () => PrincipalHistoryProtectionLease | undefined;\n /** The runtime executor, only while `database` is its ready database. */\n readonly execSqlFor: (database: ExecSqlClientLike) => ExecSql | null;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n /** Read-only: the identity the trust store already pins for a user. */\n readonly loadPinnedIdentity: (\n execSql: ExecSql,\n userId: string,\n ) => Promise<TrustedUserIdentity | null>;\n readonly signingFingerprint: () => string | null;\n}\n\n/**\n * Binds priming to the exact provisioning scope, captured before any await:\n * the bootstrap's database and runtime executor, the identity whose key signed\n * the founding states, and a protection lease for that identity. Every later\n * step, and every progress write inside its transaction, rechecks that scope,\n * so a switched identity or database aborts priming without a durable write.\n * Priming never writes a trust pin; it only reads the founder's existing one.\n */\nexport function createProvisionedPrincipalHistoryPrimer(\n runtime: ProvisionedPrincipalHistoryRuntime,\n): ProvisionedPrincipalHistoryPrimer {\n return async (input) => {\n try {\n await primeInProvisioningScope(runtime, input);\n } catch (error) {\n runtime.logError(\n \"Provisioned principal history was not primed; recovery reads it online\",\n error,\n );\n }\n };\n}\n\nasync function primeInProvisioningScope(\n runtime: ProvisionedPrincipalHistoryRuntime,\n input: Parameters<ProvisionedPrincipalHistoryPrimer>[0],\n): Promise<void> {\n // Everything below is captured synchronously, before the first await.\n const founderFingerprint =\n input.policies.organization.currentState.signerUserKeyFingerprint;\n const execSql = runtime.execSqlFor(input.database);\n const scopeCurrent = () =>\n execSql !== null &&\n input.isCurrent() &&\n runtime.execSqlFor(input.database) === execSql &&\n runtime.signingFingerprint() === founderFingerprint;\n const lease = scopeCurrent() ? runtime.bindLease() : undefined;\n if (!execSql || !lease) return;\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = async (\n signerUserId,\n ) => {\n if (signerUserId !== input.userId) return null;\n assertProjectionVerificationCurrent(scopeCurrent);\n const identity = await runtime.loadPinnedIdentity(execSql, input.userId);\n assertProjectionVerificationCurrent(scopeCurrent);\n return identity?.signingKeyFingerprint === founderFingerprint\n ? identity\n : null;\n };\n await getOrCreatePrincipalPolicyCoordinator(execSql).queueRecovery(\n input.organizationId,\n () =>\n lease(({ protection, stillCurrent }) =>\n primeProvisionedPrincipalHistory({\n execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n protection,\n resolveTrustedUserIdentity,\n // Progress writes check this inside their transactions.\n stillCurrent: () => stillCurrent() && scopeCurrent(),\n }),\n ),\n );\n}\n"]}
@@ -1,18 +0,0 @@
1
- // Per database and organization, the number of applied organization hints in
2
- // this process. Operation-scoped principal recovery records the value before
3
- // producing a result and recovers again once it changes. Hints are lossy, so
4
- // this only shortens reuse; each operation still discovers the current head.
5
- const epochs = new WeakMap();
6
- export function principalRecoveryEpoch(execSql, organizationId) {
7
- return epochs.get(execSql)?.get(organizationId) ?? 0;
8
- }
9
- /** Evict recovered directory and Admins views for this organization. */
10
- export function invalidatePrincipalRecovery(execSql, organizationId) {
11
- let scoped = epochs.get(execSql);
12
- if (!scoped) {
13
- scoped = new Map();
14
- epochs.set(execSql, scoped);
15
- }
16
- scoped.set(organizationId, (scoped.get(organizationId) ?? 0) + 1);
17
- }
18
- //# sourceMappingURL=principalRecoveryEpoch.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalRecoveryEpoch.js","sourceRoot":"","sources":["principalRecoveryEpoch.ts"],"names":[],"mappings":"AAEA,6EAA6E;AAC7E,6EAA6E;AAC7E,6EAA6E;AAC7E,6EAA6E;AAC7E,MAAM,MAAM,GAAG,IAAI,OAAO,EAAgC,CAAC;AAE3D,MAAM,UAAU,sBAAsB,CACpC,OAAgB,EAChB,cAAsB;IAEtB,OAAO,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,2BAA2B,CACzC,OAAgB,EAChB,cAAsB;IAEtB,IAAI,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACjC,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC;QACnB,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,MAAM,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import type { ExecSql } from \"../sqlite/sqlSchema\";\n\n// Per database and organization, the number of applied organization hints in\n// this process. Operation-scoped principal recovery records the value before\n// producing a result and recovers again once it changes. Hints are lossy, so\n// this only shortens reuse; each operation still discovers the current head.\nconst epochs = new WeakMap<ExecSql, Map<string, number>>();\n\nexport function principalRecoveryEpoch(\n execSql: ExecSql,\n organizationId: string,\n): number {\n return epochs.get(execSql)?.get(organizationId) ?? 0;\n}\n\n/** Evict recovered directory and Admins views for this organization. */\nexport function invalidatePrincipalRecovery(\n execSql: ExecSql,\n organizationId: string,\n): void {\n let scoped = epochs.get(execSql);\n if (!scoped) {\n scoped = new Map();\n epochs.set(execSql, scoped);\n }\n scoped.set(organizationId, (scoped.get(organizationId) ?? 0) + 1);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"acknowledgedPrincipalPredecessor.js","sourceRoot":"","sources":["acknowledgedPrincipalPredecessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,0BAA0B,GAE3B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,iCAAiC,EAAE,MAAM,uDAAuD,CAAC;AAC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,CAC3D,CAAC;QACF,mCAAmC,CAAC,OAAO,CAAC,CAAC;QAC7C,IACE,CAAC,6BAA6B,CAC5B,QAAQ,CAAC,QAAQ,CAAC,KAAK,EACvB,OAAO,CAAC,YAAY,CACrB;YAED,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;QACJ,OAAO,eAAe,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAC3D,OAA6C,EAC7C,KAA8C;IAE9C,MAAM,QAAQ,GAAG,MAAM,kCAAkC,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC1E,IACE,CAAC,6BAA6B,CAC5B,QAAQ,CAAC,QAAQ,CAAC,KAAK,EACvB,OAAO,CAAC,YAAY,CACrB;QAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,iEAAiE,CAClE,CAAC;IACJ,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n loadPrincipalHistoryPrefix,\n type PrincipalHistoryPrefix,\n} from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../principals/principalHistoryRecoveryTypes\";\nimport { principalHistoryVerificationContext } from \"../principals/principalHistoryRecoveryVerification\";\n\n/** Sealed predecessor evidence, owned by a mutation before its request is sent. */\nexport type AcknowledgedPrincipalPredecessor = Readonly<PrincipalHistoryPrefix>;\n\n/** Authenticate the entire prefix, including its scope and current artifacts. */\nexport async function restoreAcknowledgedPrincipalPrefix(\n options: RecoverPrincipalPolicyHistoryOptions,\n saved: AcknowledgedPrincipalPredecessor | null,\n) {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n if (\n !saved ||\n saved.scopeId !== scopeId ||\n saved.organizationId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledgement requires its authenticated predecessor prefix\",\n );\n const restored = await restorePrincipalPolicyHistoryVerifier(\n {\n principalId: options.expectedHead.principalId,\n principalType: options.expectedHead.principalType,\n },\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n if (!restored.ok) throw restored.error;\n const artifacts = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (!artifacts)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Acknowledged predecessor artifacts are malformed\",\n );\n const history = restored.value.finish(\n principalPolicyReferenceFromBundle(artifacts),\n );\n if (!history.ok) throw history.error;\n const previous = await verifyPrincipalPolicyCurrent({\n current: artifacts,\n history: history.value,\n });\n if (!previous.ok) throw previous.error;\n return {\n scopeId,\n saved,\n artifacts,\n verifier: restored.value,\n previous: previous.value,\n history: history.value,\n predecessorIndexRootHash: history.value.indexRootHash,\n };\n}\n\n/** Capture exact predecessor evidence while authoring, before HTTP can commit. */\nexport async function captureAcknowledgedPrincipalPredecessor(\n input: RecoverPrincipalPolicyHistoryOptions,\n): Promise<AcknowledgedPrincipalPredecessor> {\n const protection = ownPrincipalHistoryProtection(input.protection);\n const options = {\n ...input,\n expectedHead: structuredClone(input.expectedHead),\n protection: {\n ...protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n try {\n assertProjectionVerificationCurrent(current);\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n const restored = await restoreAcknowledgedPrincipalPrefix(\n options,\n await loadPrincipalHistoryPrefix(options.execSql, scopeId),\n );\n assertProjectionVerificationCurrent(current);\n if (\n !principalHeadMatchesReference(\n restored.previous.state,\n options.expectedHead,\n )\n )\n throw new Error(\n \"Principal policy changed before submission; retry the mutation\",\n );\n return structuredClone(restored.saved);\n } finally {\n protection.localKey.fill(0);\n }\n}\n\nexport async function restoreAcknowledgedPrincipalPredecessor(\n options: RecoverPrincipalPolicyHistoryOptions,\n saved: AcknowledgedPrincipalPredecessor | null,\n) {\n const restored = await restoreAcknowledgedPrincipalPrefix(options, saved);\n if (\n !principalHeadMatchesReference(\n restored.previous.state,\n options.expectedHead,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledgement predecessor does not match the authored request\",\n );\n return restored;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"initialPrincipalCurrentPublication.js","sourceRoot":"","sources":["initialPrincipalCurrentPublication.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,+BAA+B,EAAE,MAAM,wDAAwD,CAAC;AACzG,OAAO,EAAE,sCAAsC,EAAE,MAAM,kCAAkC,CAAC;AAE1F,OAAO,EACL,sCAAsC,EACtC,mCAA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,EAAE;YACV,GAAG,KAAK,CAAC,UAAU;YACnB,OAAO,EAAE,mCAAmC,CAAC,KAAK,CAAC;SACpD;KACF,CAAC;IACF,MAAM,OAAO,GAAG,MAAM,+BAA+B,CAAC;QACpD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,OAAO,CAAC,UAAU;KAC/B,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,+BAA+B,CAClD,OAAO,EACP,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,QAAQ,CACT,CAAC;IACF,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO;QACL,GAAG,MAAM;QACT,MAAM,EAAE,MAAM,CAAC,KAAK;QACpB,gBAAgB,EAAE,IAAI;QACtB,wBAAwB,EAAE,IAAI;QAC9B,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO,EAAE,CAAC,KAAK,CAAC;YAChB,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { AcknowledgedPrincipalCurrentPublication } from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../principals/policyVerification\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../principals/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../principals/principalHistoryRecoveryVerification\";\nimport type { AcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport { sealPrincipalCurrentPublication } from \"./principalCurrentPublicationSeal\";\nimport { assertPrincipalPolicyReceiptArtifacts } from \"./principalPolicyReceiptArtifacts\";\n\n/** Verify a newly authored group from genesis before its atomic directory publication. */\nexport async function prepareInitialGroupCurrentPublication(\n input: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const expectedHead = await groupPolicyMutationHead(request);\n if (\n predecessor !== null ||\n request.state.principalType !== \"group\" ||\n request.state.version !== 1 ||\n request.state.prevStateHash !== null ||\n !principalHeadMatchesReference(expectedHead, input.expectedHead)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Initial group publication must begin at its exact genesis\",\n );\n assertPrincipalPolicyReceiptArtifacts({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Initial group signer could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const verifier = createPrincipalPolicyHistoryVerifier({\n principalType: \"group\",\n principalId: expectedHead.principalId,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(input, [entry]);\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const history = verifier.finish(expectedHead);\n if (!history.ok) throw history.error;\n const policy = await verifyPrincipalPolicyCurrent({\n current: response,\n history: history.value,\n });\n if (!policy.ok) throw policy.error;\n const options = {\n ...input,\n protection: {\n ...input.protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: expectedHead,\n protection: options.protection,\n });\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n ...sealed,\n policy: policy.value,\n predecessorStage: null,\n predecessorIndexRootHash: null,\n previousPrefixProgress: null,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: input.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n"]}