@tearleads/client-sdk 0.1.230 → 0.1.231

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/data/principals/organizationPolicyRequest.d.ts +12 -0
  2. package/data/principals/organizationPolicyRequest.js +71 -0
  3. package/data/principals/organizationPolicyRequest.js.map +1 -0
  4. package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.d.ts +3 -3
  5. package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.js +3 -3
  6. package/data/principals/principalPolicyRequest.js.map +1 -0
  7. package/{workflows/principals/policyVerification.js → data/principals/principalPolicyVerification.js} +4 -4
  8. package/data/principals/principalPolicyVerification.js.map +1 -0
  9. package/package.json +1 -1
  10. package/workflows/organizations/groupMetadata/groupMetadataAccess.d.ts +1 -1
  11. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  12. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +1 -1
  13. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  14. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  15. package/workflows/organizations/groupNames/groupMembershipName.d.ts +1 -1
  16. package/workflows/organizations/groupNames/groupMembershipName.js +1 -1
  17. package/workflows/organizations/groupNames/groupMembershipName.js.map +1 -1
  18. package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
  19. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  20. package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
  21. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
  22. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  23. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  24. package/workflows/organizations/groupShare/currentShareGrantMutation.js +1 -1
  25. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
  26. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -1
  27. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
  28. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  29. package/workflows/organizations/groupShare/sharePrincipalPolicy.d.ts +1 -1
  30. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
  31. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  32. package/workflows/organizations/groupShare/shareWithGroup.d.ts +1 -1
  33. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  34. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  35. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  36. package/workflows/organizations/groups/groupCreation.js +1 -1
  37. package/workflows/organizations/groups/groupCreation.js.map +1 -1
  38. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  39. package/workflows/organizations/principalPolicy/index.d.ts +2 -2
  40. package/workflows/organizations/principalPolicy/index.js +1 -1
  41. package/workflows/organizations/principalPolicy/index.js.map +1 -1
  42. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  43. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  44. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  45. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  46. package/workflows/principals/externalAdminPolicy.js +1 -1
  47. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  48. package/workflows/principals/historyRecovery/principalHistoryPageAppend.js +1 -1
  49. package/workflows/principals/historyRecovery/principalHistoryPageAppend.js.map +1 -1
  50. package/workflows/principals/policyCache/index.js +1 -1
  51. package/workflows/principals/policyCache/index.js.map +1 -1
  52. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
  53. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  54. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
  55. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  56. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +1 -1
  57. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  58. package/workflows/registration/index.d.ts +2 -1
  59. package/workflows/registration/index.js +1 -1
  60. package/workflows/registration/index.js.map +1 -1
  61. package/workflows/registration/organizationProvisioning.d.ts +1 -12
  62. package/workflows/registration/organizationProvisioning.js +2 -70
  63. package/workflows/registration/organizationProvisioning.js.map +1 -1
  64. package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +0 -1
  65. package/workflows/principals/policyVerification.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,kDAAkD,CAAC;AAClG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AAClI,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EACL,uCAAuC,GAExC,MAAM,wCAAwC,CAAC;AAIhD,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EACL,kCAAkC,EAClC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,2BAA2B,EAC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AC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport { rethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n reportAndRethrowKeyingVerificationError,\n type SecurityIncidentReporter,\n} from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport { publishVerifiedPrincipalPolicy } from \"../policyVerification\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).ensurePrincipalPolicyTables();\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,kDAAkD,CAAC;AAClG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AAClI,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AACtG,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;A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BAA2B,CAAC,EAChD,OAAO,EACP,mBAAmB,EACnB,OAAO,EACP,GAAG,EACH,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,YAAY,GACuB;IACnC,MAAM,uBAAuB,CAAC;QAC5B,SAAS,EAAE,CAAC,MAAM,EAAE,uBAAuB,EAAE,aAAa,EAAE,EAAE,CAC5D,0BAA0B,CAAC;YACzB,MAAM;YACN,OAAO;YACP,uBAAuB;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport { rethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { publishVerifiedPrincipalPolicy } from \"../../../data/principals/principalPolicyVerification\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n reportAndRethrowKeyingVerificationError,\n type SecurityIncidentReporter,\n} from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).ensurePrincipalPolicyTables();\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { externalAuthorityCouldAuthorize, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
3
+ import { collectPrincipalPolicySignerPublicKeys, principalPolicyStates, } from "../../../data/principals/principalPolicyVerification.js";
3
4
  import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
