@tearleads/client-sdk 0.1.199 → 0.1.201

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 (64) hide show
  1. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +2 -2
  2. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  3. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
  4. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  5. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +6 -7
  6. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  7. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js +4 -16
  8. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -1
  9. package/data/persistence/principalMutationJournalPersistence.d.ts +20 -13
  10. package/data/persistence/principalMutationJournalPersistence.js +54 -43
  11. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  12. package/data/persistence/principalPolicy/heldPrincipalState.js +2 -11
  13. package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
  14. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +14 -65
  15. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
  16. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +180 -0
  17. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -0
  18. package/data/persistence/principalPolicy/principalPolicyPersistence.js +6 -62
  19. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
  20. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +11 -12
  21. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
  22. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +24 -40
  23. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -1
  24. package/data/principals/organizationGroupRoles.js +2 -2
  25. package/data/principals/organizationGroupRoles.js.map +1 -1
  26. package/data/principals/principalPolicyCrypto.js +2 -2
  27. package/data/principals/principalPolicyCrypto.js.map +1 -1
  28. package/package.json +1 -1
  29. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
  30. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  31. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -5
  32. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  33. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  34. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  35. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +4 -11
  36. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  37. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +7 -9
  38. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  39. package/workflows/organizations/groupShare/shareWithGroup.js +2 -2
  40. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  41. package/workflows/organizations/groups/deleteOrganizationGroup.js +2 -4
  42. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  43. package/workflows/organizations/groups/organizationGroupDirectory.js +2 -4
  44. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  45. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js +5 -7
  46. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js.map +1 -1
  47. package/workflows/organizations/principalMutations/principalMutationJournalSession.js +4 -6
  48. package/workflows/organizations/principalMutations/principalMutationJournalSession.js.map +1 -1
  49. package/workflows/organizations/readModel/localReadModelDetails.js +3 -3
  50. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  51. package/workflows/principals/externalAdminPolicy.js +2 -4
  52. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  53. package/workflows/principals/policyCache/index.js +3 -5
  54. package/workflows/principals/policyCache/index.js.map +1 -1
  55. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +3 -2
  56. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  57. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
  58. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  59. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
  60. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  61. package/workflows/registration/registrationPrincipalPolicyPersistence.js +2 -4
  62. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  63. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
  64. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyPersistence.js","sourceRoot":"","sources":["principalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EACL,oDAAoD,EACpD,8CAA8C,GAC/C,M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AAiB,EACjB,cAAsB,EACtB,OAAoE;IAEpE,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,qBAAqB;QACxB,GAAG,sBAAsB;KAC1B,CAAC,CAAC;IAEH,MAAM,OAAO,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC3D,MAAM,IAAI,GAAG,CAAC,EAAgC,EAAE,EAAE,CAChD,uCAAuC,CACrC,EAAE,EACF,MAAM,EACN,SAAS,EACT,cAAc,CACf,CAAC;IACJ,IAAI,OAAO,EAAE,YAAY,EAAE,CAAC;QAC1B,MAAM,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,OAAO,CAAC,YAAY,EAAE;YAC3D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, asc, desc, eq, or } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalPolicyTables } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { storedPrincipalPolicyPin } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n recordPrincipalPolicyBundleOrganizationInTransaction,\n recordPrincipalPolicyOrganizationInTransaction,\n} from \"../keyingCheckpoints/principalPolicyOrganizationPersistence\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport { indexPrincipalPolicyBundleInTransaction } from \"./principalPolicyReferenceIndexPersistence\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface PrincipalPolicyRow {\n principalType: \"group\" | \"organization\";\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\nexport interface SelectedPrincipalPolicyRow {\n principalType: string;\n principalId: string;\n stateHash: string;\n isCurrent: boolean;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\ninterface StoredPrincipalPolicyHead {\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isManagedPrincipalType(\n value: string,\n): value is PrincipalStateResponse[\"principalType\"] {\n return value === \"group\" || value === \"organization\";\n}\n\nfunction parsePrincipalPolicyRow(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyRow | null {\n if (!isManagedPrincipalType(row.principalType)) {\n return null;\n }\n\n return {\n principalType: row.principalType,\n principalId: row.principalId,\n stateHash: row.stateHash,\n currentStateJson: row.currentStateJson,\n currentPayloadJson: row.currentPayloadJson,\n currentProjectionJson: row.currentProjectionJson,\n currentGrantsJson: row.currentGrantsJson,\n currentMemberEnvelopesJson: row.currentMemberEnvelopesJson,\n previousStatesJson: row.previousStatesJson,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction parseStoredPrincipalPolicyHead(\n currentStateJson: string,\n): StoredPrincipalPolicyHead | null {\n try {\n const value: unknown = JSON.parse(currentStateJson);\n if (!value || typeof value !== \"object\") {\n return null;\n }\n const stateHash = Reflect.get(value, \"stateHash\");\n const version = Reflect.get(value, \"version\");\n return typeof stateHash === \"string\" && typeof version === \"number\"\n ? { stateHash, version }\n : null;\n } catch {\n return null;\n }\n}\n\nfunction parsePrincipalPolicyBundle(\n row: PrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n\n return bundle;\n}\n\nexport async function ensurePrincipalPolicyTables(\n execSql: ExecSql,\n): Promise<void> {\n await ensureSqlTables(execSql, principalPolicyTables);\n}\n\n/** The ONE select shape for a stored principal-policy bundle row. */\nexport const principalPolicyBundleSelection = {\n principalType: principalPolicyBundles.principalType,\n principalId: principalPolicyBundles.principalId,\n stateHash: principalPolicyBundles.stateHash,\n isCurrent: principalPolicyBundles.isCurrent,\n currentStateJson: principalPolicyBundles.currentStateJson,\n currentPayloadJson: principalPolicyBundles.currentPayloadJson,\n currentProjectionJson: principalPolicyBundles.currentProjectionJson,\n currentGrantsJson: principalPolicyBundles.currentGrantsJson,\n currentMemberEnvelopesJson: principalPolicyBundles.currentMemberEnvelopesJson,\n previousStatesJson: principalPolicyBundles.previousStatesJson,\n updatedAt: principalPolicyBundles.updatedAt,\n};\n\n/** Every stored bundle of one principal. */\nexport function wherePrincipalPolicyBundlePrincipal(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n eq(principalPolicyBundles.principalType, principal.principalType),\n eq(principalPolicyBundles.principalId, principal.principalId),\n );\n}\n\n/** The one current head of a principal. */\nfunction wherePrincipalPolicyCurrent(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(principal),\n eq(principalPolicyBundles.isCurrent, true),\n );\n}\n\nfunction wherePrincipalPolicyBundle(row: {\n readonly principalType: string;\n readonly principalId: string;\n readonly stateHash: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(row),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n );\n}\n\n/** A principal's current head and its retained bundle at `row`'s exact hash, in one read. */\nasync function loadCurrentAndRetainedPolicyBundles(\n tx: ClientSQLiteTransactionScope,\n row: PrincipalPolicyRow,\n) {\n const rows = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(row),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n ),\n ),\n );\n return {\n current: rows.find((stored) => stored.isCurrent),\n retained: rows.find(\n (stored) => !stored.isCurrent && stored.stateHash === row.stateHash,\n ),\n };\n}\n\nexport async function loadPrincipalPolicyBundle(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<PrincipalPolicyBundleResponse | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n\n const row = rows[0] ? parsePrincipalPolicyRow(rows[0]) : null;\n return row ? parsePrincipalPolicyBundle(row) : null;\n}\n\n/** Current heads first, then retained bundles. */\nexport async function loadAllPrincipalPolicyBundles(\n execSql: ExecSql,\n): Promise<PrincipalPolicyBundleResponse[]> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(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\n const bundles: PrincipalPolicyBundleResponse[] = [];\n\n for (const rawRow of rows) {\n const row = parsePrincipalPolicyRow(rawRow);\n\n if (!row) {\n continue;\n }\n\n bundles.push(parsePrincipalPolicyBundle(row));\n }\n\n return bundles;\n}\n\nexport async function loadPrincipalPolicyStateHash(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<string | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n\n return rows[0]?.stateHash ?? null;\n}\n\nfunction policyBundleRow(\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n): PrincipalPolicyRow {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n stateHash: bundle.currentState.stateHash,\n currentStateJson: JSON.stringify(bundle.currentState),\n currentPayloadJson: JSON.stringify(bundle.currentPayload),\n currentProjectionJson: JSON.stringify(bundle.currentProjection),\n currentGrantsJson: JSON.stringify(bundle.currentGrants),\n currentMemberEnvelopesJson: JSON.stringify(bundle.currentMemberEnvelopes),\n previousStatesJson: JSON.stringify(bundle.previousStates),\n updatedAt,\n };\n}\n\nfunction assertNoHeadConflict(\n incoming: StoredPrincipalPolicyHead,\n checkpoint: StoredPrincipalPolicyHead | null,\n): void {\n if (\n checkpoint &&\n incoming.version === checkpoint.version &&\n incoming.stateHash !== checkpoint.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle conflicts with the cached head at one version\",\n );\n }\n}\n\n/**\n * The replaced head stays as a retained bundle when it is an older valid\n * bundle; a corrupt cache row is dropped, never retained as key material.\n */\nasync function retirePrincipalPolicyHead(\n tx: ClientSQLiteTransactionScope,\n storedPolicy: SelectedPrincipalPolicyRow | undefined,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n if (!storedPolicy) {\n return;\n }\n const where = wherePrincipalPolicyBundle(storedPolicy);\n if (isRetainablePolicyHead(storedPolicy, storedHead, incomingHead)) {\n await tx\n .update(principalPolicyBundles)\n .set({ isCurrent: false })\n .where(where)\n .run();\n return;\n }\n await tx.delete(principalPolicyBundles).where(where).run();\n}\n\nfunction isRetainablePolicyHead(\n storedPolicy: SelectedPrincipalPolicyRow,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): boolean {\n if (!storedHead || storedHead.version >= incomingHead.version) {\n return false;\n }\n const row = parsePrincipalPolicyRow(storedPolicy);\n if (!row) {\n return false;\n }\n try {\n parsePrincipalPolicyBundle(row);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function writePrincipalPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n nextRow: PrincipalPolicyRow,\n incomingHead: StoredPrincipalPolicyHead,\n durablePin: Awaited<\n ReturnType<typeof recordPrincipalPolicyBundleOrganizationInTransaction>\n >,\n): Promise<void> {\n const { current: storedPolicy, retained: retainedPolicy } =\n await loadCurrentAndRetainedPolicyBundles(tx, nextRow);\n const durableCheckpoint = durablePin\n ? storedPrincipalPolicyPin(durablePin)\n : null;\n const storedHead = storedPolicy\n ? parseStoredPrincipalPolicyHead(storedPolicy.currentStateJson)\n : null;\n if (\n storedPolicy &&\n storedHead?.version === incomingHead.version &&\n storedHead.stateHash === incomingHead.stateHash\n ) {\n assertSameHeadPrincipalPolicyBundle(storedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n if (retainedPolicy) {\n assertSameHeadPrincipalPolicyBundle(retainedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n }\n const effectiveHead =\n durableCheckpoint &&\n (!storedHead || durableCheckpoint.version >= storedHead.version)\n ? durableCheckpoint\n : storedHead;\n assertNoHeadConflict(incomingHead, storedHead);\n assertNoHeadConflict(incomingHead, durableCheckpoint ?? null);\n if (effectiveHead && incomingHead.version < effectiveHead.version) {\n return;\n }\n\n // Promotion flips the head flag; a retained row at this hash becomes current.\n await retirePrincipalPolicyHead(tx, storedPolicy, storedHead, incomingHead);\n const currentRow = { ...nextRow, isCurrent: true };\n await tx\n .insert(principalPolicyBundles)\n .values(currentRow)\n .onConflictDoUpdate({\n target: [\n principalPolicyBundles.principalType,\n principalPolicyBundles.principalId,\n principalPolicyBundles.stateHash,\n ],\n set: currentRow,\n })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function writePrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const durableCheckpoint =\n await recordPrincipalPolicyBundleOrganizationInTransaction(\n tx,\n bundle,\n organizationId,\n );\n await writePrincipalPolicyBundle(\n tx,\n bundle,\n policyBundleRow(bundle, updatedAt),\n bundle.currentState,\n durableCheckpoint,\n );\n}\n\nexport async function assertPrincipalPolicyBundleStoredInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const expected = policyBundleRow(bundle, bundle.currentState.createdAt);\n const [stored] = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent(expected))\n .limit(1);\n if (!stored) {\n throw new Error(\"Verified principal policy bundle was not persisted\");\n }\n assertSameHeadPrincipalPolicyBundle(stored, expected);\n}\n\nexport async function retainPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const row = policyBundleRow(bundle, updatedAt);\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: row.principalId,\n principalType: row.principalType,\n });\n const { current, retained } = await loadCurrentAndRetainedPolicyBundles(\n tx,\n row,\n );\n const stored = current?.stateHash === row.stateHash ? current : retained;\n if (stored) {\n assertSameHeadPrincipalPolicyBundle(stored, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n await tx\n .insert(principalPolicyBundles)\n .values({ ...row, isCurrent: false })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function savePrincipalPolicyBundle(\n execSql: ExecSql,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n): Promise<void> {\n await ensureSqlTables(execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const save = (tx: ClientSQLiteTransactionScope) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n updatedAt,\n organizationId,\n );\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(save, options.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(save, { behavior: \"immediate\" });\n}\n"]}
