@openlup/platform 0.15.0 → 0.16.0

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 (239) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +350 -3
  3. package/dist/identity/adminAuthBinding.d.ts +28 -0
  4. package/dist/identity/adminAuthBinding.js +66 -0
  5. package/dist/identity/adminAuthorization.d.ts +34 -0
  6. package/dist/identity/adminAuthorization.js +72 -0
  7. package/dist/identity/adminContracts.d.ts +70 -0
  8. package/dist/identity/adminContracts.js +43 -0
  9. package/dist/identity/adminMagicLinkHandler.d.ts +39 -0
  10. package/dist/identity/adminMagicLinkHandler.js +94 -0
  11. package/dist/identity/adminMeHandler.d.ts +15 -0
  12. package/dist/identity/adminMeHandler.js +49 -0
  13. package/dist/identity/adminPreflight.d.ts +16 -0
  14. package/dist/identity/adminPreflight.js +38 -0
  15. package/dist/identity/adminUserActionPorts.d.ts +31 -0
  16. package/dist/identity/adminUserActionPorts.js +51 -0
  17. package/dist/identity/adminUserHandlers.d.ts +38 -0
  18. package/dist/identity/adminUserHandlers.js +140 -0
  19. package/dist/identity/authVerifyUrl.d.ts +6 -0
  20. package/dist/identity/authVerifyUrl.js +54 -0
  21. package/dist/identity/contracts/contracts.d.ts +8 -0
  22. package/dist/identity/contracts/contracts.js +2 -0
  23. package/dist/identity/contracts/emailTrust.d.ts +3 -0
  24. package/dist/identity/contracts/emailTrust.js +4 -0
  25. package/dist/identity/contracts/index.d.ts +8 -0
  26. package/dist/identity/contracts/index.js +8 -0
  27. package/dist/identity/contracts/oidc.d.ts +3 -0
  28. package/dist/identity/contracts/oidc.js +9 -0
  29. package/dist/identity/contracts/operatorAuth.d.ts +35 -0
  30. package/dist/identity/contracts/operatorAuth.js +53 -0
  31. package/dist/identity/contracts/operatorInvitations.d.ts +37 -0
  32. package/dist/identity/contracts/operatorInvitations.js +1 -0
  33. package/dist/identity/contracts/ports.d.ts +22 -0
  34. package/dist/identity/contracts/ports.js +1 -0
  35. package/dist/identity/contracts/privacy.d.ts +62 -0
  36. package/dist/identity/contracts/privacy.js +99 -0
  37. package/dist/identity/contracts/providerList.d.ts +3 -0
  38. package/dist/identity/contracts/providerList.js +11 -0
  39. package/dist/identity/contracts/types.d.ts +16 -0
  40. package/dist/identity/contracts/types.js +4 -0
  41. package/dist/identity/contribution.d.ts +8 -0
  42. package/dist/identity/contribution.js +22 -0
  43. package/dist/identity/customerAuth.d.ts +8 -0
  44. package/dist/identity/customerAuth.js +1 -0
  45. package/dist/identity/customerAuthorization.d.ts +5 -0
  46. package/dist/identity/customerAuthorization.js +22 -0
  47. package/dist/identity/customerContracts.d.ts +42 -0
  48. package/dist/identity/customerContracts.js +43 -0
  49. package/dist/identity/customerIdentityBinding.d.ts +44 -0
  50. package/dist/identity/customerIdentityBinding.js +60 -0
  51. package/dist/identity/customerIdentityVerifier.d.ts +8 -0
  52. package/dist/identity/customerIdentityVerifier.js +101 -0
  53. package/dist/identity/customerMagicLinkHandler.d.ts +38 -0
  54. package/dist/identity/customerMagicLinkHandler.js +115 -0
  55. package/dist/identity/customerMeHandler.d.ts +11 -0
  56. package/dist/identity/customerMeHandler.js +46 -0
  57. package/dist/identity/customerPorts.d.ts +4 -0
  58. package/dist/identity/customerPorts.js +1 -0
  59. package/dist/identity/customerSessionBinding.d.ts +38 -0
  60. package/dist/identity/customerSessionBinding.js +80 -0
  61. package/dist/identity/customerSessionIssuer.d.ts +10 -0
  62. package/dist/identity/customerSessionIssuer.js +57 -0
  63. package/dist/identity/customerVerifyOtpHandler.d.ts +8 -0
  64. package/dist/identity/customerVerifyOtpHandler.js +41 -0
  65. package/dist/identity/directOperatorInvitationStore.d.ts +19 -0
  66. package/dist/identity/directOperatorInvitationStore.js +193 -0
  67. package/dist/identity/emailTrustPolicy.d.ts +14 -0
  68. package/dist/identity/emailTrustPolicy.js +16 -0
  69. package/dist/identity/identityPersonalDataContributor.d.ts +7 -0
  70. package/dist/identity/identityPersonalDataContributor.js +46 -0
  71. package/dist/identity/identityReadiness.d.ts +10 -0
  72. package/dist/identity/identityReadiness.js +25 -0
  73. package/dist/identity/index.d.ts +67 -0
  74. package/dist/identity/index.js +66 -0
  75. package/dist/identity/inviteAdminUserUseCase.d.ts +89 -0
  76. package/dist/identity/inviteAdminUserUseCase.js +75 -0
  77. package/dist/identity/jwtLibrary.d.ts +54 -0
  78. package/dist/identity/jwtLibrary.js +1 -0
  79. package/dist/identity/machineActorWriteFence.d.ts +4 -0
  80. package/dist/identity/machineActorWriteFence.js +13 -0
  81. package/dist/identity/magicLinkPorts.d.ts +28 -0
  82. package/dist/identity/magicLinkPorts.js +1 -0
  83. package/dist/identity/managedAccountLinkStore.d.ts +2 -0
  84. package/dist/identity/managedAccountLinkStore.js +93 -0
  85. package/dist/identity/managedAdminAuthVerifier.d.ts +7 -0
  86. package/dist/identity/managedAdminAuthVerifier.js +27 -0
  87. package/dist/identity/managedAdminUserGateways.d.ts +123 -0
  88. package/dist/identity/managedAdminUserGateways.js +127 -0
  89. package/dist/identity/managedClient.d.ts +90 -0
  90. package/dist/identity/managedClient.js +10 -0
  91. package/dist/identity/managedClientAuthLink.d.ts +3 -0
  92. package/dist/identity/managedClientAuthLink.js +115 -0
  93. package/dist/identity/managedCustomerMe.d.ts +13 -0
  94. package/dist/identity/managedCustomerMe.js +30 -0
  95. package/dist/identity/managedEmailTrustPolicy.d.ts +11 -0
  96. package/dist/identity/managedEmailTrustPolicy.js +105 -0
  97. package/dist/identity/managedIdentityVerifier.d.ts +2 -0
  98. package/dist/identity/managedIdentityVerifier.js +16 -0
  99. package/dist/identity/managedPrivacy.d.ts +4 -0
  100. package/dist/identity/managedPrivacy.js +39 -0
  101. package/dist/identity/messages.d.ts +29 -0
  102. package/dist/identity/messages.js +39 -0
  103. package/dist/identity/oidcIdentityVerifier.d.ts +45 -0
  104. package/dist/identity/oidcIdentityVerifier.js +309 -0
  105. package/dist/identity/oidcPrincipal.d.ts +2 -0
  106. package/dist/identity/oidcPrincipal.js +10 -0
  107. package/dist/identity/operatorAdminAuth.d.ts +6 -0
  108. package/dist/identity/operatorAdminAuth.js +13 -0
  109. package/dist/identity/operatorAuthHandlers.d.ts +18 -0
  110. package/dist/identity/operatorAuthHandlers.js +71 -0
  111. package/dist/identity/operatorIdentityVerifier.d.ts +8 -0
  112. package/dist/identity/operatorIdentityVerifier.js +19 -0
  113. package/dist/identity/operatorInvitationLifecycle.d.ts +7 -0
  114. package/dist/identity/operatorInvitationLifecycle.js +15 -0
  115. package/dist/identity/operatorInvitationPorts.d.ts +31 -0
  116. package/dist/identity/operatorInvitationPorts.js +1 -0
  117. package/dist/identity/operatorPorts.d.ts +37 -0
  118. package/dist/identity/operatorPorts.js +1 -0
  119. package/dist/identity/operatorSession.d.ts +13 -0
  120. package/dist/identity/operatorSession.js +31 -0
  121. package/dist/identity/operatorTokenAdminAuth.d.ts +15 -0
  122. package/dist/identity/operatorTokenAdminAuth.js +50 -0
  123. package/dist/identity/personalDataRegistry.d.ts +4 -0
  124. package/dist/identity/personalDataRegistry.js +11 -0
  125. package/dist/identity/platformAdminAuth.d.ts +15 -0
  126. package/dist/identity/platformAdminAuth.js +1 -0
  127. package/dist/identity/ports.d.ts +127 -0
  128. package/dist/identity/ports.js +38 -0
  129. package/dist/identity/postgresAccountLinkStore.d.ts +7 -0
  130. package/dist/identity/postgresAccountLinkStore.js +52 -0
  131. package/dist/identity/postgresCustomerMe.d.ts +3 -0
  132. package/dist/identity/postgresCustomerMe.js +21 -0
  133. package/dist/identity/postgresCustomerRecovery.d.ts +11 -0
  134. package/dist/identity/postgresCustomerRecovery.js +57 -0
  135. package/dist/identity/postgresOperatorIdentity.d.ts +5 -0
  136. package/dist/identity/postgresOperatorIdentity.js +137 -0
  137. package/dist/identity/postgresPrivacy.d.ts +7 -0
  138. package/dist/identity/postgresPrivacy.js +126 -0
  139. package/dist/identity/privacyHandlers.d.ts +10 -0
  140. package/dist/identity/privacyHandlers.js +35 -0
  141. package/dist/identity/privacyPorts.d.ts +72 -0
  142. package/dist/identity/privacyPorts.js +8 -0
  143. package/dist/identity/privacyUseCases.d.ts +5 -0
  144. package/dist/identity/privacyUseCases.js +55 -0
  145. package/dist/identity/reconcileAccountForPrincipal.d.ts +20 -0
  146. package/dist/identity/reconcileAccountForPrincipal.js +66 -0
  147. package/dist/identity/reconcileAccountHandler.d.ts +11 -0
  148. package/dist/identity/reconcileAccountHandler.js +30 -0
  149. package/dist/identity/removeAdminUserUseCase.d.ts +31 -0
  150. package/dist/identity/removeAdminUserUseCase.js +60 -0
  151. package/dist/identity/response.d.ts +3 -0
  152. package/dist/identity/response.js +2 -0
  153. package/dist/identity/sql.d.ts +44 -0
  154. package/dist/identity/sql.js +10 -0
  155. package/package.json +12 -2
  156. package/release-gates.json +22 -0
  157. package/sql/20260810180001_self_host_actor_auth.sql +40 -0
  158. package/sql/20260810204057_customer_identity_read.sql +31 -0
  159. package/sql/20260814090000_customer_selfservice_recovery.sql +477 -0
  160. package/sql/20260901143000_admin_membership_authority_foundation.sql +234 -0
  161. package/sql/20261018120000_identity_operator_invitations.sql +42 -0
  162. package/sql/20261018180000_identity_operator_challenges.sql +56 -0
  163. package/sql/20261018190000_identity_privacy_erasures.sql +15 -0
  164. package/src/identity/adminAuthBinding.ts +76 -0
  165. package/src/identity/adminAuthorization.ts +106 -0
  166. package/src/identity/adminContracts.ts +52 -0
  167. package/src/identity/adminMagicLinkHandler.ts +132 -0
  168. package/src/identity/adminMeHandler.ts +64 -0
  169. package/src/identity/adminPreflight.ts +46 -0
  170. package/src/identity/adminUserActionPorts.ts +78 -0
  171. package/src/identity/adminUserHandlers.ts +174 -0
  172. package/src/identity/authVerifyUrl.ts +56 -0
  173. package/src/identity/contracts/contracts.ts +15 -0
  174. package/src/identity/contracts/emailTrust.ts +5 -0
  175. package/src/identity/contracts/index.ts +8 -0
  176. package/src/identity/contracts/oidc.ts +10 -0
  177. package/src/identity/contracts/operatorAuth.ts +61 -0
  178. package/src/identity/contracts/operatorInvitations.ts +32 -0
  179. package/src/identity/contracts/ports.ts +25 -0
  180. package/src/identity/contracts/privacy.ts +86 -0
  181. package/src/identity/contracts/providerList.ts +13 -0
  182. package/src/identity/contracts/types.ts +25 -0
  183. package/src/identity/contribution.ts +29 -0
  184. package/src/identity/customerAuth.ts +3 -0
  185. package/src/identity/customerAuthorization.ts +38 -0
  186. package/src/identity/customerContracts.ts +52 -0
  187. package/src/identity/customerIdentityBinding.ts +125 -0
  188. package/src/identity/customerIdentityVerifier.ts +141 -0
  189. package/src/identity/customerMagicLinkHandler.ts +171 -0
  190. package/src/identity/customerMeHandler.ts +64 -0
  191. package/src/identity/customerPorts.ts +2 -0
  192. package/src/identity/customerSessionBinding.ts +114 -0
  193. package/src/identity/customerSessionIssuer.ts +71 -0
  194. package/src/identity/customerVerifyOtpHandler.ts +44 -0
  195. package/src/identity/directOperatorInvitationStore.ts +178 -0
  196. package/src/identity/emailTrustPolicy.ts +16 -0
  197. package/src/identity/identityPersonalDataContributor.ts +48 -0
  198. package/src/identity/identityReadiness.ts +26 -0
  199. package/src/identity/index.ts +69 -0
  200. package/src/identity/inviteAdminUserUseCase.ts +134 -0
  201. package/src/identity/jwtLibrary.ts +24 -0
  202. package/src/identity/machineActorWriteFence.ts +19 -0
  203. package/src/identity/magicLinkPorts.ts +7 -0
  204. package/src/identity/managedAccountLinkStore.ts +105 -0
  205. package/src/identity/managedAdminAuthVerifier.ts +40 -0
  206. package/src/identity/managedAdminUserGateways.ts +164 -0
  207. package/src/identity/managedClient.ts +58 -0
  208. package/src/identity/managedClientAuthLink.ts +120 -0
  209. package/src/identity/managedCustomerMe.ts +52 -0
  210. package/src/identity/managedEmailTrustPolicy.ts +90 -0
  211. package/src/identity/managedIdentityVerifier.ts +20 -0
  212. package/src/identity/managedPrivacy.ts +37 -0
  213. package/src/identity/messages.ts +41 -0
  214. package/src/identity/oidcIdentityVerifier.ts +229 -0
  215. package/src/identity/oidcPrincipal.ts +10 -0
  216. package/src/identity/operatorAdminAuth.ts +14 -0
  217. package/src/identity/operatorAuthHandlers.ts +52 -0
  218. package/src/identity/operatorIdentityVerifier.ts +19 -0
  219. package/src/identity/operatorInvitationLifecycle.ts +14 -0
  220. package/src/identity/operatorInvitationPorts.ts +11 -0
  221. package/src/identity/operatorPorts.ts +11 -0
  222. package/src/identity/operatorSession.ts +30 -0
  223. package/src/identity/operatorTokenAdminAuth.ts +79 -0
  224. package/src/identity/personalDataRegistry.ts +8 -0
  225. package/src/identity/platformAdminAuth.ts +7 -0
  226. package/src/identity/ports.ts +158 -0
  227. package/src/identity/postgresAccountLinkStore.ts +49 -0
  228. package/src/identity/postgresCustomerMe.ts +33 -0
  229. package/src/identity/postgresCustomerRecovery.ts +72 -0
  230. package/src/identity/postgresOperatorIdentity.ts +123 -0
  231. package/src/identity/postgresPrivacy.ts +117 -0
  232. package/src/identity/privacyHandlers.ts +33 -0
  233. package/src/identity/privacyPorts.ts +52 -0
  234. package/src/identity/privacyUseCases.ts +48 -0
  235. package/src/identity/reconcileAccountForPrincipal.ts +99 -0
  236. package/src/identity/reconcileAccountHandler.ts +36 -0
  237. package/src/identity/removeAdminUserUseCase.ts +85 -0
  238. package/src/identity/response.ts +3 -0
  239. package/src/identity/sql.ts +10 -0