4
- import { collectPrincipalPolicySignerPublicKeys, principalPolicyStates, } from "../policyVerification.js";
5
5
  function getBundleReferenceFailure(reference, bundle) {
6
6
  const states = principalPolicyStates(bundle);
7
7
  const hasReferencedPrincipal = states.some((state) => state.principalType === reference.principalType &&
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,8DAA8D,CAAC;AACtE,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAGlG,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAO/B,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,sDAAsD;SAChE,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW;QAC3C,K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AiB,EAAE,KAAK,CAAC,SAAS;QAClC,qBAAqB,EAAE,KAAK,IAAI,EAAE;YAChC,uBAAuB,GAAG,IAAI,CAAC;YAC/B,MAAM,SAAS,GAAG,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC;gBACvD,EAAE,iBAAiB,CAAC;YACtB,IAAI,SAAS;gBAAE,OAAO,SAAS,CAAC;YAChC,sEAAsE;YACtE,mEAAmE;YACnE,kEAAkE;YAClE,oEAAoE;YACpE,2DAA2D;YAC3D,IACE,MAAM,+BAA+B,CAAC;gBACpC,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;gBAC5D,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,iBAAiB,EAAE,KAAK,CAAC,SAAS;gBAClC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,8DAA8D,CAAC;AACtE,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AASlG,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,sDAAsD;SAChE,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW;QAC3C,KAAK,CAAC,OAAO,KAAK,SAAS,CAAC,OAAO;QACnC,KA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KAAK,IAAI,EAAE;YAChC,uBAAuB,GAAG,IAAI,CAAC;YAC/B,MAAM,SAAS,GAAG,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC;gBACvD,EAAE,iBAAiB,CAAC;YACtB,IAAI,SAAS;gBAAE,OAAO,SAAS,CAAC;YAChC,sEAAsE;YACtE,mEAAmE;YACnE,kEAAkE;YAClE,oEAAoE;YACpE,2DAA2D;YAC3D,IACE,MAAM,+BAA+B,CAAC;gBACpC,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;gBAC5D,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,iBAAiB,EAAE,KAAK,CAAC,SAAS;gBAClC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
@@ -4,7 +4,7 @@ import { KeyingCheckpointRepository } from "../../../data/persistence/keyingChec
4
4
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
5
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
6
6
  import { verifyOrganizationAdminPolicy } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
7
- import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../policyVerification.js";
7
+ import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../../../data/principals/principalPolicyVerification.js";
8
8
  export function directoryBindsGroupReference(directory, policy, reference) {
9
9
  const head = directory?.descriptor.groupHeads.find((head) => head.principalId === reference.principalId);
10
10
  // A newer directory head authenticates its verified predecessors too.
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,8DAA8D,CAAC;AAI7G,OAAO,EACL,sCAAsC,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,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;QACJ,CAAC;QACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;YACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0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AC;YACnC,MAAM;YACN,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;YAC5D,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,IAAI,UAA2C,CAAC;QAChD,IAAI,CAAC;YACH,UAAU,GAAG,oCAAoC,CAC/C,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;QACJ,CAAC;QACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;YACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
@@ -3,7 +3,7 @@ import { assertProjectionVerificationCurrent } from "../../../data/keyingProject
3
3
  import { preparePrincipalHistoryEvidencePage } from "../../../data/persistence/principalHistory/principalHistoryEvidencePersistence.js";
4
4
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
5
5
  import { principalHistoryStageProtection } from "../../../data/principals/principalHistoryStageProtection.js";
6
- import { collectPrincipalPolicySignerPublicKeys } from "../policyVerification.js";
6
+ import { collectPrincipalPolicySignerPublicKeys } from "../../../data/principals/principalPolicyVerification.js";
7
7
  import { loadPublicHistoryAuthority, publicHistoryAuthorityJson, publicHistoryAuthorityReference, } from "./publicPrincipalHistoryAuthority.js";
8
8
  export class PublicPrincipalHistoryPrefixDisconnectedError extends Error {
9
9
  verificationError;
@@ -1 +1 @@
1
- {"version":3,"file":"publicPrincipalHistoryPage.js","sourceRoot":"","sources":["publicPrincipalHistoryPage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,+BAA+B,EAAE,MAAM,0DAA0D,CAAC;AAC3G,OAAO,EAAE,sCAAsC,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAM3C,MAAM,OAAO,6CAA8C,SAAQ,KAAK;IACjD;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;QAE7D,IAAI,CAAC,IAAI,GAAG,+CAA+C,CAAC;IAC9D,CAAC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AQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KACnD,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyStateChainEntry,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicySnapshotPage } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHistoryStageProtection } from \"../../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../policyVerification\";\nimport {\n loadPublicHistoryAuthority,\n publicHistoryAuthorityJson,\n publicHistoryAuthorityReference,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nexport class PublicPrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PublicPrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction assertPublicAuthorityScope(\n input: PublicPrincipalHistoryOptions,\n entries: readonly PrincipalPolicyStateChainEntry[],\n): void {\n if (\n input.strictAdmins &&\n entries.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public Admins history must contain only direct admin users\",\n );\n if (\n entries.some(\n ({ state }) =>\n state.externalAuthority &&\n state.externalAuthority.principalId !== input.authorityGroupId,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history cites an authority outside its directory binding\",\n );\n}\n\nexport async function appendPublicPrincipalHistoryPage(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n page: PrincipalPolicySnapshotPage,\n): Promise<PublicPrincipalHistoryProgress> {\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n const complete = page.historyPage.nextAfterVersion === null;\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: page.currentState,\n projection: page.currentProjection,\n grants: page.currentGrants,\n });\n assertPublicAuthorityScope(input, entries);\n const predecessor = progress.verifier.getLatestAcceptedProjection();\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: page,\n // The page's first signer must be the identity the last accepted state\n // committed; nothing is pinned before the history reaches its head.\n predecessor,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Public history signer identity is unavailable or mismatched\",\n );\n const references = entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n );\n const externalAuthority = await loadPublicHistoryAuthority(input, references);\n assertProjectionVerificationCurrent(stillCurrent);\n const appended = await progress.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PublicPrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n const row = {\n id: progress.id,\n organizationId: input.organizationId,\n currentJson: publicHistoryAuthorityJson(\n publicHistoryAuthorityReference(progress.authorityReference, references),\n ),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.source.head,\n row,\n ),\n );\n if (!sealed.ok) throw sealed.error;\n const saved = { ...row, progress: sealed.value };\n await new PrincipalHistoryRepository(input.execSql).savePrincipalHistoryStage(\n {\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: progress.saved?.progress ?? null,\n stillCurrent,\n },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n ...progress,\n afterVersion: row.afterVersion,\n saved,\n authorityReference: publicHistoryAuthorityReference(\n progress.authorityReference,\n references,\n ),\n completedHead: complete ? input.source.head : null,\n };\n}\n"]}
1
+ {"version":3,"file":"publicPrincipalHistoryPage.js","sourceRoot":"","sources":["publicPrincipalHistoryPage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,+BAA+B,EAAE,MAAM,0DAA0D,CAAC;AAC3G,OAAO,EAAE,sCAAsC,EAAE,MAAM,sDAAsD,CAAC;AAC9G,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAM3C,MAAM,OAAO,6CAA8C,SAAQ,KAAK;IACjD;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;QAE7D,IAAI,CAAC,IAAI,GAAG,+CAA+C,CAAC;IAC9D,CAAC;CACF;AAED,SAAS,0BAA0B,CACjC,KAAoC,EACpC,OAAkD;IAElD,IACE,KAAK,CAAC,YAAY;QAClB,OAAO,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;YAC7B,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAA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KACT,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,QAAQ,CAAC,cAAc,CACnD,MAAM,+BAA+B,CACnC,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,MAAM,CAAC,IAAI,EACjB,GAAG,CACJ,CACF,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,MAAM,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;IACjD,MAAM,IAAI,0BAA0B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,yBAAyB,CAC3E;QACE,KAAK,EAAE,KAAK;QACZ,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO;YACP,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;QACF,gBAAgB,EAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,IAAI,IAAI;QAClD,YAAY;KACb,CACF,CAAC;IACF,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO;QACL,GAAG,QAAQ;QACX,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,KAAK;QACL,kBAAkB,EAAE,+BAA+B,CACjD,QAAQ,CAAC,kBAAkB,EAC3B,UAAU,CACX;QACD,aAAa,EAAE,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KACnD,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyStateChainEntry,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicySnapshotPage } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHistoryStageProtection } from \"../../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../../../data/principals/principalPolicyVerification\";\nimport {\n loadPublicHistoryAuthority,\n publicHistoryAuthorityJson,\n publicHistoryAuthorityReference,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nexport class PublicPrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PublicPrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction assertPublicAuthorityScope(\n input: PublicPrincipalHistoryOptions,\n entries: readonly PrincipalPolicyStateChainEntry[],\n): void {\n if (\n input.strictAdmins &&\n entries.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public Admins history must contain only direct admin users\",\n );\n if (\n entries.some(\n ({ state }) =>\n state.externalAuthority &&\n state.externalAuthority.principalId !== input.authorityGroupId,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history cites an authority outside its directory binding\",\n );\n}\n\nexport async function appendPublicPrincipalHistoryPage(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n page: PrincipalPolicySnapshotPage,\n): Promise<PublicPrincipalHistoryProgress> {\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n const complete = page.historyPage.nextAfterVersion === null;\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: page.currentState,\n projection: page.currentProjection,\n grants: page.currentGrants,\n });\n assertPublicAuthorityScope(input, entries);\n const predecessor = progress.verifier.getLatestAcceptedProjection();\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: page,\n // The page's first signer must be the identity the last accepted state\n // committed; nothing is pinned before the history reaches its head.\n predecessor,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Public history signer identity is unavailable or mismatched\",\n );\n const references = entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n );\n const externalAuthority = await loadPublicHistoryAuthority(input, references);\n assertProjectionVerificationCurrent(stillCurrent);\n const appended = await progress.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PublicPrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n const row = {\n id: progress.id,\n organizationId: input.organizationId,\n currentJson: publicHistoryAuthorityJson(\n publicHistoryAuthorityReference(progress.authorityReference, references),\n ),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.source.head,\n row,\n ),\n );\n if (!sealed.ok) throw sealed.error;\n const saved = { ...row, progress: sealed.value };\n await new PrincipalHistoryRepository(input.execSql).savePrincipalHistoryStage(\n {\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: progress.saved?.progress ?? null,\n stillCurrent,\n },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n ...progress,\n afterVersion: row.afterVersion,\n saved,\n authorityReference: publicHistoryAuthorityReference(\n progress.authorityReference,\n references,\n ),\n completedHead: complete ? input.source.head : null,\n };\n}\n"]}
@@ -1,8 +1,9 @@
1
+ export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
1
2
  export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
2
3
  export { type CreateOrganizationApi, type CreateOrganizationInput, createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
3
4
  export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
4
5
  export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
5
- export { buildInitialOrganizationPolicyRequest, type ProvisionedSystemContainerSpec, } from "./organizationProvisioning.js";
6
+ export type { ProvisionedSystemContainerSpec } from "./organizationProvisioning.js";
6
7
  export { persistRegistrationBootstrap } from "./persistRegistrationBootstrap.js";
7
8
  export { type RegisterIdentityInput, type RegistrationApi, registerIdentity, } from "./registerIdentity.js";
8
9
  export { principalPolicyBundleFromInitialGroupRequest } from "./registrationPrincipalPolicyPersistence.js";
@@ -1,8 +1,8 @@
1
+ export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
1
2
  export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
2
3
  export { createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
3
4
  export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
4
5
  export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
5
- export { buildInitialOrganizationPolicyRequest, } from "./organizationProvisioning.js";
6
6
  export { persistRegistrationBootstrap } from "./persistRegistrationBootstrap.js";
7
7
  export { registerIdentity, } from "./registerIdentity.js";
8
8
  export { principalPolicyBundleFromInitialGroupRequest } from "./registrationPrincipalPolicyPersistence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAGL,kBAAkB,EAClB,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AACnH,OAAO,EACL,qCAAqC,GAEtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAGL,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,4CAA4C,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,EACL,kCAAkC,GAEnC,MAAM,yBAAyB,CAAC","sourcesContent":["export { bootstrapRootContainer } from \"./bootstrapRootContainer\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationCreation/createOrganization\";\nexport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"./organizationCreation/organizationProvisioningAttempt\";\nexport { verifyOrganizationReplacementResponse } from \"./organizationCreation/organizationReplacementVerification\";\nexport {\n buildInitialOrganizationPolicyRequest,\n type ProvisionedSystemContainerSpec,\n} from \"./organizationProvisioning\";\nexport { persistRegistrationBootstrap } from \"./persistRegistrationBootstrap\";\nexport {\n type RegisterIdentityInput,\n type RegistrationApi,\n registerIdentity,\n} from \"./registerIdentity\";\nexport { principalPolicyBundleFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nexport {\n createInitialRootMetadataBootstrap,\n type InitialRootMetadataBootstrap,\n} from \"./rootMetadataBootstrap\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAGL,kBAAkB,EAClB,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AAEnH,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAGL,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,4CAA4C,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,EACL,kCAAkC,GAEnC,MAAM,yBAAyB,CAAC","sourcesContent":["export { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nexport { bootstrapRootContainer } from \"./bootstrapRootContainer\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationCreation/createOrganization\";\nexport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"./organizationCreation/organizationProvisioningAttempt\";\nexport { verifyOrganizationReplacementResponse } from \"./organizationCreation/organizationReplacementVerification\";\nexport type { ProvisionedSystemContainerSpec } from \"./organizationProvisioning\";\nexport { persistRegistrationBootstrap } from \"./persistRegistrationBootstrap\";\nexport {\n type RegisterIdentityInput,\n type RegistrationApi,\n registerIdentity,\n} from \"./registerIdentity\";\nexport { principalPolicyBundleFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nexport {\n createInitialRootMetadataBootstrap,\n type InitialRootMetadataBootstrap,\n} from \"./rootMetadataBootstrap\";\n"]}
@@ -1,5 +1,4 @@
1
- import { type EncapsulationKeyPair, type ReferencedPrincipalHead, type SigningKeyPair } from "../../internal/crypto/index.js";
2
- import type { RegistrationRequest } from "../../internal/validators/request/index.js";
1
+ import { type EncapsulationKeyPair, type SigningKeyPair } from "../../internal/crypto/index.js";
3
2
  import type { OrganizationProvisioningArtifacts } from "./organizationProvisioningArtifacts.js";
4
3
  import { type ProvisionedSystemContainerSpec } from "./provisioningBootstrapBuilders.js";
5
4
  export type { OrganizationProvisioningArtifacts } from "./organizationProvisioningArtifacts.js";
@@ -27,15 +26,5 @@ export interface OrganizationProvisioningArtifactsInput {
27
26
  signingKeyPair: SigningKeyPair;
28
27
  userId: string;
29
28
  }
30
- export declare function buildInitialOrganizationPolicyRequest(input: {
31
- identityTrustDomain: string;
32
- adminGroupId: string;
33
- groupHeads: readonly ReferencedPrincipalHead[];
34
- encapsulationPublicKey: Uint8Array;
35
- memberGroupId: string;
36
- organizationId: string;
37
- signingKeyPair: SigningKeyPair;
38
- userId: string;
39
- }): Promise<RegistrationRequest["initialOrganizationPolicy"]>;
40
29
  /** Builds the signed artifacts shared by registration and org creation. */
41
30
  export declare function buildOrganizationProvisioningArtifacts(input: OrganizationProvisioningArtifactsInput): Promise<OrganizationProvisioningArtifacts>;
@@ -1,82 +1,14 @@
1
1
  // Registration and additional-organization creation build and persist an
2
2
  // organization's founding policies, system containers, and profile documents
3
3
  // through this module.
4
- import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "../../internal/crypto/index.js";
5
- import { bytesToBase64 } from "../../internal/encoding/index.js";
6
- import { encodeOrganizationAuthorityDescriptor } from "../../data/principalContracts/organizationAuthorityDescriptor.js";
7
- import { createPrincipalProjectionMember } from "../../data/principalContracts/principalIdentityCommitments.js";
4
+ import { toFingerprint, } from "../../internal/crypto/index.js";
5
+ import { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
8
6
  import { resolveDocumentCreateAuthor } from "../documents/index.js";
9
7
  import { groupPolicyMutationHead } from "../organizations/groupPolicy/groupPolicyMutationHead.js";
10
8
  import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, } from "../organizations/principalPolicy/index.js";
11
9
  import { buildInitialOrganizationMetadataBootstrap, buildInitialRootProvisioning, buildInitialRosterProfileBootstrap, buildInitialSystemContainerBootstrap, } from "./provisioningBootstrapBuilders.js";
12
10
  import { createInitialRootMetadataBootstrap } from "./rootMetadataBootstrap.js";
13
11
  export { persistOrganizationProvisioningState } from "./organizationProvisioningPersistence.js";
14
- export async function buildInitialOrganizationPolicyRequest(input) {
15
- const organizationKem = generateKemSeedAndKeyPair();
16
- const signerUserKeyFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
17
- const userEncapsulationKeyFingerprint = await toFingerprint(input.encapsulationPublicKey);
18
- const projection = [
19
- await createPrincipalProjectionMember({
20
- userId: input.userId,
21
- identityTrustDomain: input.identityTrustDomain,
22
- signingPublicKey: input.signingKeyPair.signingPublicKey,
23
- encapsulationPublicKey: input.encapsulationPublicKey,
24
- }, "admin"),
25
- ];
26
- const payloadCiphertext = encodeOrganizationAuthorityDescriptor({
27
- version: 2,
28
- organizationId: input.organizationId,
29
- adminGroupId: input.adminGroupId,
30
- memberGroupId: input.memberGroupId,
31
- groupHeads: input.groupHeads.map((head) => {
32
- if (head.principalType !== "group") {
33
- throw new Error("Organization directory can contain only group heads");
34
- }
35
- return { ...head, principalType: "group" };
36
- }),
37
- });
38
- const [memberEnvelope] = await wrapDekForRecipients(organizationKem.secretKey, [input.encapsulationPublicKey]);
39
- if (!memberEnvelope) {
40
- throw new Error("Failed to wrap organization key for registering user");
41
- }
42
- const memberEnvelopes = [
43
- {
44
- userId: input.userId,
45
- memberKeyFingerprint: userEncapsulationKeyFingerprint,
46
- kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),
47
- wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),
48
- },
49
- ];
50
- const state = await signPrincipalState(await buildPrincipalStateSigningInput({
51
- principalType: "organization",
52
- principalId: input.organizationId,
53
- version: 1,
54
- prevStateHash: null,
55
- keyEpoch: 1,
56
- encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
57
- keyFingerprint: await toFingerprint(organizationKem.publicKey),
58
- members: [{ userId: input.userId }],
59
- memberEnvelopes,
60
- projection,
61
- grants: [],
62
- payloadCiphertext,
63
- externalAuthority: null,
64
- signedAt: new Date().toISOString(),
65
- signerUserId: input.userId,
66
- signerUserKeyFingerprint,
67
- }), input.signingKeyPair.signingPrivateKey);
68
- return {
69
- state,
70
- encryptedPayload: {
71
- cipherSuite: "aes-256-gcm",
72
- ciphertext: payloadCiphertext,
73
- ciphertextHash: state.payloadCiphertextHash,
74
- },
75
- projection,
76
- grants: [],
77
- memberEnvelopes,
78
- };
79
- }
80
12
  async function createOrganizationPrincipalPolicies(input) {
81
13
  const organizationId = crypto.randomUUID();
82
14
  const signingFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
@@ -1 +1 @@
1
- {"version":3,"file":"organizationProvisioning.js","sourceRoot":"","sources":["organizationProvisioning.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,OAAO,EACL,+BAA+B,EAE/B,yBAAyB,EAGzB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,EAAE,qCAAqC,EAAE,MAAM,+DAA+D,CAAC;AACtH,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,sDAAsD,CAAC;AAC/F,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EACL,yCAAyC,EACzC,4BAA4B,EAC5B,kCAAkC,EAClC,oCAAoC,GAErC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kCAAkC,E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O;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n generateKemSeedAndKeyPair,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { createPrincipalProjectionMember } from \"../../data/principalContracts/principalIdentityCommitments\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n identityTrustDomain: string;\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n await createPrincipalProjectionMember(\n {\n userId: input.userId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.encapsulationPublicKey,\n },\n \"admin\",\n ),\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
1
+ {"version":3,"file":"organizationProvisioning.js","sourceRoot":"","sources":["organizationProvisioning.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,OAAO,EAGL,aAAa,GACd,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,sDAAsD,CAAC;AAC/F,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EACL,yCAAyC,EACzC,4BAA4B,EAC5B,kCAAkC,EAClC,oCAAoC,GAErC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kCAAkC,EAAE,MAAM,yBAAyB,CAAC;AAG7E,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAoC7F,KAAK,UAAU,mCAAmC,CAAC,KAOlD;IACC,MAAM,cAAc,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAC3C,MAAM,kBAAkB,GAAG,MAAM,aAAa,CAC5C,KAAK,CAAC,cAAc,CAAC,gBAAgB,CACtC,CAAC;IACF,MAAM,iBAAiB,GAAG,MAAM,8BAA8B,CAAC;QAC7D,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,2BAA2B,EAAE,KAAK,CAAC,oBAAoB;QACvD,OAAO,EAAE,MAAM,CAAC,UAAU,EAAE;QAC5B,MAAM,EAAE;YACN,EAAE,WAAW,EAAE,KAAK,CAAC,eAAe,EAAE,WAAW,EAAE,OAAO,EAAE;YAC5D;gBACE,WAAW,EAAE,KAAK,CAAC,+BAA+B;gBAClD,WAAW,EAAE,OAAO;aACrB;SACF;QACD,IAAI,EAA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AAK,CAAC,oBAAoB,CAAC,SAAS;QAC5D,iBAAiB;QACjB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,aAAa;QACb,uBAAuB;QACvB,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACH,MAAM,6BAA6B,GACjC,MAAM,yCAAyC,CAAC;QAC9C,MAAM;QACN,WAAW,EAAE,+BAA+B;QAC5C,iBAAiB;QACjB,kBAAkB;QAClB,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,aAAa;QACb,uBAAuB;QACvB,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACL,MAAM,yBAAyB,GAAG,MAAM,OAAO,CAAC,GAAG,CACjD,CAAC,KAAK,CAAC,2BAA2B,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,oCAAoC,CAAC;QACnC,MAAM;QACN,iBAAiB;QACjB,aAAa;QACb,uBAAuB;QACvB,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC,iBAAiB;QACzD,IAAI;QACJ,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CACH,CACF,CAAC;IAEF,OAAO;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n type EncapsulationKeyPair,\n type SigningKeyPair,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyRequest.js","sourceRoot":"","sources":["principalPolicyRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAE/B,0BAA0B,EAC1B,oBAAoB,EAEpB,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,EAGnC,iBAAiB,EAEjB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAQpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAmBhH,SAAS,wBAAwB,CAC/B,UAA2D;IAE3D,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AACjE,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,8BAA8B,CAAC,IAAY;IAClD,OAAO,uDAAuD,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC5E,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,OAAO,CACL,IAAI;SACD,SAAS,C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QACpC,GAAG,KAAK;QACR,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,SAAS;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n encodeBuiltinGroupMetadata,\n encryptGroupMetadata,\n type GroupMetadataKey,\n generateKemSeedAndKeyPair,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type PrincipalContainerGrant,\n type PrincipalPolicyExternalAuthority,\n readGroupMetadata,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { createPrincipalProjectionMember } from \"../../../data/principalContracts/principalIdentityCommitments\";\n\ninterface BuildInitialGroupPolicyInput {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly externalAuthority?:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly includeSignerAsAdmin?: boolean;\n readonly name: string;\n readonly metadataKey?: GroupMetadataKey;\n readonly builtinRole?: \"admins\" | \"members\";\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}\n\nfunction projectionToStateMembers(\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n) {\n return projection.map((member) => ({ userId: member.userId }));\n}\n\n/**\n * Code points that must never appear in a group name: control and format\n * characters (bidi overrides, zero-width joiners, newlines), lone surrogates\n * (re-encoded as U+FFFD when signed, so the signed name would no longer match\n * the one sent to the server), and every other default-ignorable code point\n * (Hangul fillers, variation selectors), which render as nothing and would\n * let one name pass for another. A group name is an identifier here, so this\n * deliberately refuses ZWJ emoji sequences as well. One predicate serves the\n * signing-time and the share-time refusal so the two cannot drift.\n */\nfunction hasForbiddenGroupNameCharacter(name: string): boolean {\n return /[\\p{Cc}\\p{Cf}\\p{Cs}\\p{Default_Ignorable_Code_Point}]/u.test(name);\n}\n\n/**\n * The comparison key for a group display name: width- and compatibility-\n * normalized, stripped of control, format, and default-ignorable characters,\n * whitespace-collapsed, and case-folded. Two names that a user cannot tell\n * apart in a picker must compare equal, or a look-alike name would slip past\n * the share-time binding. Cross-script homoglyphs (Latin \"A\" against Greek\n * \"Α\") are not folded: that needs the UTS #39 confusables table, and both\n * names would still have to be signed groups the organization's own admins\n * created.\n */\nexport function canonicalGroupNameKey(name: string): string {\n return (\n name\n .normalize(\"NFKC\")\n .replace(/[\\p{Cc}\\p{Cf}\\p{Default_Ignorable_Code_Point}]/gu, \"\")\n .replace(/\\s+/gu, \" \")\n .trim()\n .toLocaleLowerCase(\"en-US\")\n // Case folding can leave the string un-normalized (U+0130 lowercases to\n // \"i\" plus a combining dot), so normalize once more after it.\n .normalize(\"NFKC\")\n );\n}\n\ntype GroupPolicyNameInput = Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentPayload\"\n>;\n\nexport type GroupPolicyNameReader = (\n bundle: GroupPolicyNameInput,\n) => Promise<string>;\n\n/** Read only after the policy and its organization-directory binding verify. */\nexport async function readGroupPolicyPayloadName(\n bundle: GroupPolicyNameInput,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<string> {\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (!readEncryptedName)\n throw new Error(\"Group metadata decryption context is unavailable\");\n return readEncryptedName(bundle);\n}\n\n/** One binding predicate for every operation selected by a read-model label. */\nexport async function groupPolicyNameMismatch(\n bundle: GroupPolicyNameInput,\n expectedGroupName: string,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<\"forbidden_characters\" | \"name_mismatch\" | null> {\n if (hasForbiddenGroupNameCharacter(expectedGroupName)) {\n return \"forbidden_characters\";\n }\n const signedName = await readGroupPolicyPayloadName(\n bundle,\n readEncryptedName,\n );\n if (hasForbiddenGroupNameCharacter(signedName)) return \"forbidden_characters\";\n return canonicalGroupNameKey(signedName) ===\n canonicalGroupNameKey(expectedGroupName)\n ? null\n : \"name_mismatch\";\n}\n\nexport async function signedGroupPolicyRequest(input: {\n readonly currentPolicy?: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly encapsulationPublicKey: string;\n readonly externalAuthority:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly grants: ReadonlyArray<PrincipalContainerGrant>;\n readonly memberEnvelopes: ReadonlyArray<PrincipalMemberEnvelopeRequest>;\n readonly payloadCiphertext: string;\n readonly principalId: string;\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly signedAt: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.projection);\n const grants = normalizePrincipalContainerGrants(input.grants);\n const payloadCiphertext = input.payloadCiphertext;\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"group\",\n principalId: input.principalId,\n version: input.currentPolicy\n ? input.currentPolicy.currentState.version + 1\n : 1,\n prevStateHash: input.currentPolicy?.currentState.stateHash ?? null,\n keyEpoch: input.keyEpoch,\n encapsulationPublicKey: input.encapsulationPublicKey,\n keyFingerprint: input.keyFingerprint,\n members: projectionToStateMembers(projection),\n memberEnvelopes: [...input.memberEnvelopes],\n projection,\n grants,\n payloadCiphertext,\n externalAuthority: input.externalAuthority,\n signedAt: input.signedAt,\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants,\n memberEnvelopes: [...input.memberEnvelopes],\n };\n}\n\nexport async function buildInitialGroupPolicyRequest(\n input: BuildInitialGroupPolicyInput,\n): Promise<CreateOrganizationGroupRequest> {\n const groupKem = generateKemSeedAndKeyPair();\n const withSigner = input.includeSignerAsAdmin ?? true;\n const projection = withSigner\n ? [\n await createPrincipalProjectionMember(\n {\n userId: input.signerUserId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.creatorEncapsulationKeyPair.publicKey,\n },\n \"admin\",\n ),\n ]\n : [];\n const memberEnvelopes: PrincipalMemberEnvelopeRequest[] = [];\n\n if (withSigner) {\n const creatorFingerprint = await toFingerprint(\n input.creatorEncapsulationKeyPair.publicKey,\n );\n const [creatorEnvelope] = await wrapDekForRecipients(groupKem.secretKey, [\n input.creatorEncapsulationKeyPair.publicKey,\n ]);\n\n if (!creatorEnvelope) {\n throw new Error(\"Failed to wrap group key for creator\");\n }\n\n memberEnvelopes.push({\n userId: input.signerUserId,\n memberKeyFingerprint: creatorFingerprint,\n kemCipherText: bytesToBase64(creatorEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(creatorEnvelope.wrappedKey),\n });\n }\n const name = input.name.trim();\n // A name is compared by canonical key but displayed raw, so an invisible\n // code point would let one signed name render as another. Refuse them\n // where the name is signed.\n if (name.length === 0 || hasForbiddenGroupNameCharacter(name)) {\n throw new Error(\n \"Group names must be non-empty and contain no control, format, or surrogate characters\",\n );\n }\n const payloadCiphertext = input.builtinRole\n ? encodeBuiltinGroupMetadata(input.builtinRole)\n : input.metadataKey\n ? await encryptGroupMetadata({\n key: input.metadataKey,\n groupId: input.groupId,\n name,\n })\n : (() => {\n throw new Error(\"Group metadata encryption context is unavailable\");\n })();\n const policyRequest = await signedGroupPolicyRequest({\n encapsulationPublicKey: bytesToBase64(groupKem.publicKey),\n externalAuthority: input.externalAuthority ?? null,\n keyEpoch: 1,\n keyFingerprint: await toFingerprint(groupKem.publicKey),\n grants: input.grants ?? [],\n memberEnvelopes,\n payloadCiphertext,\n principalId: input.groupId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n\n return {\n groupId: input.groupId,\n initialGroupPolicy: policyRequest,\n };\n}\n\n/**\n * Members at bootstrap holds the registering user alone.\n *\n * It used to also contain the Admins group as a nested member, so that admins\n * were implicitly members. Principals contain only users now, so an admin is an\n * ordinary Members entry — and bootstrap has exactly one user, who is that\n * admin.\n */\nexport async function buildInitialMemberGroupPolicyRequest(input: {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<CreateOrganizationGroupRequest> {\n return buildInitialGroupPolicyRequest({\n ...input,\n name: \"Members\",\n builtinRole: \"members\",\n });\n}\n"]}