1
+ {"version":3,"file":"principalPolicyPersistence.js","sourceRoot":"","sources":["principalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EACL,oDAAoD,EACpD,8CAA8C,GAC/C,MAAM,6DAA6D,CAAC;AACrE,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EAAE,uCAAuC,EAAE,MAAM,4CAA4C,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAkCpF,SAAS,sBAAsB,CAC7B,KAAa;IAEb,OAAO,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,cAAc,CAAC;AACvD,CAAC;AAED,SAAS,uBAAuB,CAC9B,GAA+B;IAE/B,IAAI,CAAC,sBAA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AC;SAC9B,MAAM,CAAC,EAAE,GAAG,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;SACpC,GAAG,EAAE,CAAC;IACT,MAAM,uCAAuC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, eq, or } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { storedPrincipalPolicyPin } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n recordPrincipalPolicyBundleOrganizationInTransaction,\n recordPrincipalPolicyOrganizationInTransaction,\n} from \"../keyingCheckpoints/principalPolicyOrganizationPersistence\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport { indexPrincipalPolicyBundleInTransaction } from \"./principalPolicyReferenceIndexPersistence\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface PrincipalPolicyRow {\n principalType: \"group\" | \"organization\";\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\nexport interface SelectedPrincipalPolicyRow {\n principalType: string;\n principalId: string;\n stateHash: string;\n isCurrent: boolean;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\ninterface StoredPrincipalPolicyHead {\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isManagedPrincipalType(\n value: string,\n): value is PrincipalStateResponse[\"principalType\"] {\n return value === \"group\" || value === \"organization\";\n}\n\nfunction parsePrincipalPolicyRow(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyRow | null {\n if (!isManagedPrincipalType(row.principalType)) {\n return null;\n }\n\n return {\n principalType: row.principalType,\n principalId: row.principalId,\n stateHash: row.stateHash,\n currentStateJson: row.currentStateJson,\n currentPayloadJson: row.currentPayloadJson,\n currentProjectionJson: row.currentProjectionJson,\n currentGrantsJson: row.currentGrantsJson,\n currentMemberEnvelopesJson: row.currentMemberEnvelopesJson,\n previousStatesJson: row.previousStatesJson,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction parseStoredPrincipalPolicyHead(\n currentStateJson: string,\n): StoredPrincipalPolicyHead | null {\n try {\n const value: unknown = JSON.parse(currentStateJson);\n if (!value || typeof value !== \"object\") {\n return null;\n }\n const stateHash = Reflect.get(value, \"stateHash\");\n const version = Reflect.get(value, \"version\");\n return typeof stateHash === \"string\" && typeof version === \"number\"\n ? { stateHash, version }\n : null;\n } catch {\n return null;\n }\n}\n\nfunction parsePrincipalPolicyBundle(\n row: PrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n\n return bundle;\n}\n\n/** A selected row's bundle; null when the row is not a managed principal. */\nexport function parseSelectedPrincipalPolicyBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse | null {\n const parsed = parsePrincipalPolicyRow(row);\n return parsed ? parsePrincipalPolicyBundle(parsed) : null;\n}\n\n/** The ONE select shape for a stored principal-policy bundle row. */\nexport const principalPolicyBundleSelection = {\n principalType: principalPolicyBundles.principalType,\n principalId: principalPolicyBundles.principalId,\n stateHash: principalPolicyBundles.stateHash,\n isCurrent: principalPolicyBundles.isCurrent,\n currentStateJson: principalPolicyBundles.currentStateJson,\n currentPayloadJson: principalPolicyBundles.currentPayloadJson,\n currentProjectionJson: principalPolicyBundles.currentProjectionJson,\n currentGrantsJson: principalPolicyBundles.currentGrantsJson,\n currentMemberEnvelopesJson: principalPolicyBundles.currentMemberEnvelopesJson,\n previousStatesJson: principalPolicyBundles.previousStatesJson,\n updatedAt: principalPolicyBundles.updatedAt,\n};\n\n/** Every stored bundle of one principal. */\nexport function wherePrincipalPolicyBundlePrincipal(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n eq(principalPolicyBundles.principalType, principal.principalType),\n eq(principalPolicyBundles.principalId, principal.principalId),\n );\n}\n\n/** The one current head of a principal. */\nexport function wherePrincipalPolicyCurrent(principal: {\n readonly principalType: string;\n readonly principalId: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(principal),\n eq(principalPolicyBundles.isCurrent, true),\n );\n}\n\nfunction wherePrincipalPolicyBundle(row: {\n readonly principalType: string;\n readonly principalId: string;\n readonly stateHash: string;\n}) {\n return and(\n wherePrincipalPolicyBundlePrincipal(row),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n );\n}\n\n/** A principal's current head and its retained bundle at `row`'s exact hash, in one read. */\nasync function loadCurrentAndRetainedPolicyBundles(\n tx: ClientSQLiteTransactionScope,\n row: PrincipalPolicyRow,\n) {\n const rows = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(row),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n eq(principalPolicyBundles.stateHash, row.stateHash),\n ),\n ),\n );\n return {\n current: rows.find((stored) => stored.isCurrent),\n retained: rows.find(\n (stored) => !stored.isCurrent && stored.stateHash === row.stateHash,\n ),\n };\n}\n\nfunction policyBundleRow(\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n): PrincipalPolicyRow {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n stateHash: bundle.currentState.stateHash,\n currentStateJson: JSON.stringify(bundle.currentState),\n currentPayloadJson: JSON.stringify(bundle.currentPayload),\n currentProjectionJson: JSON.stringify(bundle.currentProjection),\n currentGrantsJson: JSON.stringify(bundle.currentGrants),\n currentMemberEnvelopesJson: JSON.stringify(bundle.currentMemberEnvelopes),\n previousStatesJson: JSON.stringify(bundle.previousStates),\n updatedAt,\n };\n}\n\nfunction assertNoHeadConflict(\n incoming: StoredPrincipalPolicyHead,\n checkpoint: StoredPrincipalPolicyHead | null,\n): void {\n if (\n checkpoint &&\n incoming.version === checkpoint.version &&\n incoming.stateHash !== checkpoint.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle conflicts with the cached head at one version\",\n );\n }\n}\n\n/**\n * The replaced head stays as a retained bundle when it is an older valid\n * bundle; a corrupt cache row is dropped, never retained as key material.\n */\nasync function retirePrincipalPolicyHead(\n tx: ClientSQLiteTransactionScope,\n storedPolicy: SelectedPrincipalPolicyRow | undefined,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n if (!storedPolicy) {\n return;\n }\n const where = wherePrincipalPolicyBundle(storedPolicy);\n if (isRetainablePolicyHead(storedPolicy, storedHead, incomingHead)) {\n await tx\n .update(principalPolicyBundles)\n .set({ isCurrent: false })\n .where(where)\n .run();\n return;\n }\n await tx.delete(principalPolicyBundles).where(where).run();\n}\n\nfunction isRetainablePolicyHead(\n storedPolicy: SelectedPrincipalPolicyRow,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): boolean {\n if (!storedHead || storedHead.version >= incomingHead.version) {\n return false;\n }\n const row = parsePrincipalPolicyRow(storedPolicy);\n if (!row) {\n return false;\n }\n try {\n parsePrincipalPolicyBundle(row);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function writePrincipalPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n nextRow: PrincipalPolicyRow,\n incomingHead: StoredPrincipalPolicyHead,\n durablePin: Awaited<\n ReturnType<typeof recordPrincipalPolicyBundleOrganizationInTransaction>\n >,\n): Promise<void> {\n const { current: storedPolicy, retained: retainedPolicy } =\n await loadCurrentAndRetainedPolicyBundles(tx, nextRow);\n const durableCheckpoint = durablePin\n ? storedPrincipalPolicyPin(durablePin)\n : null;\n const storedHead = storedPolicy\n ? parseStoredPrincipalPolicyHead(storedPolicy.currentStateJson)\n : null;\n if (\n storedPolicy &&\n storedHead?.version === incomingHead.version &&\n storedHead.stateHash === incomingHead.stateHash\n ) {\n assertSameHeadPrincipalPolicyBundle(storedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n if (retainedPolicy) {\n assertSameHeadPrincipalPolicyBundle(retainedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n }\n const effectiveHead =\n durableCheckpoint &&\n (!storedHead || durableCheckpoint.version >= storedHead.version)\n ? durableCheckpoint\n : storedHead;\n assertNoHeadConflict(incomingHead, storedHead);\n assertNoHeadConflict(incomingHead, durableCheckpoint ?? null);\n if (effectiveHead && incomingHead.version < effectiveHead.version) {\n return;\n }\n\n // Promotion flips the head flag; a retained row at this hash becomes current.\n await retirePrincipalPolicyHead(tx, storedPolicy, storedHead, incomingHead);\n const currentRow = { ...nextRow, isCurrent: true };\n await tx\n .insert(principalPolicyBundles)\n .values(currentRow)\n .onConflictDoUpdate({\n target: [\n principalPolicyBundles.principalType,\n principalPolicyBundles.principalId,\n principalPolicyBundles.stateHash,\n ],\n set: currentRow,\n })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function writePrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const durableCheckpoint =\n await recordPrincipalPolicyBundleOrganizationInTransaction(\n tx,\n bundle,\n organizationId,\n );\n await writePrincipalPolicyBundle(\n tx,\n bundle,\n policyBundleRow(bundle, updatedAt),\n bundle.currentState,\n durableCheckpoint,\n );\n}\n\nexport async function assertPrincipalPolicyBundleStoredInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const expected = policyBundleRow(bundle, bundle.currentState.createdAt);\n const [stored] = await tx\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent(expected))\n .limit(1);\n if (!stored) {\n throw new Error(\"Verified principal policy bundle was not persisted\");\n }\n assertSameHeadPrincipalPolicyBundle(stored, expected);\n}\n\nexport async function retainPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const row = policyBundleRow(bundle, updatedAt);\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: row.principalId,\n principalType: row.principalType,\n });\n const { current, retained } = await loadCurrentAndRetainedPolicyBundles(\n tx,\n row,\n );\n const stored = current?.stateHash === row.stateHash ? current : retained;\n if (stored) {\n assertSameHeadPrincipalPolicyBundle(stored, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n await tx\n .insert(principalPolicyBundles)\n .values({ ...row, isCurrent: false })\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n"]}
@@ -3,9 +3,8 @@ import { isPrincipalPolicyBundleResponse, isReferencedPrincipalStateResponse, }
3
3
  import { and, eq, inArray, or } from "drizzle-orm";
