@tearleads/client-sdk 0.1.111 → 0.1.112

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 (50) 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/trustedUserIdentityPinPersistence.js +30 -4
  21. package/data/persistence/trustedUserIdentityPinPersistence.js.map +1 -1
  22. package/data/sqlite/schema/index.d.ts +45 -5
  23. package/data/sqlite/schema/index.js +14 -6
  24. package/data/sqlite/schema/index.js.map +1 -1
  25. package/data/trustedUserIdentity/admission.d.ts +10 -0
  26. package/data/trustedUserIdentity/admission.js +15 -0
  27. package/data/trustedUserIdentity/admission.js.map +1 -0
  28. package/data/trustedUserIdentity/index.d.ts +1 -0
  29. package/data/trustedUserIdentity/index.js +1 -0
  30. package/data/trustedUserIdentity/index.js.map +1 -1
  31. package/data/trustedUserIdentity/service.d.ts +1 -5
  32. package/data/trustedUserIdentity/service.js +119 -46
  33. package/data/trustedUserIdentity/service.js.map +1 -1
  34. package/data/trustedUserIdentity/types.d.ts +12 -1
  35. package/data/trustedUserIdentity/types.js.map +1 -1
  36. package/index.d.ts +3 -3
  37. package/index.js +2 -2
  38. package/index.js.map +1 -1
  39. package/package.json +1 -1
  40. package/stores/container-contents/containerContentsStore.js +10 -1
  41. package/stores/container-contents/containerContentsStore.js.map +1 -1
  42. package/workflows/container-contents/runtime.d.ts +7 -1
  43. package/workflows/container-contents/runtime.js +2 -1
  44. package/workflows/container-contents/runtime.js.map +1 -1
  45. package/workflows/organizations/index.d.ts +0 -1
  46. package/workflows/organizations/index.js +0 -1
  47. package/workflows/organizations/index.js.map +1 -1
  48. package/workflows/organizations/organizationUserImport.d.ts +0 -8
  49. package/workflows/organizations/organizationUserImport.js +0 -10
  50. 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,oBAAoB,EACpB,2BAA2B,EAC3B,sBAAsB,EACtB,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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AC,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+B,CAAC;AACvC,OAAO,EAEL,wCAAwC,EAExC,2CAA2C,EAC3C,qCAAqC,EACrC,sCAAsC,GACvC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAEL,0BAA0B,EAC1B,0BAA0B,EAC1B,0BAA0B,EAG1B,+BAA+B,EAC/B,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAkD9B,MAA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AAK;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":"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,0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AAE,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,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAyEpE,SAAS,wBAAwB,CAC/B,YAAyC,EACzC,cAA4B;IAE5B,OAAO,iCAAiC,CAAC;QACvC,GAAG,EAAE,YAAY,CAAC,GAAG;QACr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AE,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"]}
@@ -4,6 +4,10 @@ import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceR
4
4
  import { ensureSqlTables } from "../sqlite/sqlSchema.js";
5
5
  import { TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE, TRUSTED_USER_IDENTITY_FORMAT_VERSION, TRUSTED_USER_IDENTITY_SIGNING_SUITE, } from "../trustedUserIdentity/types.js";
6
6
  import { runTrustedUserIdentityPinTransaction } from "./trustedUserIdentityPinTransaction.js";
7
+ const provenanceRank = { observed: 0, link: 1, self: 2 };
8
+ function isTrustedUserIdentityPinProvenance(value) {
9
+ return value === "self" || value === "link" || value === "observed";
10
+ }
7
11
  const comparedPinFields = [
8
12
  "userId",
9
13
  "formatVersion",
@@ -117,6 +121,9 @@ function validationFailure(value) {
117
121
  !Number.isFinite(Date.parse(firstSeenAt))) {
118
122
  return "firstSeenAt must be a valid timestamp";
119
123
  }
124
+ if (!isTrustedUserIdentityPinProvenance(Reflect.get(value, "provenance"))) {
125
+ return "provenance must be self, link, or observed";
126
+ }
120
127
  return null;
121
128
  }
122
129
  function validatedStringField(value, field) {
@@ -133,6 +140,13 @@ function validatedFormatVersion(value) {
133
140
  }
134
141
  return formatVersion;
135
142
  }