@@ -0,0 +1,234 @@
1
+ -- Dormant direct human membership authority.
2
+ --
3
+ -- This forward introduces a provider-neutral human principal and its separate
4
+ -- current-panel membership for the direct bundle. It mirrors the managed role,
5
+ -- active/revoked state, provenance, acceptance, revocation, retained identity,
6
+ -- last-human-administrator refusal, and one-row revoke audit semantics. It does
7
+ -- not verify a login, grant browser access, seed a person, or link to the
8
+ -- existing platform_control_operators machine authority. The direct host owns
9
+ -- activation of a future human-login adapter; until then these relations are
10
+ -- deliberately dormant and default-deny for the actor roles.
11
+
12
+ CREATE TABLE public.platform_human_principals (
13
+ principal_id uuid PRIMARY KEY,
14
+ email text NOT NULL UNIQUE,
15
+ created_at timestamptz NOT NULL DEFAULT now()
16
+ );
17
+
18
+ CREATE TABLE public.platform_human_memberships (
19
+ principal_id uuid PRIMARY KEY REFERENCES public.platform_human_principals(principal_id) ON DELETE RESTRICT,
20
+ role text NOT NULL CHECK (role IN ('admin', 'distributor')),
21
+ membership_state text NOT NULL CHECK (membership_state IN ('active', 'revoked')),
22
+ membership_provenance text NOT NULL CHECK (membership_provenance IN ('legacy', 'invitation')),
23
+ membership_accepted_at timestamptz NOT NULL,
24
+ membership_revoked_at timestamptz,
25
+ membership_revoked_by uuid REFERENCES public.platform_human_principals(principal_id) ON DELETE RESTRICT,
26
+ membership_revocation_reason text,
27
+ CONSTRAINT platform_human_memberships_lifecycle_check CHECK (
28
+ (membership_state = 'active'
29
+ AND membership_revoked_at IS NULL
30
+ AND membership_revoked_by IS NULL
31
+ AND membership_revocation_reason IS NULL)
32
+ OR
33
+ (membership_state = 'revoked'
34
+ AND membership_revoked_at IS NOT NULL
35
+ AND membership_revoked_by IS NOT NULL)
36
+ ),
37
+ CONSTRAINT platform_human_memberships_distinct_revoker_check
38
+ CHECK (membership_revoked_by IS NULL OR membership_revoked_by <> principal_id),
39
+ CONSTRAINT platform_human_memberships_reason_length_check
40
+ CHECK (membership_revocation_reason IS NULL OR char_length(membership_revocation_reason) <= 1000)
41
+ );
42
+
43
+ CREATE TABLE public.platform_human_membership_audit_events (
44
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
45
+ actor_principal_id uuid NOT NULL REFERENCES public.platform_human_principals(principal_id) ON DELETE RESTRICT,
46
+ target_principal_id uuid NOT NULL REFERENCES public.platform_human_principals(principal_id) ON DELETE RESTRICT,
47
+ action text NOT NULL CHECK (action = 'revoke'),
48
+ old_value jsonb NOT NULL,
49
+ new_value jsonb NOT NULL,
50
+ reason text,
51
+ occurred_at timestamptz NOT NULL DEFAULT now()
52
+ );
53
+
54
+ CREATE INDEX platform_human_membership_audit_target_idx
55
+ ON public.platform_human_membership_audit_events(target_principal_id, occurred_at DESC);
56
+
57
+ REVOKE ALL ON TABLE
58
+ public.platform_human_principals,
59
+ public.platform_human_memberships,
60
+ public.platform_human_membership_audit_events
61
+ FROM PUBLIC, anon, authenticated;
62
+
63
+ CREATE FUNCTION public.platform_human_membership_is_active(p_principal_id uuid)
64
+ RETURNS boolean
65
+ LANGUAGE sql
66
+ STABLE
67
+ SET search_path = pg_catalog
68
+ AS $$
69
+ SELECT EXISTS (
70
+ SELECT 1
71
+ FROM public.platform_human_memberships AS membership_row
72
+ WHERE membership_row.principal_id = p_principal_id
73
+ AND membership_row.membership_state = 'active'
74
+ );
75
+ $$;
76
+
77
+ CREATE FUNCTION public.platform_human_membership_is_administrator(p_principal_id uuid)
78
+ RETURNS boolean
79
+ LANGUAGE sql
80
+ STABLE
81
+ SET search_path = pg_catalog
82
+ AS $$
83
+ SELECT EXISTS (
84
+ SELECT 1
85
+ FROM public.platform_human_memberships AS membership_row
86
+ WHERE membership_row.principal_id = p_principal_id
87
+ AND membership_row.membership_state = 'active'
88
+ AND membership_row.role = 'admin'
89
+ );
90
+ $$;
91
+
92
+ CREATE FUNCTION public.platform_human_memberships_guard()
93
+ RETURNS trigger
94
+ LANGUAGE plpgsql
95
+ SET search_path = pg_catalog, public
96
+ AS $$
97
+ DECLARE
98
+ v_removes_active_human_admin boolean := false;
99
+ v_other_active_human_admins integer;
100
+ BEGIN
101
+ IF TG_OP = 'DELETE' THEN
102
+ v_removes_active_human_admin := OLD.membership_state = 'active' AND OLD.role = 'admin';
103
+ ELSE
104
+ IF (OLD.membership_state, OLD.membership_provenance, OLD.membership_accepted_at,
105
+ OLD.membership_revoked_at, OLD.membership_revoked_by,
106
+ OLD.membership_revocation_reason)
107
+ IS DISTINCT FROM
108
+ (NEW.membership_state, NEW.membership_provenance, NEW.membership_accepted_at,
109
+ NEW.membership_revoked_at, NEW.membership_revoked_by,
110
+ NEW.membership_revocation_reason)
111
+ AND current_setting('app.platform_human_membership_revoke', true) IS DISTINCT FROM 'true' THEN
112
+ RAISE EXCEPTION 'platform_human_membership_lifecycle_update_forbidden' USING ERRCODE = '42501';
113
+ END IF;
114
+
115
+ IF OLD.membership_state <> 'active' AND NEW.role IS DISTINCT FROM OLD.role THEN
116
+ RAISE EXCEPTION 'platform_human_target_membership_inactive' USING ERRCODE = 'P0001';
117
+ END IF;
118
+
119
+ v_removes_active_human_admin := OLD.membership_state = 'active'
120
+ AND OLD.role = 'admin'
121
+ AND (NEW.membership_state <> 'active' OR NEW.role <> 'admin');
122
+ END IF;
123
+
124
+ IF v_removes_active_human_admin THEN
125
+ PERFORM pg_advisory_xact_lock(hashtext('platform_human_memberships_active_admin')::bigint);
126
+ SELECT count(*)
127
+ INTO v_other_active_human_admins
128
+ FROM public.platform_human_memberships
129
+ WHERE principal_id <> OLD.principal_id
130
+ AND membership_state = 'active'
131
+ AND role = 'admin';
132
+
133
+ IF v_other_active_human_admins < 1 THEN
134
+ RAISE EXCEPTION 'platform_human_last_admin_lockout' USING ERRCODE = 'P0001';
135
+ END IF;
136
+ END IF;
137
+
138
+ IF TG_OP = 'DELETE' THEN
139
+ RAISE EXCEPTION 'platform_human_membership_delete_forbidden' USING ERRCODE = '42501';
140
+ END IF;
141
+
142
+ RETURN NEW;
143
+ END;
144
+ $$;
145
+
146
+ CREATE TRIGGER trg_platform_human_memberships_guard
147
+ BEFORE UPDATE OR DELETE ON public.platform_human_memberships
148
+ FOR EACH ROW EXECUTE FUNCTION public.platform_human_memberships_guard();
149
+
150
+ CREATE FUNCTION public.platform_revoke_human_membership(
151
+ p_actor_principal_id uuid,
152
+ p_target_principal_id uuid,
153
+ p_reason text DEFAULT NULL
154
+ )
155
+ RETURNS public.platform_human_memberships
156
+ LANGUAGE plpgsql
157
+ SET search_path = pg_catalog, public
158
+ AS $$
159
+ DECLARE
160
+ v_target public.platform_human_memberships;
161
+ v_reason text := NULLIF(btrim(p_reason), '');
162
+ v_revoked_at timestamptz := clock_timestamp();
163
+ BEGIN
164
+ IF NOT public.platform_human_membership_is_administrator(p_actor_principal_id) THEN
165
+ RAISE EXCEPTION 'platform_human_revoke_forbidden' USING ERRCODE = '42501';
166
+ END IF;
167
+
168
+ IF p_target_principal_id IS NULL THEN
169
+ RAISE EXCEPTION 'platform_human_target_required' USING ERRCODE = '22023';
170
+ END IF;
171
+
172
+ IF p_target_principal_id = p_actor_principal_id THEN
173
+ RAISE EXCEPTION 'platform_human_self_revoke_forbidden' USING ERRCODE = 'P0001';
174
+ END IF;
175
+
176
+ IF v_reason IS NOT NULL AND char_length(v_reason) > 1000 THEN
177
+ RAISE EXCEPTION 'platform_human_revocation_reason_too_long' USING ERRCODE = '22023';
178
+ END IF;
179
+
180
+ SELECT * INTO v_target
181
+ FROM public.platform_human_memberships
182
+ WHERE principal_id = p_target_principal_id
183
+ FOR UPDATE;
184
+
185
+ IF NOT FOUND THEN
186
+ RAISE EXCEPTION 'platform_human_target_not_found' USING ERRCODE = 'P0002';
187
+ END IF;
188
+
189
+ IF v_target.membership_state = 'revoked' THEN
190
+ RETURN v_target;
191
+ END IF;
192
+
193
+ PERFORM set_config('app.platform_human_membership_revoke', 'true', true);
194
+
195
+ UPDATE public.platform_human_memberships
196
+ SET membership_state = 'revoked',
197
+ membership_revoked_at = v_revoked_at,
198
+ membership_revoked_by = p_actor_principal_id,
199
+ membership_revocation_reason = v_reason
200
+ WHERE principal_id = p_target_principal_id
201
+ RETURNING * INTO v_target;
202
+
203
+ INSERT INTO public.platform_human_membership_audit_events
204
+ (actor_principal_id, target_principal_id, action, old_value, new_value, reason, occurred_at)
205
+ VALUES (
206
+ p_actor_principal_id,
207
+ p_target_principal_id,
208
+ 'revoke',
209
+ jsonb_build_object('membershipState', 'active', 'role', v_target.role),
210
+ jsonb_build_object(
211
+ 'membershipState', 'revoked',
212
+ 'revokedAt', v_revoked_at,
213
+ 'revokedBy', p_actor_principal_id,
214
+ 'revocationReason', v_reason
215
+ ),
216
+ v_reason,
217
+ v_revoked_at
218
+ );
219
+
220
+ RETURN v_target;
221
+ END;
222
+ $$;
223
+
224
+ REVOKE ALL ON FUNCTION public.platform_human_membership_is_active(uuid)
225
+ FROM PUBLIC, anon, authenticated;
226
+ REVOKE ALL ON FUNCTION public.platform_human_membership_is_administrator(uuid)
227
+ FROM PUBLIC, anon, authenticated;
228
+ REVOKE ALL ON FUNCTION public.platform_human_memberships_guard()
229
+ FROM PUBLIC, anon, authenticated;
230
+ REVOKE ALL ON FUNCTION public.platform_revoke_human_membership(uuid, uuid, text)
231
+ FROM PUBLIC, anon, authenticated;
232
+
233
+ COMMENT ON FUNCTION public.platform_revoke_human_membership(uuid, uuid, text) IS
234
+ 'Dormant direct-bundle revoke command. Requires an active human administrator, retains the target principal/membership, refuses self and last-admin removal, and records one atomic revoke event.';
@@ -0,0 +1,42 @@
1
+ -- Pending direct operator invitations. Lifecycle commands use the trusted
2
+ -- server transaction lane; this forward adds no function or actor privilege.
3
+ CREATE TABLE public.identity_operator_invitations (
4
+ principal_id uuid PRIMARY KEY REFERENCES public.platform_human_principals(principal_id),
5
+ invitation_id uuid NOT NULL UNIQUE,
6
+ email_key text NOT NULL UNIQUE,
7
+ role text NOT NULL CHECK (role IN ('admin', 'distributor')),
8
+ phase text NOT NULL CHECK (phase IN ('invited', 'accepted', 'expired', 'cancelled')),
9
+ invited_by uuid NOT NULL REFERENCES public.platform_human_principals(principal_id),
10
+ invited_at timestamptz NOT NULL,
11
+ expires_at timestamptz NOT NULL,
12
+ accepted_at timestamptz,
13
+ closed_at timestamptz,
14
+ CHECK (email_key = lower(btrim(email_key)) AND NOT email_key = ''),
15
+ CHECK (expires_at BETWEEN invited_at + interval '60 seconds' AND invited_at + interval '30 days'),
16
+ CHECK (
17
+ (phase = 'invited' AND accepted_at IS NULL AND closed_at IS NULL)
18
+ OR (phase = 'accepted' AND accepted_at IS NOT NULL
19
+ AND accepted_at BETWEEN invited_at AND expires_at
20
+ AND NOT accepted_at = expires_at AND closed_at = accepted_at)
21
+ OR (phase = 'expired' AND accepted_at IS NULL AND closed_at = expires_at)
22
+ OR (phase = 'cancelled' AND accepted_at IS NULL AND closed_at IS NOT NULL)
23
+ )
24
+ );
25
+
26
+ CREATE TABLE public.identity_operator_invitation_events (
27
+ event_id uuid PRIMARY KEY,
28
+ invitation_id uuid NOT NULL,
29
+ principal_id uuid NOT NULL REFERENCES public.platform_human_principals(principal_id),
30
+ action text NOT NULL CHECK (action IN ('issue', 'reissue', 'accept', 'expire', 'cancel')),
31
+ actor_kind text NOT NULL CHECK (actor_kind IN ('human', 'system')),
32
+ actor_principal_id uuid REFERENCES public.platform_human_principals(principal_id),
33
+ old_value jsonb NOT NULL,
34
+ new_value jsonb NOT NULL,
35
+ occurred_at timestamptz NOT NULL,
36
+ UNIQUE (invitation_id, action),
37
+ CHECK ((actor_kind = 'human' AND actor_principal_id IS NOT NULL)
38
+ OR (actor_kind = 'system' AND actor_principal_id IS NULL))
39
+ );
40
+
41
+ CREATE INDEX identity_operator_invitation_events_target_idx
42
+ ON public.identity_operator_invitation_events(principal_id, occurred_at DESC);
@@ -0,0 +1,56 @@
1
+ CREATE UNIQUE INDEX platform_human_principals_normalized_email_key
2
+ ON public.platform_human_principals (lower(btrim(email)));
3
+
4
+ CREATE TABLE public.operator_identity_challenges (
5
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
6
+ principal_id uuid NOT NULL
7
+ REFERENCES public.platform_human_principals(principal_id),
8
+ email_fingerprint text NOT NULL,
9
+ token_hash text NOT NULL,
10
+ created_at timestamptz NOT NULL DEFAULT now(),
11
+ expires_at timestamptz NOT NULL,
12
+ used_at timestamptz,
13
+
14
+ CONSTRAINT operator_identity_challenges_email_fingerprint_check
15
+ CHECK (
16
+ length(email_fingerprint) = 64
17
+ AND translate(
18
+ email_fingerprint,
19
+ '0123456789abcdef',
20
+ ''
21
+ ) = ''
22
+ ),
23
+
24
+ CONSTRAINT operator_identity_challenges_token_hash_check
25
+ CHECK (
26
+ length(token_hash) = 64
27
+ AND translate(
28
+ token_hash,
29
+ '0123456789abcdef',
30
+ ''
31
+ ) = ''
32
+ ),
33
+
34
+ CONSTRAINT operator_identity_challenges_token_hash_key
35
+ UNIQUE (token_hash),
36
+
37
+ CONSTRAINT operator_identity_challenges_expiry_check
38
+ CHECK (
39
+ expires_at BETWEEN
40
+ created_at + INTERVAL '1 second'
41
+ AND created_at + INTERVAL '10 minutes'
42
+ ),
43
+
44
+ CONSTRAINT operator_identity_challenges_used_at_check
45
+ CHECK (
46
+ used_at IS NULL
47
+ OR used_at BETWEEN created_at AND expires_at
48
+ )
49
+ );
50
+
51
+ CREATE INDEX operator_identity_challenges_principal_created_idx
52
+ ON public.operator_identity_challenges
53
+ (principal_id, created_at DESC);
54
+
55
+ CREATE INDEX operator_identity_challenges_expiry_idx
56
+ ON public.operator_identity_challenges (expires_at, id);
@@ -0,0 +1,15 @@
1
+ -- Direct identity erasure receipts. Audit and idempotency share one retained
2
+ -- pseudonymous record; no personal export snapshot or actor grants are stored.
3
+ CREATE TABLE public.identity_privacy_erasures (
4
+ erasure_id uuid PRIMARY KEY,
5
+ idempotency_key uuid NOT NULL UNIQUE,
6
+ client_id uuid UNIQUE REFERENCES public.clients(id),
7
+ principal_id uuid UNIQUE,
8
+ actor_principal_id uuid NOT NULL REFERENCES public.platform_human_principals(principal_id),
9
+ contract_version text NOT NULL CHECK (contract_version = 'identity.erasure.v1'),
10
+ contributor_versions jsonb NOT NULL,
11
+ dispositions jsonb NOT NULL,
12
+ retained_obligations jsonb NOT NULL,
13
+ completed_at timestamptz NOT NULL,
14
+ CHECK (client_id IS NOT NULL OR principal_id IS NOT NULL)
15
+ );
@@ -0,0 +1,76 @@
1
+ import { createOperatorTokenAdminAuth, resolvePlatformOperatorAuthConfig } from "./operatorTokenAdminAuth.js";
2
+ import { resolveBundleId } from "../kernel/index.js";
3
+ import type { AdminAuthPort } from "./ports.js";
4
+ import type { AdminAuthBinding } from "./adminPreflight.js";
5
+ type Env = Record<string, string | undefined>;
6
+ export interface PlatformOperatorChecker { isOperatorAllowed(principalId: string): Promise<boolean>; close(): Promise<void> }
7
+ export type PlatformOperatorCheckerFactory = (env: Env) => PlatformOperatorChecker | Promise<PlatformOperatorChecker>;
8
+ export type AdminAuthBindingResolution =
9
+ | { readonly binding: AdminAuthBinding; readonly error?: undefined }
10
+ | { readonly binding?: undefined; readonly error: "managed_admin_auth_env_required" | "direct_admin_auth_config_invalid" };
11
+ export interface AdminAuthBindingOptions {
12
+ humanAuthFactory?: (env: Env) => AdminAuthPort & { close(): Promise<void> };
13
+ checkerFactory?: PlatformOperatorCheckerFactory;
14
+ managedAuthFactory?: (env: { url: string; anonKey: string }, accessToken: string | null) => AdminAuthPort;
15
+ }
16
+ function managedAuthEnv(env: Env): { url: string; anonKey: string } | null {
17
+ const url = env.SUPABASE_URL ?? env.VITE_SUPABASE_URL;
18
+ const anonKey = env.VITE_SUPABASE_PUBLISHABLE_KEY ?? env.VITE_SUPABASE_ANON_KEY ?? env.SUPABASE_ANON_KEY;
19
+ return url && anonKey ? { url, anonKey } : null;
20
+ }
21
+
22
+ /** Bind the admin authorizer selected by PLATFORM_BUNDLE. */
23
+ export function createAdminAuthBindingResolver(defaults: Required<Pick<AdminAuthBindingOptions, "checkerFactory" | "managedAuthFactory">> & Pick<AdminAuthBindingOptions, "humanAuthFactory">) {
24
+ return function resolveAdminAuthBinding(
25
+ env: Env,
26
+ options: AdminAuthBindingOptions = {},
27
+ ): AdminAuthBindingResolution {
28
+ const bundleId = resolveBundleId(env);
29
+ if (bundleId === "node-postgres") {
30
+ const config = resolvePlatformOperatorAuthConfig(env);
31
+ const humanFactory = options.humanAuthFactory ?? defaults.humanAuthFactory;
32
+ const humanEnabled = !!env.OPERATOR_IDENTITY_AUDIENCE && !!humanFactory;
33
+ if (!config.config && !humanEnabled) return { error: "direct_admin_auth_config_invalid" };
34
+ const checkerFactory = options.checkerFactory ?? defaults.checkerFactory;
35
+ return {
36
+ binding: {
37
+ identity: bundleId,
38
+ async run(accessToken, work) {
39
+ const scope: { checker?: PlatformOperatorChecker } = {};
40
+ const machine = config.config ? createOperatorTokenAdminAuth(config.config, async (principalId) => {
41
+ scope.checker ??= await checkerFactory(env);
42
+ return scope.checker.isOperatorAllowed(principalId);
43
+ }) : null;
44
+ let human: (AdminAuthPort & { close(): Promise<void> }) | undefined;
45
+ const auth: AdminAuthPort = { async authorize(token, restrictions) {
46
+ // Only a credential mismatch may select human verification; machine
47
+ // revocation and database errors retain their existing result.
48
+ const result = machine ? await machine.authorize(token, restrictions) : null;
49
+ if (result && (result.ok || result.code !== "UNAUTHORIZED")) return result;
50
+ if (!humanEnabled || !token) return result ?? { ok: false, code: "UNAUTHORIZED", message: "Operator authentication required" };
51
+ human ??= humanFactory!(env);
52
+ return human.authorize(token, restrictions);
53
+ } };
54
+ try {
55
+ return await work(auth);
56
+ } finally {
57
+ try { await scope.checker?.close(); } finally { await human?.close(); }
58
+ }
59
+ },
60
+ },
61
+ };
62
+ }
63
+
64
+ const authEnv = managedAuthEnv(env);
65
+ if (!authEnv) return { error: "managed_admin_auth_env_required" };
66
+ const managedAuthFactory = options.managedAuthFactory ?? defaults.managedAuthFactory;
67
+ return {
68
+ binding: {
69
+ identity: bundleId,
70
+ run: (accessToken, work) => work(managedAuthFactory(authEnv, accessToken)),
71
+ },
72
+ };
73
+ }
74
+
75
+
76
+ }
@@ -0,0 +1,106 @@
1
+ import type { HttpResponse, HttpRequest } from "../http/index.js";
2
+ import type { ManagedIdentityClient } from "./managedClient.js";
3
+ import { createIdentityResponder, type IdentityResponseOptions } from "./response.js";
4
+ export type AdminRole = "admin" | "distributor";
5
+
6
+ /** Authorization outcome: a resolved admin `userId`, or a typed denial. */
7
+ export type AdminAuthorization =
8
+ | { ok: true; userId: string; role: AdminRole; isMachineActor: boolean }
9
+ | { ok: false; code: "UNAUTHORIZED" | "FORBIDDEN"; message: string; identityCode?: string };
10
+
11
+ /** A request-bound thunk that resolves the calling admin (or a denial). */
12
+ export type AuthorizeAdmin = () => Promise<AdminAuthorization>;
13
+
14
+ export async function authorizeAdminWithUser(
15
+ rawClient: unknown,
16
+ accessToken: string | null,
17
+ options: { allowedRoles?: readonly AdminRole[] } = {},
18
+ ): Promise<AdminAuthorization> {
19
+ const client = rawClient as ManagedIdentityClient;
20
+ if (!accessToken) {
21
+ return { ok: false, code: "UNAUTHORIZED", message: "Admin session required" };
22
+ }
23
+
24
+ const { data: userData, error: userError } = await client.auth.getUser(accessToken);
25
+ if (userError || !userData.user) {
26
+ return { ok: false, code: "UNAUTHORIZED", message: "Admin session required" };
27
+ }
28
+
29
+ const { data, error } = await client
30
+ .from("admin_users")
31
+ .select("id, role, is_machine_actor")
32
+ .eq("id", userData.user.id)
33
+ .eq("membership_state", "active")
34
+ .maybeSingle();
35
+ if (error) throw error;
36
+ if (!data) {
37
+ return { ok: false, code: "FORBIDDEN", message: "Admin role required" };
38
+ }
39
+
40
+ const role = normalizeAdminRole(data.role);
41
+ if (role === null || (options.allowedRoles && !options.allowedRoles.includes(role))) {
42
+ return { ok: false, code: "FORBIDDEN", message: "Admin role required" };
43
+ }
44
+
45
+ // Fail closed: mirror the activate RPC's `COALESCE(is_machine_actor, true)` — only an
46
+ // explicit `false` is a human actor; anything else is treated as a machine. The DB row
47
+ // (`admin_users.is_machine_actor`, re-derived here and in every write RPC) is the single
48
+ // source of truth for actor kind — never trusted from the caller.
49
+ return {
50
+ ok: true,
51
+ userId: userData.user.id,
52
+ role,
53
+ isMachineActor: data.is_machine_actor !== false,
54
+ };
55
+ }
56
+
57
+ export function authorizeCommerceAdminWithUser(
58
+ client: unknown,
59
+ accessToken: string | null,
60
+ ): Promise<AdminAuthorization> {
61
+ return authorizeAdminWithUser(client, accessToken, { allowedRoles: ["admin"] });
62
+ }
63
+
64
+ export async function authorizeAdminBooleanWithUser(
65
+ client: unknown,
66
+ accessToken: string | null,
67
+ options: { allowedRoles?: readonly AdminRole[] } = {},
68
+ ): Promise<boolean> {
69
+ const authorization = await authorizeAdminWithUser(client, accessToken, options);
70
+ return authorization.ok;
71
+ }
72
+
73
+ /**
74
+ * Shared authz gate: returns the resolved admin (`userId` + DB-derived
75
+ * `isMachineActor`) or sends the error envelope and returns null.
76
+ */
77
+ export async function resolveAdmin(
78
+ authorizeAdmin: AuthorizeAdmin,
79
+ res: HttpResponse,
80
+ options: IdentityResponseOptions = {},
81
+ ): Promise<{ userId: string; role: AdminRole; isMachineActor: boolean } | null> {
82
+ const { sendBffError } = createIdentityResponder(options);
83
+ let authz: AdminAuthorization;
84
+ try {
85
+ authz = await authorizeAdmin();
86
+ } catch {
87
+ sendBffError(res, "UPSTREAM_UNAVAILABLE", "Admin authorization failed");
88
+ return null;
89
+ }
90
+ if (authz.ok === false) {
91
+ sendBffError(res, authz.code, authz.message);
92
+ return null;
93
+ }
94
+ return { userId: authz.userId, role: authz.role, isMachineActor: authz.isMachineActor };
95
+ }
96
+
97
+ function normalizeAdminRole(role: unknown): AdminRole | null {
98
+ return role === "admin" || role === "distributor" ? role : null;
99
+ }
100
+ export function readBearerToken(req: HttpRequest): string | null {
101
+ const raw = req.headers.authorization;
102
+ const value = Array.isArray(raw) ? raw[0] : raw;
103
+ const match = value?.match(/^Bearer\s+(.+)$/i);
104
+ return match?.[1]?.trim() || null;
105
+ }
106
+
@@ -0,0 +1,52 @@
1
+ import { z } from "zod";
2
+ z.config({ jitless: true });
3
+ export const adminUserRoleSchema = z.enum(["admin", "distributor"]);
4
+
5
+ export const adminPlatformMeRequestSchema = z.object({}).strict();
6
+
7
+ export const adminPlatformMeResponseSchema = z.object({
8
+ isAdmin: z.boolean(),
9
+ role: adminUserRoleSchema.nullable(),
10
+ });
11
+
12
+ export const adminUserRoleUpdateRequestSchema = z.object({
13
+ userId: z.string().min(1),
14
+ role: adminUserRoleSchema,
15
+ });
16
+
17
+ export const adminUserRoleUpdateResponseSchema = z.object({
18
+ userId: z.string().min(1),
19
+ role: adminUserRoleSchema,
20
+ saved: z.literal(true),
21
+ });
22
+
23
+ export const adminUserInviteRequestSchema = z.object({
24
+ email: z.string().trim().email().toLowerCase(),
25
+ role: adminUserRoleSchema,
26
+ });
27
+
28
+ export const adminUserInviteResponseSchema = z.discriminatedUnion("membershipState", [z.object({
29
+ principalId: z.string().min(1),
30
+ invitationId: z.string().min(1),
31
+ membershipState: z.literal("invited"),
32
+ role: adminUserRoleSchema,
33
+ invitedAt: z.iso.datetime(),
34
+ expiresAt: z.iso.datetime(),
35
+ code: z.enum(["INVITATION_CREATED", "ALREADY_INVITED", "INVITATION_REISSUED"]),
36
+ message: z.string().optional(),
37
+ }), z.object({
38
+ principalId: z.string().min(1),
39
+ membershipState: z.literal("active"),
40
+ role: adminUserRoleSchema,
41
+ code: z.enum(["MEMBERSHIP_CREATED", "ALREADY_ACTIVE"]),
42
+ message: z.string().optional(),
43
+ })]);
44
+
45
+ export const adminUserRemoveRequestSchema = z.object({
46
+ userId: z.string().min(1),
47
+ });
48
+
49
+ export const adminUserRemoveResponseSchema = z.object({
50
+ revoked: z.literal(true),
51
+ });
52
+