4
4
  import { principalPolicyBundleContainsReference, principalPolicyBundleStates, } from "../../principals/principalPolicyStates.js";
5
5
  import { principalPolicyBundleReferences, principalPolicyBundles, } from "../../sqlite/schema/index.js";
6
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
7
6
  import { assertSameHeadPrincipalPolicyBundle } from "./principalPolicyBundleIntegrity.js";
8
- import { ensurePrincipalPolicyTables, principalPolicyBundleSelection, wherePrincipalPolicyBundlePrincipal, } from "./principalPolicyPersistence.js";
7
+ import { principalPolicyBundleSelection, wherePrincipalPolicyBundlePrincipal, } from "./principalPolicyPersistence.js";
9
8
  import { applyPrincipalPolicyReferenceCheckpoint } from "./principalPolicyReferenceCheckpoint.js";
10
9
  import { storedPrincipalPolicyBundleFromJson } from "./storedPrincipalPolicyBundle.js";
11
10
  function assertUnambiguousBundleChain(bundle) {
@@ -103,7 +102,7 @@ function selectNewestCandidate(candidates) {
103
102
  }
104
103
  return selected;
105
104
  }
106
- function assertReferenceShape(reference) {
105
+ export function assertReferenceShape(reference) {
107
106
  if (!isReferencedPrincipalStateResponse(reference)) {
108
107
  throw new KeyingVerificationError("invalid_shape", "principal policy reference is malformed");
109
108
  }
@@ -117,8 +116,7 @@ function assertReferenceShape(reference) {
117
116
  throw new KeyingVerificationError("invalid_shape", "principal policy reference is malformed");
118
117
  }
119
118
  }
120
- async function loadIndexedHeads(execSql, reference) {
121
- const { db } = getClientSQLitePersistenceRuntime(execSql);
119
+ async function loadIndexedHeads(db, reference) {
122
120
  return db
123
121
  .select({
124
122
  bundleStateHash: principalPolicyBundleReferences.bundleStateHash,
@@ -144,11 +142,10 @@ function indexHeadsByHash(heads) {
144
142
  return new Map(heads.map((head) => [head.bundleStateHash, head]));
145
143
  }
146
144
  /** The current head and the retained bundles at the referenced or indexed hashes, in one read. */
147
- async function loadReferencedRows(execSql, reference, indexedByHash) {
145
+ async function loadReferencedRows(db, reference, indexedByHash) {
148
146
  // Remote reset deliberately clears mutable heads while retaining historical
149
147
  // key material, so an index target can outlive its bundle row. Such a target
150
148
  // is only a selection hint; rows that still exist remain authoritative.
151
- const { db } = getClientSQLitePersistenceRuntime(execSql);
152
149
  const rows = await db
153
150
  .select(principalPolicyBundleSelection)
154
151
  .from(principalPolicyBundles)
@@ -188,11 +185,13 @@ function collectCandidates(currentRow, retainedRows, indexedByHash, reference) {
188
185
  }
189
186
  return candidates;
190
187
  }
191
- export async function loadPrincipalPolicyBundleForReference(execSql, reference, checkpoint) {
192
- assertReferenceShape(reference);
193
- await ensurePrincipalPolicyTables(execSql);
194
- const indexedByHash = indexHeadsByHash(await loadIndexedHeads(execSql, reference));
195
- const { currentRow, retainedRows } = await loadReferencedRows(execSql, reference, indexedByHash);
188
+ /**
189
+ * The newest stored bundle containing the exact reference, read after the
190
+ * caller checked its shape and ensured the principal policy tables.
191
+ */
192
+ export async function selectReferencedPrincipalPolicyBundle(db, reference, checkpoint) {
193
+ const indexedByHash = indexHeadsByHash(await loadIndexedHeads(db, reference));
194
+ const { currentRow, retainedRows } = await loadReferencedRows(db, reference, indexedByHash);
196
195
  const candidates = collectCandidates(currentRow, retainedRows, indexedByHash, reference);
197
196
  const selected = selectNewestCandidate(candidates);
198
197
  return selected
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACL,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAE9B,mCAAmC,GACpC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAC/F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CA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UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IACxC,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,OAAgB,EAChB,SAAkC,EAClC,UAA4C;IAE5C,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,aAAa,GAAG,gBAAgB,CACpC,MAAM,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,CAC3C,CAAC;IACF,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,MAAM,kBAAkB,CAC3D,OAAO,EACP,SAAS,EACT,aAAa,CACd,CAAC;IACF,MAAM,UAAU,GAAG,iBAAiB,CAClC,UAAU,EACV,YAAY,EACZ,aAAa,EACb,SAAS,CACV,CAAC;IACF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,OAAO,QAAQ;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../../principals/principalPolicyStates\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n} from \"../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n ensurePrincipalPolicyTables,\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n wherePrincipalPolicyBundlePrincipal,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nfunction assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadIndexedHeads(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\n/** The current head and the retained bundles at the referenced or indexed hashes, in one read. */\nasync function loadReferencedRows(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<{\n currentRow: SelectedPrincipalPolicyRow | undefined;\n retainedRows: SelectedPrincipalPolicyRow[];\n}> {\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(reference),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n inArray(principalPolicyBundles.stateHash, [\n ...new Set([reference.stateHash, ...indexedByHash.keys()]),\n ]),\n ),\n ),\n );\n return {\n currentRow: rows.find((row) => row.isCurrent),\n retainedRows: rows.filter((row) => !row.isCurrent),\n };\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\nexport async function loadPrincipalPolicyBundleForReference(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await ensurePrincipalPolicyTables(execSql);\n const indexedByHash = indexHeadsByHash(\n await loadIndexedHeads(execSql, reference),\n );\n const { currentRow, retainedRows } = await loadReferencedRows(\n execSql,\n reference,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAC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,EAAE,CAAC;QAC/B,MAAM,MAAM,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC;QACrC,MAAM,OAAO,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,OAAO,EAAE,CAAC;YACZ,mBAAmB,CAAC,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;QAClD,CAAC;aAAM,IAAI,CAAC,sCAAsC,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,CAAC;YACtE,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,wEAAwE,CACzE,CAAC;QACJ,CAAC;QACD,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IACxC,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,EAAwB,EACxB,SAAkC,EAClC,UAA4C;IAE5C,MAAM,aAAa,GAAG,gBAAgB,CAAC,MAAM,gBAAgB,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC;IAC9E,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,MAAM,kBAAkB,CAC3D,EAAE,EACF,SAAS,EACT,aAAa,CACd,CAAC;IACF,MAAM,UAAU,GAAG,iBAAiB,CAClC,UAAU,EACV,YAAY,EACZ,aAAa,EACb,SAAS,CACV,CAAC;IACF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,OAAO,QAAQ;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../../principals/principalPolicyStates\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n wherePrincipalPolicyBundlePrincipal,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nexport function assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadIndexedHeads(\n db: ClientSQLiteDatabase,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\n/** The current head and the retained bundles at the referenced or indexed hashes, in one read. */\nasync function loadReferencedRows(\n db: ClientSQLiteDatabase,\n reference: ReferencedPrincipalHead,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<{\n currentRow: SelectedPrincipalPolicyRow | undefined;\n retainedRows: SelectedPrincipalPolicyRow[];\n}> {\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(\n and(\n wherePrincipalPolicyBundlePrincipal(reference),\n or(\n eq(principalPolicyBundles.isCurrent, true),\n inArray(principalPolicyBundles.stateHash, [\n ...new Set([reference.stateHash, ...indexedByHash.keys()]),\n ]),\n ),\n ),\n );\n return {\n currentRow: rows.find((row) => row.isCurrent),\n retainedRows: rows.filter((row) => !row.isCurrent),\n };\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\n/**\n * The newest stored bundle containing the exact reference, read after the\n * caller checked its shape and ensured the principal policy tables.\n */\nexport async function selectReferencedPrincipalPolicyBundle(\n db: ClientSQLiteDatabase,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n const indexedByHash = indexHeadsByHash(await loadIndexedHeads(db, reference));\n const { currentRow, retainedRows } = await loadReferencedRows(\n db,\n reference,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
@@ -1,57 +1,41 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { keyingCheckpointTables } from "../../sqlite/schema/keyingCheckpointSchema.js";
3
- import { principalPolicyTables } from "../../sqlite/schema/principalPolicySchema.js";
4
- import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
5
- import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
2
  import { validatePrincipalPolicyCheckpointAdvances, writePrincipalPolicyCheckpoints, } from "../keyingCheckpoints/keyingCheckpointAdvancePersistence.js";
7
3
  import { loadStoredPrincipalPolicyCheckpoints, principalPolicyKey, } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
8
4
  import { assertPrincipalPolicyBundleStoredInTransaction, writePrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
9
5
  import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
10
- /**
11
- * Persists each verified full policy bundle together with its durable head.
12
- * This prevents a crash or bundle-write failure from leaving a checkpoint
13
- * without the exact same-head payload and member-envelope evidence.
14
- */
15
- export async function persistVerifiedPrincipalPolicyBundlesAtomically(input) {
6
+ /** Rejects a batch that repeats a principal or mismatches its verified policy. */
7
+ export async function assertVerifiedPrincipalPolicyBundles(entries) {
16
8
  const seen = new Set();
17
- for (const entry of input.entries) {
9
+ for (const entry of entries) {
18
10
  const key = principalPolicyKey(entry.policy);
19
11
  if (seen.has(key)) {
20
12
  throw new KeyingVerificationError("duplicate_entry", `verified policy bundle batch repeats ${key}`);
21
13
  }
22
14
  seen.add(key);
23
15
  }
24
- await Promise.all(input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)));
25
- await ensureSqlTables(input.execSql, [
26
- ...principalPolicyTables,
27
- ...keyingCheckpointTables,
16
+ await Promise.all(entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)));
17
+ }
18
+ /**
19
+ * Writes each verified bundle with its durable head, then reads both back, so
20
+ * a checkpoint never lands without its exact same-head bundle.
21
+ */
22
+ export async function persistVerifiedPrincipalPolicyBundlesInTransaction(tx, input, updatedAt) {
23
+ const policies = await validatePrincipalPolicyCheckpointAdvances(tx, input.entries.map((entry) => entry.policy));
24
+ for (const entry of input.entries) {
25
+ await writePrincipalPolicyBundleInTransaction(tx, entry.bundle, updatedAt, input.organizationId);
26
+ await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);
27
+ }
28
+ await writePrincipalPolicyCheckpoints(tx, policies, updatedAt, input.organizationId);
29
+ const stored = await loadStoredPrincipalPolicyCheckpoints(tx, [
30
+ ...policies.values(),
28
31
  ]);
29
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
30
- const persist = async (tx) => {
31
- const policies = await validatePrincipalPolicyCheckpointAdvances(tx, input.entries.map((entry) => entry.policy));
32
- for (const entry of input.entries) {
33
- await writePrincipalPolicyBundleInTransaction(tx, entry.bundle, input.updatedAt, input.organizationId);
34
- await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);
35
- }
36
- await writePrincipalPolicyCheckpoints(tx, policies, input.updatedAt, input.organizationId);
37
- const stored = await loadStoredPrincipalPolicyCheckpoints(tx, [
38
- ...policies.values(),
39
- ]);
40
- for (const policy of policies.values()) {
41
- const checkpoint = stored.get(principalPolicyKey(policy));
42
- if (!checkpoint ||
43
- checkpoint.version !== policy.version ||
44
- checkpoint.stateHash !== policy.stateHash) {
45
- throw new Error("Verified principal policy checkpoint was not persisted");
46
- }
32
+ for (const policy of policies.values()) {
33
+ const checkpoint = stored.get(principalPolicyKey(policy));
34
+ if (!checkpoint ||
35
+ checkpoint.version !== policy.version ||
36
+ checkpoint.stateHash !== policy.stateHash) {
37
+ throw new Error("Verified principal policy checkpoint was not persisted");
47
38
  }
48
- };
49
- if (input.stillCurrent) {
50
- await runtime.guardedTransaction(persist, input.stillCurrent, {
51
- behavior: "immediate",
52
- });
53
- return;
54
39
  }
55
- await runtime.transaction(persist, { behavior: "immediate" });
56
40
  }
57
41
  //# sourceMappingURL=verifiedPrincipalPolicyBundlePersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyBundlePersistence.js","sourceRoot":"","sources":["verifiedPrincipalPolicyBundlePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,yCAAyC,EACzC,+BAA+B,GAChC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,oCAAoC,EACpC,kBAAkB,GACnB,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,8CAA8C,EAC9C,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAOpF;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,+CAA+C,CAAC,KAMrE;IACC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QAClC,MAAM,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAClB,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,wCAAwC,GAAG,EAAE,CAC9C,CAAC;QACJ,CAAC;QACD,IAAI,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X,UAAU,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;gBACrC,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EACzC,CAAC;gBACD,MAAM,IAAI,KAAK,CACb,wDAAwD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalPolicyTables } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n validatePrincipalPolicyCheckpointAdvances,\n writePrincipalPolicyCheckpoints,\n} from \"../keyingCheckpoints/keyingCheckpointAdvancePersistence\";\nimport {\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n} from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\ninterface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n const seen = new Set<string>();\n for (const entry of input.entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const persist = async (tx: ClientSQLiteTransactionScope) => {\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n input.updatedAt,\n input.organizationId,\n );\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, [\n ...policies.values(),\n ]);\n for (const policy of policies.values()) {\n const checkpoint = stored.get(principalPolicyKey(policy));\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\n \"Verified principal policy checkpoint was not persisted\",\n );\n }\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(persist, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(persist, { behavior: \"immediate\" });\n}\n"]}
1
+ {"version":3,"file":"verifiedPrincipalPolicyBundlePersistence.js","sourceRoot":"","sources":["verifiedPrincipalPolicyBundlePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,yCAAyC,EACzC,+BAA+B,GAChC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,oCAAoC,EACpC,kBAAkB,GACnB,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,8CAA8C,EAC9C,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAOpF,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAsD;IAEtD,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAClB,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,wCAAwC,GAAG,EAAE,CAC9C,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC;IACD,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,iCAAiC,CAAC,KAAK,CAAC,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,kDAAkD,CACtE,EAAgC,EAChC,KAGC,EACD,SAAiB;IAEjB,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,EAAE,EACF,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAC3C,CAAC;IACF,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QAClC,MAAM,uCAAuC,CAC3C,EAAE,EACF,KAAK,CAAC,MAAM,EACZ,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,MAAM,8CAA8C,CAAC,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACzE,CAAC;IACD,MAAM,+BAA+B,CACnC,EAAE,EACF,QAAQ,EACR,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,oCAAoC,CAAC,EAAE,EAAE;QAC5D,GAAG,QAAQ,CAAC,MAAM,EAAE;KACrB,CAAC,CAAC;IACH,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACvC,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1D,IACE,CAAC,UAAU;YACX,UAAU,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;YACrC,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EACzC,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;QAC5E,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n validatePrincipalPolicyCheckpointAdvances,\n writePrincipalPolicyCheckpoints,\n} from \"../keyingCheckpoints/keyingCheckpointAdvancePersistence\";\nimport {\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n} from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/** Rejects a batch that repeats a principal or mismatches its verified policy. */\nexport async function assertVerifiedPrincipalPolicyBundles(\n entries: readonly VerifiedPrincipalPolicyBundleEntry[],\n): Promise<void> {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n}\n\n/**\n * Writes each verified bundle with its durable head, then reads both back, so\n * a checkpoint never lands without its exact same-head bundle.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n },\n updatedAt: string,\n): Promise<void> {\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n input.organizationId,\n );\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, [\n ...policies.values(),\n ]);\n for (const policy of policies.values()) {\n const checkpoint = stored.get(principalPolicyKey(policy));\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\"Verified principal policy checkpoint was not persisted\");\n }\n }\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  import { computePrincipalStateHash, computePrincipalStatePayloadCiphertextHash, } from "../../internal/crypto/index.js";
2
2
  import { KeyingCheckpointRepository } from "../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
- import { loadPrincipalPolicyBundle } from "../persistence/principalPolicy/principalPolicyPersistence.js";
3
+ import { PrincipalPolicyBundleRepository } from "../persistence/principalPolicy/principalPolicyBundleRepository.js";
4
4
  import { parseOrganizationAuthorityDescriptor } from "./organizationAuthorityDescriptor.js";
5
5
  /** Public labels come only from a descriptor pinned by prior verification. */
6
6
  export async function loadVerifiedOrganizationGroupRoles(execSql, organizationId) {
7
7
  const checkpoint = await new KeyingCheckpointRepository(execSql).loadPrincipalPolicyCheckpoint("organization", organizationId);
8
- const bundle = await loadPrincipalPolicyBundle(execSql, "organization", organizationId);
8
+ const bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundle("organization", organizationId);
9
9
  if (!checkpoint || !bundle)
10
10
  return new Map();
11
11
  const state = bundle.currentState;
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupRoles.js","sourceRoot":"","sources":["organizationGroupRoles.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,0CAA0C,GAC3C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,6DAA6D,CAAC;AACzG,OAAO,EAAE,yBAAyB,EAAE,MAAM,2DAA2D,CAAC;AAEtG,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AAEzF,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAAgB,EAChB,cAAsB;IAEtB,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,OAAO,CACR,CAAC,6BAA6B,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,yBAAyB,CAC5C,OAAO,EACP,cAAc,EACd,cAAc,CACf,CAAC;IACF,IAAI,CAAC,UAAU,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,GAAG,EAAE,CAAC;IAC7C,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,CAAC;IAClC,IACE,KAAK,CAAC,aAAa,KAAK,cAAc;QACtC,KAAK,CAAC,WAAW,KAAK,cAAc;QACpC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO;QACpC,KAAK,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS;QACxC,CAAC,MAAM,yBAAyB,CAAC,KAAK,CAAC,CAAC,KAAK,UAAU,CAAC,SAAS;QACjE,CAAC,MAAM,0CAA0C,CAC/C,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC,KAAK,KAAK,CAAC,qBAAqB;QAElC,OAAO,IAAI,GAAG,EAAE,CAAC;IACnB,MAAM,UAAU,GAAG,oCAAoC,CACrD,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC;IACF,IAAI,UAAU,CAAC,cAAc,KAAK,cAAc;QAAE,OAAO,IAAI,GAAG,EAAE,CAAC;IACnE,OAAO,IAAI,GAAG,CAAC;QACb,CAAC,UAAU,CAAC,YAAY,EAAE,QAAQ,CAAC;QACnC,CAAC,UAAU,CAAC,aAAa,EAAE,SAAS,CAAC;KACtC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n computePrincipalStatePayloadCiphertextHash,\n} from \"@tearleads/crypto\";\nimport { KeyingCheckpointRepository } from \"../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { loadPrincipalPolicyBundle } from \"../persistence/principalPolicy/principalPolicyPersistence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { parseOrganizationAuthorityDescriptor } from \"./organizationAuthorityDescriptor\";\n\n/** Public labels come only from a descriptor pinned by prior verification. */\nexport async function loadVerifiedOrganizationGroupRoles(\n execSql: ExecSql,\n organizationId: string,\n): Promise<ReadonlyMap<string, string>> {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", organizationId);\n const bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n organizationId,\n );\n if (!checkpoint || !bundle) return new Map();\n const state = bundle.currentState;\n if (\n state.principalType !== \"organization\" ||\n state.principalId !== organizationId ||\n state.version !== checkpoint.version ||\n state.stateHash !== checkpoint.stateHash ||\n (await computePrincipalStateHash(state)) !== checkpoint.stateHash ||\n (await computePrincipalStatePayloadCiphertextHash(\n bundle.currentPayload.ciphertext,\n )) !== state.payloadCiphertextHash\n )\n return new Map();\n const descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== organizationId) return new Map();\n return new Map([\n [descriptor.adminGroupId, \"Admins\"],\n [descriptor.memberGroupId, \"Members\"],\n ]);\n}\n"]}
1
+ {"version":3,"file":"organizationGroupRoles.js","sourceRoot":"","sources":["organizationGroupRoles.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,0CAA0C,GAC3C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,6DAA6D,CAAC;AACzG,OAAO,EAAE,+BAA+B,EAAE,MAAM,gEAAgE,CAAC;AAEjH,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AAEzF,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAAgB,EAChB,cAAsB;IAEtB,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,OAAO,CACR,CAAC,6BAA6B,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,IAAI,+BAA+B,CACtD,OAAO,CACR,CAAC,yBAAyB,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IAC5D,IAAI,CAAC,UAAU,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,GAAG,EAAE,CAAC;IAC7C,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,CAAC;IAClC,IACE,KAAK,CAAC,aAAa,KAAK,cAAc;QACtC,KAAK,CAAC,WAAW,KAAK,cAAc;QACpC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO;QACpC,KAAK,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS;QACxC,CAAC,MAAM,yBAAyB,CAAC,KAAK,CAAC,CAAC,KAAK,UAAU,CAAC,SAAS;QACjE,CAAC,MAAM,0CAA0C,CAC/C,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC,KAAK,KAAK,CAAC,qBAAqB;QAElC,OAAO,IAAI,GAAG,EAAE,CAAC;IACnB,MAAM,UAAU,GAAG,oCAAoC,CACrD,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC;IACF,IAAI,UAAU,CAAC,cAAc,KAAK,cAAc;QAAE,OAAO,IAAI,GAAG,EAAE,CAAC;IACnE,OAAO,IAAI,GAAG,CAAC;QACb,CAAC,UAAU,CAAC,YAAY,EAAE,QAAQ,CAAC;QACnC,CAAC,UAAU,CAAC,aAAa,EAAE,SAAS,CAAC;KACtC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n computePrincipalStatePayloadCiphertextHash,\n} from \"@tearleads/crypto\";\nimport { KeyingCheckpointRepository } from \"../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { parseOrganizationAuthorityDescriptor } from \"./organizationAuthorityDescriptor\";\n\n/** Public labels come only from a descriptor pinned by prior verification. */\nexport async function loadVerifiedOrganizationGroupRoles(\n execSql: ExecSql,\n organizationId: string,\n): Promise<ReadonlyMap<string, string>> {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", organizationId);\n const bundle = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundle(\"organization\", organizationId);\n if (!checkpoint || !bundle) return new Map();\n const state = bundle.currentState;\n if (\n state.principalType !== \"organization\" ||\n state.principalId !== organizationId ||\n state.version !== checkpoint.version ||\n state.stateHash !== checkpoint.stateHash ||\n (await computePrincipalStateHash(state)) !== checkpoint.stateHash ||\n (await computePrincipalStatePayloadCiphertextHash(\n bundle.currentPayload.ciphertext,\n )) !== state.payloadCiphertextHash\n )\n return new Map();\n const descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== organizationId) return new Map();\n return new Map([\n [descriptor.adminGroupId, \"Admins\"],\n [descriptor.memberGroupId, \"Members\"],\n ]);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { unwrapDek } from "../../internal/crypto/index.js";
2
2
  import { base64ToBytes } from "../../internal/encoding/index.js";
3
- import { loadPrincipalKeyEnvelopeCandidates, } from "../persistence/principalKeys/principalKeyEnvelopeCandidates.js";
3
+ import { PrincipalPolicyBundleRepository } from "../persistence/principalPolicy/principalPolicyBundleRepository.js";
4
4
  function toKeyEnvelopeEntries(envelopes) {
5
5
  return envelopes.map((envelope) => ({
6
6
  keyFingerprint: envelope.keyFingerprint,
@@ -19,7 +19,7 @@ function principalBundleKey(bundle) {
19
19
  return `${bundle.principalType}:${bundle.principalId}`;
20
20
  }
21
21
  async function createPrincipalPolicyResolutionContext(execSql, fingerprints) {
22
- const bundles = await loadPrincipalKeyEnvelopeCandidates(execSql, fingerprints);
22
+ const bundles = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalKeyEnvelopeCandidates(fingerprints);
23
23
  const bundlesByKeyFingerprint = new Map();
24
24
  for (const bundle of bundles) {
25
25
  const matchingBundles = bundlesByKeyFingerprint.get(bundle.currentState.keyFingerprint) ?? [];
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCrypto.js","sourceRoot":"","sources":["principalPolicyCrypto.ts"],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AK,CAAC,SAAS,EAAE,CAAC;QACvC,IAAI,qBAAqB,CAAC,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC;YAAE,SAAS;QACjE,qBAAqB,CAAC,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;QACnD,MAAM,gBAAgB,GACpB,OAAO,CAAC,uBAAuB,CAAC,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;QAErE,KAAK,MAAM,MAAM,IAAI,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC;gBACH,MAAM,kBAAkB,GAAG,MAAM,wBAAwB,CACvD,MAAM,EACN,KAAK,CAAC,SAAS,CAChB,CAAC;gBAEF,OAAO,MAAM,SAAS,CAAC,UAAU,EAAE,kBAAkB,CAAC,CAAC;YACzD,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;QACZ,CAAC;IACH,CAAC;IAED,MAAM,IAAI,KAAK,CACb,uFAAuF,CACxF,CAAC;AACJ,CAAC","sourcesContent":["import { type RecipientEntry, unwrapDek } from \"@tearleads/crypto\";\nimport { base64ToBytes } from \"@tearleads/encoding\";\nimport type { PrincipalMemberEnvelopeResponse } from \"@tearleads/validators/response\";\nimport type { SerializedKeyEnvelope } from \"@tearleads/validators/util\";\nimport {\n loadPrincipalKeyEnvelopeCandidates,\n type PrincipalKeyEnvelopeCandidate,\n} from \"../persistence/principalKeys/principalKeyEnvelopeCandidates\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\n\ninterface PrincipalPolicyResolutionContext {\n bundlesByKeyFingerprint: ReadonlyMap<\n string,\n ReadonlyArray<PrincipalKeyEnvelopeCandidate>\n >;\n}\n\nfunction toKeyEnvelopeEntries(\n envelopes: ReadonlyArray<SerializedKeyEnvelope>,\n): RecipientEntry[] {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.keyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\nfunction toMemberEnvelopeEntries(\n envelopes: ReadonlyArray<PrincipalMemberEnvelopeResponse>,\n): RecipientEntry[] {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.memberKeyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\nfunction principalBundleKey(\n bundle: Pick<\n PrincipalKeyEnvelopeCandidate[\"currentState\"],\n \"principalType\" | \"principalId\"\n >,\n): string {\n return `${bundle.principalType}:${bundle.principalId}`;\n}\n\nasync function createPrincipalPolicyResolutionContext(\n execSql: ExecSql,\n fingerprints: readonly string[],\n): Promise<PrincipalPolicyResolutionContext> {\n const bundles = await loadPrincipalKeyEnvelopeCandidates(\n execSql,\n fingerprints,\n );\n const bundlesByKeyFingerprint = new Map<\n string,\n PrincipalKeyEnvelopeCandidate[]\n >();\n\n for (const bundle of bundles) {\n const matchingBundles =\n bundlesByKeyFingerprint.get(bundle.currentState.keyFingerprint) ?? [];\n matchingBundles.push(bundle);\n bundlesByKeyFingerprint.set(\n bundle.currentState.keyFingerprint,\n matchingBundles,\n );\n }\n\n return {\n bundlesByKeyFingerprint,\n };\n}\n\nasync function unwrapPrincipalSecretKey(\n bundle: PrincipalKeyEnvelopeCandidate,\n secretKey: Uint8Array,\n): Promise<Uint8Array> {\n const principalKey = principalBundleKey(bundle.currentState);\n const memberEnvelopeEntries = toMemberEnvelopeEntries(\n bundle.currentMemberEnvelopes.envelopes,\n );\n\n try {\n return await unwrapDek(memberEnvelopeEntries, secretKey);\n } catch {\n // No transitive fallback: a principal's envelopes are all addressed to\n // users directly, so if this identity key opens none of them the requester\n // is not a member.\n }\n\n throw new Error(`No matching principal member envelope for ${principalKey}`);\n}\n\nexport async function unwrapKeyEnvelopesWithPrincipalPolicies(input: {\n envelopes: ReadonlyArray<SerializedKeyEnvelope>;\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n}): Promise<Uint8Array> {\n const keyEntries = toKeyEnvelopeEntries(input.envelopes);\n\n try {\n return await unwrapDek(keyEntries, input.secretKey);\n } catch {\n if (!input.execSql) {\n throw new Error(\n \"No matching key envelope entry found for this secret key and no principal policy cache is available\",\n );\n }\n }\n\n const context = await createPrincipalPolicyResolutionContext(\n input.execSql,\n input.envelopes.map((envelope) => envelope.keyFingerprint),\n );\n const attemptedFingerprints = new Set<string>();\n\n for (const envelope of input.envelopes) {\n if (attemptedFingerprints.has(envelope.keyFingerprint)) continue;\n attemptedFingerprints.add(envelope.keyFingerprint);\n const candidateBundles =\n context.bundlesByKeyFingerprint.get(envelope.keyFingerprint) ?? [];\n\n for (const bundle of candidateBundles) {\n try {\n const principalSecretKey = await unwrapPrincipalSecretKey(\n bundle,\n input.secretKey,\n );\n\n return await unwrapDek(keyEntries, principalSecretKey);\n } catch {}\n }\n }\n\n throw new Error(\n \"No matching key envelope entry found for this secret key or cached principal policies\",\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCrypto.js","sourceRoot":"","sources":["principalPolicyCrypto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAIpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,gEAAgE,CAAC;AAUjH,SAAS,oBAAoB,CAC3B,SAA+C;IAE/C,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QAClC,cAAc,EAAE,QAAQ,CAAC,cAAc;QACvC,aAAa,EAAE,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC;QACpD,UAAU,EAAE,aAAa,CAAC,QAAQ,CAAC,UAAU,CAAC;KAC/C,CAAC,CAAC,CAAC;AACN,CAAC;AAED,SAAS,uBAAuB,CAC9B,SAAyD;IAEzD,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QAClC,cAAc,EAAE,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AED,MAAM,IAAI,KAAK,CACb,uFAAuF,CACxF,CAAC;AACJ,CAAC","sourcesContent":["import { type RecipientEntry, unwrapDek } from \"@tearleads/crypto\";\nimport { base64ToBytes } from \"@tearleads/encoding\";\nimport type { PrincipalMemberEnvelopeResponse } from \"@tearleads/validators/response\";\nimport type { SerializedKeyEnvelope } from \"@tearleads/validators/util\";\nimport type { PrincipalKeyEnvelopeCandidate } from \"../persistence/principalKeys/principalKeyEnvelopeCandidates\";\nimport { PrincipalPolicyBundleRepository } from \"../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\n\ninterface PrincipalPolicyResolutionContext {\n bundlesByKeyFingerprint: ReadonlyMap<\n string,\n ReadonlyArray<PrincipalKeyEnvelopeCandidate>\n >;\n}\n\nfunction toKeyEnvelopeEntries(\n envelopes: ReadonlyArray<SerializedKeyEnvelope>,\n): RecipientEntry[] {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.keyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\nfunction toMemberEnvelopeEntries(\n envelopes: ReadonlyArray<PrincipalMemberEnvelopeResponse>,\n): RecipientEntry[] {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.memberKeyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\nfunction principalBundleKey(\n bundle: Pick<\n PrincipalKeyEnvelopeCandidate[\"currentState\"],\n \"principalType\" | \"principalId\"\n >,\n): string {\n return `${bundle.principalType}:${bundle.principalId}`;\n}\n\nasync function createPrincipalPolicyResolutionContext(\n execSql: ExecSql,\n fingerprints: readonly string[],\n): Promise<PrincipalPolicyResolutionContext> {\n const bundles = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalKeyEnvelopeCandidates(fingerprints);\n const bundlesByKeyFingerprint = new Map<\n string,\n PrincipalKeyEnvelopeCandidate[]\n >();\n\n for (const bundle of bundles) {\n const matchingBundles =\n bundlesByKeyFingerprint.get(bundle.currentState.keyFingerprint) ?? [];\n matchingBundles.push(bundle);\n bundlesByKeyFingerprint.set(\n bundle.currentState.keyFingerprint,\n matchingBundles,\n );\n }\n\n return {\n bundlesByKeyFingerprint,\n };\n}\n\nasync function unwrapPrincipalSecretKey(\n bundle: PrincipalKeyEnvelopeCandidate,\n secretKey: Uint8Array,\n): Promise<Uint8Array> {\n const principalKey = principalBundleKey(bundle.currentState);\n const memberEnvelopeEntries = toMemberEnvelopeEntries(\n bundle.currentMemberEnvelopes.envelopes,\n );\n\n try {\n return await unwrapDek(memberEnvelopeEntries, secretKey);\n } catch {\n // No transitive fallback: a principal's envelopes are all addressed to\n // users directly, so if this identity key opens none of them the requester\n // is not a member.\n }\n\n throw new Error(`No matching principal member envelope for ${principalKey}`);\n}\n\nexport async function unwrapKeyEnvelopesWithPrincipalPolicies(input: {\n envelopes: ReadonlyArray<SerializedKeyEnvelope>;\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n}): Promise<Uint8Array> {\n const keyEntries = toKeyEnvelopeEntries(input.envelopes);\n\n try {\n return await unwrapDek(keyEntries, input.secretKey);\n } catch {\n if (!input.execSql) {\n throw new Error(\n \"No matching key envelope entry found for this secret key and no principal policy cache is available\",\n );\n }\n }\n\n const context = await createPrincipalPolicyResolutionContext(\n input.execSql,\n input.envelopes.map((envelope) => envelope.keyFingerprint),\n );\n const attemptedFingerprints = new Set<string>();\n\n for (const envelope of input.envelopes) {\n if (attemptedFingerprints.has(envelope.keyFingerprint)) continue;\n attemptedFingerprints.add(envelope.keyFingerprint);\n const candidateBundles =\n context.bundlesByKeyFingerprint.get(envelope.keyFingerprint) ?? [];\n\n for (const bundle of candidateBundles) {\n try {\n const principalSecretKey = await unwrapPrincipalSecretKey(\n bundle,\n input.secretKey,\n );\n\n return await unwrapDek(keyEntries, principalSecretKey);\n } catch {}\n }\n }\n\n throw new Error(\n \"No matching key envelope entry found for this secret key or cached principal policies\",\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.199",
3
+ "version": "0.1.201",
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,5 +1,5 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
- import { loadPrincipalPolicyBundle } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
2
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
3
3
  import { principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
4
  import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
5
5
  import { verifyDirectoryGroup } from "../groupNames/groupNameUniqueness.js";
@@ -9,7 +9,7 @@ import { assertMetadataRootBinding } from "./groupMetadataRootBinding.js";
9
9
  export function createGroupMetadataContainerVerifier(input) {
10
10
  return async (state) => {
11
11
  assertProjectionVerificationCurrent(input.stillCurrent);
12
- const cached = await loadPrincipalPolicyBundle(input.execSql, "organization", input.organizationId);
12
+ const cached = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
13
13
  let authority = await loadGroupNameDirectoryAuthority({
14
14
  ...input,
15
15
  organizationPolicyReference: cached
@@ -1 +1 @@
1
- {"version":3,"file":"groupMetadataContainerAuthority.js","sourceRoot":"","sources":["groupMetadataContainerAuthority.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,yBAAyB,EAAE,MAAM,sEAAsE,CAAC;AACjH,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0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C,UAAU;YAChC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;SAC/C,EACD,UAAU,CACX,CAAC;QACF,yBAAyB,CAAC;YACxB,SAAS;YACT,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAC1D,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { verifyDirectoryGroup } from \"../groupNames/groupNameUniqueness\";\nimport { loadGroupNameDirectoryAuthority } from \"../groupNames/organizationGroupNamePolicies\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\ntype Input = Omit<\n Parameters<typeof loadGroupNameDirectoryAuthority>[0],\n \"organizationPolicyReference\"\n> & { readonly reportSecurityIncident: SecurityIncidentReporter };\n\n/** A public system slot alone cannot bind a self-authorized root to an organization. */\nexport function createGroupMetadataContainerVerifier(input: Input) {\n return async (state: ContainerAccessManifestState): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const cached = await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n let authority = await loadGroupNameDirectoryAuthority({\n ...input,\n organizationPolicyReference: cached\n ? principalPolicyReferenceFromBundle(cached)\n : null,\n });\n if (\n cached &&\n authority &&\n state.referencedPrincipalHeads.some(\n (head) =>\n !authority?.descriptor.groupHeads.some((known) =>\n principalHeadMatchesReference(head, known),\n ),\n )\n ) {\n authority = await loadGroupNameDirectoryAuthority(input);\n }\n if (!authority)\n throw new Error(\"Organization metadata authority is unavailable\");\n const memberHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.memberGroupId,\n );\n const members = await verifyDirectoryGroup(\n {\n ...input,\n descriptor: authority.descriptor,\n externalAuthority: authority.externalAuthority,\n },\n memberHead,\n );\n assertMetadataRootBinding({\n authority,\n members,\n organizationId: input.organizationId,\n state,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n };\n}\n"]}
1
+ {"version":3,"file":"groupMetadataContainerAuthority.js","sourceRoot":"","sources":["groupMetadataContainerAuthority.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAE1G,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,+BAA+B,EAAE,MAAM,6CAA6C,CAAC;AAC9F,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAOvE,wFAAwF;AACxF,MAAM,UAAU,oCAAoC,CAAC,KAAY;IAC/D,OAAO,KAAK,EAAE,KAAmC,EAAiB,EAAE;QAClE,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,MAAM,GAAG,MAAM,IAAI,+BAA+B,CACtD,KAAK,CAAC,OAAO,CACd,CAAC,yBAAyB,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;QAClE,IAAI,SAAS,GAAG,MAAM,+BAA+B,CAAC;YACpD,GAAG,KAAK;YACR,2BAA2B,EAAE,MAAM;gBACjC,CAAC,CAAC,kCAAkC,CAAC,MAAM,CAAC;gBAC5C,CAAC,CAAC,IAAI;SACT,CAAC,CAAC;QACH,IACE,MAAM;YACN,SAAS;YACT,KAAK,CAAC,wBAAwB,CAAC,IAAI,CACjC,CAAC,IAAI,EAAE,EAAE,CACP,CAAC,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAC/C,6BAA6B,CAAC,IAAI,EAAE,KAAK,CAAC,CAC3C,CACJ,EACD,CAAC;YACD,SAAS,GAAG,MAAM,+BAA+B,CAAC,KAAK,CAAC,CAAC;QAC3D,CAAC;QACD,IAAI,CAAC,SAAS;YACZ,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACpE,MAAM,UAAU,GAAG,4BAA4B,CAC7C,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,aAAa,CACxB,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,oBAAoB,CACxC;YACE,GAAG,KAAK;YACR,UAAU,EAAE,SAAS,CAAC,UAAU;YAChC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;SAC/C,EACD,UAAU,CACX,CAAC;QACF,yBAAyB,CAAC;YACxB,SAAS;YACT,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAC1D,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { verifyDirectoryGroup } from \"../groupNames/groupNameUniqueness\";\nimport { loadGroupNameDirectoryAuthority } from \"../groupNames/organizationGroupNamePolicies\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\ntype Input = Omit<\n Parameters<typeof loadGroupNameDirectoryAuthority>[0],\n \"organizationPolicyReference\"\n> & { readonly reportSecurityIncident: SecurityIncidentReporter };\n\n/** A public system slot alone cannot bind a self-authorized root to an organization. */\nexport function createGroupMetadataContainerVerifier(input: Input) {\n return async (state: ContainerAccessManifestState): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n let authority = await loadGroupNameDirectoryAuthority({\n ...input,\n organizationPolicyReference: cached\n ? principalPolicyReferenceFromBundle(cached)\n : null,\n });\n if (\n cached &&\n authority &&\n state.referencedPrincipalHeads.some(\n (head) =>\n !authority?.descriptor.groupHeads.some((known) =>\n principalHeadMatchesReference(head, known),\n ),\n )\n ) {\n authority = await loadGroupNameDirectoryAuthority(input);\n }\n if (!authority)\n throw new Error(\"Organization metadata authority is unavailable\");\n const memberHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.memberGroupId,\n );\n const members = await verifyDirectoryGroup(\n {\n ...input,\n descriptor: authority.descriptor,\n externalAuthority: authority.externalAuthority,\n },\n memberHead,\n );\n assertMetadataRootBinding({\n authority,\n members,\n organizationId: input.organizationId,\n state,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n };\n}\n"]}
@@ -1,8 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { throwKeyingVerificationErrorWithContext } from "../../../data/keyingProjectionVerification/error.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
- import { loadPrincipalPolicyBundleForReference } from "../../../data/persistence/principalPolicy/principalPolicyReferencePersistence.js";
5
- import { retainVerifiedPrincipalPolicyBundle } from "../../../data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js";
4
+ import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
5
  import { principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
7
6
  import { principalPolicyReferenceFromBundle, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principals/principalPolicyAdminSigners.js";
8
7
  import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../../principals/policyVerification.js";
@@ -15,7 +14,7 @@ import { canonicalGroupNameKey, readGroupPolicyPayloadName, } from "../principal
15
14
  */
16
15
  async function loadDirectoryGroupBundle(input, head) {
17
16
  const localCheckpoint = await new KeyingCheckpointRepository(input.execSql).loadPrincipalPolicyCheckpoint("group", head.principalId);
18
- const cached = await loadPrincipalPolicyBundleForReference(input.execSql, head, localCheckpoint);
17
+ const cached = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundleForReference(head, localCheckpoint);
19
18
  const bundle = cached ??
20
19
  (await input.apiClient.getCurrentPrincipalPolicy("group", head.principalId));
21
20
  if (!bundle) {
@@ -135,9 +134,8 @@ export async function assertGroupNameUniqueInDirectory(input) {
135
134
  let retention = Promise.resolve();
136
135
  const verifyAndRetain = async (head) => {
137
136
  const group = await verifyDirectoryGroup(input, head);
138
- retention = retention.then(() => retainVerifiedPrincipalPolicyBundle({
137
+ retention = retention.then(() => new PrincipalPolicyBundleRepository(input.execSql).retainVerifiedPrincipalPolicyBundle({
139
138
  bundle: group.bundle,
140
- execSql: input.execSql,
141
139
  organizationId: input.organizationId,
142
140
  policy: group.policy,
143
141
  updatedAt: retainedAt,