@tearleads/client-sdk 0.1.223 → 0.1.224

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 (65) hide show
  1. package/data/documents/shared/containerKek/containerKekPathVerification.js +2 -0
  2. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -1
  3. package/data/documents/shared/projection/index.js +2 -0
  4. package/data/documents/shared/projection/index.js.map +1 -1
  5. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +3 -0
  6. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +2 -1
  7. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  8. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +2 -1
  9. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +1 -0
  10. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  11. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +3 -2
  12. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +2 -0
  13. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  14. package/data/keyingProjectionVerification/document/documentProjectionVerification.d.ts +2 -1
  15. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +2 -0
  16. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +3 -2
  18. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  19. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.d.ts +2 -1
  20. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js +7 -3
  21. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js.map +1 -1
  22. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -2
  23. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  24. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +17 -6
  25. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  26. package/data/keyingProjectionVerification/types.d.ts +20 -2
  27. package/data/keyingProjectionVerification/types.js.map +1 -1
  28. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +2 -0
  29. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  30. package/package.json +1 -1
  31. package/workflows/container-contents/container-state/create/createAdoption.js +2 -0
  32. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  33. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +2 -0
  34. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  35. package/workflows/container-contents/container-state/share/groupGrantVerification.js +2 -0
  36. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  37. package/workflows/container-contents/container-state/share/index.js +2 -0
  38. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  39. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +2 -0
  40. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  41. package/workflows/containers/child/create/index.d.ts +1 -1
  42. package/workflows/containers/child/create/index.js +2 -0
  43. package/workflows/containers/child/create/index.js.map +1 -1
  44. package/workflows/containers/child/move/moveWraps.js +3 -0
  45. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  46. package/workflows/containers/child/rekey/carriedDescendantRekeys.js +2 -0
  47. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  48. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js +2 -0
  49. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  50. package/workflows/containers/child/share/sharePlanCore.js +2 -0
  51. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  52. package/workflows/containers/rematerialization/principalContainerRematerialization.js +2 -0
  53. package/workflows/containers/rematerialization/principalContainerRematerialization.js.map +1 -1
  54. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js +2 -0
  55. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  56. package/workflows/documents/create/index.js +2 -0
  57. package/workflows/documents/create/index.js.map +1 -1
  58. package/workflows/documents/linkSet/linkSetAuthority.js +2 -0
  59. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  60. package/workflows/documents/purge/index.js +6 -0
  61. package/workflows/documents/purge/index.js.map +1 -1
  62. package/workflows/documents/sync/syncSubmittedResult.js +2 -0
  63. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  64. package/workflows/documents/syncFailures/syncRepairAccess.js +2 -0
  65. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyBundleRepository.js","sourceRoot":"","sources":["principalPolicyBundleRepository.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAEL,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,+CAA+C,EAI/C,2DAA2D,GAC5D,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,wCAAwC,EACxC,2BAA2B,EAC3B,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,uCAAuC,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,MAAM,+CAA+C,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrE,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE;YAClC,GAAG,qBAAqB;YACxB,GAAG,sBAAsB;SAC1B,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,YAAY,CACrB,CAAC,EAAE,EAAE,EAAE,CACL,2DAA2D,CACzD,EAAE,EACF,KAAK,EACL,IAAI,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CACzB,EACH,KAAK,CAAC,YAAY,CACnB,CAAC;IACJ,CAAC;IAED,8EAA8E;IACtE,KAAK,CAAC,YAAY,CACxB,IAAyD,EACzD,YAAyC;QAEzC,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE;gBACnD,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { asc, desc } from \"drizzle-orm\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalGrantRetirements } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type PrincipalKeyEnvelopeCandidate,\n selectPrincipalKeyEnvelopeCandidates,\n} from \"../principalKeys/principalKeyEnvelopeCandidates\";\nimport { selectHeldPrincipalState } from \"./heldPrincipalState\";\nimport {\n assertLocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyBundle,\n type LocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyStore,\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction,\n} from \"./locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n parseSelectedPrincipalPolicyBundle,\n principalPolicyBundleSelection,\n retainPrincipalPolicyBundleInTransaction,\n wherePrincipalPolicyCurrent,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n assertReferenceShape,\n selectReferencedPrincipalPolicyBundle,\n} from \"./principalPolicyReferencePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\nimport {\n assertVerifiedPrincipalPolicyBundles,\n persistVerifiedPrincipalPolicyBundlesInTransaction,\n type VerifiedPrincipalPolicyBundleEntry,\n} from \"./verifiedPrincipalPolicyBundlePersistence\";\n\n/**\n * The cached principal policy bundles, current heads and retained epochs, and\n * the member key envelopes they carry, bound to one executor and clock. Each\n * method ensures its tables; each writer runs its own immediate transaction\n * and silently skips a commit its `stillCurrent` refuses. Work inside a\n * caller's transaction takes the locked handle per call through the\n * `*InTransaction` functions instead.\n */\nexport class PrincipalPolicyBundleRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensurePrincipalPolicyTables(): Promise<void> {\n await ensureSqlTables(this.execSql, principalPolicyTables);\n }\n\n async loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row ? parseSelectedPrincipalPolicyBundle(row) : null;\n }\n\n /** Current heads first, then retained bundles. */\n async loadAllPrincipalPolicyBundles(): Promise<\n PrincipalPolicyBundleResponse[]\n > {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n const bundles: PrincipalPolicyBundleResponse[] = [];\n for (const row of rows) {\n const bundle = parseSelectedPrincipalPolicyBundle(row);\n if (bundle) bundles.push(bundle);\n }\n return bundles;\n }\n\n async loadPrincipalPolicyStateHash(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<string | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row?.stateHash ?? null;\n }\n\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n async loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);\n }\n\n /**\n * A signed state this device stored for exactly `head`: history evidence it\n * verified or acknowledged, or a cached policy bundle chain. It is untrusted;\n * the caller verifies it as it would a served copy, and a miss only means the\n * server sends one.\n */\n async loadHeldPrincipalState(\n head: ReferencedPrincipalHead,\n ): Promise<PrincipalStateResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHeldPrincipalState(db, head);\n }\n\n /**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\n async loadPrincipalKeyEnvelopeCandidates(\n fingerprints: readonly string[],\n ): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);\n }\n\n async savePrincipalPolicyBundle(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n ): Promise<void> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n this.now().toISOString(),\n organizationId,\n ),\n options?.stillCurrent,\n );\n }\n\n /**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\n async persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<void> {\n await assertVerifiedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /**\n * Retains a just-verified epoch without promoting it to the mutable head.\n * `updatedAt` stays explicit: callers stamp a whole retention walk at once.\n */\n async retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n }): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await this.ensurePrincipalPolicyTables();\n await this.runImmediate(\n (tx) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n ),\n input.stillCurrent,\n );\n }\n\n /** Atomically pins and caches exact full policy bundles acknowledged by the API. */\n persistLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n }\n\n persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n return this.persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n }\n\n /**\n * Seed a provisioning acknowledgement without making genesis current again.\n * The cache writer still checks ownership, equal-version forks and retained\n * same-hash bundle integrity, and preserves any newer cached policy head.\n */\n seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n }\n\n retainLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles & {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n },\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n }\n\n private async storeLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyStore & {\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /** Guarded when `stillCurrent` is given; a refused commit is not an error. */\n private async runImmediate(\n body: (tx: ClientSQLiteTransactionScope) => Promise<void>,\n stillCurrent: (() => boolean) | undefined,\n ): Promise<void> {\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (stillCurrent) {\n await runtime.guardedTransaction(body, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(body, { behavior: \"immediate\" });\n }\n}\n"]}