143
+ function validatedProvenance(value) {
144
+ const provenance = Reflect.get(value, "provenance");
145
+ if (!isTrustedUserIdentityPinProvenance(provenance)) {
146
+ throw new TypeError("Validated pin provenance is not a provenance");
147
+ }
148
+ return provenance;
149
+ }
136
150
  function assertCandidatePin(pin) {
137
151
  const failure = validationFailure(pin);
138
152
  if (failure) {
@@ -158,6 +172,7 @@ function parseStoredPin(value, scope) {
158
172
  encapsulationPublicKey: validatedStringField(value, "encapsulationPublicKey"),
159
173
  encapsulationKeyFingerprint: validatedStringField(value, "encapsulationKeyFingerprint"),
160
174
  firstSeenAt: validatedStringField(value, "firstSeenAt"),
175
+ provenance: validatedProvenance(value),
161
176
  };
162
177
  if (pin.identityTrustDomain !== scope.identityTrustDomain ||
163
178
  pin.userId !== scope.userId) {
@@ -199,12 +214,14 @@ export async function loadTrustedUserIdForSigningKey(input) {
199
214
  return rows[0]?.userId ?? null;
200
215
  }
201
216
  /**
202
- * Atomically establishes or verifies a trust-on-first-use identity pin.
217
+ * Atomically establishes or verifies a durable identity pin.
203
218
  *
204
219
  * The immediate transaction serializes first contact across SDK instances that
205
220
  * share the SQLite database. Conflict handling never replaces the existing
206
- * row: the winning pin is re-read and every identity field is compared before
207
- * this function returns.
221
+ * keys: the winning pin is re-read and every identity field is compared before
222
+ * this function returns. When the keys match and the candidate's provenance
223
+ * ranks higher (an identity link confirming an observed pin), only the
224
+ * provenance is raised; it is never lowered.
208
225
  */
209
226
  export async function compareOrInsertTrustedUserIdentityPin(input) {
210
227
  assertCandidatePin(input.pin);
@@ -245,7 +262,16 @@ export async function compareOrInsertTrustedUserIdentityPin(input) {
245
262
  if (differingFields.length > 0) {
246
263
  throw new TrustedUserIdentityPinMismatchError(stored, input.pin, differingFields);
247
264
  }
248
- return stored;
265
+ if (provenanceRank[input.pin.provenance] <=
266
+ provenanceRank[stored.provenance]) {
267
+ return stored;
268
+ }
269
+ await tx
270
+ .update(trustedUserIdentityPins)
271
+ .set({ provenance: input.pin.provenance })
272
+ .where(and(eq(trustedUserIdentityPins.identityTrustDomain, input.pin.identityTrustDomain), eq(trustedUserIdentityPins.userId, input.pin.userId)))
273
+ .run();
274
+ return { ...stored, provenance: input.pin.provenance };
249
275
  }, { behavior: "immediate" });
250
276
  });
251
277
  }
