@simplelayer/graniteer-core 0.2.0 → 0.2.2

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 (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -460
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -309
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -95
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,248 +1,248 @@
1
- // THIRD SIBLING HMAC SCHEME. busClient.ts signs "v1" bookings under
2
- // BUS_HMAC_SECRET; membershipBusClient.ts signs "m1" membership snapshots
3
- // under BUS_HMAC_SECRET_MEMBERSHIP. This signs "r1" single-member resend
4
- // requests under BUS_HMAC_SECRET_RESEND and posts to
5
- // /membership/resend-invite. The three constructions are byte-distinct and
6
- // must never be merged or generalized.
7
- //
8
- // Canonical message -- 7 lines joined with "\n", no trailing newline:
9
- // r1
10
- // {source} trim().toLowerCase()
11
- // {event} trim().toLowerCase()
12
- // {request_id} trim().toLowerCase()
13
- // {requested_at} trim() only, verbatim
14
- // {email} trim().toLowerCase()
15
- // {unifi_user_id} trim() ONLY -- Access ids are CASE-SENSITIVE
16
- //
17
- // Auth is the portal bearer session ONLY. The email and unifi_user_id are
18
- // resolved server-side from the caller's own memberships row; nothing from the
19
- // request body is ever read. That scoping is the entire security model here.
20
- import { createClient } from 'npm:@supabase/supabase-js@2';
21
- import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
22
- import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
23
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
24
-
25
- const corsHeaders = {
26
- 'Access-Control-Allow-Origin': '*',
27
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
28
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
29
- };
30
-
31
- const CONTRACT = 'v0.3';
32
- const EVENT = 'membership.resend_invite';
33
- const TIMEOUT_MS = 10_000;
34
-
35
- export interface PortalResendInviteConfig {
36
- busBase: string;
37
- source: string;
38
- }
39
-
40
- function json(status: number, body: unknown) {
41
- return new Response(JSON.stringify(body), {
42
- status,
43
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
44
- });
45
- }
46
-
47
- function b64urlNoPad(bytes: Uint8Array): string {
48
- let s = '';
49
- for (const b of bytes) s += String.fromCharCode(b);
50
- return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
51
- }
52
-
53
- export function canonicalResendMessage(
54
- source: string,
55
- event: string,
56
- requestId: string,
57
- requestedAt: string,
58
- email: string,
59
- unifiUserId: string,
60
- ): string {
61
- return [
62
- 'r1',
63
- (source ?? '').trim().toLowerCase(),
64
- (event ?? '').trim().toLowerCase(),
65
- (requestId ?? '').trim().toLowerCase(),
66
- (requestedAt ?? '').trim(),
67
- (email ?? '').trim().toLowerCase(),
68
- // NEVER case-fold: UniFi Access user ids are case-sensitive.
69
- (unifiUserId ?? '').trim(),
70
- ].join('\n');
71
- }
72
-
73
- async function signResend(msg: string, secret: string): Promise<string> {
74
- const key = await crypto.subtle.importKey(
75
- 'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
76
- );
77
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
78
- return b64urlNoPad(sig);
79
- }
80
-
81
- export async function handle(req: Request, config: PortalResendInviteConfig): Promise<Response> {
82
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
83
- if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
84
-
85
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
86
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
87
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
88
- auth: { persistSession: false, autoRefreshToken: false },
89
- });
90
-
91
- try {
92
- const session = await resolvePortalSession(req, admin);
93
- if (!session) return json(401, { error: 'unauthorized' });
94
- const email = session.email.toLowerCase();
95
-
96
- // Per-email (not per-IP) app-level limit: a shared office IP must not
97
- // throttle other members. Defense-in-depth on top of the middleware's own
98
- // 300s per-email cooldown, not a substitute for it.
99
- const ok = await checkRateLimit(admin, 'portal-resend-invite', email, 5, 300);
100
- if (!ok) return json(429, { error: 'rate_limited' });
101
-
102
- // Step A: linked identity match. Step B (transition): email match limited
103
- // to still-unlinked rows.
104
- // PLURALITY: never .maybeSingle() here -- supabase-js returns data:null when
105
- // >1 row matches, which would break resend for exactly the member holding
106
- // two memberships. Oldest-first + limit(1), matching
107
- // _shared/membership.ts's "THE OLDEST ENTITLED MEMBERSHIP PAYS" intent.
108
- const { data: byIdRows, error: byIdErr } = await admin
109
- .from('memberships')
110
- .select('id,email,unifi_access_user_id')
111
- .eq('auth_user_id', session.id)
112
- .order('created_at', { ascending: true })
113
- .limit(1);
114
- if (byIdErr) return json(500, { error: 'lookup_failed' });
115
- let membership = (byIdRows ?? [])[0];
116
- if (!membership) {
117
- const { data: byEmailRows, error: byEmailErr } = await admin
118
- .from('memberships')
119
- .select('id,email,unifi_access_user_id')
120
- .eq('email', email)
121
- .is('auth_user_id', null)
122
- .order('created_at', { ascending: true })
123
- .limit(1);
124
- if (byEmailErr) return json(500, { error: 'lookup_failed' });
125
- membership = (byEmailRows ?? [])[0];
126
- }
127
-
128
- const unifiUserId = (membership?.unifi_access_user_id as string | null | undefined)?.trim() ?? '';
129
- if (!membership || !unifiUserId) {
130
- return json(400, { error: 'not_invited_yet' });
131
- }
132
-
133
- const secret = Deno.env.get('BUS_HMAC_SECRET_RESEND');
134
- if (!secret) {
135
- console.log('[portal-resend-invite] BUS_HMAC_SECRET_RESEND unset; skip');
136
- return json(503, { error: 'not_configured' });
137
- }
138
-
139
- const requestId = crypto.randomUUID();
140
- const requestedAt = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
141
- const hmac = await signResend(
142
- canonicalResendMessage(config.source, EVENT, requestId, requestedAt, email, unifiUserId),
143
- secret,
144
- );
145
-
146
- const body = {
147
- schema: 1,
148
- contract: CONTRACT,
149
- event: EVENT,
150
- source: config.source,
151
- request_id: requestId,
152
- requested_at: requestedAt,
153
- email,
154
- unifi_user_id: unifiUserId,
155
- hmac,
156
- };
157
-
158
- const res = await fetch(`${config.busBase}/membership/resend-invite`, {
159
- method: 'POST',
160
- headers: { 'Content-Type': 'application/json' },
161
- body: JSON.stringify(body),
162
- signal: AbortSignal.timeout(TIMEOUT_MS),
163
- });
164
-
165
- // Own-shape passthrough (same convention as membershipBusEnforce): any
166
- // parsed JSON carrying `ok`/`error`/`contract` is this endpoint's own
167
- // documented response -- success OR refusal -- and is handed back with its
168
- // own status. Only a body that is not this shape at all is a transport fault.
169
- const rawText = await res.text();
170
- let parsed: Record<string, unknown> | null = null;
171
- if (rawText.length > 0) {
172
- try {
173
- const candidate = JSON.parse(rawText);
174
- if (candidate && typeof candidate === 'object') parsed = candidate as Record<string, unknown>;
175
- } catch {
176
- parsed = null;
177
- }
178
- }
179
- const isOwnShape = parsed !== null &&
180
- ('contract' in parsed || 'error' in parsed || 'ok' in parsed);
181
- if (isOwnShape) {
182
- // Mirror membership-door-sync's T8 identity-status write-back: the
183
- // literal string 'sent' is the only value that means an invite actually
184
- // reached the member. 'dry_run' and every error/refusal shape must never
185
- // stamp this column. A failed stamp write must never mask the original
186
- // middleware response to the caller -- log and fall through regardless.
187
- if (parsed?.result === 'sent') {
188
- // identity_invited_at is a per-person fact, not a per-membership one
189
- // (same reasoning as membership-door-sync's T8 identity-status
190
- // write-back): a member holding more than one membership row must
191
- // have every row sharing their email stamped, not just whichever one
192
- // `membership` above happened to resolve to. Re-query by the SAME
193
- // `email` used to resolve `membership` and batch the write with
194
- // .in('id', ids) so one member never ends up with a stale unstamped
195
- // sibling row.
196
- const { data: emailRows, error: emailLookupErr } = await admin
197
- .from('memberships')
198
- .select('id')
199
- .eq('email', email);
200
- if (emailLookupErr) {
201
- await logOps(admin, 'resend_invite_stamp_failed', {
202
- event: EVENT,
203
- contract: CONTRACT,
204
- request_id: requestId,
205
- membership_id: membership.id,
206
- error: emailLookupErr.message,
207
- }, { severity: 'error' });
208
- } else {
209
- const ids = (emailRows ?? []).map((r) => r.id as string);
210
- if (ids.length > 0) {
211
- const { error: stampErr } = await admin
212
- .from('memberships')
213
- .update({ identity_invited_at: new Date().toISOString() })
214
- .in('id', ids);
215
- if (stampErr) {
216
- await logOps(admin, 'resend_invite_stamp_failed', {
217
- event: EVENT,
218
- contract: CONTRACT,
219
- request_id: requestId,
220
- membership_id: membership.id,
221
- error: stampErr.message,
222
- }, { severity: 'error' });
223
- }
224
- }
225
- }
226
- }
227
- return json(res.status, parsed);
228
- }
229
-
230
- await logOps(admin, 'resend_invite_bus_call_error', {
231
- event: EVENT,
232
- contract: CONTRACT,
233
- request_id: requestId,
234
- status: res.status,
235
- detail: rawText.slice(0, 300),
236
- }, { severity: 'error' });
237
- return json(502, { error: 'bus_unreachable' });
238
- } catch (e) {
239
- try {
240
- await logOps(admin, 'resend_invite_bus_call_error', {
241
- event: EVENT,
242
- contract: CONTRACT,
243
- message: e instanceof Error ? e.message : String(e),
244
- }, { severity: 'error' });
245
- } catch { /* ignore */ }
246
- return json(502, { error: 'bus_unreachable' });
247
- }
248
- }
1
+ // THIRD SIBLING HMAC SCHEME. busClient.ts signs "v1" bookings under
2
+ // BUS_HMAC_SECRET; membershipBusClient.ts signs "m1" membership snapshots
3
+ // under BUS_HMAC_SECRET_MEMBERSHIP. This signs "r1" single-member resend
4
+ // requests under BUS_HMAC_SECRET_RESEND and posts to
5
+ // /membership/resend-invite. The three constructions are byte-distinct and
6
+ // must never be merged or generalized.
7
+ //
8
+ // Canonical message -- 7 lines joined with "\n", no trailing newline:
9
+ // r1
10
+ // {source} trim().toLowerCase()
11
+ // {event} trim().toLowerCase()
12
+ // {request_id} trim().toLowerCase()
13
+ // {requested_at} trim() only, verbatim
14
+ // {email} trim().toLowerCase()
15
+ // {unifi_user_id} trim() ONLY -- Access ids are CASE-SENSITIVE
16
+ //
17
+ // Auth is the portal bearer session ONLY. The email and unifi_user_id are
18
+ // resolved server-side from the caller's own memberships row; nothing from the
19
+ // request body is ever read. That scoping is the entire security model here.
20
+ import { createClient } from 'npm:@supabase/supabase-js@2';
21
+ import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
22
+ import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
23
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
24
+
25
+ const corsHeaders = {
26
+ 'Access-Control-Allow-Origin': '*',
27
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
28
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
29
+ };
30
+
31
+ const CONTRACT = 'v0.3';
32
+ const EVENT = 'membership.resend_invite';
33
+ const TIMEOUT_MS = 10_000;
34
+
35
+ export interface PortalResendInviteConfig {
36
+ busBase: string;
37
+ source: string;
38
+ }
39
+
40
+ function json(status: number, body: unknown) {
41
+ return new Response(JSON.stringify(body), {
42
+ status,
43
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
44
+ });
45
+ }
46
+
47
+ function b64urlNoPad(bytes: Uint8Array): string {
48
+ let s = '';
49
+ for (const b of bytes) s += String.fromCharCode(b);
50
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
51
+ }
52
+
53
+ export function canonicalResendMessage(
54
+ source: string,
55
+ event: string,
56
+ requestId: string,
57
+ requestedAt: string,
58
+ email: string,
59
+ unifiUserId: string,
60
+ ): string {
61
+ return [
62
+ 'r1',
63
+ (source ?? '').trim().toLowerCase(),
64
+ (event ?? '').trim().toLowerCase(),
65
+ (requestId ?? '').trim().toLowerCase(),
66
+ (requestedAt ?? '').trim(),
67
+ (email ?? '').trim().toLowerCase(),
68
+ // NEVER case-fold: UniFi Access user ids are case-sensitive.
69
+ (unifiUserId ?? '').trim(),
70
+ ].join('\n');
71
+ }
72
+
73
+ async function signResend(msg: string, secret: string): Promise<string> {
74
+ const key = await crypto.subtle.importKey(
75
+ 'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
76
+ );
77
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
78
+ return b64urlNoPad(sig);
79
+ }
80
+
81
+ export async function handle(req: Request, config: PortalResendInviteConfig): Promise<Response> {
82
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
83
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
84
+
85
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
86
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
87
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
88
+ auth: { persistSession: false, autoRefreshToken: false },
89
+ });
90
+
91
+ try {
92
+ const session = await resolvePortalSession(req, admin);
93
+ if (!session) return json(401, { error: 'unauthorized' });
94
+ const email = session.email.toLowerCase();
95
+
96
+ // Per-email (not per-IP) app-level limit: a shared office IP must not
97
+ // throttle other members. Defense-in-depth on top of the middleware's own
98
+ // 300s per-email cooldown, not a substitute for it.
99
+ const ok = await checkRateLimit(admin, 'portal-resend-invite', email, 5, 300);
100
+ if (!ok) return json(429, { error: 'rate_limited' });
101
+
102
+ // Step A: linked identity match. Step B (transition): email match limited
103
+ // to still-unlinked rows.
104
+ // PLURALITY: never .maybeSingle() here -- supabase-js returns data:null when
105
+ // >1 row matches, which would break resend for exactly the member holding
106
+ // two memberships. Oldest-first + limit(1), matching
107
+ // _shared/membership.ts's "THE OLDEST ENTITLED MEMBERSHIP PAYS" intent.
108
+ const { data: byIdRows, error: byIdErr } = await admin
109
+ .from('memberships')
110
+ .select('id,email,unifi_access_user_id')
111
+ .eq('auth_user_id', session.id)
112
+ .order('created_at', { ascending: true })
113
+ .limit(1);
114
+ if (byIdErr) return json(500, { error: 'lookup_failed' });
115
+ let membership = (byIdRows ?? [])[0];
116
+ if (!membership) {
117
+ const { data: byEmailRows, error: byEmailErr } = await admin
118
+ .from('memberships')
119
+ .select('id,email,unifi_access_user_id')
120
+ .eq('email', email)
121
+ .is('auth_user_id', null)
122
+ .order('created_at', { ascending: true })
123
+ .limit(1);
124
+ if (byEmailErr) return json(500, { error: 'lookup_failed' });
125
+ membership = (byEmailRows ?? [])[0];
126
+ }
127
+
128
+ const unifiUserId = (membership?.unifi_access_user_id as string | null | undefined)?.trim() ?? '';
129
+ if (!membership || !unifiUserId) {
130
+ return json(400, { error: 'not_invited_yet' });
131
+ }
132
+
133
+ const secret = Deno.env.get('BUS_HMAC_SECRET_RESEND');
134
+ if (!secret) {
135
+ console.log('[portal-resend-invite] BUS_HMAC_SECRET_RESEND unset; skip');
136
+ return json(503, { error: 'not_configured' });
137
+ }
138
+
139
+ const requestId = crypto.randomUUID();
140
+ const requestedAt = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
141
+ const hmac = await signResend(
142
+ canonicalResendMessage(config.source, EVENT, requestId, requestedAt, email, unifiUserId),
143
+ secret,
144
+ );
145
+
146
+ const body = {
147
+ schema: 1,
148
+ contract: CONTRACT,
149
+ event: EVENT,
150
+ source: config.source,
151
+ request_id: requestId,
152
+ requested_at: requestedAt,
153
+ email,
154
+ unifi_user_id: unifiUserId,
155
+ hmac,
156
+ };
157
+
158
+ const res = await fetch(`${config.busBase}/membership/resend-invite`, {
159
+ method: 'POST',
160
+ headers: { 'Content-Type': 'application/json' },
161
+ body: JSON.stringify(body),
162
+ signal: AbortSignal.timeout(TIMEOUT_MS),
163
+ });
164
+
165
+ // Own-shape passthrough (same convention as membershipBusEnforce): any
166
+ // parsed JSON carrying `ok`/`error`/`contract` is this endpoint's own
167
+ // documented response -- success OR refusal -- and is handed back with its
168
+ // own status. Only a body that is not this shape at all is a transport fault.
169
+ const rawText = await res.text();
170
+ let parsed: Record<string, unknown> | null = null;
171
+ if (rawText.length > 0) {
172
+ try {
173
+ const candidate = JSON.parse(rawText);
174
+ if (candidate && typeof candidate === 'object') parsed = candidate as Record<string, unknown>;
175
+ } catch {
176
+ parsed = null;
177
+ }
178
+ }
179
+ const isOwnShape = parsed !== null &&
180
+ ('contract' in parsed || 'error' in parsed || 'ok' in parsed);
181
+ if (isOwnShape) {
182
+ // Mirror membership-door-sync's T8 identity-status write-back: the
183
+ // literal string 'sent' is the only value that means an invite actually
184
+ // reached the member. 'dry_run' and every error/refusal shape must never
185
+ // stamp this column. A failed stamp write must never mask the original
186
+ // middleware response to the caller -- log and fall through regardless.
187
+ if (parsed?.result === 'sent') {
188
+ // identity_invited_at is a per-person fact, not a per-membership one
189
+ // (same reasoning as membership-door-sync's T8 identity-status
190
+ // write-back): a member holding more than one membership row must
191
+ // have every row sharing their email stamped, not just whichever one
192
+ // `membership` above happened to resolve to. Re-query by the SAME
193
+ // `email` used to resolve `membership` and batch the write with
194
+ // .in('id', ids) so one member never ends up with a stale unstamped
195
+ // sibling row.
196
+ const { data: emailRows, error: emailLookupErr } = await admin
197
+ .from('memberships')
198
+ .select('id')
199
+ .eq('email', email);
200
+ if (emailLookupErr) {
201
+ await logOps(admin, 'resend_invite_stamp_failed', {
202
+ event: EVENT,
203
+ contract: CONTRACT,
204
+ request_id: requestId,
205
+ membership_id: membership.id,
206
+ error: emailLookupErr.message,
207
+ }, { severity: 'error' });
208
+ } else {
209
+ const ids = (emailRows ?? []).map((r) => r.id as string);
210
+ if (ids.length > 0) {
211
+ const { error: stampErr } = await admin
212
+ .from('memberships')
213
+ .update({ identity_invited_at: new Date().toISOString() })
214
+ .in('id', ids);
215
+ if (stampErr) {
216
+ await logOps(admin, 'resend_invite_stamp_failed', {
217
+ event: EVENT,
218
+ contract: CONTRACT,
219
+ request_id: requestId,
220
+ membership_id: membership.id,
221
+ error: stampErr.message,
222
+ }, { severity: 'error' });
223
+ }
224
+ }
225
+ }
226
+ }
227
+ return json(res.status, parsed);
228
+ }
229
+
230
+ await logOps(admin, 'resend_invite_bus_call_error', {
231
+ event: EVENT,
232
+ contract: CONTRACT,
233
+ request_id: requestId,
234
+ status: res.status,
235
+ detail: rawText.slice(0, 300),
236
+ }, { severity: 'error' });
237
+ return json(502, { error: 'bus_unreachable' });
238
+ } catch (e) {
239
+ try {
240
+ await logOps(admin, 'resend_invite_bus_call_error', {
241
+ event: EVENT,
242
+ contract: CONTRACT,
243
+ message: e instanceof Error ? e.message : String(e),
244
+ }, { severity: 'error' });
245
+ } catch { /* ignore */ }
246
+ return json(502, { error: 'bus_unreachable' });
247
+ }
248
+ }