1
+ {"version":3,"file":"principalPolicyBundleRepository.js","sourceRoot":"","sources":["principalPolicyBundleRepository.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAEL,oCAAoC,GACrC,MAAM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rincipalHead,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { asc, desc } from \"drizzle-orm\";\nimport type { OpenPrincipalPolicyBundleReader } from \"../../keyingProjectionVerification/types\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalGrantRetirements } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type PrincipalKeyEnvelopeCandidate,\n selectPrincipalKeyEnvelopeCandidates,\n} from \"../principalKeys/principalKeyEnvelopeCandidates\";\nimport { selectHeldPrincipalState } from \"./heldPrincipalState\";\nimport {\n assertLocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyBundle,\n type LocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyStore,\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction,\n} from \"./locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n parseSelectedPrincipalPolicyBundle,\n principalPolicyBundleSelection,\n retainPrincipalPolicyBundleInTransaction,\n wherePrincipalPolicyCurrent,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n assertReferenceShape,\n selectReferencedPrincipalPolicyBundle,\n} from \"./principalPolicyReferencePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\nimport {\n assertVerifiedPrincipalPolicyBundles,\n persistVerifiedPrincipalPolicyBundlesInTransaction,\n type VerifiedPrincipalPolicyBundleEntry,\n} from \"./verifiedPrincipalPolicyBundlePersistence\";\n\n/**\n * The cached principal policy bundles, current heads and retained epochs, and\n * the member key envelopes they carry, bound to one executor and clock. Each\n * method ensures its tables; each writer runs its own immediate transaction\n * and silently skips a commit its `stillCurrent` refuses. Work inside a\n * caller's transaction takes the locked handle per call through the\n * `*InTransaction` functions instead.\n */\nexport class PrincipalPolicyBundleRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensurePrincipalPolicyTables(): Promise<void> {\n await ensureSqlTables(this.execSql, principalPolicyTables);\n }\n\n async loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row ? parseSelectedPrincipalPolicyBundle(row) : null;\n }\n\n /** Current heads first, then retained bundles. */\n async loadAllPrincipalPolicyBundles(): Promise<\n PrincipalPolicyBundleResponse[]\n > {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n const bundles: PrincipalPolicyBundleResponse[] = [];\n for (const row of rows) {\n const bundle = parseSelectedPrincipalPolicyBundle(row);\n if (bundle) bundles.push(bundle);\n }\n return bundles;\n }\n\n async loadPrincipalPolicyStateHash(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<string | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row?.stateHash ?? null;\n }\n\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n async loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);\n }\n\n /**\n * A signed state this device stored for exactly `head`: history evidence it\n * verified or acknowledged, or a cached policy bundle chain. It is untrusted;\n * the caller verifies it as it would a served copy, and a miss only means the\n * server sends one.\n */\n async loadHeldPrincipalState(\n head: ReferencedPrincipalHead,\n ): Promise<PrincipalStateResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHeldPrincipalState(db, head);\n }\n\n /**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\n async loadPrincipalKeyEnvelopeCandidates(\n fingerprints: readonly string[],\n ): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);\n }\n\n async savePrincipalPolicyBundle(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n ): Promise<void> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n this.now().toISOString(),\n organizationId,\n ),\n options?.stillCurrent,\n );\n }\n\n /**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\n async persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<void> {\n await assertVerifiedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /**\n * Retains a just-verified epoch without promoting it to the mutable head.\n * `updatedAt` stays explicit: callers stamp a whole retention walk at once.\n */\n async retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n }): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await this.ensurePrincipalPolicyTables();\n await this.runImmediate(\n (tx) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n ),\n input.stillCurrent,\n );\n }\n\n /** Atomically pins and caches exact full policy bundles acknowledged by the API. */\n persistLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n }\n\n persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n return this.persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n }\n\n /**\n * Seed a provisioning acknowledgement without making genesis current again.\n * The cache writer still checks ownership, equal-version forks and retained\n * same-hash bundle integrity, and preserves any newer cached policy head.\n */\n seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n }\n\n retainLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles & {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n },\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n }\n\n private async storeLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyStore & {\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /** Guarded when `stillCurrent` is given; a refused commit is not an error. */\n private async runImmediate(\n body: (tx: ClientSQLiteTransactionScope) => Promise<void>,\n stillCurrent: (() => boolean) | undefined,\n ): Promise<void> {\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (stillCurrent) {\n await runtime.guardedTransaction(body, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(body, { behavior: \"immediate\" });\n }\n}\n\n/** The bundle store Keying Verification reads, opened on one executor. */\nexport const openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader =\n (execSql) => new PrincipalPolicyBundleRepository(execSql);\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.223",
3
+ "version": "0.1.224",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,6 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../../internal/crypto/index.js";
2
2
  import { verifiedContainerCreateManifest, verifyContainerDestinationProjection, } from "../../../../data/keyingProjectionVerification/index.js";
3
3
  import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, } from "../../../../data/keyingProjectionVerification/error.js";
4
+ import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
4
5
  import { errorMessage } from "../../../../data/shared/errorMessage.js";
5
6
  import { settleContainerCreateIntent } from "./createIntentSettlement.js";
6
7
  const LABEL = "Container create conflict";
@@ -26,6 +27,7 @@ async function verifyAdoptableProjection(input) {
26
27
  }
27
28
  const { path, verifiedByHash } = await verifyContainerDestinationProjection({
28
29
  execSql: input.state.runtime.infra.execSql,
30
+ openPrincipalPolicyBundleReader,
29
31
  projection,
30
32
  resolveUserKey: input.state.resolveProjectionUserKey,
31
33
  warmReferencedPrincipalPolicies: input.state.runtime.principalPolicies.createWarmer(),
@@ -1 +1 @@
1
- {"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,yBAAyB,EACzB,yCAAyC,GAC1C,MAAM,qDAAq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nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n} from \"../../../../data/keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type {\n AdoptedContainerPlacement,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n} from \"../types\";\nimport { settleContainerCreateIntent } from \"./createIntentSettlement\";\n\nconst LABEL = \"Container create conflict\";\n\n/** The recorded error that parks an intent whose listed create is foreign. */\nexport const CONTAINER_CREATE_ADOPTION_REFUSED =\n \"Container create adoption was refused\";\n\n/**\n * The listed create's signed identity is not this device's pending create: its\n * signed create names another signer, another organization, or a root. An honest server never lists that under the\n * id this device minted, and no later read can change those signed facts, so\n * the intent parks instead of re-verifying.\n */\nclass ForeignContainerCreateError extends KeyingVerificationError {}\n\nfunction foreignCreate(\n code: KeyingVerificationCode,\n message: string,\n): ForeignContainerCreateError {\n return new ForeignContainerCreateError(code, `${LABEL} ${message}`);\n}\n\nasync function verifyAdoptableProjection(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly projection: ContainerWriterProjectionResponse;\n readonly sessionUserId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { projection } = input;\n if (\n projection.containerId !== input.containerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n // The envelope is unsigned: a corrupt read is retried, not parked.\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection has the wrong identity`,\n );\n }\n const { path, verifiedByHash } = await verifyContainerDestinationProjection({\n execSql: input.state.runtime.infra.execSql,\n projection,\n resolveUserKey: input.state.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n });\n const head = path.at(-1);\n // One read naming another container says nothing signed about this id.\n if (!head || head.state.containerId !== input.containerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection names another container`,\n );\n }\n const create = verifiedContainerCreateManifest({\n head,\n label: LABEL,\n verifiedByHash,\n });\n if (create.event.event.signerUserId !== input.sessionUserId) {\n throw foreignCreate(\"signer_mismatch\", \"was signed by another user\");\n }\n if (create.state.organizationId !== input.expectedOrganizationId) {\n throw foreignCreate(\"object_mismatch\", \"belongs to another organization\");\n }\n const createdParentId = create.state.parentContainerId;\n const currentParentId = head.state.parentContainerId;\n if (createdParentId === null || currentParentId === null) {\n throw foreignCreate(\"object_mismatch\", \"is an organization root\");\n }\n return { createdParentId, currentParentId };\n}\n\n/**\n * A pending create whose container the listing already carries is adopted\n * only when the container's signed epoch-1 `container.create` is this user's,\n * in the intended organization (#2365 finding 26). Listing metadata is\n * unsigned: a create by another writer that collides on the pending id, or one\n * a dishonest server invents, must not become this device's container.\n * Documents apply the same rule (`workflows/documents/createAdoption.ts`).\n *\n * Returns where the create committed and where the verified head sits now.\n * The user may have moved the pending container since, which rewrites its\n * intent's parent; that is a move still owed, not a mismatch.\n */\nasync function assertContainerCreateAdoptable(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { runtime } = input.state;\n const sessionUserId = runtime.auth.userId;\n // Without a session user there is no signer to compare: not tampering.\n if (!sessionUserId) {\n throw new Error(`${LABEL} needs a signed-in session user`);\n }\n const projection = await runtime.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!projection) {\n throw new Error(`${LABEL} is unavailable to verify`);\n }\n try {\n return await verifyAdoptableProjection({\n ...input,\n projection,\n sessionUserId,\n });\n } catch (error) {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error)) {\n runtime.apiClient.evictContainerWriterProjection(input.containerId);\n }\n throw error;\n }\n}\n\nfunction verifyListedContainerCreate(input: {\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly parentState: ContainerState;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const adoption = {\n containerId: input.intent.containerId,\n expectedOrganizationId: input.parentState.container.organizationId,\n };\n return input.state.verifyCreateAdoption\n ? input.state.verifyCreateAdoption(adoption)\n : assertContainerCreateAdoptable({ ...adoption, state: input.state });\n}\n\n/** Settles a verified adoption against the row hydration installed. */\nasync function markContainerCreateIntentAdopted(input: {\n containerState: ContainerState;\n placement: AdoptedContainerPlacement;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<boolean> {\n const { containerState, placement, syncInput } = input;\n const remoteMetadataDocumentId = containerState.record.documentId;\n const remoteMetadataAccessStateHash = containerState.record.accessStateHash;\n\n if (!remoteMetadataDocumentId || !remoteMetadataAccessStateHash) {\n return false;\n }\n return settleContainerCreateIntent({\n createdParentContainerId: placement.createdParentId,\n desiredParentContainerId: syncInput.intent.parentContainerId,\n intent: syncInput.intent,\n isCurrent: syncInput.isCurrent,\n remoteContainerId: containerState.container.id,\n remoteMetadataAccessStateHash,\n remoteMetadataDocumentId,\n state: syncInput.state,\n supersededMovePreviousParentId: placement.currentParentId,\n });\n}\n\n/**\n * Records a failed adoption and leaves the lane's other intents to proceed. A\n * foreign create parks the intent: its signed facts never change, so later\n * passes neither re-read it nor report it again. Any other failure retries.\n */\nasync function recordAdoptionFailure(input: {\n readonly error: unknown;\n readonly organizationId: string;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"failed\"> {\n const { intent, isCurrent, state } = input.syncInput;\n if (!isCurrent()) return \"abandoned\";\n await reportKeyingVerificationErrorInCauseChain(\n input.error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n if (!isCurrent()) return \"abandoned\";\n const action =\n input.error instanceof ForeignContainerCreateError\n ? CONTAINER_CREATE_ADOPTION_REFUSED\n : \"Container create adoption verification failed\";\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: `${action}: ${errorMessage(input.error)}`,\n stillCurrent: isCurrent,\n },\n );\n return isCurrent() ? \"failed\" : \"abandoned\";\n}\n\n/**\n * Adopts a pending create the listing already carries, once its signed create\n * proves it is this device's. A parked refusal stays blocked without a read.\n */\nexport async function syncListedContainerCreate(input: {\n readonly containerState: ContainerState;\n readonly parentState: ContainerState;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"blocked\" | \"created\" | \"failed\"> {\n const { containerState, parentState, syncInput } = input;\n const { intent, isCurrent, state } = syncInput;\n if (intent.lastError?.startsWith(CONTAINER_CREATE_ADOPTION_REFUSED)) {\n return \"blocked\";\n }\n let placement: AdoptedContainerPlacement;\n try {\n placement = await verifyListedContainerCreate({\n intent,\n parentState,\n state,\n });\n } catch (error) {\n return recordAdoptionFailure({\n error,\n organizationId: parentState.container.organizationId,\n syncInput,\n });\n }\n const marked = await markContainerCreateIntentAdopted({\n containerState,\n placement,\n syncInput,\n });\n if (!marked) return isCurrent() ? \"blocked\" : \"abandoned\";\n // The folder now sits elsewhere; list it there rather than waiting for the\n // next poll to correct the local parent.\n if (placement.currentParentId !== intent.parentContainerId) {\n syncInput.requestRemoteReconciliation(placement.currentParentId);\n }\n return \"created\";\n}\n"]}
1
+ {"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,yBAAyB,EACzB,yCAAyC,GAC1C,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,+BAA+B,EAAE,MAA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Error,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n} from \"../../../../data/keyingProjectionVerification/error\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type {\n AdoptedContainerPlacement,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n} from \"../types\";\nimport { settleContainerCreateIntent } from \"./createIntentSettlement\";\n\nconst LABEL = \"Container create conflict\";\n\n/** The recorded error that parks an intent whose listed create is foreign. */\nexport const CONTAINER_CREATE_ADOPTION_REFUSED =\n \"Container create adoption was refused\";\n\n/**\n * The listed create's signed identity is not this device's pending create: its\n * signed create names another signer, another organization, or a root. An honest server never lists that under the\n * id this device minted, and no later read can change those signed facts, so\n * the intent parks instead of re-verifying.\n */\nclass ForeignContainerCreateError extends KeyingVerificationError {}\n\nfunction foreignCreate(\n code: KeyingVerificationCode,\n message: string,\n): ForeignContainerCreateError {\n return new ForeignContainerCreateError(code, `${LABEL} ${message}`);\n}\n\nasync function verifyAdoptableProjection(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly projection: ContainerWriterProjectionResponse;\n readonly sessionUserId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { projection } = input;\n if (\n projection.containerId !== input.containerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n // The envelope is unsigned: a corrupt read is retried, not parked.\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection has the wrong identity`,\n );\n }\n const { path, verifiedByHash } = await verifyContainerDestinationProjection({\n execSql: input.state.runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: input.state.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n });\n const head = path.at(-1);\n // One read naming another container says nothing signed about this id.\n if (!head || head.state.containerId !== input.containerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection names another container`,\n );\n }\n const create = verifiedContainerCreateManifest({\n head,\n label: LABEL,\n verifiedByHash,\n });\n if (create.event.event.signerUserId !== input.sessionUserId) {\n throw foreignCreate(\"signer_mismatch\", \"was signed by another user\");\n }\n if (create.state.organizationId !== input.expectedOrganizationId) {\n throw foreignCreate(\"object_mismatch\", \"belongs to another organization\");\n }\n const createdParentId = create.state.parentContainerId;\n const currentParentId = head.state.parentContainerId;\n if (createdParentId === null || currentParentId === null) {\n throw foreignCreate(\"object_mismatch\", \"is an organization root\");\n }\n return { createdParentId, currentParentId };\n}\n\n/**\n * A pending create whose container the listing already carries is adopted\n * only when the container's signed epoch-1 `container.create` is this user's,\n * in the intended organization (#2365 finding 26). Listing metadata is\n * unsigned: a create by another writer that collides on the pending id, or one\n * a dishonest server invents, must not become this device's container.\n * Documents apply the same rule (`workflows/documents/createAdoption.ts`).\n *\n * Returns where the create committed and where the verified head sits now.\n * The user may have moved the pending container since, which rewrites its\n * intent's parent; that is a move still owed, not a mismatch.\n */\nasync function assertContainerCreateAdoptable(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { runtime } = input.state;\n const sessionUserId = runtime.auth.userId;\n // Without a session user there is no signer to compare: not tampering.\n if (!sessionUserId) {\n throw new Error(`${LABEL} needs a signed-in session user`);\n }\n const projection = await runtime.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!projection) {\n throw new Error(`${LABEL} is unavailable to verify`);\n }\n try {\n return await verifyAdoptableProjection({\n ...input,\n projection,\n sessionUserId,\n });\n } catch (error) {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error)) {\n runtime.apiClient.evictContainerWriterProjection(input.containerId);\n }\n throw error;\n }\n}\n\nfunction verifyListedContainerCreate(input: {\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly parentState: ContainerState;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const adoption = {\n containerId: input.intent.containerId,\n expectedOrganizationId: input.parentState.container.organizationId,\n };\n return input.state.verifyCreateAdoption\n ? input.state.verifyCreateAdoption(adoption)\n : assertContainerCreateAdoptable({ ...adoption, state: input.state });\n}\n\n/** Settles a verified adoption against the row hydration installed. */\nasync function markContainerCreateIntentAdopted(input: {\n containerState: ContainerState;\n placement: AdoptedContainerPlacement;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<boolean> {\n const { containerState, placement, syncInput } = input;\n const remoteMetadataDocumentId = containerState.record.documentId;\n const remoteMetadataAccessStateHash = containerState.record.accessStateHash;\n\n if (!remoteMetadataDocumentId || !remoteMetadataAccessStateHash) {\n return false;\n }\n return settleContainerCreateIntent({\n createdParentContainerId: placement.createdParentId,\n desiredParentContainerId: syncInput.intent.parentContainerId,\n intent: syncInput.intent,\n isCurrent: syncInput.isCurrent,\n remoteContainerId: containerState.container.id,\n remoteMetadataAccessStateHash,\n remoteMetadataDocumentId,\n state: syncInput.state,\n supersededMovePreviousParentId: placement.currentParentId,\n });\n}\n\n/**\n * Records a failed adoption and leaves the lane's other intents to proceed. A\n * foreign create parks the intent: its signed facts never change, so later\n * passes neither re-read it nor report it again. Any other failure retries.\n */\nasync function recordAdoptionFailure(input: {\n readonly error: unknown;\n readonly organizationId: string;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"failed\"> {\n const { intent, isCurrent, state } = input.syncInput;\n if (!isCurrent()) return \"abandoned\";\n await reportKeyingVerificationErrorInCauseChain(\n input.error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n if (!isCurrent()) return \"abandoned\";\n const action =\n input.error instanceof ForeignContainerCreateError\n ? CONTAINER_CREATE_ADOPTION_REFUSED\n : \"Container create adoption verification failed\";\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: `${action}: ${errorMessage(input.error)}`,\n stillCurrent: isCurrent,\n },\n );\n return isCurrent() ? \"failed\" : \"abandoned\";\n}\n\n/**\n * Adopts a pending create the listing already carries, once its signed create\n * proves it is this device's. A parked refusal stays blocked without a read.\n */\nexport async function syncListedContainerCreate(input: {\n readonly containerState: ContainerState;\n readonly parentState: ContainerState;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"blocked\" | \"created\" | \"failed\"> {\n const { containerState, parentState, syncInput } = input;\n const { intent, isCurrent, state } = syncInput;\n if (intent.lastError?.startsWith(CONTAINER_CREATE_ADOPTION_REFUSED)) {\n return \"blocked\";\n }\n let placement: AdoptedContainerPlacement;\n try {\n placement = await verifyListedContainerCreate({\n intent,\n parentState,\n state,\n });\n } catch (error) {\n return recordAdoptionFailure({\n error,\n organizationId: parentState.container.organizationId,\n syncInput,\n });\n }\n const marked = await markContainerCreateIntentAdopted({\n containerState,\n placement,\n syncInput,\n });\n if (!marked) return isCurrent() ? \"blocked\" : \"abandoned\";\n // The folder now sits elsewhere; list it there rather than waiting for the\n // next poll to correct the local parent.\n if (placement.currentParentId !== intent.parentContainerId) {\n syncInput.requestRemoteReconciliation(placement.currentParentId);\n }\n return \"created\";\n}\n"]}
@@ -4,6 +4,7 @@ import { runWithSecurityIncidentReporting } from "../../../../data/keyingProject
4
4
  import { rethrowProjectionVerificationCancelled } from "../../../../data/keyingProjectionVerification/types.js";
5
5
  import { hasUnsettledDocumentPlacement } from "../../../../data/persistence/container-contents/documentPurgePlacement.js";
6
6
  import { sqlDocumentsPersistence } from "../../../../data/persistence/documents/documentsPersistence.js";
7
+ import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
7
8
  import { errorMessage } from "../../../../data/shared/errorMessage.js";
8
9
  import { assertLocalPurgeScope } from "./localPurgeScope.js";
9
10
  import { snapshotContainerStates } from "./purgeTreeCollection.js";
@@ -26,6 +27,7 @@ async function verifiedRemoteScope(input, current, verifiedAncestorsById) {
26
27
  }
27
28
  const path = await verifyContainerWriterProjection({
28
29
  execSql: runtime.infra.execSql,
30
+ openPrincipalPolicyBundleReader,
29
31
  projection,
30
32
  resolveUserKey: input.resolveProjectionUserKey,
31
33
  stillCurrent: input.stillCurrent,
@@ -1 +1 @@
1
- {"version":3,"file":"purgeTreeScope.js","sourceRoot":"","sources":["purgeTreeScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC;AAChG,OAAO,EAAE,gCAAgC,EAAE,MAAM,qDAAqD,CAAC;AACvG,OAAO,EAAE,sCAAsC,EAAE,MAAM,qDAAqD,CAAC;AAC7G,OAAO,EAAE,6BAA6B,EAAE,MAAM,wEAAwE,CAAC;AACvH,OAAO,EAAE,uBAAuB,EAAE,MAAM,6DAA6D,CAAC;AACtG,OAAO,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAMpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAW5D,KAAK,UAAU,mBAAmB,CAChC,KAA6B,EAC7B,OAAqD,EACrD,qBAAqD;IAErD,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,KAAK,CAAC;IAC3C,MAAM,QAAQ,GAAG,OAA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E,CAAC,QAAyB,EAAE,EAAE,CAC5C,mBAAmB,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE;YACpC,IACE,CAAC,QAAQ,CAAC,WAAW;gBACrB,CAAC,CAAC,MAAM,0BAA0B,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;gBAEpD,OAAO,KAAK,CAAC;YACf,IACE,CAAC,CAAC,MAAM,eAAe,CACrB,KAAK,EACL,QAAQ,CAAC,WAAW,EACpB,qBAAqB,EACrB,CAAC,QAAQ,CAAC,UAAU,CACrB,CAAC;gBAEF,OAAO,KAAK,CAAC;YACf,wEAAwE;YACxE,OAAO,mBAAmB,CACxB;gBACE,GAAG,KAAK;gBACR,WAAW,EAAE,QAAQ,CAAC,WAAW;gBACjC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;gBACpC,OAAO,EAAE,QAAQ,CAAC,EAAE;gBACpB,qBAAqB;aACtB,EACD,QAAQ,CACT,CAAC;QACJ,CAAC,CAAC;KACL,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,KAA6B,EAC7B,KAA6B;IAE7B,IAAI,CAAC;QACH,OAAO,MAAM,KAAK,EAAE,CAAC;IACvB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,sCAAsC,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,KAAK,YAAY,uBAAuB;YAAE,MAAM,KAAK,CAAC;QAC1D,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CACpB,gDAAgD,YAAY,CAAC,KAAK,CAAC,EAAE,CACtE,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { verifyContainerWriterProjection } from \"../../../../data/keyingProjectionVerification\";\nimport { runWithSecurityIncidentReporting } from \"../../../../data/keyingProjectionVerification/error\";\nimport { rethrowProjectionVerificationCancelled } from \"../../../../data/keyingProjectionVerification/types\";\nimport { hasUnsettledDocumentPlacement } from \"../../../../data/persistence/container-contents/documentPurgePlacement\";\nimport { sqlDocumentsPersistence } from \"../../../../data/persistence/documents/documentsPersistence\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../../../data/sqlite/sqlSchema\";\n\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../../runtime\";\nimport { assertLocalPurgeScope } from \"./localPurgeScope\";\nimport { snapshotContainerStates } from \"./purgeTreeCollection\";\nimport { readLocalPurgeScope } from \"./readLocalPurgeScope\";\n\ninterface SubtreePurgeScopeInput {\n containersById: ReadonlyMap<string, ContainerState>;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rootContainerId: string;\n runtime: ContainerContentsWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function verifiedRemoteScope(\n input: SubtreePurgeScopeInput,\n current: Pick<ContainerState, \"container\" | \"record\">,\n verifiedAncestorsById: Map<string, readonly string[]>,\n): Promise<boolean> {\n const { runtime, rootContainerId } = input;\n const targetId = current.container.id;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: targetId,\n objectKind: \"container\",\n operation: \"container.purge.scope\",\n },\n async () => {\n runtime.apiClient.evictContainerWriterProjection(targetId);\n const projection =\n await runtime.apiClient.getContainerWriterProjection(targetId);\n if (!projection || input.stillCurrent?.() === false) return false;\n if (\n projection.containerId !== targetId ||\n projection.organizationId !== current.container.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Subtree purge container identity mismatch\",\n );\n }\n const path = await verifyContainerWriterProjection({\n execSql: runtime.infra.execSql,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n runtime.principalPolicies.createWarmer(),\n });\n const rootIndex = path.findIndex(\n (head) => head.state.containerId === rootContainerId,\n );\n const latest = await input.persistence.loadContainerMetadataState(\n runtime.infra.execSql,\n targetId,\n );\n const pendingMoves = await readPendingMoves(input);\n const allowed =\n rootIndex >= 0 &&\n path[rootIndex]?.state.parentContainerId ===\n input.containersById.get(rootContainerId)?.container.parentId &&\n latest?.container.parentId === current.container.parentId &&\n latest.record?.documentId === current.record.documentId &&\n !path\n .slice(rootIndex)\n .some((head) => pendingMoves.has(head.state.containerId)) &&\n input.stillCurrent?.() !== false;\n if (allowed)\n verifiedAncestorsById.set(\n targetId,\n path.slice(rootIndex).map((head) => head.state.containerId),\n );\n return allowed;\n },\n );\n}\n\n/**\n * A local-only unit cites no signed request, so a remote ordinary root must\n * prove that it still sits under the parent it was selected from. A system\n * root's signed topology is fixed by its destination role.\n */\nasync function rootPlacementIsCurrent(\n input: SubtreePurgeScopeInput,\n verifiedAncestorsById: Map<string, readonly string[]>,\n): Promise<boolean> {\n const root = input.containersById.get(input.rootContainerId);\n if (!root?.record.documentId || (root.container.systemSlot ?? null) !== null)\n return true;\n return verifiedRemoteScope(input, root, verifiedAncestorsById);\n}\n\n/** A cycle or a pending move anywhere on the walk leaves the scope unproven. */\nfunction isUnvisitedSettledAncestor(\n currentId: string | null,\n seen: ReadonlySet<string>,\n pendingMoves: { has(containerId: string): boolean },\n): currentId is string {\n if (!currentId) return false;\n return !seen.has(currentId) && !pendingMoves.has(currentId);\n}\n\nasync function allowsContainer(\n input: SubtreePurgeScopeInput,\n containerId: string,\n verifiedAncestorsById: Map<string, readonly string[]>,\n localOnlyUnit: boolean,\n): Promise<boolean> {\n const { runtime, persistence, rootContainerId } = input;\n if (input.stillCurrent?.() === false) return false;\n const execSql = runtime.infra.execSql;\n const pendingMoves = await readPendingMoves(input);\n if (pendingMoves.has(rootContainerId)) return false;\n const seen = new Set<string>([rootContainerId]);\n let currentId: string | null = containerId;\n let verifiedRemoteAncestry = false;\n while (currentId !== rootContainerId) {\n if (!isUnvisitedSettledAncestor(currentId, seen, pendingMoves))\n return false;\n seen.add(currentId);\n const expected = input.containersById.get(currentId);\n const current = await persistence.loadContainerMetadataState(\n execSql,\n currentId,\n );\n if (\n !expected ||\n !current?.record ||\n current.container.parentId !== expected.container.parentId ||\n current.container.organizationId !== expected.container.organizationId ||\n current.record.documentId !== expected.record.documentId\n )\n return false;\n if (current.record.documentId) {\n if (\n !(await verifiedRemoteScope(\n input,\n {\n container: current.container,\n record: current.record,\n },\n verifiedAncestorsById,\n ))\n )\n return false;\n verifiedRemoteAncestry = true;\n break;\n }\n currentId = current.container.parentId;\n }\n if (\n localOnlyUnit &&\n !verifiedRemoteAncestry &&\n !(await rootPlacementIsCurrent(input, verifiedAncestorsById))\n )\n return false;\n return readLocalPurgeScope({\n ...input,\n containerId,\n execSql,\n verifiedAncestorsById,\n });\n}\n\nasync function readPendingMoves(input: SubtreePurgeScopeInput) {\n return new Set(\n (\n await input.persistence.listUnsyncedMoveIntents(\n input.runtime.infra.execSql,\n )\n ).map((intent) => intent.containerId),\n );\n}\n\nasync function documentPlacementIsCurrent(\n input: SubtreePurgeScopeInput,\n document: DocumentSummary,\n): Promise<boolean> {\n const execSql = input.runtime.infra.execSql;\n if (await hasUnsettledDocumentPlacement(execSql, document.id)) return false;\n const current = await sqlDocumentsPersistence.loadDocument(\n execSql,\n document.id,\n );\n return (\n current !== null &&\n current.documentId === document.documentId &&\n current.containerId === document.containerId &&\n input.stillCurrent?.() !== false\n );\n}\n\n/** Listing edges only select candidates; each destructive unit proves its scope. */\nexport function createSubtreePurgeScope(request: SubtreePurgeScopeInput) {\n const input = {\n ...request,\n containersById: snapshotContainerStates(request.containersById),\n };\n const verifiedAncestorsById = new Map<string, readonly string[]>();\n return {\n allowsLocalScopeInTransaction: (execSql: ExecSql, containerId: string) =>\n checkAvailableScope(input, async () => {\n await assertLocalPurgeScope({\n ...input,\n execSql,\n containerId,\n verifiedAncestorsById,\n });\n return true;\n }),\n assertLocalScopeInTransaction: (\n execSql: ExecSql,\n containerId: string | null | undefined,\n localId: string,\n ) =>\n assertLocalPurgeScope({\n ...input,\n execSql,\n containerId,\n localId,\n verifiedAncestorsById,\n }),\n allowsContainer: (containerId: string) =>\n checkAvailableScope(input, () =>\n allowsContainer(\n input,\n containerId,\n verifiedAncestorsById,\n !input.containersById.get(containerId)?.record.documentId,\n ),\n ),\n allowsDocument: (document: DocumentSummary) =>\n checkAvailableScope(input, async () => {\n if (\n !document.containerId ||\n !(await documentPlacementIsCurrent(input, document))\n )\n return false;\n if (\n !(await allowsContainer(\n input,\n document.containerId,\n verifiedAncestorsById,\n !document.documentId,\n ))\n )\n return false;\n // Freeze local placement checks together after all remote verification.\n return readLocalPurgeScope(\n {\n ...input,\n containerId: document.containerId,\n execSql: input.runtime.infra.execSql,\n localId: document.id,\n verifiedAncestorsById,\n },\n document,\n );\n }),\n };\n}\n\nasync function checkAvailableScope(\n input: SubtreePurgeScopeInput,\n check: () => Promise<boolean>,\n): Promise<boolean> {\n try {\n return await check();\n } catch (error) {\n rethrowProjectionVerificationCancelled(error);\n if (error instanceof KeyingVerificationError) throw error;\n input.runtime.util.log(\n `Container contents: purge scope unavailable: ${errorMessage(error)}`,\n );\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"purgeTreeScope.js","sourceRoot":"","sources":["purgeTreeScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC;AAChG,OAAO,EAAE,gCAAgC,EAAE,MAAM,qDAAqD,CAAC;AACvG,OAAO,EAAE,sCAAsC,EAAE,MAAM,qDAAqD,CAAC;AAC7G,OAAO,EAAE,6BAA6B,EAAE,MAAM,wEAAwE,CAAC;AACvH,OAAO,EAAE,uBAAuB,EAAE,MAAM,6DAA6D,C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AE,CAAC;QACf,sCAAsC,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,KAAK,YAAY,uBAAuB;YAAE,MAAM,KAAK,CAAC;QAC1D,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CACpB,gDAAgD,YAAY,CAAC,KAAK,CAAC,EAAE,CACtE,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { verifyContainerWriterProjection } from \"../../../../data/keyingProjectionVerification\";\nimport { runWithSecurityIncidentReporting } from \"../../../../data/keyingProjectionVerification/error\";\nimport { rethrowProjectionVerificationCancelled } from \"../../../../data/keyingProjectionVerification/types\";\nimport { hasUnsettledDocumentPlacement } from \"../../../../data/persistence/container-contents/documentPurgePlacement\";\nimport { sqlDocumentsPersistence } from \"../../../../data/persistence/documents/documentsPersistence\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../../../data/sqlite/sqlSchema\";\n\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../../runtime\";\nimport { assertLocalPurgeScope } from \"./localPurgeScope\";\nimport { snapshotContainerStates } from \"./purgeTreeCollection\";\nimport { readLocalPurgeScope } from \"./readLocalPurgeScope\";\n\ninterface SubtreePurgeScopeInput {\n containersById: ReadonlyMap<string, ContainerState>;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rootContainerId: string;\n runtime: ContainerContentsWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function verifiedRemoteScope(\n input: SubtreePurgeScopeInput,\n current: Pick<ContainerState, \"container\" | \"record\">,\n verifiedAncestorsById: Map<string, readonly string[]>,\n): Promise<boolean> {\n const { runtime, rootContainerId } = input;\n const targetId = current.container.id;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: targetId,\n objectKind: \"container\",\n operation: \"container.purge.scope\",\n },\n async () => {\n runtime.apiClient.evictContainerWriterProjection(targetId);\n const projection =\n await runtime.apiClient.getContainerWriterProjection(targetId);\n if (!projection || input.stillCurrent?.() === false) return false;\n if (\n projection.containerId !== targetId ||\n projection.organizationId !== current.container.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Subtree purge container identity mismatch\",\n );\n }\n const path = await verifyContainerWriterProjection({\n execSql: runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n runtime.principalPolicies.createWarmer(),\n });\n const rootIndex = path.findIndex(\n (head) => head.state.containerId === rootContainerId,\n );\n const latest = await input.persistence.loadContainerMetadataState(\n runtime.infra.execSql,\n targetId,\n );\n const pendingMoves = await readPendingMoves(input);\n const allowed =\n rootIndex >= 0 &&\n path[rootIndex]?.state.parentContainerId ===\n input.containersById.get(rootContainerId)?.container.parentId &&\n latest?.container.parentId === current.container.parentId &&\n latest.record?.documentId === current.record.documentId &&\n !path\n .slice(rootIndex)\n .some((head) => pendingMoves.has(head.state.containerId)) &&\n input.stillCurrent?.() !== false;\n if (allowed)\n verifiedAncestorsById.set(\n targetId,\n path.slice(rootIndex).map((head) => head.state.containerId),\n );\n return allowed;\n },\n );\n}\n\n/**\n * A local-only unit cites no signed request, so a remote ordinary root must\n * prove that it still sits under the parent it was selected from. A system\n * root's signed topology is fixed by its destination role.\n */\nasync function rootPlacementIsCurrent(\n input: SubtreePurgeScopeInput,\n verifiedAncestorsById: Map<string, readonly string[]>,\n): Promise<boolean> {\n const root = input.containersById.get(input.rootContainerId);\n if (!root?.record.documentId || (root.container.systemSlot ?? null) !== null)\n return true;\n return verifiedRemoteScope(input, root, verifiedAncestorsById);\n}\n\n/** A cycle or a pending move anywhere on the walk leaves the scope unproven. */\nfunction isUnvisitedSettledAncestor(\n currentId: string | null,\n seen: ReadonlySet<string>,\n pendingMoves: { has(containerId: string): boolean },\n): currentId is string {\n if (!currentId) return false;\n return !seen.has(currentId) && !pendingMoves.has(currentId);\n}\n\nasync function allowsContainer(\n input: SubtreePurgeScopeInput,\n containerId: string,\n verifiedAncestorsById: Map<string, readonly string[]>,\n localOnlyUnit: boolean,\n): Promise<boolean> {\n const { runtime, persistence, rootContainerId } = input;\n if (input.stillCurrent?.() === false) return false;\n const execSql = runtime.infra.execSql;\n const pendingMoves = await readPendingMoves(input);\n if (pendingMoves.has(rootContainerId)) return false;\n const seen = new Set<string>([rootContainerId]);\n let currentId: string | null = containerId;\n let verifiedRemoteAncestry = false;\n while (currentId !== rootContainerId) {\n if (!isUnvisitedSettledAncestor(currentId, seen, pendingMoves))\n return false;\n seen.add(currentId);\n const expected = input.containersById.get(currentId);\n const current = await persistence.loadContainerMetadataState(\n execSql,\n currentId,\n );\n if (\n !expected ||\n !current?.record ||\n current.container.parentId !== expected.container.parentId ||\n current.container.organizationId !== expected.container.organizationId ||\n current.record.documentId !== expected.record.documentId\n )\n return false;\n if (current.record.documentId) {\n if (\n !(await verifiedRemoteScope(\n input,\n {\n container: current.container,\n record: current.record,\n },\n verifiedAncestorsById,\n ))\n )\n return false;\n verifiedRemoteAncestry = true;\n break;\n }\n currentId = current.container.parentId;\n }\n if (\n localOnlyUnit &&\n !verifiedRemoteAncestry &&\n !(await rootPlacementIsCurrent(input, verifiedAncestorsById))\n )\n return false;\n return readLocalPurgeScope({\n ...input,\n containerId,\n execSql,\n verifiedAncestorsById,\n });\n}\n\nasync function readPendingMoves(input: SubtreePurgeScopeInput) {\n return new Set(\n (\n await input.persistence.listUnsyncedMoveIntents(\n input.runtime.infra.execSql,\n )\n ).map((intent) => intent.containerId),\n );\n}\n\nasync function documentPlacementIsCurrent(\n input: SubtreePurgeScopeInput,\n document: DocumentSummary,\n): Promise<boolean> {\n const execSql = input.runtime.infra.execSql;\n if (await hasUnsettledDocumentPlacement(execSql, document.id)) return false;\n const current = await sqlDocumentsPersistence.loadDocument(\n execSql,\n document.id,\n );\n return (\n current !== null &&\n current.documentId === document.documentId &&\n current.containerId === document.containerId &&\n input.stillCurrent?.() !== false\n );\n}\n\n/** Listing edges only select candidates; each destructive unit proves its scope. */\nexport function createSubtreePurgeScope(request: SubtreePurgeScopeInput) {\n const input = {\n ...request,\n containersById: snapshotContainerStates(request.containersById),\n };\n const verifiedAncestorsById = new Map<string, readonly string[]>();\n return {\n allowsLocalScopeInTransaction: (execSql: ExecSql, containerId: string) =>\n checkAvailableScope(input, async () => {\n await assertLocalPurgeScope({\n ...input,\n execSql,\n containerId,\n verifiedAncestorsById,\n });\n return true;\n }),\n assertLocalScopeInTransaction: (\n execSql: ExecSql,\n containerId: string | null | undefined,\n localId: string,\n ) =>\n assertLocalPurgeScope({\n ...input,\n execSql,\n containerId,\n localId,\n verifiedAncestorsById,\n }),\n allowsContainer: (containerId: string) =>\n checkAvailableScope(input, () =>\n allowsContainer(\n input,\n containerId,\n verifiedAncestorsById,\n !input.containersById.get(containerId)?.record.documentId,\n ),\n ),\n allowsDocument: (document: DocumentSummary) =>\n checkAvailableScope(input, async () => {\n if (\n !document.containerId ||\n !(await documentPlacementIsCurrent(input, document))\n )\n return false;\n if (\n !(await allowsContainer(\n input,\n document.containerId,\n verifiedAncestorsById,\n !document.documentId,\n ))\n )\n return false;\n // Freeze local placement checks together after all remote verification.\n return readLocalPurgeScope(\n {\n ...input,\n containerId: document.containerId,\n execSql: input.runtime.infra.execSql,\n localId: document.id,\n verifiedAncestorsById,\n },\n document,\n );\n }),\n };\n}\n\nasync function checkAvailableScope(\n input: SubtreePurgeScopeInput,\n check: () => Promise<boolean>,\n): Promise<boolean> {\n try {\n return await check();\n } catch (error) {\n rethrowProjectionVerificationCancelled(error);\n if (error instanceof KeyingVerificationError) throw error;\n input.runtime.util.log(\n `Container contents: purge scope unavailable: ${errorMessage(error)}`,\n );\n return false;\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { getTargetContainerContext, readContainerState, } from "../../../../data/containers/shared/projection.js";
2
2
  import { nullOnProjectionVerificationCancellation, verifyContainerWriterProjection, } from "../../../../data/keyingProjectionVerification/index.js";
3
3
  import { principalPolicyCacheForVerifiedPolicies } from "../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js";
4
+ import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
4
5
  import { ProjectionDependencyUnavailableError } from "../../../../data/shared/dependencyUnavailable.js";
5
6
  import { referencedPrincipalHeadFromPolicy } from "../../../containers/index.js";
6
7
  import { createRuntimeCurrentSharePrincipalPolicy } from "../../../organizations/groupShare/index.js";
@@ -48,6 +49,7 @@ async function containerStateHasCurrentGroupGrantInternal(input) {
48
49
  }, async ({ checkpointPolicies, policy, stillCurrent }) => {
49
50
  await verifyContainerWriterProjection({
50
51
  execSql: input.runtime.infra.execSql,
52
+ openPrincipalPolicyBundleReader,
51
53
  principalPolicyCache: principalPolicyCacheForVerifiedPolicies(checkpointPolicies),
52
54
  projection,
53
55
  resolveUserKey: input.resolveProjectionUserKey,
@@ -1 +1 @@
1
- {"version":3,"file":"groupGrantVerification.js","sourceRoot":"","sources":["groupGrantVerification.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,uCAAuC,EAAE,MAAM,oFAAoF,CAAC;AAC7I,OAAO,EAAE,oCAAoC,EAAE,MAAM,+CAA+C,CAAC;AACrG,OAAO,EAAE,iCAAiC,EAAE,MAAM,qBA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B,CAAC,YAAY,EAAE;SACjD,CAAC,CAAC;QACH,OAAO,8BAA8B,CAAC;YACpC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,WAAW,EAAE,iCAAiC,CAAC,MAAM,CAAC;YACtD,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,UAAU;SACX,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuE;IAEvE,OAAO,CACL,CAAC,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACnD,0CAA0C,CAAC,KAAK,CAAC,CAClD,CAAC,IAAI,KAAK,CACZ,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/shared/dependencyUnavailable\";\nimport { referencedPrincipalHeadFromPolicy } from \"../../../containers\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"../../../organizations/groupShare\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\ntype GroupGrantAccessLevel = \"read\" | \"write\" | \"admin\";\n\nfunction projectionHasCurrentGroupGrant(input: {\n accessLevel: GroupGrantAccessLevel;\n expectedContainerId: string;\n expectedOrganizationId: string;\n groupId: string;\n currentHead: ReferencedPrincipalHead;\n projection: NonNullable<\n Awaited<ReturnType<typeof loadContainerWriterProjectionForState>>\n >;\n}): boolean {\n const state = readContainerState(\n getTargetContainerContext(input.projection).manifest,\n );\n return (\n state.containerId === input.expectedContainerId &&\n state.organizationId === input.expectedOrganizationId &&\n state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n ) &&\n state.referencedPrincipalHeads.some(\n (head) =>\n head.principalType === input.currentHead.principalType &&\n head.principalId === input.currentHead.principalId &&\n head.version === input.currentHead.version &&\n head.keyEpoch === input.currentHead.keyEpoch &&\n head.stateHash === input.currentHead.stateHash &&\n head.keyFingerprint === input.currentHead.keyFingerprint,\n )\n );\n}\n\nasync function containerStateHasCurrentGroupGrantInternal(input: {\n accessLevel: GroupGrantAccessLevel;\n containerState: ContainerState;\n expectedContainerId: string;\n expectedGroupHead: ReferencedPrincipalHead;\n expectedOrganizationId: string;\n groupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.stillCurrent?.() === false) return false;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (\n !projection ||\n input.stillCurrent?.() === false ||\n input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId ||\n input.containerState.container.id !== input.expectedContainerId ||\n input.containerState.container.organizationId !==\n input.expectedOrganizationId ||\n projection.containerId !== input.expectedContainerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n return false;\n }\n\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(input.runtime);\n if (!readCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n return readCurrent(\n {\n expectedGroupHead: input.expectedGroupHead,\n groupId: input.groupId,\n organizationId: input.expectedOrganizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ checkpointPolicies, policy, stillCurrent }) => {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n return projectionHasCurrentGroupGrant({\n accessLevel: input.accessLevel,\n currentHead: referencedPrincipalHeadFromPolicy(policy),\n expectedContainerId: input.expectedContainerId,\n expectedOrganizationId: input.expectedOrganizationId,\n groupId: input.groupId,\n projection,\n });\n },\n );\n}\n\nexport async function containerStateHasCurrentGroupGrant(\n input: Parameters<typeof containerStateHasCurrentGroupGrantInternal>[0],\n): Promise<boolean> {\n return (\n (await nullOnProjectionVerificationCancellation(() =>\n containerStateHasCurrentGroupGrantInternal(input),\n )) ?? false\n );\n}\n"]}
1
+ {"version":3,"file":"groupGrantVerification.js","sourceRoot":"","sources":["groupGrantVerification.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,uCAAuC,EAAE,MAAM,oFAAoF,CAAC;AAC7I,OAAO,EAAE,+BAA+B,EAAE,MAAM,8EAA8E,CAAC;AAC/H,OAAO,EAAE,oCAAoC,EAAE,MAAM,+CAA+C,CAAC;AACrG,OAAO,EAAE,iCAAiC,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,wCAAwC,EAAE,MAAM,mCAAmC,CAAC;AAG7F,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAK3E,SAAS,8BAA8B,CAAC,KASvC;IACC,MAAM,KAAK,GAAG,kBAAkB,CAC9B,yBAAyB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,QAAQ,CACrD,CAAC;IACF,OAAO,CACL,KAAK,CAAC,WAAW,KA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U;SACX,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuE;IAEvE,OAAO,CACL,CAAC,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACnD,0CAA0C,CAAC,KAAK,CAAC,CAClD,CAAC,IAAI,KAAK,CACZ,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/shared/dependencyUnavailable\";\nimport { referencedPrincipalHeadFromPolicy } from \"../../../containers\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"../../../organizations/groupShare\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\ntype GroupGrantAccessLevel = \"read\" | \"write\" | \"admin\";\n\nfunction projectionHasCurrentGroupGrant(input: {\n accessLevel: GroupGrantAccessLevel;\n expectedContainerId: string;\n expectedOrganizationId: string;\n groupId: string;\n currentHead: ReferencedPrincipalHead;\n projection: NonNullable<\n Awaited<ReturnType<typeof loadContainerWriterProjectionForState>>\n >;\n}): boolean {\n const state = readContainerState(\n getTargetContainerContext(input.projection).manifest,\n );\n return (\n state.containerId === input.expectedContainerId &&\n state.organizationId === input.expectedOrganizationId &&\n state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n ) &&\n state.referencedPrincipalHeads.some(\n (head) =>\n head.principalType === input.currentHead.principalType &&\n head.principalId === input.currentHead.principalId &&\n head.version === input.currentHead.version &&\n head.keyEpoch === input.currentHead.keyEpoch &&\n head.stateHash === input.currentHead.stateHash &&\n head.keyFingerprint === input.currentHead.keyFingerprint,\n )\n );\n}\n\nasync function containerStateHasCurrentGroupGrantInternal(input: {\n accessLevel: GroupGrantAccessLevel;\n containerState: ContainerState;\n expectedContainerId: string;\n expectedGroupHead: ReferencedPrincipalHead;\n expectedOrganizationId: string;\n groupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.stillCurrent?.() === false) return false;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (\n !projection ||\n input.stillCurrent?.() === false ||\n input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId ||\n input.containerState.container.id !== input.expectedContainerId ||\n input.containerState.container.organizationId !==\n input.expectedOrganizationId ||\n projection.containerId !== input.expectedContainerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n return false;\n }\n\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(input.runtime);\n if (!readCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n return readCurrent(\n {\n expectedGroupHead: input.expectedGroupHead,\n groupId: input.groupId,\n organizationId: input.expectedOrganizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ checkpointPolicies, policy, stillCurrent }) => {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n return projectionHasCurrentGroupGrant({\n accessLevel: input.accessLevel,\n currentHead: referencedPrincipalHeadFromPolicy(policy),\n expectedContainerId: input.expectedContainerId,\n expectedOrganizationId: input.expectedOrganizationId,\n groupId: input.groupId,\n projection,\n });\n },\n );\n}\n\nexport async function containerStateHasCurrentGroupGrant(\n input: Parameters<typeof containerStateHasCurrentGroupGrantInternal>[0],\n): Promise<boolean> {\n return (\n (await nullOnProjectionVerificationCancellation(() =>\n containerStateHasCurrentGroupGrantInternal(input),\n )) ?? false\n );\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { getTargetContainerContext, readContainerState, } from "../../../../data/containers/shared/projection.js";
2
2
  import { unwrapContainerKekPath } from "../../../../data/documents/shared/projection/index.js";
3
3
  import { nullOnProjectionVerificationCancellation, verifyContainerWriterProjection, } from "../../../../data/keyingProjectionVerification/index.js";
4
+ import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
4
5
  import { projectionGeneration } from "../../projectionGeneration.js";
5
6
  import { loadContainerWriterProjectionForState } from "../projectionCache.js";
6
7
  import { shareRemoteContainer, shareRemoteContainerWithGroup } from "../remote.js";
@@ -111,6 +112,7 @@ async function prepareContainerStateGroupRewrapInternal(input) {
111
112
  if (input.requireExistingGrant) {
112
113
  await verifyContainerWriterProjection({
113
114
  execSql: input.runtime.infra.execSql,
115
+ openPrincipalPolicyBundleReader,
114
116
  projection,
115
117
  resolveUserKey: input.resolveProjectionUserKey,
116
118
  stillCurrent: input.stillCurrent,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EAA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C;YACpC,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,KAAK,EAAE,YAAY,CAAC,aAAa;YACjC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,UAAU,EAAE,YAAY,CAAC,UAAU;YACnC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,0BAA0B;SAC3B,CAAC,CAAC;IACL,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,6BAA6B,CAAC;QACjD,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,WAAW,EAAE,KAAK,CAAC,cAAc,CAAC,SAAS,CAAC,EAAE;QAC9C,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,kBAAkB,EAAE,YAAY,CAAC,UAAU;QAC3C,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IAEH,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IAErE,OAAO,2BAA2B,CAAC;QACjC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../../data/documents/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\n\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { shareRemoteContainer, shareRemoteContainerWithGroup } from \"../remote\";\nimport type {\n ContainerWorkflowRuntime,\n SharedContainerStateResult,\n} from \"../types\";\nimport { resolveCurrentGroupKeyEpoch } from \"./groupShareEpoch\";\nimport {\n type MatchingRemoteContainerGrant,\n persistDuplicateContainerShare,\n persistSharedContainerState,\n} from \"./sharePersistence\";\n\ntype ContainerShareSubjectType = \"group\" | \"user\";\ntype ContainerShareAccessLevel = \"read\" | \"write\" | \"admin\";\n\ninterface RemoteContainerShareContext {\n matchingGrant: MatchingRemoteContainerGrant | null;\n projection: ContainerWriterProjectionResponse;\n}\n\nfunction readOptionalProjectionString(\n projection: ContainerWriterProjectionResponse,\n key: string,\n): string | null {\n const value = Reflect.get(projection, key);\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n// A container's KEK is wrapped to a group's encapsulation key at a specific key\n// epoch, pinned into the manifest as a referenced principal head. When the group\n// rotates (org-admin add or any removal bumps the epoch and mints a fresh KEM\n// keypair), that wrap goes stale: members holding only the new epoch secret can\n// no longer unwrap it. A re-share to the same group at the same access level is\n// therefore NOT redundant when the pinned epoch trails the group's current head,\n// so it must not be deduped away. The current epoch comes from a network-fresh,\n// fully verified current policy guarded by durable local checkpoints.\nfunction groupGrantIsStale(input: {\n currentKeyEpoch: number;\n referencedPrincipalHeads: ReadonlyArray<ReferencedPrincipalStateResponse>;\n subjectId: string;\n}): boolean {\n const pinnedHead = (input.referencedPrincipalHeads ?? []).find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n if (!pinnedHead) {\n return true;\n }\n return pinnedHead.keyEpoch !== input.currentKeyEpoch;\n}\n\nfunction newGrantShareContext(\n input: {\n containerState: ContainerState;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n },\n projection: RemoteContainerShareContext[\"projection\"],\n): RemoteContainerShareContext | null {\n if (input.requireExistingGrant) {\n // Re-wrap-only callers must never mint a brand-new grant: the container's\n // system slot is server-supplied and could point at a container that does\n // not already grant this subject, so minting here would leak its contents.\n input.runtime.util.log(\n `Container contents: refused to create a new ${input.subjectType} grant for ${input.subjectId} on container ${input.containerState.container.id} because the re-share requires an existing grant`,\n );\n return null;\n }\n return { matchingGrant: null, projection };\n}\n\nasync function loadRemoteContainerShareContext(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n forceExistingGrantRewrap?: boolean | undefined;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n}): Promise<RemoteContainerShareContext | null> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const remoteState = readContainerState(target.manifest);\n const hasMatchingGrant = remoteState.directGrants.some(\n (grant) =>\n grant.subjectType === input.subjectType &&\n grant.subjectId === input.subjectId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasMatchingGrant) {\n return newGrantShareContext(input, projection);\n }\n\n if (\n input.subjectType === \"group\" &&\n input.requireExistingGrant &&\n input.forceExistingGrantRewrap\n ) {\n // The cheap epoch probe below reads an unverified response and cannot prove\n // that a security-critical re-wrap is current. Force the verified policy\n // load and a real same-level mutation; failures must reach the retry owner.\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because an existing grant re-wrap is required`,\n );\n return { matchingGrant: null, projection };\n }\n\n if (input.subjectType === \"group\") {\n const pinnedHead = remoteState.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n const currentKeyEpoch = pinnedHead\n ? await resolveCurrentGroupKeyEpoch({\n expectedGroupName: input.expectedGroupName,\n groupId: input.subjectId,\n organizationId: remoteState.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n })\n : null;\n if (input.stillCurrent?.() === false) return null;\n if (\n !pinnedHead ||\n (currentKeyEpoch !== null &&\n groupGrantIsStale({\n currentKeyEpoch,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n subjectId: input.subjectId,\n }))\n ) {\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because its key epoch advanced past the pinned grant`,\n );\n return { matchingGrant: null, projection };\n }\n }\n\n return {\n matchingGrant: {\n accessEpoch: remoteState.epoch,\n accessStateHash: target.manifest.manifestHash,\n createdAt: readOptionalProjectionString(projection, \"createdAt\"),\n metadataDocumentId: remoteState.metadataDocumentId,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n updatedAt: readOptionalProjectionString(projection, \"updatedAt\"),\n },\n projection,\n };\n}\n\nasync function prepareContainerStateGroupRewrapInternal(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n groupId: string;\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | { status: \"not-granted\" }\n | {\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n status: \"prepared\";\n }\n | null\n> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n if (input.requireExistingGrant) {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (input.stillCurrent?.() === false) return null;\n const verifiedState = readContainerState(\n getTargetContainerContext(projection).manifest,\n );\n if (\n projection.containerId !== input.containerState.container.id ||\n projection.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.containerId !== input.containerState.container.id ||\n verifiedState.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.parentContainerId !==\n input.containerState.container.parentId\n ) {\n throw new Error(\n \"Prepared container group re-wrap target is inconsistent\",\n );\n }\n const hasGrant = verifiedState.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasGrant) {\n return { status: \"not-granted\" };\n }\n }\n\n const targetSecretKey =\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null;\n if (!targetSecretKey) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const keksByEpochId = await unwrapContainerKekPath({\n execSql: input.runtime.infra.execSql,\n projection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n secretKey: targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (input.stillCurrent?.() === false) return null;\n const targetKek = keksByEpochId.get(target.kek.containerKeyEpochId);\n return targetKek\n ? {\n knownContainerKeks: new Map([\n [target.kek.containerKeyEpochId, targetKek],\n ]),\n status: \"prepared\",\n }\n : null;\n}\n\nexport function prepareContainerStateGroupRewrap(\n input: Parameters<typeof prepareContainerStateGroupRewrapInternal>[0],\n): ReturnType<typeof prepareContainerStateGroupRewrapInternal> {\n return nullOnProjectionVerificationCancellation(() =>\n prepareContainerStateGroupRewrapInternal(input),\n );\n}\n\nexport async function shareContainerState(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n persistence: ContainerContentsPersistence;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with user ${input.recipientUserId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainer({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n previousProjection: shareContext.projection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n\nexport async function shareContainerStateWithGroup(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistence: ContainerContentsPersistence;\n recipientGroupId: string;\n // When set, a re-share only re-wraps an already-granted group and never mints\n // a new grant. Used by organization access repair so a server cannot redirect\n // the operation onto a container the group is not entitled to. A prepared\n // re-wrap also supplies captured KEKs and must submit a real mutation.\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n // A share chosen by name must carry that name so it can be bound to the\n // signed group policy. Only the grant-preserving re-wrap, which never mints\n // a grant, may run without one. Enforced here, in the workflow facade, so\n // every caller (not only the store) meets the invariant.\n if (!input.requireExistingGrant && input.expectedGroupName === undefined) {\n throw new Error(\"Container group share requires the chosen group name\");\n }\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n expectedGroupName: input.expectedGroupName,\n forceExistingGrantRewrap:\n input.requireExistingGrant && input.knownContainerKeks !== undefined,\n requireExistingGrant: input.requireExistingGrant,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n // A duplicate share mints nothing, but it must not report success for a\n // group the user did not choose. A matching grant is only found after the\n // key-epoch probe verified the group's policy with the chosen name bound,\n // so the name is already checked here.\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with group ${input.recipientGroupId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainerWithGroup({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n expectedGroupName: input.expectedGroupName,\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: shareContext.projection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,8EAA8E,CAAC;AAG/H,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC;AAKhF,OAAO,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,EAEL,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,oBAAoB,CAAC;AAU5B,SAAS,4BAA4B,CACnC,UAA6C,EAC7C,GAAW;IAEX,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtE,CAAC;AAED,gFAAgF;AAChF,iFAAiF;AACjF,8EAA8E;AAC9E,gFAAgF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AE,KAAK,CAAC,wBAAwB;QACxD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IAEH,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IAErE,OAAO,2BAA2B,CAAC;QACjC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../../data/documents/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\n\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { shareRemoteContainer, shareRemoteContainerWithGroup } from \"../remote\";\nimport type {\n ContainerWorkflowRuntime,\n SharedContainerStateResult,\n} from \"../types\";\nimport { resolveCurrentGroupKeyEpoch } from \"./groupShareEpoch\";\nimport {\n type MatchingRemoteContainerGrant,\n persistDuplicateContainerShare,\n persistSharedContainerState,\n} from \"./sharePersistence\";\n\ntype ContainerShareSubjectType = \"group\" | \"user\";\ntype ContainerShareAccessLevel = \"read\" | \"write\" | \"admin\";\n\ninterface RemoteContainerShareContext {\n matchingGrant: MatchingRemoteContainerGrant | null;\n projection: ContainerWriterProjectionResponse;\n}\n\nfunction readOptionalProjectionString(\n projection: ContainerWriterProjectionResponse,\n key: string,\n): string | null {\n const value = Reflect.get(projection, key);\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n// A container's KEK is wrapped to a group's encapsulation key at a specific key\n// epoch, pinned into the manifest as a referenced principal head. When the group\n// rotates (org-admin add or any removal bumps the epoch and mints a fresh KEM\n// keypair), that wrap goes stale: members holding only the new epoch secret can\n// no longer unwrap it. A re-share to the same group at the same access level is\n// therefore NOT redundant when the pinned epoch trails the group's current head,\n// so it must not be deduped away. The current epoch comes from a network-fresh,\n// fully verified current policy guarded by durable local checkpoints.\nfunction groupGrantIsStale(input: {\n currentKeyEpoch: number;\n referencedPrincipalHeads: ReadonlyArray<ReferencedPrincipalStateResponse>;\n subjectId: string;\n}): boolean {\n const pinnedHead = (input.referencedPrincipalHeads ?? []).find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n if (!pinnedHead) {\n return true;\n }\n return pinnedHead.keyEpoch !== input.currentKeyEpoch;\n}\n\nfunction newGrantShareContext(\n input: {\n containerState: ContainerState;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n },\n projection: RemoteContainerShareContext[\"projection\"],\n): RemoteContainerShareContext | null {\n if (input.requireExistingGrant) {\n // Re-wrap-only callers must never mint a brand-new grant: the container's\n // system slot is server-supplied and could point at a container that does\n // not already grant this subject, so minting here would leak its contents.\n input.runtime.util.log(\n `Container contents: refused to create a new ${input.subjectType} grant for ${input.subjectId} on container ${input.containerState.container.id} because the re-share requires an existing grant`,\n );\n return null;\n }\n return { matchingGrant: null, projection };\n}\n\nasync function loadRemoteContainerShareContext(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n forceExistingGrantRewrap?: boolean | undefined;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n}): Promise<RemoteContainerShareContext | null> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const remoteState = readContainerState(target.manifest);\n const hasMatchingGrant = remoteState.directGrants.some(\n (grant) =>\n grant.subjectType === input.subjectType &&\n grant.subjectId === input.subjectId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasMatchingGrant) {\n return newGrantShareContext(input, projection);\n }\n\n if (\n input.subjectType === \"group\" &&\n input.requireExistingGrant &&\n input.forceExistingGrantRewrap\n ) {\n // The cheap epoch probe below reads an unverified response and cannot prove\n // that a security-critical re-wrap is current. Force the verified policy\n // load and a real same-level mutation; failures must reach the retry owner.\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because an existing grant re-wrap is required`,\n );\n return { matchingGrant: null, projection };\n }\n\n if (input.subjectType === \"group\") {\n const pinnedHead = remoteState.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n const currentKeyEpoch = pinnedHead\n ? await resolveCurrentGroupKeyEpoch({\n expectedGroupName: input.expectedGroupName,\n groupId: input.subjectId,\n organizationId: remoteState.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n })\n : null;\n if (input.stillCurrent?.() === false) return null;\n if (\n !pinnedHead ||\n (currentKeyEpoch !== null &&\n groupGrantIsStale({\n currentKeyEpoch,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n subjectId: input.subjectId,\n }))\n ) {\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because its key epoch advanced past the pinned grant`,\n );\n return { matchingGrant: null, projection };\n }\n }\n\n return {\n matchingGrant: {\n accessEpoch: remoteState.epoch,\n accessStateHash: target.manifest.manifestHash,\n createdAt: readOptionalProjectionString(projection, \"createdAt\"),\n metadataDocumentId: remoteState.metadataDocumentId,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n updatedAt: readOptionalProjectionString(projection, \"updatedAt\"),\n },\n projection,\n };\n}\n\nasync function prepareContainerStateGroupRewrapInternal(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n groupId: string;\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | { status: \"not-granted\" }\n | {\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n status: \"prepared\";\n }\n | null\n> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n if (input.requireExistingGrant) {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (input.stillCurrent?.() === false) return null;\n const verifiedState = readContainerState(\n getTargetContainerContext(projection).manifest,\n );\n if (\n projection.containerId !== input.containerState.container.id ||\n projection.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.containerId !== input.containerState.container.id ||\n verifiedState.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.parentContainerId !==\n input.containerState.container.parentId\n ) {\n throw new Error(\n \"Prepared container group re-wrap target is inconsistent\",\n );\n }\n const hasGrant = verifiedState.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasGrant) {\n return { status: \"not-granted\" };\n }\n }\n\n const targetSecretKey =\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null;\n if (!targetSecretKey) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const keksByEpochId = await unwrapContainerKekPath({\n execSql: input.runtime.infra.execSql,\n projection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n secretKey: targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (input.stillCurrent?.() === false) return null;\n const targetKek = keksByEpochId.get(target.kek.containerKeyEpochId);\n return targetKek\n ? {\n knownContainerKeks: new Map([\n [target.kek.containerKeyEpochId, targetKek],\n ]),\n status: \"prepared\",\n }\n : null;\n}\n\nexport function prepareContainerStateGroupRewrap(\n input: Parameters<typeof prepareContainerStateGroupRewrapInternal>[0],\n): ReturnType<typeof prepareContainerStateGroupRewrapInternal> {\n return nullOnProjectionVerificationCancellation(() =>\n prepareContainerStateGroupRewrapInternal(input),\n );\n}\n\nexport async function shareContainerState(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n persistence: ContainerContentsPersistence;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with user ${input.recipientUserId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainer({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n previousProjection: shareContext.projection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n\nexport async function shareContainerStateWithGroup(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistence: ContainerContentsPersistence;\n recipientGroupId: string;\n // When set, a re-share only re-wraps an already-granted group and never mints\n // a new grant. Used by organization access repair so a server cannot redirect\n // the operation onto a container the group is not entitled to. A prepared\n // re-wrap also supplies captured KEKs and must submit a real mutation.\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n // A share chosen by name must carry that name so it can be bound to the\n // signed group policy. Only the grant-preserving re-wrap, which never mints\n // a grant, may run without one. Enforced here, in the workflow facade, so\n // every caller (not only the store) meets the invariant.\n if (!input.requireExistingGrant && input.expectedGroupName === undefined) {\n throw new Error(\"Container group share requires the chosen group name\");\n }\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n expectedGroupName: input.expectedGroupName,\n forceExistingGrantRewrap:\n input.requireExistingGrant && input.knownContainerKeks !== undefined,\n requireExistingGrant: input.requireExistingGrant,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n // A duplicate share mints nothing, but it must not report success for a\n // group the user did not choose. A matching grant is only found after the\n // key-epoch probe verified the group's policy with the chosen name bound,\n // so the name is already checked here.\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with group ${input.recipientGroupId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainerWithGroup({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n expectedGroupName: input.expectedGroupName,\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: shareContext.projection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n"]}
@@ -3,6 +3,7 @@ import { deriveOrganizationMetadataContainerSystemSlot } from "../../../../inter
3
3
  import { verifiedContainerCreateManifest, verifyContainerDestinationProjection, verifyContainerWriterProjection, } from "../../../../data/keyingProjectionVerification/index.js";
4
4
  import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, runWithSecurityIncidentReporting, } from "../../../../data/keyingProjectionVerification/error.js";
5
5
  import { listingRepeatsHeldOrdinaryBinding, } from "../../../../data/persistence/container-contents/containerBinding.js";
6
+ import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
7
  import { verifyRuntimeGroupMetadataAuthority } from "../../../organizations/groupMetadata/runtimeGroupMetadataAuthority.js";
7
8
  import { cachedDestinationRole, rememberDestinationRole, } from "./destinationRoleCache.js";
8
9
  import { resolveWithMetadataRootReload } from "./destinationRootReload.js";
@@ -96,6 +97,7 @@ async function verifyDestinationRole(input) {
96
97
  assertDestinationProjectionIdentity(projection, listed);
97
98
  const verificationInput = {
98
99
  execSql: runtime.infra.execSql,
100
+ openPrincipalPolicyBundleReader,
99
101
  projection,
100
102
  resolveUserKey: runtime.resolveTrustedUserIdentity,
101
103
  stillCurrent: isCurrent,