@tearleads/client-sdk 0.1.111 → 0.1.113

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 (81) hide show
  1. package/Tearleads.js +0 -2
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/index.js +5 -1
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +5 -1
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/identity/userIdentities.d.ts +13 -8
  8. package/client/identity/userIdentities.js +4 -22
  9. package/client/identity/userIdentities.js.map +1 -1
  10. package/client/index.d.ts +2 -2
  11. package/client/index.js +1 -0
  12. package/client/index.js.map +1 -1
  13. package/client/organizations/index.d.ts +1 -1
  14. package/client/organizations/index.js +12 -9
  15. package/client/organizations/index.js.map +1 -1
  16. package/client/organizations/organizationsTypes.d.ts +1 -2
  17. package/client/organizations/organizationsTypes.js.map +1 -1
  18. package/client/runtime/workflowRuntime.d.ts +1 -1
  19. package/client/runtime/workflowRuntime.js.map +1 -1
  20. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +16 -11
  21. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  22. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js +150 -2
  23. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -1
  24. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js +3 -2
  25. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -1
  26. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.d.ts +14 -1
  27. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js +128 -34
  28. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -1
  29. package/data/persistence/principalHistory/principalHistoryNodeRetention.js +64 -24
  30. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -1
  31. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js +6 -1
  32. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -1
  33. package/data/persistence/principalHistory/principalHistoryRootOwnership.d.ts +45 -0
  34. package/data/persistence/principalHistory/principalHistoryRootOwnership.js +41 -4
  35. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -1
  36. package/data/persistence/principalHistory/principalHistoryStagePersistence.js +12 -8
  37. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -1
  38. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js +35 -1
  39. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -1
  40. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js +62 -1
  41. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -1
  42. package/data/persistence/trustedUserIdentityPinPersistence.js +70 -21
  43. package/data/persistence/trustedUserIdentityPinPersistence.js.map +1 -1
  44. package/data/persistence/verifiedManifestBundlePersistence.js +27 -10
  45. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  46. package/data/sqlite/schema/index.d.ts +45 -5
  47. package/data/sqlite/schema/index.js +14 -6
  48. package/data/sqlite/schema/index.js.map +1 -1
  49. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.d.ts +222 -0
  50. package/data/trustedUserIdentity/admission.d.ts +10 -0
  51. package/data/trustedUserIdentity/admission.js +15 -0
  52. package/data/trustedUserIdentity/admission.js.map +1 -0
  53. package/data/trustedUserIdentity/index.d.ts +1 -0
  54. package/data/trustedUserIdentity/index.js +1 -0
  55. package/data/trustedUserIdentity/index.js.map +1 -1
  56. package/data/trustedUserIdentity/service.d.ts +1 -5
  57. package/data/trustedUserIdentity/service.js +119 -46
  58. package/data/trustedUserIdentity/service.js.map +1 -1
  59. package/data/trustedUserIdentity/types.d.ts +12 -1
  60. package/data/trustedUserIdentity/types.js.map +1 -1
  61. package/index.d.ts +3 -3
  62. package/index.js +2 -2
  63. package/index.js.map +1 -1
  64. package/package.json +1 -1
  65. package/stores/container-contents/containerContentsStore.js +10 -1
  66. package/stores/container-contents/containerContentsStore.js.map +1 -1
  67. package/workflows/container-contents/runtime.d.ts +7 -1
  68. package/workflows/container-contents/runtime.js +2 -1
  69. package/workflows/container-contents/runtime.js.map +1 -1
  70. package/workflows/organizations/index.d.ts +0 -1
  71. package/workflows/organizations/index.js +0 -1
  72. package/workflows/organizations/index.js.map +1 -1
  73. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +13 -12
  74. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  75. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +17 -19
  76. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  77. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +8 -10
  78. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  79. package/workflows/organizations/organizationUserImport.d.ts +0 -8
  80. package/workflows/organizations/organizationUserImport.js +0 -10
  81. package/workflows/organizations/organizationUserImport.js.map +0 -1
@@ -1,5 +1,6 @@
1
1
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
2
- import { cancelStripeSubscription, checkNativePurchaseEligibility, claimNativeOrganizationSubscription, createStripeCheckout, createStripeCheckoutSession, importOrganizationUser, listLocalOrganizations, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, loadStripeCheckoutOptions, startOrganizationTrial, updateOrganizationProfile, updateOrganizationRosterEntry, withVerifiedDirectoryUser, } from "../../workflows/organizations/index.js";
2
+ import { DatabaseUnavailableError } from "../../data/sync/databaseUnavailable.js";
3
+ import { cancelStripeSubscription, checkNativePurchaseEligibility, claimNativeOrganizationSubscription, createStripeCheckout, createStripeCheckoutSession, listLocalOrganizations, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, loadStripeCheckoutOptions, startOrganizationTrial, updateOrganizationProfile, updateOrganizationRosterEntry, withVerifiedDirectoryUser, } from "../../workflows/organizations/index.js";
3
4
  import { createOrganizationDataUsageCoordinator, } from "./organizationDataUsage.js";
4
5
  import { loadOrganizationGroupPresentationDetails } from "./organizationGroupPresentation.js";
5
6
  import { createOrganizationMemberships, } from "./organizationMemberships.js";
@@ -25,11 +26,20 @@ class OrganizationsService {
25
26
  this.memberships = createOrganizationMemberships(this.runtimeService, this.containerContents, openReconciler);
26
27
  }
27
28
  async addUserToGroup(input) {
29
+ // Group membership admits a user: only a verified identity link or this
30
+ // device's own keys can establish the identity it is granted to.
31
+ // The check reads the trust store of the scope this mutation captured, and
32
+ // that scope must still be current once it returns.
33
+ const mutation = currentOrganizationMutation(this.runtimeService);
34
+ await this.runtimeService.identityLinks.requireVerified(input.targetUserId, mutation.runtime.infra.execSql);
35
+ if (!mutation.stillCurrent()) {
36
+ throw new DatabaseUnavailableError("The active database changed while admitting this user. Try again.");
37
+ }
28
38
  return addUserToOrganizationGroup({
29
39
  ...input,
30
40
  containerContents: this.containerContents,
31
41
  readModelCoordinator: this.readModelCoordinator,
32
- ...currentOrganizationMutation(this.runtimeService),
42
+ ...mutation,
33
43
  });
34
44
  }
35
45
  readPendingPolicyMutation(organizationId) {
@@ -56,13 +66,6 @@ class OrganizationsService {
56
66
  ...currentOrganizationMutation(this.runtimeService),
57
67
  });
58
68
  }