@@ -1 +1 @@
1
- {"version":3,"file":"trustedUserIdentityPinPersistence.js","sourceRoot":"","sources":["trustedUserIdentityPinPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EA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C","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n} from \"../trustedUserIdentity/types\";\nimport { runTrustedUserIdentityPinTransaction } from \"./trustedUserIdentityPinTransaction\";\n\nexport interface TrustedUserIdentityPin {\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingPublicKey: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationPublicKey: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n}\n\ntype ComparedPinField =\n | \"userId\"\n | \"formatVersion\"\n | \"signingSuite\"\n | \"signingPublicKey\"\n | \"signingKeyFingerprint\"\n | \"encapsulationSuite\"\n | \"encapsulationPublicKey\"\n | \"encapsulationKeyFingerprint\";\n\ninterface PinDiagnostic {\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n}\n\ninterface PinScope {\n readonly identityTrustDomain: string;\n readonly userId: string;\n}\n\nconst comparedPinFields: readonly ComparedPinField[] = [\n \"userId\",\n \"formatVersion\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n];\n\nconst requiredStringFields = [\n \"identityTrustDomain\",\n \"userId\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n] as const satisfies readonly (keyof TrustedUserIdentityPin)[];\n\nfunction pinDiagnostic(pin: TrustedUserIdentityPin): PinDiagnostic {\n return {\n userId: pin.userId,\n formatVersion: pin.formatVersion,\n signingSuite: pin.signingSuite,\n signingKeyFingerprint: pin.signingKeyFingerprint,\n encapsulationSuite: pin.encapsulationSuite,\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n firstSeenAt: pin.firstSeenAt,\n };\n}\n\nexport class TrustedUserIdentityPinMismatchError extends Error {\n readonly code = \"trusted_user_identity_pin_mismatch\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly existing: PinDiagnostic;\n readonly candidate: PinDiagnostic;\n readonly differingFields: readonly ComparedPinField[];\n\n constructor(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n differingFields: readonly ComparedPinField[],\n ) {\n super(\n `Trusted identity pin mismatch for ${candidate.userId} in ${candidate.identityTrustDomain}: ${differingFields.join(\", \")}`,\n );\n this.name = \"TrustedUserIdentityPinMismatchError\";\n this.identityTrustDomain = candidate.identityTrustDomain;\n this.userId = candidate.userId;\n this.existing = pinDiagnostic(existing);\n this.candidate = pinDiagnostic(candidate);\n this.differingFields = differingFields;\n }\n}\n\nexport class TrustedUserIdentityPinCorruptError extends Error {\n readonly code = \"trusted_user_identity_pin_corrupt\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(\n `Stored trusted identity pin is corrupt for ${scope.userId} in ${scope.identityTrustDomain}: ${reason}`,\n );\n this.name = \"TrustedUserIdentityPinCorruptError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nexport class TrustedUserIdentityPinInputError extends Error {\n readonly code = \"trusted_user_identity_pin_invalid_input\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(`Invalid trusted identity pin candidate: ${reason}`);\n this.name = \"TrustedUserIdentityPinInputError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nfunction pinScope(value: unknown): PinScope {\n if (typeof value !== \"object\" || value === null) {\n return { identityTrustDomain: \"<invalid>\", userId: \"<invalid>\" };\n }\n const identityTrustDomain = Reflect.get(value, \"identityTrustDomain\");\n const userId = Reflect.get(value, \"userId\");\n return {\n identityTrustDomain:\n typeof identityTrustDomain === \"string\"\n ? identityTrustDomain\n : \"<invalid>\",\n userId: typeof userId === \"string\" ? userId : \"<invalid>\",\n };\n}\n\nfunction validationFailure(value: unknown): string | null {\n if (typeof value !== \"object\" || value === null) {\n return \"row must be an object\";\n }\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (formatVersion !== TRUSTED_USER_IDENTITY_FORMAT_VERSION) {\n return `formatVersion must be ${TRUSTED_USER_IDENTITY_FORMAT_VERSION}`;\n }\n for (const field of requiredStringFields) {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\" || fieldValue.trim().length === 0) {\n return `${field} must be a non-empty string`;\n }\n }\n if (\n Reflect.get(value, \"signingSuite\") !== TRUSTED_USER_IDENTITY_SIGNING_SUITE\n ) {\n return `signingSuite must be ${TRUSTED_USER_IDENTITY_SIGNING_SUITE}`;\n }\n if (\n Reflect.get(value, \"encapsulationSuite\") !==\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE\n ) {\n return `encapsulationSuite must be ${TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE}`;\n }\n const firstSeenAt = Reflect.get(value, \"firstSeenAt\");\n if (\n typeof firstSeenAt !== \"string\" ||\n !Number.isFinite(Date.parse(firstSeenAt))\n ) {\n return \"firstSeenAt must be a valid timestamp\";\n }\n return null;\n}\n\nfunction validatedStringField(\n value: object,\n field: (typeof requiredStringFields)[number] | \"firstSeenAt\",\n): string {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\") {\n throw new TypeError(`Validated pin field ${field} is not a string`);\n }\n return fieldValue;\n}\n\nfunction validatedFormatVersion(value: object): number {\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (typeof formatVersion !== \"number\") {\n throw new TypeError(\"Validated pin formatVersion is not a number\");\n }\n return formatVersion;\n}\n\nfunction assertCandidatePin(pin: TrustedUserIdentityPin): void {\n const failure = validationFailure(pin);\n if (failure) {\n throw new TrustedUserIdentityPinInputError(pinScope(pin), failure);\n }\n}\n\nfunction parseStoredPin(\n value: unknown,\n scope: PinScope,\n): TrustedUserIdentityPin {\n const failure = validationFailure(value);\n if (failure) {\n throw new TrustedUserIdentityPinCorruptError(scope, failure);\n }\n if (typeof value !== \"object\" || value === null) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"row must be an object\",\n );\n }\n const pin: TrustedUserIdentityPin = {\n identityTrustDomain: validatedStringField(value, \"identityTrustDomain\"),\n userId: validatedStringField(value, \"userId\"),\n formatVersion: validatedFormatVersion(value),\n signingSuite: validatedStringField(value, \"signingSuite\"),\n signingPublicKey: validatedStringField(value, \"signingPublicKey\"),\n signingKeyFingerprint: validatedStringField(value, \"signingKeyFingerprint\"),\n encapsulationSuite: validatedStringField(value, \"encapsulationSuite\"),\n encapsulationPublicKey: validatedStringField(\n value,\n \"encapsulationPublicKey\",\n ),\n encapsulationKeyFingerprint: validatedStringField(\n value,\n \"encapsulationKeyFingerprint\",\n ),\n firstSeenAt: validatedStringField(value, \"firstSeenAt\"),\n };\n if (\n pin.identityTrustDomain !== scope.identityTrustDomain ||\n pin.userId !== scope.userId\n ) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"primary-key scope does not match the requested pin\",\n );\n }\n return pin;\n}\n\nasync function selectStoredPin(\n db: ClientSQLiteDatabase | ClientSQLiteTransactionScope,\n scope: PinScope,\n): Promise<TrustedUserIdentityPin | null> {\n const rows = await db\n .select()\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n scope.identityTrustDomain,\n ),\n eq(trustedUserIdentityPins.userId, scope.userId),\n ),\n )\n .limit(1);\n const row = rows[0];\n return row ? parseStoredPin(row, scope) : null;\n}\n\nfunction differingPinFields(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n): readonly ComparedPinField[] {\n return comparedPinFields.filter(\n (field) => existing[field] !== candidate[field],\n );\n}\n\nexport async function loadTrustedUserIdentityPin(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentityPin | null> {\n const scope: PinScope = {\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n };\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n return selectStoredPin(\n getClientSQLitePersistenceRuntime(input.execSql).db,\n scope,\n );\n}\n\n/**\n * The user a signing key is already bound to in this trust domain, if any.\n * Each key has at most one such user: the reverse binding is unique.\n */\nexport async function loadTrustedUserIdForSigningKey(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n}): Promise<string | null> {\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n const rows = await getClientSQLitePersistenceRuntime(input.execSql)\n .db.select({ userId: trustedUserIdentityPins.userId })\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.identityTrustDomain,\n ),\n eq(\n trustedUserIdentityPins.signingKeyFingerprint,\n input.signingKeyFingerprint,\n ),\n ),\n )\n .limit(1);\n return rows[0]?.userId ?? null;\n}\n\n/**\n * Atomically establishes or verifies a trust-on-first-use identity pin.\n *\n * The immediate transaction serializes first contact across SDK instances that\n * share the SQLite database. Conflict handling never replaces the existing\n * row: the winning pin is re-read and every identity field is compared before\n * this function returns.\n */\nexport async function compareOrInsertTrustedUserIdentityPin(input: {\n readonly execSql: ExecSql;\n readonly pin: TrustedUserIdentityPin;\n}): Promise<TrustedUserIdentityPin> {\n assertCandidatePin(input.pin);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n return runTrustedUserIdentityPinTransaction(async () => {\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n return runtime.transaction(\n async (tx) => {\n const aliases = await tx\n .select()\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.pin.identityTrustDomain,\n ),\n eq(\n trustedUserIdentityPins.signingKeyFingerprint,\n input.pin.signingKeyFingerprint,\n ),\n ),\n )\n .limit(1);\n const alias = aliases[0];\n if (alias && alias.userId !== input.pin.userId) {\n throw new TrustedUserIdentityPinMismatchError(\n parseStoredPin(alias, {\n identityTrustDomain: input.pin.identityTrustDomain,\n userId: alias.userId,\n }),\n input.pin,\n [\"userId\"],\n );\n }\n // Targets the primary key only: re-pinning the same user is a no-op,\n // but a write that would bind this key to a second user must fail at\n // the unique index rather than be silently skipped.\n await tx\n .insert(trustedUserIdentityPins)\n .values(input.pin)\n .onConflictDoNothing({\n target: [\n trustedUserIdentityPins.identityTrustDomain,\n trustedUserIdentityPins.userId,\n ],\n })\n .run();\n\n const stored = await selectStoredPin(tx, input.pin);\n if (!stored) {\n throw new TrustedUserIdentityPinCorruptError(\n input.pin,\n \"row is missing after compare-or-insert\",\n );\n }\n\n const differingFields = differingPinFields(stored, input.pin);\n if (differingFields.length > 0) {\n throw new TrustedUserIdentityPinMismatchError(\n stored,\n input.pin,\n differingFields,\n );\n }\n return stored;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
1
+ {"version":3,"file":"trustedUserIdentityPinPersistence.js","sourceRoot":"","sources":["trustedUserIdentityPinPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B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serIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n} from \"../trustedUserIdentity/types\";\nimport { runTrustedUserIdentityPinTransaction } from \"./trustedUserIdentityPinTransaction\";\n\n/**\n * How this device came to trust a pin. `self` is the user's own local keys,\n * `link` an independently exchanged identity link, and `observed` the first\n * server answer for a user already referenced by signed state. Only `self` and\n * `link` admit a user; provenance only ever rises, and never changes the keys.\n */\nexport type TrustedUserIdentityPinProvenance = \"self\" | \"link\" | \"observed\";\n\nconst provenanceRank: Readonly<\n Record<TrustedUserIdentityPinProvenance, number>\n> = { observed: 0, link: 1, self: 2 };\n\nfunction isTrustedUserIdentityPinProvenance(\n value: unknown,\n): value is TrustedUserIdentityPinProvenance {\n return value === \"self\" || value === \"link\" || value === \"observed\";\n}\n\nexport interface TrustedUserIdentityPin {\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingPublicKey: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationPublicKey: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}\n\ntype ComparedPinField =\n | \"userId\"\n | \"formatVersion\"\n | \"signingSuite\"\n | \"signingPublicKey\"\n | \"signingKeyFingerprint\"\n | \"encapsulationSuite\"\n | \"encapsulationPublicKey\"\n | \"encapsulationKeyFingerprint\";\n\ninterface PinDiagnostic {\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n}\n\ninterface PinScope {\n readonly identityTrustDomain: string;\n readonly userId: string;\n}\n\nconst comparedPinFields: readonly ComparedPinField[] = [\n \"userId\",\n \"formatVersion\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n];\n\nconst requiredStringFields = [\n \"identityTrustDomain\",\n \"userId\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n] as const satisfies readonly (keyof TrustedUserIdentityPin)[];\n\nfunction pinDiagnostic(pin: TrustedUserIdentityPin): PinDiagnostic {\n return {\n userId: pin.userId,\n formatVersion: pin.formatVersion,\n signingSuite: pin.signingSuite,\n signingKeyFingerprint: pin.signingKeyFingerprint,\n encapsulationSuite: pin.encapsulationSuite,\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n firstSeenAt: pin.firstSeenAt,\n };\n}\n\nexport class TrustedUserIdentityPinMismatchError extends Error {\n readonly code = \"trusted_user_identity_pin_mismatch\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly existing: PinDiagnostic;\n readonly candidate: PinDiagnostic;\n readonly differingFields: readonly ComparedPinField[];\n\n constructor(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n differingFields: readonly ComparedPinField[],\n ) {\n super(\n `Trusted identity pin mismatch for ${candidate.userId} in ${candidate.identityTrustDomain}: ${differingFields.join(\", \")}`,\n );\n this.name = \"TrustedUserIdentityPinMismatchError\";\n this.identityTrustDomain = candidate.identityTrustDomain;\n this.userId = candidate.userId;\n this.existing = pinDiagnostic(existing);\n this.candidate = pinDiagnostic(candidate);\n this.differingFields = differingFields;\n }\n}\n\nexport class TrustedUserIdentityPinCorruptError extends Error {\n readonly code = \"trusted_user_identity_pin_corrupt\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(\n `Stored trusted identity pin is corrupt for ${scope.userId} in ${scope.identityTrustDomain}: ${reason}`,\n );\n this.name = \"TrustedUserIdentityPinCorruptError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nexport class TrustedUserIdentityPinInputError extends Error {\n readonly code = \"trusted_user_identity_pin_invalid_input\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(`Invalid trusted identity pin candidate: ${reason}`);\n this.name = \"TrustedUserIdentityPinInputError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nfunction pinScope(value: unknown): PinScope {\n if (typeof value !== \"object\" || value === null) {\n return { identityTrustDomain: \"<invalid>\", userId: \"<invalid>\" };\n }\n const identityTrustDomain = Reflect.get(value, \"identityTrustDomain\");\n const userId = Reflect.get(value, \"userId\");\n return {\n identityTrustDomain:\n typeof identityTrustDomain === \"string\"\n ? identityTrustDomain\n : \"<invalid>\",\n userId: typeof userId === \"string\" ? userId : \"<invalid>\",\n };\n}\n\nfunction validationFailure(value: unknown): string | null {\n if (typeof value !== \"object\" || value === null) {\n return \"row must be an object\";\n }\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (formatVersion !== TRUSTED_USER_IDENTITY_FORMAT_VERSION) {\n return `formatVersion must be ${TRUSTED_USER_IDENTITY_FORMAT_VERSION}`;\n }\n for (const field of requiredStringFields) {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\" || fieldValue.trim().length === 0) {\n return `${field} must be a non-empty string`;\n }\n }\n if (\n Reflect.get(value, \"signingSuite\") !== TRUSTED_USER_IDENTITY_SIGNING_SUITE\n ) {\n return `signingSuite must be ${TRUSTED_USER_IDENTITY_SIGNING_SUITE}`;\n }\n if (\n Reflect.get(value, \"encapsulationSuite\") !==\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE\n ) {\n return `encapsulationSuite must be ${TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE}`;\n }\n const firstSeenAt = Reflect.get(value, \"firstSeenAt\");\n if (\n typeof firstSeenAt !== \"string\" ||\n !Number.isFinite(Date.parse(firstSeenAt))\n ) {\n return \"firstSeenAt must be a valid timestamp\";\n }\n if (!isTrustedUserIdentityPinProvenance(Reflect.get(value, \"provenance\"))) {\n return \"provenance must be self, link, or observed\";\n }\n return null;\n}\n\nfunction validatedStringField(\n value: object,\n field: (typeof requiredStringFields)[number] | \"firstSeenAt\",\n): string {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\") {\n throw new TypeError(`Validated pin field ${field} is not a string`);\n }\n return fieldValue;\n}\n\nfunction validatedFormatVersion(value: object): number {\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (typeof formatVersion !== \"number\") {\n throw new TypeError(\"Validated pin formatVersion is not a number\");\n }\n return formatVersion;\n}\n\nfunction validatedProvenance(value: object): TrustedUserIdentityPinProvenance {\n const provenance = Reflect.get(value, \"provenance\");\n if (!isTrustedUserIdentityPinProvenance(provenance)) {\n throw new TypeError(\"Validated pin provenance is not a provenance\");\n }\n return provenance;\n}\n\nfunction assertCandidatePin(pin: TrustedUserIdentityPin): void {\n const failure = validationFailure(pin);\n if (failure) {\n throw new TrustedUserIdentityPinInputError(pinScope(pin), failure);\n }\n}\n\nfunction parseStoredPin(\n value: unknown,\n scope: PinScope,\n): TrustedUserIdentityPin {\n const failure = validationFailure(value);\n if (failure) {\n throw new TrustedUserIdentityPinCorruptError(scope, failure);\n }\n if (typeof value !== \"object\" || value === null) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"row must be an object\",\n );\n }\n const pin: TrustedUserIdentityPin = {\n identityTrustDomain: validatedStringField(value, \"identityTrustDomain\"),\n userId: validatedStringField(value, \"userId\"),\n formatVersion: validatedFormatVersion(value),\n signingSuite: validatedStringField(value, \"signingSuite\"),\n signingPublicKey: validatedStringField(value, \"signingPublicKey\"),\n signingKeyFingerprint: validatedStringField(value, \"signingKeyFingerprint\"),\n encapsulationSuite: validatedStringField(value, \"encapsulationSuite\"),\n encapsulationPublicKey: validatedStringField(\n value,\n \"encapsulationPublicKey\",\n ),\n encapsulationKeyFingerprint: validatedStringField(\n value,\n \"encapsulationKeyFingerprint\",\n ),\n firstSeenAt: validatedStringField(value, \"firstSeenAt\"),\n provenance: validatedProvenance(value),\n };\n if (\n pin.identityTrustDomain !== scope.identityTrustDomain ||\n pin.userId !== scope.userId\n ) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"primary-key scope does not match the requested pin\",\n );\n }\n return pin;\n}\n\nasync function selectStoredPin(\n db: ClientSQLiteDatabase | ClientSQLiteTransactionScope,\n scope: PinScope,\n): Promise<TrustedUserIdentityPin | null> {\n const rows = await db\n .select()\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n scope.identityTrustDomain,\n ),\n eq(trustedUserIdentityPins.userId, scope.userId),\n ),\n )\n .limit(1);\n const row = rows[0];\n return row ? parseStoredPin(row, scope) : null;\n}\n\nfunction differingPinFields(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n): readonly ComparedPinField[] {\n return comparedPinFields.filter(\n (field) => existing[field] !== candidate[field],\n );\n}\n\nexport async function loadTrustedUserIdentityPin(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentityPin | null> {\n const scope: PinScope = {\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n };\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n return selectStoredPin(\n getClientSQLitePersistenceRuntime(input.execSql).db,\n scope,\n );\n}\n\n/**\n * The user a signing key is already bound to in this trust domain, if any.\n * Each key has at most one such user: the reverse binding is unique.\n */\nexport async function loadTrustedUserIdForSigningKey(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n}): Promise<string | null> {\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n const rows = await getClientSQLitePersistenceRuntime(input.execSql)\n .db.select({ userId: trustedUserIdentityPins.userId })\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.identityTrustDomain,\n ),\n eq(\n trustedUserIdentityPins.signingKeyFingerprint,\n input.signingKeyFingerprint,\n ),\n ),\n )\n .limit(1);\n return rows[0]?.userId ?? null;\n}\n\n/**\n * Atomically establishes or verifies a durable identity pin.\n *\n * The immediate transaction serializes first contact across SDK instances that\n * share the SQLite database. Conflict handling never replaces the existing\n * keys: the winning pin is re-read and every identity field is compared before\n * this function returns. When the keys match and the candidate's provenance\n * ranks higher (an identity link confirming an observed pin), only the\n * provenance is raised; it is never lowered.\n */\nexport async function compareOrInsertTrustedUserIdentityPin(input: {\n readonly execSql: ExecSql;\n readonly pin: TrustedUserIdentityPin;\n}): Promise<TrustedUserIdentityPin> {\n assertCandidatePin(input.pin);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n return runTrustedUserIdentityPinTransaction(async () => {\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n return runtime.transaction(\n async (tx) => {\n const aliases = await tx\n .select()\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.pin.identityTrustDomain,\n ),\n eq(\n trustedUserIdentityPins.signingKeyFingerprint,\n input.pin.signingKeyFingerprint,\n ),\n ),\n )\n .limit(1);\n const alias = aliases[0];\n if (alias && alias.userId !== input.pin.userId) {\n throw new TrustedUserIdentityPinMismatchError(\n parseStoredPin(alias, {\n identityTrustDomain: input.pin.identityTrustDomain,\n userId: alias.userId,\n }),\n input.pin,\n [\"userId\"],\n );\n }\n // Targets the primary key only: re-pinning the same user is a no-op,\n // but a write that would bind this key to a second user must fail at\n // the unique index rather than be silently skipped.\n await tx\n .insert(trustedUserIdentityPins)\n .values(input.pin)\n .onConflictDoNothing({\n target: [\n trustedUserIdentityPins.identityTrustDomain,\n trustedUserIdentityPins.userId,\n ],\n })\n .run();\n\n const stored = await selectStoredPin(tx, input.pin);\n if (!stored) {\n throw new TrustedUserIdentityPinCorruptError(\n input.pin,\n \"row is missing after compare-or-insert\",\n );\n }\n\n const differingFields = differingPinFields(stored, input.pin);\n if (differingFields.length > 0) {\n throw new TrustedUserIdentityPinMismatchError(\n stored,\n input.pin,\n differingFields,\n );\n }\n if (\n provenanceRank[input.pin.provenance] <=\n provenanceRank[stored.provenance]\n ) {\n return stored;\n }\n await tx\n .update(trustedUserIdentityPins)\n .set({ provenance: input.pin.provenance })\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.pin.identityTrustDomain,\n ),\n eq(trustedUserIdentityPins.userId, input.pin.userId),\n ),\n )\n .run();\n return { ...stored, provenance: input.pin.provenance };\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
@@ -1046,13 +1046,15 @@ export declare const documentPurgeCheckpoints: import("drizzle-orm/sqlite-core")
1046
1046
  dialect: "sqlite";
1047
1047
  }>;
1048
1048
  /**
1049
- * Durable trust-on-first-use pins for remote user identity bundles.
1049
+ * Durable pins for user identity bundles.
1050
1050
  *
1051
- * The first validated identity observed for a user in a configured API trust
1051
+ * The first validated identity accepted for a user in a configured API trust
1052
1052
  * domain is inserted once. Later observations must match every suite, public
1053
- * key, and fingerprint exactly; the persistence adapter never updates these
1054
- * rows. `firstSeenAt` records when the local trust decision was made and is
1055
- * likewise immutable.
1053
+ * key, and fingerprint exactly; the persistence adapter never changes those
1054
+ * columns. `firstSeenAt` records when the local trust decision was made and is
1055
+ * likewise immutable. `provenance` (`self`, `link`, or `observed`) records how
1056
+ * the pin was established; only `self` and `link` admit a user, and it only
1057
+ * rises. A table without it is an obsolete local database.
1056
1058
  *
1057
1059
  * Indexes:
1058
1060
  * - `(identityTrustDomain, userId)` is the primary key and scopes a user pin to
@@ -1258,6 +1260,25 @@ export declare const trustedUserIdentityPins: import("drizzle-orm/sqlite-core").
1258
1260
  }, {}, {
1259
1261
  length: number | undefined;
1260
1262
  }>;
1263
+ provenance: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1264
+ name: "provenance";
1265
+ tableName: "trusted_user_identity_pins";
1266
+ dataType: "string";
1267
+ columnType: "SQLiteText";
1268
+ data: "link" | "self" | "observed";
1269
+ driverParam: string;
1270
+ notNull: true;
1271
+ hasDefault: false;
1272
+ isPrimaryKey: false;
1273
+ isAutoincrement: false;
1274
+ hasRuntimeDefault: false;
1275
+ enumValues: ["self", "link", "observed"];
1276
+ baseColumn: never;
1277
+ identity: undefined;
1278
+ generated: undefined;
1279
+ }, {}, {
1280
+ length: number | undefined;
1281
+ }>;
1261
1282
  };
1262
1283
  dialect: "sqlite";
1263
1284
  }>;
@@ -7925,6 +7946,25 @@ export declare const clientSQLiteSchema: {
7925
7946
  }, {}, {
7926
7947
  length: number | undefined;
7927
7948
  }>;
7949
+ provenance: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7950
+ name: "provenance";
7951
+ tableName: "trusted_user_identity_pins";
7952
+ dataType: "string";
7953
+ columnType: "SQLiteText";
7954
+ data: "link" | "self" | "observed";
7955
+ driverParam: string;
7956
+ notNull: true;
7957
+ hasDefault: false;
7958
+ isPrimaryKey: false;
7959
+ isAutoincrement: false;
7960
+ hasRuntimeDefault: false;
7961
+ enumValues: ["self", "link", "observed"];
7962
+ baseColumn: never;
7963
+ identity: undefined;
7964
+ generated: undefined;
7965
+ }, {}, {
7966
+ length: number | undefined;
7967
+ }>;
7928
7968
  };
7929
7969
  dialect: "sqlite";
7930
7970
  }>;