59
- importUserById(userId) {
60
- const runtime = this.runtimeService.workflowInput();
61
- return importOrganizationUser({
62
- resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
63
- userId,
64
- });
65
- }
66
69
  loadBilling() {
67
70
  return runForOrganization(this.runtimeService, loadOrganizationBilling);
68
71
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAC9B,mCAAmC,EACnC,oBA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oB,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE;gBACjD,cAAc;gBACd,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE;aAClC,CAAC,CACH,CACF,CAAC;IACJ,CAAC;IAED,aAAa,CAAC,iBAAgC;QAC5C,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC;QACpD,MAAM,cAAc,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;QAC5D,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAED,OAAO,yBAAyB,CAAC;YAC/B,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,cAAc;YACd,iBAAiB;SAClB,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,KAAuC;QAC/D,OAAO,+BAA+B,CAAC;YACrC,GAAG,KAAK;YACR,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,GAAG,2BAA2B,CAAC,IAAI,CAAC,cAAc,CAAC;SACpD,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,KAA2B;QAC3C,OAAO,uBAAuB,CAAC;YAC7B,GAAG,KAAK;YACR,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,GAAG,2BAA2B,CAAC,IAAI,CAAC,cAAc,CAAC;SACpD,CAAC,CAAC;IACL,CAAC;IAED,UAAU,CAAC,cAAuB;QAChC,OAAO,kBAAkB,CACvB,IAAI,CAAC,cAAc,EACnB,sBAAsB,EACtB,cAAc,CACf,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { NativeSubscriptionStore } from \"@tearleads/validators/billing\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n cancelStripeSubscription,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createStripeCheckout,\n createStripeCheckoutSession,\n importOrganizationUser,\n listLocalOrganizations,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n startOrganizationTrial,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n withVerifiedDirectoryUser,\n} from \"../../workflows/organizations\";\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n createOrganizationDataUsageCoordinator,\n type OrganizationDataUsageCoordinator,\n} from \"./organizationDataUsage\";\nimport { loadOrganizationGroupPresentationDetails } from \"./organizationGroupPresentation\";\nimport {\n createOrganizationMemberships,\n type OrganizationContentReconciler,\n type OrganizationMemberships,\n} from \"./organizationMemberships\";\nimport {\n createOrganizationReadModelCoordinator,\n leaveRequestVerifier,\n type OrganizationReadModelCoordinator,\n} from \"./organizationReadModels\";\nimport type { Organizations } from \"./organizationsTypes\";\nimport {\n authenticatedOrganizationId,\n runForOrganization,\n} from \"./organizationWorkflowRuntime\";\nimport {\n type AbandonOrganizationPolicyMutationInput,\n abandonPendingOrganizationPolicyMutation,\n type DiscardUnreadableOrganizationPolicyMutationInput,\n discardUnreadableOrganizationPolicyMutation,\n readPendingOrganizationPolicyMutation,\n retryPendingOrganizationPolicyMutation,\n} from \"./principalMutationRecovery\";\nimport { currentOrganizationMutation } from \"./principalMutationScope\";\nimport {\n type AddOrganizationGroupUserInput,\n addUserToOrganizationGroup,\n createGroupForOrganization,\n deleteGroupForOrganization,\n type OrganizationGrantRef,\n type RemoveOrganizationGroupUserInput,\n removeUserFromOrganizationGroup,\n revokeOrganizationGrant,\n} from \"./principalMutations\";\n\nexport type {\n ImportedOrganizationUser,\n LocalOrganizationSummary,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\n OrganizationUserDetail,\n} from \"../../workflows/organizations\";\nexport type {\n OrganizationContentReconciler,\n OrganizationMemberships,\n} from \"./organizationMemberships\";\nexport type {\n OrganizationGroupMutationReceipt,\n Organizations,\n} from \"./organizationsTypes\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n} from \"./principalMutationRecovery\";\nexport type {\n AddOrganizationGroupUserInput,\n OrganizationGrantRef,\n RemoveOrganizationGroupUserInput,\n} from \"./principalMutations\";\n\nexport function createOrganizations(\n runtime: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): Organizations {\n return new OrganizationsService(runtime, containerContents, openReconciler);\n}\n\nclass OrganizationsService implements Organizations {\n readonly memberships: OrganizationMemberships;\n private readonly dataUsageCoordinator: OrganizationDataUsageCoordinator;\n private readonly readModelCoordinator: OrganizationReadModelCoordinator;\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n ) {\n this.dataUsageCoordinator = createOrganizationDataUsageCoordinator(\n this.runtimeService,\n );\n this.readModelCoordinator = createOrganizationReadModelCoordinator(\n this.runtimeService,\n );\n this.memberships = createOrganizationMemberships(\n this.runtimeService,\n this.containerContents,\n openReconciler,\n );\n }\n\n async addUserToGroup(input: AddOrganizationGroupUserInput) {\n return addUserToOrganizationGroup({\n ...input,\n containerContents: this.containerContents,\n readModelCoordinator: this.readModelCoordinator,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n readPendingPolicyMutation(organizationId: string) {\n return readPendingOrganizationPolicyMutation(\n this.runtimeService,\n organizationId,\n );\n }\n\n discardUnreadablePolicyMutation(\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n ) {\n return discardUnreadableOrganizationPolicyMutation(\n this.runtimeService,\n input,\n );\n }\n\n retryPendingPolicyMutation(organizationId: string) {\n return retryPendingOrganizationPolicyMutation(\n this.runtimeService,\n organizationId,\n );\n }\n\n abandonPendingPolicyMutation(input: AbandonOrganizationPolicyMutationInput) {\n return abandonPendingOrganizationPolicyMutation(this.runtimeService, input);\n }\n\n createGroup(name: string) {\n return createGroupForOrganization({\n name,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n deleteGroup(groupId: string) {\n return deleteGroupForOrganization({\n groupId,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n importUserById(userId: string) {\n const runtime = this.runtimeService.workflowInput();\n return importOrganizationUser({\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n userId,\n });\n }\n\n loadBilling() {\n return runForOrganization(this.runtimeService, loadOrganizationBilling);\n }\n\n loadBillingForOrganization(organizationId: string) {\n // Gated on an authenticated session rather than on the target being the\n // active org. The server still enforces membership, so an org the caller\n // cannot reach resolves to `null`.\n return runForOrganization(\n this.runtimeService,\n loadOrganizationBilling,\n organizationId,\n );\n }\n\n loadBillingHistory() {\n return runForOrganization(\n this.runtimeService,\n loadOrganizationBillingHistory,\n );\n }\n\n loadBillingManagementUrl() {\n return runForOrganization(\n this.runtimeService,\n loadOrganizationBillingManagementUrl,\n );\n }\n\n loadStripeCheckoutOptions(organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n loadStripeCheckoutOptions,\n organizationId,\n );\n }\n\n createStripeCheckout(organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n createStripeCheckout,\n organizationId,\n );\n }\n\n createStripeCheckoutSession(returnUrl: string, organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n (input) => createStripeCheckoutSession({ ...input, returnUrl }),\n organizationId,\n );\n }\n\n cancelStripeSubscription() {\n return runForOrganization(this.runtimeService, cancelStripeSubscription);\n }\n\n claimNativeSubscription(\n organizationId: string,\n store: NativeSubscriptionStore,\n ) {\n return runForOrganization(\n this.runtimeService,\n (input) => claimNativeOrganizationSubscription({ ...input, store }),\n organizationId,\n );\n }\n\n checkNativePurchaseEligibility(\n organizationId: string,\n store: NativeSubscriptionStore,\n ) {\n return runForOrganization(\n this.runtimeService,\n (input) => checkNativePurchaseEligibility({ ...input, store }),\n organizationId,\n );\n }\n\n loadDataUsage() {\n return this.dataUsageCoordinator.reconcile();\n }\n\n loadLocalDataUsage() {\n return this.dataUsageCoordinator.loadLocal();\n }\n\n loadDirectoryAndGroups() {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: runtime.auth.organizationId,\n objectKind: \"principal\",\n operation: \"organization.read_model.reconcile\",\n organizationId: runtime.auth.organizationId,\n },\n () => this.readModelCoordinator.reconcile(),\n );\n }\n\n loadDirectoryAndGroupsAfterMutation() {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: runtime.auth.organizationId,\n objectKind: \"principal\",\n operation: \"organization.read_model.reconcile_after_mutation\",\n organizationId: runtime.auth.organizationId,\n },\n () => this.readModelCoordinator.reconcileAfterMutation(),\n );\n }\n\n loadLocalDirectoryAndGroups() {\n return this.readModelCoordinator.loadLocal();\n }\n\n loadGroupMembers(groupId: string) {\n const runtime = this.runtimeService.workflowInput();\n const organizationId = authenticatedOrganizationId(runtime);\n if (!organizationId || groupId.length === 0) {\n return Promise.resolve(null);\n }\n\n return runtime.apiClient.listOrganizationGroupMembers(\n organizationId,\n groupId,\n );\n }\n\n loadGroupPresentationDetails(groupId: string, beforeVersion?: number) {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: groupId,\n objectKind: \"principal\",\n operation: \"group.presentation.load\",\n organizationId: runtime.auth.organizationId,\n },\n () =>\n loadOrganizationGroupPresentationDetails({\n groupId,\n beforeVersion,\n readModelCoordinator: this.readModelCoordinator,\n runtime,\n }),\n );\n }\n\n loadGrants() {\n return this.readModelCoordinator.loadLocalGrants();\n }\n\n loadGroupContainers(groupId: string) {\n return this.readModelCoordinator.loadLocalGroupContainers(groupId);\n }\n\n listLocalOrganizations() {\n const runtime = this.runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return Promise.resolve([]);\n }\n\n return listLocalOrganizations({ execSql: runtime.infra.execSql });\n }\n\n loadPolicyHistory(beforeVersion?: number) {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: runtime.auth.organizationId,\n objectKind: \"principal\",\n operation: \"organization.policy_history.load\",\n organizationId: runtime.auth.organizationId,\n },\n () =>\n this.readModelCoordinator.loadOrganizationPolicyHistory(\n undefined,\n beforeVersion,\n ),\n );\n }\n\n loadUserDetail(userId: string) {\n return this.readModelCoordinator.loadLocalUserDetail(userId);\n }\n\n async updateRosterEntry(userId: string, profileDocumentId: string | null) {\n const runtime = this.runtimeService.workflowInput();\n const organizationId = authenticatedOrganizationId(runtime);\n if (!organizationId || userId.length === 0) {\n return null;\n }\n\n const user = await updateOrganizationRosterEntry({\n apiClient: runtime.apiClient,\n organizationId,\n profileDocumentId,\n userId,\n });\n // Callers store this response as directory state, so its leave request\n // passes the same check as one read from the read model.\n return (\n user &&\n withVerifiedDirectoryUser(\n organizationId,\n user,\n leaveRequestVerifier(this.runtimeService, runtime, {\n organizationId,\n userId: runtime.auth.userId ?? \"\",\n }),\n )\n );\n }\n\n updateProfile(profileDocumentId: string | null) {\n const runtime = this.runtimeService.workflowInput();\n const organizationId = authenticatedOrganizationId(runtime);\n if (!organizationId) {\n return Promise.resolve(null);\n }\n\n return updateOrganizationProfile({\n apiClient: runtime.apiClient,\n organizationId,\n profileDocumentId,\n });\n }\n\n async removeUserFromGroup(input: RemoveOrganizationGroupUserInput) {\n return removeUserFromOrganizationGroup({\n ...input,\n containerContents: this.containerContents,\n readModelCoordinator: this.readModelCoordinator,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n async revokeGrant(grant: OrganizationGrantRef) {\n return revokeOrganizationGrant({\n ...grant,\n containerContents: this.containerContents,\n readModelCoordinator: this.readModelCoordinator,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n startTrial(organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n startOrganizationTrial,\n organizationId,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAC9B,mCAAmC,EACnC,oBAAoB,EACpB,2BAA2B,EAC3B,sBAAsB,EACtB,uBAAuB,EACvB,8BAA8B,EAC9B,oCAAoC,EACpC,yBAAyB,EACzB,sBAAsB,EACtB,yBAAyB,EACzB,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EACL,sCAAsC,GAEvC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,wCAAwC,EAAE,MAAM,iCAAiC,CAAC;AAC3F,OAAO,EACL,6BAA6B,GAG9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,sCAAsC,EACtC,oBAAoB,GAErB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,+BAA+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AC,cAAc,EAAE,CAAC;YACpB,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAED,OAAO,yBAAyB,CAAC;YAC/B,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,cAAc;YACd,iBAAiB;SAClB,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,KAAuC;QAC/D,OAAO,+BAA+B,CAAC;YACrC,GAAG,KAAK;YACR,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,GAAG,2BAA2B,CAAC,IAAI,CAAC,cAAc,CAAC;SACpD,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,KAA2B;QAC3C,OAAO,uBAAuB,CAAC;YAC7B,GAAG,KAAK;YACR,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,GAAG,2BAA2B,CAAC,IAAI,CAAC,cAAc,CAAC;SACpD,CAAC,CAAC;IACL,CAAC;IAED,UAAU,CAAC,cAAuB;QAChC,OAAO,kBAAkB,CACvB,IAAI,CAAC,cAAc,EACnB,sBAAsB,EACtB,cAAc,CACf,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { NativeSubscriptionStore } from \"@tearleads/validators/billing\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { DatabaseUnavailableError } from \"../../data/sync/databaseUnavailable\";\nimport {\n cancelStripeSubscription,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createStripeCheckout,\n createStripeCheckoutSession,\n listLocalOrganizations,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n startOrganizationTrial,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n withVerifiedDirectoryUser,\n} from \"../../workflows/organizations\";\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n createOrganizationDataUsageCoordinator,\n type OrganizationDataUsageCoordinator,\n} from \"./organizationDataUsage\";\nimport { loadOrganizationGroupPresentationDetails } from \"./organizationGroupPresentation\";\nimport {\n createOrganizationMemberships,\n type OrganizationContentReconciler,\n type OrganizationMemberships,\n} from \"./organizationMemberships\";\nimport {\n createOrganizationReadModelCoordinator,\n leaveRequestVerifier,\n type OrganizationReadModelCoordinator,\n} from \"./organizationReadModels\";\nimport type { Organizations } from \"./organizationsTypes\";\nimport {\n authenticatedOrganizationId,\n runForOrganization,\n} from \"./organizationWorkflowRuntime\";\nimport {\n type AbandonOrganizationPolicyMutationInput,\n abandonPendingOrganizationPolicyMutation,\n type DiscardUnreadableOrganizationPolicyMutationInput,\n discardUnreadableOrganizationPolicyMutation,\n readPendingOrganizationPolicyMutation,\n retryPendingOrganizationPolicyMutation,\n} from \"./principalMutationRecovery\";\nimport { currentOrganizationMutation } from \"./principalMutationScope\";\nimport {\n type AddOrganizationGroupUserInput,\n addUserToOrganizationGroup,\n createGroupForOrganization,\n deleteGroupForOrganization,\n type OrganizationGrantRef,\n type RemoveOrganizationGroupUserInput,\n removeUserFromOrganizationGroup,\n revokeOrganizationGrant,\n} from \"./principalMutations\";\n\nexport type {\n LocalOrganizationSummary,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\n OrganizationUserDetail,\n} from \"../../workflows/organizations\";\nexport type {\n OrganizationContentReconciler,\n OrganizationMemberships,\n} from \"./organizationMemberships\";\nexport type {\n OrganizationGroupMutationReceipt,\n Organizations,\n} from \"./organizationsTypes\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n} from \"./principalMutationRecovery\";\nexport type {\n AddOrganizationGroupUserInput,\n OrganizationGrantRef,\n RemoveOrganizationGroupUserInput,\n} from \"./principalMutations\";\n\nexport function createOrganizations(\n runtime: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): Organizations {\n return new OrganizationsService(runtime, containerContents, openReconciler);\n}\n\nclass OrganizationsService implements Organizations {\n readonly memberships: OrganizationMemberships;\n private readonly dataUsageCoordinator: OrganizationDataUsageCoordinator;\n private readonly readModelCoordinator: OrganizationReadModelCoordinator;\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n ) {\n this.dataUsageCoordinator = createOrganizationDataUsageCoordinator(\n this.runtimeService,\n );\n this.readModelCoordinator = createOrganizationReadModelCoordinator(\n this.runtimeService,\n );\n this.memberships = createOrganizationMemberships(\n this.runtimeService,\n this.containerContents,\n openReconciler,\n );\n }\n\n async addUserToGroup(input: AddOrganizationGroupUserInput) {\n // Group membership admits a user: only a verified identity link or this\n // device's own keys can establish the identity it is granted to.\n // The check reads the trust store of the scope this mutation captured, and\n // that scope must still be current once it returns.\n const mutation = currentOrganizationMutation(this.runtimeService);\n await this.runtimeService.identityLinks.requireVerified(\n input.targetUserId,\n mutation.runtime.infra.execSql,\n );\n if (!mutation.stillCurrent()) {\n throw new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n }\n return addUserToOrganizationGroup({\n ...input,\n containerContents: this.containerContents,\n readModelCoordinator: this.readModelCoordinator,\n ...mutation,\n });\n }\n\n readPendingPolicyMutation(organizationId: string) {\n return readPendingOrganizationPolicyMutation(\n this.runtimeService,\n organizationId,\n );\n }\n\n discardUnreadablePolicyMutation(\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n ) {\n return discardUnreadableOrganizationPolicyMutation(\n this.runtimeService,\n input,\n );\n }\n\n retryPendingPolicyMutation(organizationId: string) {\n return retryPendingOrganizationPolicyMutation(\n this.runtimeService,\n organizationId,\n );\n }\n\n abandonPendingPolicyMutation(input: AbandonOrganizationPolicyMutationInput) {\n return abandonPendingOrganizationPolicyMutation(this.runtimeService, input);\n }\n\n createGroup(name: string) {\n return createGroupForOrganization({\n name,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n deleteGroup(groupId: string) {\n return deleteGroupForOrganization({\n groupId,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n loadBilling() {\n return runForOrganization(this.runtimeService, loadOrganizationBilling);\n }\n\n loadBillingForOrganization(organizationId: string) {\n // Gated on an authenticated session rather than on the target being the\n // active org. The server still enforces membership, so an org the caller\n // cannot reach resolves to `null`.\n return runForOrganization(\n this.runtimeService,\n loadOrganizationBilling,\n organizationId,\n );\n }\n\n loadBillingHistory() {\n return runForOrganization(\n this.runtimeService,\n loadOrganizationBillingHistory,\n );\n }\n\n loadBillingManagementUrl() {\n return runForOrganization(\n this.runtimeService,\n loadOrganizationBillingManagementUrl,\n );\n }\n\n loadStripeCheckoutOptions(organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n loadStripeCheckoutOptions,\n organizationId,\n );\n }\n\n createStripeCheckout(organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n createStripeCheckout,\n organizationId,\n );\n }\n\n createStripeCheckoutSession(returnUrl: string, organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n (input) => createStripeCheckoutSession({ ...input, returnUrl }),\n organizationId,\n );\n }\n\n cancelStripeSubscription() {\n return runForOrganization(this.runtimeService, cancelStripeSubscription);\n }\n\n claimNativeSubscription(\n organizationId: string,\n store: NativeSubscriptionStore,\n ) {\n return runForOrganization(\n this.runtimeService,\n (input) => claimNativeOrganizationSubscription({ ...input, store }),\n organizationId,\n );\n }\n\n checkNativePurchaseEligibility(\n organizationId: string,\n store: NativeSubscriptionStore,\n ) {\n return runForOrganization(\n this.runtimeService,\n (input) => checkNativePurchaseEligibility({ ...input, store }),\n organizationId,\n );\n }\n\n loadDataUsage() {\n return this.dataUsageCoordinator.reconcile();\n }\n\n loadLocalDataUsage() {\n return this.dataUsageCoordinator.loadLocal();\n }\n\n loadDirectoryAndGroups() {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: runtime.auth.organizationId,\n objectKind: \"principal\",\n operation: \"organization.read_model.reconcile\",\n organizationId: runtime.auth.organizationId,\n },\n () => this.readModelCoordinator.reconcile(),\n );\n }\n\n loadDirectoryAndGroupsAfterMutation() {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: runtime.auth.organizationId,\n objectKind: \"principal\",\n operation: \"organization.read_model.reconcile_after_mutation\",\n organizationId: runtime.auth.organizationId,\n },\n () => this.readModelCoordinator.reconcileAfterMutation(),\n );\n }\n\n loadLocalDirectoryAndGroups() {\n return this.readModelCoordinator.loadLocal();\n }\n\n loadGroupMembers(groupId: string) {\n const runtime = this.runtimeService.workflowInput();\n const organizationId = authenticatedOrganizationId(runtime);\n if (!organizationId || groupId.length === 0) {\n return Promise.resolve(null);\n }\n\n return runtime.apiClient.listOrganizationGroupMembers(\n organizationId,\n groupId,\n );\n }\n\n loadGroupPresentationDetails(groupId: string, beforeVersion?: number) {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: groupId,\n objectKind: \"principal\",\n operation: \"group.presentation.load\",\n organizationId: runtime.auth.organizationId,\n },\n () =>\n loadOrganizationGroupPresentationDetails({\n groupId,\n beforeVersion,\n readModelCoordinator: this.readModelCoordinator,\n runtime,\n }),\n );\n }\n\n loadGrants() {\n return this.readModelCoordinator.loadLocalGrants();\n }\n\n loadGroupContainers(groupId: string) {\n return this.readModelCoordinator.loadLocalGroupContainers(groupId);\n }\n\n listLocalOrganizations() {\n const runtime = this.runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return Promise.resolve([]);\n }\n\n return listLocalOrganizations({ execSql: runtime.infra.execSql });\n }\n\n loadPolicyHistory(beforeVersion?: number) {\n const runtime = this.runtimeService.workflowInput();\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: runtime.auth.organizationId,\n objectKind: \"principal\",\n operation: \"organization.policy_history.load\",\n organizationId: runtime.auth.organizationId,\n },\n () =>\n this.readModelCoordinator.loadOrganizationPolicyHistory(\n undefined,\n beforeVersion,\n ),\n );\n }\n\n loadUserDetail(userId: string) {\n return this.readModelCoordinator.loadLocalUserDetail(userId);\n }\n\n async updateRosterEntry(userId: string, profileDocumentId: string | null) {\n const runtime = this.runtimeService.workflowInput();\n const organizationId = authenticatedOrganizationId(runtime);\n if (!organizationId || userId.length === 0) {\n return null;\n }\n\n const user = await updateOrganizationRosterEntry({\n apiClient: runtime.apiClient,\n organizationId,\n profileDocumentId,\n userId,\n });\n // Callers store this response as directory state, so its leave request\n // passes the same check as one read from the read model.\n return (\n user &&\n withVerifiedDirectoryUser(\n organizationId,\n user,\n leaveRequestVerifier(this.runtimeService, runtime, {\n organizationId,\n userId: runtime.auth.userId ?? \"\",\n }),\n )\n );\n }\n\n updateProfile(profileDocumentId: string | null) {\n const runtime = this.runtimeService.workflowInput();\n const organizationId = authenticatedOrganizationId(runtime);\n if (!organizationId) {\n return Promise.resolve(null);\n }\n\n return updateOrganizationProfile({\n apiClient: runtime.apiClient,\n organizationId,\n profileDocumentId,\n });\n }\n\n async removeUserFromGroup(input: RemoveOrganizationGroupUserInput) {\n return removeUserFromOrganizationGroup({\n ...input,\n containerContents: this.containerContents,\n readModelCoordinator: this.readModelCoordinator,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n async revokeGrant(grant: OrganizationGrantRef) {\n return revokeOrganizationGrant({\n ...grant,\n containerContents: this.containerContents,\n readModelCoordinator: this.readModelCoordinator,\n ...currentOrganizationMutation(this.runtimeService),\n });\n }\n\n startTrial(organizationId?: string) {\n return runForOrganization(\n this.runtimeService,\n startOrganizationTrial,\n organizationId,\n );\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { NativeSubscriptionStore } from "../../internal/validators/billing.js";
2
2
  import type { PrincipalPolicyMutationResponse } from "../../internal/validators/response/index.js";
3
- import type { cancelStripeSubscription, checkNativePurchaseEligibility, claimNativeOrganizationSubscription, createOrganizationGroup, createStripeCheckout, createStripeCheckoutSession, importOrganizationUser, LocalOrganizationSummary, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, loadStripeCheckoutOptions, revokeOrganizationContainerGrant, startOrganizationTrial, updateOrganizationProfile, updateOrganizationRosterEntry } from "../../workflows/organizations/index.js";
3
+ import type { cancelStripeSubscription, checkNativePurchaseEligibility, claimNativeOrganizationSubscription, createOrganizationGroup, createStripeCheckout, createStripeCheckoutSession, LocalOrganizationSummary, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, loadStripeCheckoutOptions, revokeOrganizationContainerGrant, startOrganizationTrial, updateOrganizationProfile, updateOrganizationRosterEntry } from "../../workflows/organizations/index.js";
4
4
  import type { InternalWorkflowRuntimeInput } from "../runtime/workflowRuntime.js";
5
5
  import type { OrganizationDataUsageCoordinator } from "./organizationDataUsage.js";
6
6
  import type { loadOrganizationGroupPresentationDetails } from "./organizationGroupPresentation.js";
@@ -18,7 +18,6 @@ export interface Organizations {
18
18
  addUserToGroup: (input: AddOrganizationGroupUserInput) => Promise<OrganizationGroupMutationReceipt>;
19
19
  createGroup: (name: string) => ReturnType<typeof createOrganizationGroup>;
20
20
  deleteGroup: (groupId: string) => ReturnType<typeof deleteGroupForOrganization>;
21
- importUserById: (userId: string) => ReturnType<typeof importOrganizationUser>;
22
21
  loadBilling: () => ReturnType<typeof loadOrganizationBilling>;
23
22
  /** Billing for an organization the session is not currently switched to. */
24
23
  loadBillingForOrganization: (organizationId: string) => ReturnType<typeof loadOrganizationBilling>;
@@ -1 +1 @@
1
- {"version":3,"file":"organizationsTypes.js","sourceRoot":"","sources":["organizationsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { NativeSubscriptionStore } from \"@tearleads/validators/billing\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport type {\n cancelStripeSubscription,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createOrganizationGroup,\n createStripeCheckout,\n createStripeCheckoutSession,\n importOrganizationUser,\n LocalOrganizationSummary,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n revokeOrganizationContainerGrant,\n startOrganizationTrial,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"../../workflows/organizations\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport type { OrganizationDataUsageCoordinator } from \"./organizationDataUsage\";\nimport type { loadOrganizationGroupPresentationDetails } from \"./organizationGroupPresentation\";\nimport type { OrganizationMemberships } from \"./organizationMemberships\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport type {\n AbandonOrganizationPolicyMutationInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n readPendingOrganizationPolicyMutation,\n} from \"./principalMutationRecovery\";\nimport type {\n AddOrganizationGroupUserInput,\n deleteGroupForOrganization,\n OrganizationGrantRef,\n RemoveOrganizationGroupUserInput,\n} from \"./principalMutations\";\n\n/** Exact current artifacts and container receipts; no historical prefix. */\nexport type OrganizationGroupMutationReceipt = PrincipalPolicyMutationResponse;\n\nexport interface Organizations {\n discardUnreadablePolicyMutation: (\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n readPendingPolicyMutation: (\n organizationId: string,\n ) => ReturnType<typeof readPendingOrganizationPolicyMutation>;\n retryPendingPolicyMutation: (organizationId: string) => Promise<void>;\n abandonPendingPolicyMutation: (\n input: AbandonOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n addUserToGroup: (\n input: AddOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationReceipt>;\n createGroup: (name: string) => ReturnType<typeof createOrganizationGroup>;\n deleteGroup: (\n groupId: string,\n ) => ReturnType<typeof deleteGroupForOrganization>;\n importUserById: (userId: string) => ReturnType<typeof importOrganizationUser>;\n loadBilling: () => ReturnType<typeof loadOrganizationBilling>;\n /** Billing for an organization the session is not currently switched to. */\n loadBillingForOrganization: (\n organizationId: string,\n ) => ReturnType<typeof loadOrganizationBilling>;\n loadBillingHistory: () => ReturnType<typeof loadOrganizationBillingHistory>;\n loadBillingManagementUrl: () => ReturnType<\n typeof loadOrganizationBillingManagementUrl\n >;\n /** Direct Stripe checkout (issue #1654): options, start, and cancel. */\n loadStripeCheckoutOptions: (\n organizationId?: string,\n ) => ReturnType<typeof loadStripeCheckoutOptions>;\n createStripeCheckout: (\n organizationId?: string,\n ) => ReturnType<typeof createStripeCheckout>;\n createStripeCheckoutSession: (\n returnUrl: string,\n organizationId?: string,\n ) => ReturnType<typeof createStripeCheckoutSession>;\n cancelStripeSubscription: () => ReturnType<typeof cancelStripeSubscription>;\n claimNativeSubscription: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof claimNativeOrganizationSubscription>;\n checkNativePurchaseEligibility: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof checkNativePurchaseEligibility>;\n loadDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"reconcile\"]\n >;\n loadLocalDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"loadLocal\"]\n >;\n loadDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcile\"]\n >;\n loadDirectoryAndGroupsAfterMutation: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcileAfterMutation\"]\n >;\n loadLocalDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocal\"]\n >;\n loadGroupMembers: (\n groupId: string,\n ) => ReturnType<\n InternalWorkflowRuntimeInput[\"apiClient\"][\"listOrganizationGroupMembers\"]\n >;\n loadGroupPresentationDetails(\n groupId: string,\n beforeVersion?: number,\n ): ReturnType<typeof loadOrganizationGroupPresentationDetails>;\n loadGroupContainers: (\n groupId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalGroupContainers\"]>;\n loadGrants: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocalGrants\"]\n >;\n listLocalOrganizations: () => Promise<LocalOrganizationSummary[]>;\n /** The user's own memberships and per-organization sync choices. */\n readonly memberships: OrganizationMemberships;\n loadPolicyHistory: (\n beforeVersion?: number,\n ) => ReturnType<\n OrganizationReadModelCoordinator[\"loadOrganizationPolicyHistory\"]\n >;\n loadUserDetail: (\n userId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalUserDetail\"]>;\n updateRosterEntry: (\n userId: string,\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationRosterEntry>;\n updateProfile: (\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationProfile>;\n removeUserFromGroup: (\n input: RemoveOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationReceipt>;\n revokeGrant: (\n grant: OrganizationGrantRef,\n ) => Promise<\n | Awaited<ReturnType<typeof revokeOrganizationContainerGrant>>\n | OrganizationGroupMutationReceipt\n >;\n startTrial: (\n organizationId?: string,\n ) => ReturnType<typeof startOrganizationTrial>;\n}\n"]}
1
+ {"version":3,"file":"organizationsTypes.js","sourceRoot":"","sources":["organizationsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { NativeSubscriptionStore } from \"@tearleads/validators/billing\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport type {\n cancelStripeSubscription,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createOrganizationGroup,\n createStripeCheckout,\n createStripeCheckoutSession,\n LocalOrganizationSummary,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n revokeOrganizationContainerGrant,\n startOrganizationTrial,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"../../workflows/organizations\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport type { OrganizationDataUsageCoordinator } from \"./organizationDataUsage\";\nimport type { loadOrganizationGroupPresentationDetails } from \"./organizationGroupPresentation\";\nimport type { OrganizationMemberships } from \"./organizationMemberships\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport type {\n AbandonOrganizationPolicyMutationInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n readPendingOrganizationPolicyMutation,\n} from \"./principalMutationRecovery\";\nimport type {\n AddOrganizationGroupUserInput,\n deleteGroupForOrganization,\n OrganizationGrantRef,\n RemoveOrganizationGroupUserInput,\n} from \"./principalMutations\";\n\n/** Exact current artifacts and container receipts; no historical prefix. */\nexport type OrganizationGroupMutationReceipt = PrincipalPolicyMutationResponse;\n\nexport interface Organizations {\n discardUnreadablePolicyMutation: (\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n readPendingPolicyMutation: (\n organizationId: string,\n ) => ReturnType<typeof readPendingOrganizationPolicyMutation>;\n retryPendingPolicyMutation: (organizationId: string) => Promise<void>;\n abandonPendingPolicyMutation: (\n input: AbandonOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n addUserToGroup: (\n input: AddOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationReceipt>;\n createGroup: (name: string) => ReturnType<typeof createOrganizationGroup>;\n deleteGroup: (\n groupId: string,\n ) => ReturnType<typeof deleteGroupForOrganization>;\n loadBilling: () => ReturnType<typeof loadOrganizationBilling>;\n /** Billing for an organization the session is not currently switched to. */\n loadBillingForOrganization: (\n organizationId: string,\n ) => ReturnType<typeof loadOrganizationBilling>;\n loadBillingHistory: () => ReturnType<typeof loadOrganizationBillingHistory>;\n loadBillingManagementUrl: () => ReturnType<\n typeof loadOrganizationBillingManagementUrl\n >;\n /** Direct Stripe checkout (issue #1654): options, start, and cancel. */\n loadStripeCheckoutOptions: (\n organizationId?: string,\n ) => ReturnType<typeof loadStripeCheckoutOptions>;\n createStripeCheckout: (\n organizationId?: string,\n ) => ReturnType<typeof createStripeCheckout>;\n createStripeCheckoutSession: (\n returnUrl: string,\n organizationId?: string,\n ) => ReturnType<typeof createStripeCheckoutSession>;\n cancelStripeSubscription: () => ReturnType<typeof cancelStripeSubscription>;\n claimNativeSubscription: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof claimNativeOrganizationSubscription>;\n checkNativePurchaseEligibility: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof checkNativePurchaseEligibility>;\n loadDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"reconcile\"]\n >;\n loadLocalDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"loadLocal\"]\n >;\n loadDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcile\"]\n >;\n loadDirectoryAndGroupsAfterMutation: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcileAfterMutation\"]\n >;\n loadLocalDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocal\"]\n >;\n loadGroupMembers: (\n groupId: string,\n ) => ReturnType<\n InternalWorkflowRuntimeInput[\"apiClient\"][\"listOrganizationGroupMembers\"]\n >;\n loadGroupPresentationDetails(\n groupId: string,\n beforeVersion?: number,\n ): ReturnType<typeof loadOrganizationGroupPresentationDetails>;\n loadGroupContainers: (\n groupId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalGroupContainers\"]>;\n loadGrants: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocalGrants\"]\n >;\n listLocalOrganizations: () => Promise<LocalOrganizationSummary[]>;\n /** The user's own memberships and per-organization sync choices. */\n readonly memberships: OrganizationMemberships;\n loadPolicyHistory: (\n beforeVersion?: number,\n ) => ReturnType<\n OrganizationReadModelCoordinator[\"loadOrganizationPolicyHistory\"]\n >;\n loadUserDetail: (\n userId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalUserDetail\"]>;\n updateRosterEntry: (\n userId: string,\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationRosterEntry>;\n updateProfile: (\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationProfile>;\n removeUserFromGroup: (\n input: RemoveOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationReceipt>;\n revokeGrant: (\n grant: OrganizationGrantRef,\n ) => Promise<\n | Awaited<ReturnType<typeof revokeOrganizationContainerGrant>>\n | OrganizationGroupMutationReceipt\n >;\n startTrial: (\n organizationId?: string,\n ) => ReturnType<typeof startOrganizationTrial>;\n}\n"]}
@@ -32,7 +32,7 @@ export interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {
32
32
  readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
33
33
  }
34
34
  export interface InternalRuntime {
35
- identityLinks: Pick<TrustedUserIdentityService, "createLink" | "verifyLink" | "resolvePinned">;
35
+ identityLinks: Pick<TrustedUserIdentityService, "createLink" | "verifyLink" | "resolvePinned" | "resolveVerified" | "requireVerified">;
36
36
  retirePrincipalHistoryProtection(): void;
37
37
  readonly sessionGeneration: number;
38
38
  readonly adoptRootContainer: ContainerContentsRootAdopter;
@@ -1 +1 @@
1
- {"version":3,"file":"work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EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AAIjG,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAEhC,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,uCAAuC,GAExC,MAAM,0DAA0D,CAAC;AAWlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAI1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,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1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"verifyLink\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
@@ -3,11 +3,11 @@ import { keyingCheckpointTables, principalPolicyTables, } from "../../sqlite/sch
3
3
  import { verifiedManifestBundleTables } from "../../sqlite/schema/verifiedManifestBundleSchema.js";
4
4
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
- import { assertContainerNotRetired } from "../principalKeys/principalGrantRetirementPersistence.js";
6
+ import { loadContainerRetirementCheck } from "../principalKeys/principalGrantRetirementPersistence.js";
7
7
  import { verifiedManifestBundleRows, writeVerifiedManifestBundlesInTransaction, } from "../verifiedManifestBundlePersistence.js";
8
8
  import { storeDocumentPurgeCheckpointInTransaction, } from "./documentPurgeCheckpointPersistence.js";
9
9
  import { validateAccessManifestCheckpointEvidence } from "./keyingCheckpointEvidence.js";
10
- import { accessManifestObjectKey, loadStoredAccessManifestCheckpoint, loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertAccessManifestCheckpointInTransaction, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpointPersistence.js";
10
+ import { accessManifestObjectKey, loadAccessManifestCheckpointRows, loadStoredPrincipalPolicyCheckpoints, principalPolicyKey, upsertAccessManifestCheckpointsInTransaction, upsertPrincipalPolicyCheckpointsInTransaction, } from "./keyingCheckpointPersistence.js";
11
11
  import { validatePrincipalAuthorizationCheckpoints } from "./principalAuthorizationCheckpoints.js";
12
12
  function validateAccessAdvance(advance, localCheckpoint) {
13
13
  const current = {
@@ -40,13 +40,21 @@ function validateAccessAdvance(advance, localCheckpoint) {
40
40
  }
41
41
  async function validateAccessAdvances(tx, advances) {
42
42
  const pending = new Map();
43
+ if (advances.length === 0)
44
+ return pending;
45
+ // Set reads first; the checks then replay in order, so the same advance
46
+ // fails first with the same error.
47
+ const heads = advances.map((advance) => advance.head.checkpoint);
48
+ const assertNotRetired = await loadContainerRetirementCheck(tx, heads);
49
+ const stored = await loadAccessManifestCheckpointRows(tx, heads);
43
50
  for (const advance of advances) {
44
- await assertContainerNotRetired(tx, advance.head.checkpoint);
51
+ assertNotRetired(advance.head.checkpoint);
45
52
  const key = accessManifestObjectKey(advance.head.checkpoint);
46
53
  if (pending.has(key)) {
47
54
  throw new KeyingVerificationError("equivocation", `projection declares multiple access checkpoint heads for ${key}`);
48
55
  }
49
- const localCheckpoint = await loadStoredAccessManifestCheckpoint(tx, advance.head.checkpoint);
56
+ const row = stored.get(key);
57
+ const localCheckpoint = row ? { ...advance.head.checkpoint, ...row } : null;
50
58
  pending.set(key, validateAccessAdvance(advance, localCheckpoint));
51
59
  }
52
60
  return pending;
@@ -72,6 +80,7 @@ export async function validatePrincipalPolicyCheckpointAdvances(tx, policies) {
72
80
  policiesByPrincipal.set(key, candidates);
73
81
  }
74
82
  const pending = new Map();
83
+ const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);
75
84
  for (const key of [...policiesByPrincipal.keys()].sort()) {
76
85
  const candidates = policiesByPrincipal.get(key) ?? [];
77
86
  const maxVersion = Math.max(...candidates.map((policy) => policy.version));
@@ -91,7 +100,7 @@ export async function validatePrincipalPolicyCheckpointAdvances(tx, policies) {
91
100
  throw new KeyingVerificationError("stale_predecessor", `principal policy head does not extend observed state for ${key}`);
92
101
  }
93
102
  }
94
- const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);
103
+ const localCheckpoint = stored.get(key) ?? null;
95
104
  verifyPrincipalPolicyCheckpoint({
96
105
  chain: "retainedHistory" in head ? head.retainedHistory : (head.history ?? []),
97
106
  currentState: head.state,
@@ -102,15 +111,11 @@ export async function validatePrincipalPolicyCheckpointAdvances(tx, policies) {
102
111
  return pending;
103
112
  }
104
113
  async function writeAccessCheckpoints(tx, pending, updatedAt) {
105
- for (const { checkpoint } of pending.values()) {
106
- await upsertAccessManifestCheckpointInTransaction(tx, checkpoint, updatedAt);
107
- }
114
+ await upsertAccessManifestCheckpointsInTransaction(tx, [...pending.values()].map(({ checkpoint }) => checkpoint), updatedAt);
108
115
  }
109
116
  /** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */
110
117
  export async function writePrincipalPolicyCheckpoints(tx, pending, updatedAt, organizationId) {
111
- for (const policy of pending.values()) {
112
- await upsertPrincipalPolicyCheckpointInTransaction(tx, policy.checkpoint, updatedAt, organizationId);
113
- }
118
+ await upsertPrincipalPolicyCheckpointsInTransaction(tx, [...pending.values()].map((policy) => policy.checkpoint), updatedAt, organizationId);
114
119
  }
115
120
  /**
116
121
  * Digests the verified bundles and ensures every table the batch touches,
@@ -1 +1 @@
1
- {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAIvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,yBAAyB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AAE,EACF,KAAK,CAAC,uBAAuB,EAC7B,SAAS,CACV,CAAC;QACJ,CAAC;QACD,MAAM,yCAAyC,CAAC,EAAE,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;IAC7E,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../../sqlite/schema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { assertContainerNotRetired } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\n/**\n * Checks, inside the caller's transaction, that each principal's newest policy\n * extends every other candidate and its durable checkpoint. Returns the heads\n * to pin, keyed by principal.\n */\nexport async function validatePrincipalPolicyCheckpointAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\n/** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */\nexport async function writePrincipalPolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\n/**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\nasync function prepareKeyingCheckpointBatch(\n input: KeyingCheckpointValidationInput,\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n input.verifiedBundles ?? [],\n );\n await ensureSqlTables(input.execSql, [\n ...(input.policies.length > 0 ||\n (input.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ]);\n return bundleRows;\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const verifiedAt = new Date().toISOString();\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePrincipalPolicyCheckpointAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput & {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n },\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n input.policies,\n );\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n input.organizationId,\n );\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n"]}
1
+ {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAIvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,4BAA4B,EAAE,MAAM,sDAAsD,CAAC;AACpG,OAAO,EAGL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,EACL,uBAAuB,EACvB,gCAAgC,EAChC,oCAAoC,EACpC,kBAAkB,EAClB,4CAA4C,EAC5C,6CAA6C,GAC9C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AA8BhG,SAAS,qBAAqB,CAC5B,OAAwC,EACxC,eAAgD;IAEhD,MAAM,OAAO,GAAG;QACd,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU;QAC1B,oBAAoB,EAAE,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC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,MAAM,yCAAyC,CAC7C,EAAE,EACF,KAAK,CAAC,uBAAuB,EAC7B,SAAS,CACV,CAAC;QACJ,CAAC;QACD,MAAM,yCAAyC,CAAC,EAAE,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;IAC7E,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../../sqlite/schema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { loadContainerRetirementCheck } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadAccessManifestCheckpointRows,\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n upsertAccessManifestCheckpointsInTransaction,\n upsertPrincipalPolicyCheckpointsInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n if (advances.length === 0) return pending;\n // Set reads first; the checks then replay in order, so the same advance\n // fails first with the same error.\n const heads = advances.map((advance) => advance.head.checkpoint);\n const assertNotRetired = await loadContainerRetirementCheck(tx, heads);\n const stored = await loadAccessManifestCheckpointRows(tx, heads);\n\n for (const advance of advances) {\n assertNotRetired(advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const row = stored.get(key);\n const localCheckpoint = row ? { ...advance.head.checkpoint, ...row } : null;\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\n/**\n * Checks, inside the caller's transaction, that each principal's newest policy\n * extends every other candidate and its durable checkpoint. Returns the heads\n * to pin, keyed by principal.\n */\nexport async function validatePrincipalPolicyCheckpointAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = stored.get(key) ?? null;\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n await upsertAccessManifestCheckpointsInTransaction(\n tx,\n [...pending.values()].map(({ checkpoint }) => checkpoint),\n updatedAt,\n );\n}\n\n/** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */\nexport async function writePrincipalPolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await upsertPrincipalPolicyCheckpointsInTransaction(\n tx,\n [...pending.values()].map((policy) => policy.checkpoint),\n updatedAt,\n organizationId,\n );\n}\n\n/**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\nasync function prepareKeyingCheckpointBatch(\n input: KeyingCheckpointValidationInput,\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n input.verifiedBundles ?? [],\n );\n await ensureSqlTables(input.execSql, [\n ...(input.policies.length > 0 ||\n (input.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ]);\n return bundleRows;\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const verifiedAt = new Date().toISOString();\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePrincipalPolicyCheckpointAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput & {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n },\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n input.policies,\n );\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n input.organizationId,\n );\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n"]}