@simplelayer/graniteer-core 0.2.1 → 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 -334
  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 -217
  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,348 +1,348 @@
1
- // frAIdays Community v2, Feature B — admin-triggered push send.
2
- //
3
- // Auth pattern copied from admin-cancel-booking/index.ts: JWT/JWKS
4
- // verification, aal2 (MFA) requirement, and a direct admin_users table
5
- // lookup by the caller's email (no is_admin() RPC).
6
- import { createClient } from 'npm:@supabase/supabase-js@2';
7
- import webpush from 'npm:web-push@3.6.7';
8
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
9
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
10
-
11
- const corsHeaders = {
12
- 'Access-Control-Allow-Origin': '*',
13
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
14
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
15
- };
16
-
17
- interface CallerClaims {
18
- sub: string;
19
- email?: string;
20
- aal?: string;
21
- }
22
-
23
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
24
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
25
- function getJwks(supabaseUrl: string) {
26
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
- return jwksCache;
28
- }
29
-
30
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
31
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
32
- const token = authHeader.slice(7).trim();
33
- try {
34
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
35
- const claims = payload as unknown as CallerClaims;
36
- if (!claims.sub) return null;
37
- return claims;
38
- } catch {
39
- return null;
40
- }
41
- }
42
-
43
- function json(status: number, body: unknown) {
44
- return new Response(JSON.stringify(body), {
45
- status,
46
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
47
- });
48
- }
49
-
50
- type Topic = 'recaps' | 'event_reminders';
51
- type Kind = 'post_published' | 'event_reminder' | 'manual';
52
- type Audience = 'public' | 'fraidays_rsvpd' | 'fraidays_attended';
53
-
54
- interface SendBody {
55
- kind?: string;
56
- post_id?: string;
57
- event_ref?: string;
58
- topic?: string;
59
- title?: string;
60
- body?: string;
61
- url?: string;
62
- audience?: string;
63
- dry_run?: boolean;
64
- dedupe_key?: string;
65
- }
66
-
67
- interface SubscriptionForSend {
68
- id: string;
69
- endpoint: string;
70
- p256dh: string;
71
- auth_secret: string;
72
- fraidays_profile_id: string;
73
- failure_count: number | null;
74
- }
75
-
76
- export async function handle(req: Request, operator: { vapidContact: string }): Promise<Response> {
77
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
78
-
79
- // Kill switch — checked before any auth/validation work runs at all.
80
- if (Deno.env.get('PUSH_SEND_DISABLED') === 'true') {
81
- return json(503, { ok: false, error: 'push sending is currently disabled' });
82
- }
83
-
84
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
85
-
86
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
87
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
88
-
89
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
90
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
91
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
92
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
93
- const callerEmail = (caller.email ?? '').toLowerCase();
94
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
95
-
96
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
97
- auth: { persistSession: false, autoRefreshToken: false },
98
- });
99
-
100
- const [ipOk, emailOk] = await Promise.all([
101
- checkRateLimit(admin, 'push-send-ip', clientIp(req), 30, 300),
102
- checkRateLimit(admin, 'push-send-email', callerEmail, 20, 300),
103
- ]);
104
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
105
-
106
- const { data: allow, error: allowErr } = await admin
107
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
108
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
109
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
110
-
111
- let raw: SendBody;
112
- try {
113
- raw = await req.json();
114
- } catch {
115
- return json(400, { ok: false, error: 'invalid_json' });
116
- }
117
-
118
- // --- Validation. Nothing is written until every check below passes. ---
119
-
120
- if (raw.topic !== 'recaps' && raw.topic !== 'event_reminders') {
121
- return json(400, { ok: false, error: 'invalid_topic' });
122
- }
123
- const topic = raw.topic as Topic;
124
-
125
- if (raw.kind === 'test') return json(400, { ok: false, error: 'kind_test_not_allowed_here' });
126
- if (raw.kind !== 'post_published' && raw.kind !== 'event_reminder' && raw.kind !== 'manual') {
127
- return json(400, { ok: false, error: 'invalid_kind' });
128
- }
129
- const kind = raw.kind as Kind;
130
-
131
- const title = (raw.title ?? '').trim();
132
- if (!title || title.length > 80) return json(400, { ok: false, error: 'invalid_title' });
133
-
134
- const bodyText = (raw.body ?? '').trim();
135
- if (!bodyText || bodyText.length > 160) return json(400, { ok: false, error: 'invalid_body' });
136
-
137
- const url = raw.url ?? '';
138
- if (!url.startsWith('/')) return json(400, { ok: false, error: 'invalid_url' });
139
-
140
- if (raw.audience !== 'public' && raw.audience !== 'fraidays_rsvpd' && raw.audience !== 'fraidays_attended') {
141
- return json(400, { ok: false, error: 'invalid_audience' });
142
- }
143
- const audience = raw.audience as Audience;
144
-
145
- const postId = kind === 'post_published' ? (raw.post_id ?? '').trim() : (raw.post_id ?? null) || null;
146
- if (kind === 'post_published' && !postId) return json(400, { ok: false, error: 'post_id_required' });
147
-
148
- const eventRef = kind === 'event_reminder' ? (raw.event_ref ?? '').trim() : (raw.event_ref ?? null) || null;
149
- if (kind === 'event_reminder' && !eventRef) return json(400, { ok: false, error: 'event_ref_required' });
150
-
151
- const dryRun = !!raw.dry_run;
152
-
153
- let dedupeKey: string;
154
- if (kind === 'post_published') {
155
- dedupeKey = `post_published:${postId}`;
156
- } else if (kind === 'event_reminder') {
157
- dedupeKey = `event_reminder:${eventRef}`;
158
- } else {
159
- const supplied = (raw.dedupe_key ?? '').trim();
160
- dedupeKey = supplied || `manual:${topic}:${Date.now()}`;
161
- }
162
-
163
- // --- Step 1: insert the notification_sends row. The unique index on
164
- // dedupe_key WHERE dry_run=false is the idempotency guard for real sends.
165
- const { data: sendRow, error: insertErr } = await admin
166
- .from('notification_sends')
167
- .insert({
168
- kind,
169
- post_id: postId,
170
- event_ref: eventRef,
171
- audience,
172
- topic,
173
- title,
174
- body: bodyText,
175
- url,
176
- dedupe_key: dedupeKey,
177
- status: dryRun ? 'dry_run_complete' : 'queued',
178
- dry_run: dryRun,
179
- recipients_targeted: 0,
180
- created_by: caller.sub,
181
- })
182
- .select('id')
183
- .single();
184
-
185
- if (insertErr) {
186
- if ((insertErr as { code?: string }).code === '23505') {
187
- return json(409, { ok: false, error: 'duplicate_send', message: 'A real send with this dedupe key already exists.' });
188
- }
189
- return json(500, { ok: false, error: 'insert_failed', detail: insertErr.message });
190
- }
191
- const sendId = sendRow.id as string;
192
-
193
- // --- Step 2: compute recipients.
194
- //
195
- // The spec query is a single SQL statement with a LEFT JOIN + CASE-based
196
- // audience/topic filter. This codebase has no existing helper for running
197
- // raw parameterized SQL from an Edge Function, and adding one (a new
198
- // SECURITY DEFINER Postgres function) would require a migration — out of
199
- // scope for this task (DB schema is frozen here; see task instructions).
200
- // Instead the same semantics are built from two chained, fully-parameterized
201
- // PostgREST queries plus an in-memory merge — no SQL text is ever
202
- // constructed from caller input (topic/audience are already validated to
203
- // one of a small fixed enum above, and are only ever used to choose which
204
- // .eq()/ternary branch to take, never concatenated into a query string).
205
- let subsQuery = admin
206
- .from('push_subscriptions')
207
- .select('id,endpoint,p256dh,auth_secret,fraidays_profile_id,failure_count,fraidays_profiles!inner(id,auth_user_id,rsvp_current,attended_ever)')
208
- .is('disabled_at', null)
209
- .not('fraidays_profiles.auth_user_id', 'is', null);
210
-
211
- if (audience === 'fraidays_rsvpd') {
212
- subsQuery = subsQuery.eq('fraidays_profiles.rsvp_current', true);
213
- } else if (audience === 'fraidays_attended') {
214
- subsQuery = subsQuery.eq('fraidays_profiles.attended_ever', true);
215
- }
216
- // audience === 'public' -> no additional filter.
217
-
218
- const { data: candidateSubs, error: subsErr } = await subsQuery;
219
- if (subsErr) {
220
- await admin.from('notification_sends').update({ status: 'failed' }).eq('id', sendId);
221
- return json(500, { ok: false, error: 'recipients_lookup_failed', detail: subsErr.message });
222
- }
223
-
224
- const profileIds = Array.from(new Set((candidateSubs ?? []).map((s: any) => s.fraidays_profile_id as string)));
225
- type PrefRow = { fraidays_profile_id: string; notify_recaps: boolean; notify_event_reminders: boolean };
226
- const { data: prefsRows, error: prefsErr } = profileIds.length
227
- ? await admin
228
- .from('fraidays_notification_prefs')
229
- .select('fraidays_profile_id,notify_recaps,notify_event_reminders')
230
- .in('fraidays_profile_id', profileIds)
231
- : { data: [] as PrefRow[], error: null };
232
- if (prefsErr) {
233
- await admin.from('notification_sends').update({ status: 'failed' }).eq('id', sendId);
234
- return json(500, { ok: false, error: 'prefs_lookup_failed', detail: prefsErr.message });
235
- }
236
- const prefsByProfile = new Map(((prefsRows ?? []) as PrefRow[]).map((p) => [p.fraidays_profile_id, p]));
237
-
238
- const recipients: SubscriptionForSend[] = (candidateSubs ?? [])
239
- .filter((s: any) => {
240
- const pref = prefsByProfile.get(s.fraidays_profile_id);
241
- const allowed = topic === 'recaps' ? (pref?.notify_recaps ?? true) : (pref?.notify_event_reminders ?? true);
242
- return allowed;
243
- })
244
- .map((s: any) => ({
245
- id: s.id,
246
- endpoint: s.endpoint,
247
- p256dh: s.p256dh,
248
- auth_secret: s.auth_secret,
249
- fraidays_profile_id: s.fraidays_profile_id,
250
- failure_count: s.failure_count,
251
- }));
252
-
253
- await admin.from('notification_sends').update({ recipients_targeted: recipients.length }).eq('id', sendId);
254
-
255
- if (dryRun) {
256
- return json(200, { ok: true, dry_run: true, send_id: sendId, recipients_targeted: recipients.length });
257
- }
258
-
259
- // --- Step 4: real send.
260
- const startedAt = new Date().toISOString();
261
- await admin.from('notification_sends').update({ status: 'sending', started_at: startedAt }).eq('id', sendId);
262
-
263
- const vapidPublicKey = Deno.env.get('VAPID_PUBLIC_KEY');
264
- const vapidPrivateKey = Deno.env.get('VAPID_PRIVATE_KEY');
265
- if (!vapidPublicKey || !vapidPrivateKey) {
266
- await admin.from('notification_sends').update({ status: 'failed', finished_at: new Date().toISOString() }).eq('id', sendId);
267
- return json(500, { ok: false, error: 'vapid_not_configured' });
268
- }
269
- webpush.setVapidDetails(operator.vapidContact, vapidPublicKey, vapidPrivateKey);
270
-
271
- let delivered = 0;
272
- let failed = 0;
273
- let expired = 0;
274
-
275
- for (const sub of recipients) {
276
- // Claim this (send_id, subscription_id) slot BEFORE sending, with a
277
- // pessimistic 'failed' placeholder — if the function dies between this
278
- // insert and the update below, the row is left as a safe, retryable
279
- // 'failed' rather than a false 'sent'. UNIQUE(send_id, subscription_id):
280
- // a conflict here means this pair already has a delivery row for this
281
- // send; skip rather than erroring the whole run (retry-safety).
282
- const { error: deliveryInsertErr } = await admin.from('notification_deliveries').insert({
283
- send_id: sendId,
284
- subscription_id: sub.id,
285
- endpoint_snapshot: sub.endpoint,
286
- status: 'failed',
287
- error: 'send_in_progress',
288
- });
289
- if (deliveryInsertErr) {
290
- if ((deliveryInsertErr as { code?: string }).code === '23505') continue;
291
- failed++;
292
- continue;
293
- }
294
-
295
- try {
296
- await webpush.sendNotification(
297
- { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth_secret } },
298
- JSON.stringify({ topic, title, body: bodyText, url, tag: postId ?? undefined }),
299
- );
300
- delivered++;
301
- await admin.from('notification_deliveries')
302
- .update({ status: 'sent', http_status: null, error: null, attempted_at: new Date().toISOString() })
303
- .eq('send_id', sendId).eq('subscription_id', sub.id);
304
- await admin.from('push_subscriptions')
305
- .update({ last_success_at: new Date().toISOString() })
306
- .eq('id', sub.id);
307
- } catch (e) {
308
- const statusCode = (e as { statusCode?: number })?.statusCode;
309
- const message = e instanceof Error ? e.message : String(e);
310
- if (statusCode === 404 || statusCode === 410) {
311
- expired++;
312
- await admin.from('notification_deliveries')
313
- .update({ status: 'expired', http_status: statusCode, error: message, attempted_at: new Date().toISOString() })
314
- .eq('send_id', sendId).eq('subscription_id', sub.id);
315
- await admin.from('push_subscriptions')
316
- .update({ disabled_at: new Date().toISOString() })
317
- .eq('id', sub.id);
318
- } else {
319
- failed++;
320
- await admin.from('notification_deliveries')
321
- .update({ status: 'failed', http_status: statusCode ?? null, error: message, attempted_at: new Date().toISOString() })
322
- .eq('send_id', sendId).eq('subscription_id', sub.id);
323
- await admin.from('push_subscriptions')
324
- .update({ failure_count: (sub.failure_count ?? 0) + 1, last_failure_at: new Date().toISOString() })
325
- .eq('id', sub.id);
326
- }
327
- }
328
- }
329
-
330
- const finalStatus = delivered === recipients.length ? 'sent' : delivered === 0 ? 'failed' : 'partial';
331
- await admin.from('notification_sends').update({
332
- delivered,
333
- failed,
334
- expired,
335
- status: finalStatus,
336
- finished_at: new Date().toISOString(),
337
- }).eq('id', sendId);
338
-
339
- return json(200, {
340
- ok: true,
341
- send_id: sendId,
342
- status: finalStatus,
343
- recipients_targeted: recipients.length,
344
- delivered,
345
- failed,
346
- expired,
347
- });
348
- }
1
+ // frAIdays Community v2, Feature B — admin-triggered push send.
2
+ //
3
+ // Auth pattern copied from admin-cancel-booking/index.ts: JWT/JWKS
4
+ // verification, aal2 (MFA) requirement, and a direct admin_users table
5
+ // lookup by the caller's email (no is_admin() RPC).
6
+ import { createClient } from 'npm:@supabase/supabase-js@2';
7
+ import webpush from 'npm:web-push@3.6.7';
8
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
9
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
10
+
11
+ const corsHeaders = {
12
+ 'Access-Control-Allow-Origin': '*',
13
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
14
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
15
+ };
16
+
17
+ interface CallerClaims {
18
+ sub: string;
19
+ email?: string;
20
+ aal?: string;
21
+ }
22
+
23
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
24
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
25
+ function getJwks(supabaseUrl: string) {
26
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
+ return jwksCache;
28
+ }
29
+
30
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
31
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
32
+ const token = authHeader.slice(7).trim();
33
+ try {
34
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
35
+ const claims = payload as unknown as CallerClaims;
36
+ if (!claims.sub) return null;
37
+ return claims;
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ function json(status: number, body: unknown) {
44
+ return new Response(JSON.stringify(body), {
45
+ status,
46
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
47
+ });
48
+ }
49
+
50
+ type Topic = 'recaps' | 'event_reminders';
51
+ type Kind = 'post_published' | 'event_reminder' | 'manual';
52
+ type Audience = 'public' | 'fraidays_rsvpd' | 'fraidays_attended';
53
+
54
+ interface SendBody {
55
+ kind?: string;
56
+ post_id?: string;
57
+ event_ref?: string;
58
+ topic?: string;
59
+ title?: string;
60
+ body?: string;
61
+ url?: string;
62
+ audience?: string;
63
+ dry_run?: boolean;
64
+ dedupe_key?: string;
65
+ }
66
+
67
+ interface SubscriptionForSend {
68
+ id: string;
69
+ endpoint: string;
70
+ p256dh: string;
71
+ auth_secret: string;
72
+ fraidays_profile_id: string;
73
+ failure_count: number | null;
74
+ }
75
+
76
+ export async function handle(req: Request, operator: { vapidContact: string }): Promise<Response> {
77
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
78
+
79
+ // Kill switch — checked before any auth/validation work runs at all.
80
+ if (Deno.env.get('PUSH_SEND_DISABLED') === 'true') {
81
+ return json(503, { ok: false, error: 'push sending is currently disabled' });
82
+ }
83
+
84
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
85
+
86
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
87
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
88
+
89
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
90
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
91
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
92
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
93
+ const callerEmail = (caller.email ?? '').toLowerCase();
94
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
95
+
96
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
97
+ auth: { persistSession: false, autoRefreshToken: false },
98
+ });
99
+
100
+ const [ipOk, emailOk] = await Promise.all([
101
+ checkRateLimit(admin, 'push-send-ip', clientIp(req), 30, 300),
102
+ checkRateLimit(admin, 'push-send-email', callerEmail, 20, 300),
103
+ ]);
104
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
105
+
106
+ const { data: allow, error: allowErr } = await admin
107
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
108
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
109
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
110
+
111
+ let raw: SendBody;
112
+ try {
113
+ raw = await req.json();
114
+ } catch {
115
+ return json(400, { ok: false, error: 'invalid_json' });
116
+ }
117
+
118
+ // --- Validation. Nothing is written until every check below passes. ---
119
+
120
+ if (raw.topic !== 'recaps' && raw.topic !== 'event_reminders') {
121
+ return json(400, { ok: false, error: 'invalid_topic' });
122
+ }
123
+ const topic = raw.topic as Topic;
124
+
125
+ if (raw.kind === 'test') return json(400, { ok: false, error: 'kind_test_not_allowed_here' });
126
+ if (raw.kind !== 'post_published' && raw.kind !== 'event_reminder' && raw.kind !== 'manual') {
127
+ return json(400, { ok: false, error: 'invalid_kind' });
128
+ }
129
+ const kind = raw.kind as Kind;
130
+
131
+ const title = (raw.title ?? '').trim();
132
+ if (!title || title.length > 80) return json(400, { ok: false, error: 'invalid_title' });
133
+
134
+ const bodyText = (raw.body ?? '').trim();
135
+ if (!bodyText || bodyText.length > 160) return json(400, { ok: false, error: 'invalid_body' });
136
+
137
+ const url = raw.url ?? '';
138
+ if (!url.startsWith('/')) return json(400, { ok: false, error: 'invalid_url' });
139
+
140
+ if (raw.audience !== 'public' && raw.audience !== 'fraidays_rsvpd' && raw.audience !== 'fraidays_attended') {
141
+ return json(400, { ok: false, error: 'invalid_audience' });
142
+ }
143
+ const audience = raw.audience as Audience;
144
+
145
+ const postId = kind === 'post_published' ? (raw.post_id ?? '').trim() : (raw.post_id ?? null) || null;
146
+ if (kind === 'post_published' && !postId) return json(400, { ok: false, error: 'post_id_required' });
147
+
148
+ const eventRef = kind === 'event_reminder' ? (raw.event_ref ?? '').trim() : (raw.event_ref ?? null) || null;
149
+ if (kind === 'event_reminder' && !eventRef) return json(400, { ok: false, error: 'event_ref_required' });
150
+
151
+ const dryRun = !!raw.dry_run;
152
+
153
+ let dedupeKey: string;
154
+ if (kind === 'post_published') {
155
+ dedupeKey = `post_published:${postId}`;
156
+ } else if (kind === 'event_reminder') {
157
+ dedupeKey = `event_reminder:${eventRef}`;
158
+ } else {
159
+ const supplied = (raw.dedupe_key ?? '').trim();
160
+ dedupeKey = supplied || `manual:${topic}:${Date.now()}`;
161
+ }
162
+
163
+ // --- Step 1: insert the notification_sends row. The unique index on
164
+ // dedupe_key WHERE dry_run=false is the idempotency guard for real sends.
165
+ const { data: sendRow, error: insertErr } = await admin
166
+ .from('notification_sends')
167
+ .insert({
168
+ kind,
169
+ post_id: postId,
170
+ event_ref: eventRef,
171
+ audience,
172
+ topic,
173
+ title,
174
+ body: bodyText,
175
+ url,
176
+ dedupe_key: dedupeKey,
177
+ status: dryRun ? 'dry_run_complete' : 'queued',
178
+ dry_run: dryRun,
179
+ recipients_targeted: 0,
180
+ created_by: caller.sub,
181
+ })
182
+ .select('id')
183
+ .single();
184
+
185
+ if (insertErr) {
186
+ if ((insertErr as { code?: string }).code === '23505') {
187
+ return json(409, { ok: false, error: 'duplicate_send', message: 'A real send with this dedupe key already exists.' });
188
+ }
189
+ return json(500, { ok: false, error: 'insert_failed', detail: insertErr.message });
190
+ }
191
+ const sendId = sendRow.id as string;
192
+
193
+ // --- Step 2: compute recipients.
194
+ //
195
+ // The spec query is a single SQL statement with a LEFT JOIN + CASE-based
196
+ // audience/topic filter. This codebase has no existing helper for running
197
+ // raw parameterized SQL from an Edge Function, and adding one (a new
198
+ // SECURITY DEFINER Postgres function) would require a migration — out of
199
+ // scope for this task (DB schema is frozen here; see task instructions).
200
+ // Instead the same semantics are built from two chained, fully-parameterized
201
+ // PostgREST queries plus an in-memory merge — no SQL text is ever
202
+ // constructed from caller input (topic/audience are already validated to
203
+ // one of a small fixed enum above, and are only ever used to choose which
204
+ // .eq()/ternary branch to take, never concatenated into a query string).
205
+ let subsQuery = admin
206
+ .from('push_subscriptions')
207
+ .select('id,endpoint,p256dh,auth_secret,fraidays_profile_id,failure_count,fraidays_profiles!inner(id,auth_user_id,rsvp_current,attended_ever)')
208
+ .is('disabled_at', null)
209
+ .not('fraidays_profiles.auth_user_id', 'is', null);
210
+
211
+ if (audience === 'fraidays_rsvpd') {
212
+ subsQuery = subsQuery.eq('fraidays_profiles.rsvp_current', true);
213
+ } else if (audience === 'fraidays_attended') {
214
+ subsQuery = subsQuery.eq('fraidays_profiles.attended_ever', true);
215
+ }
216
+ // audience === 'public' -> no additional filter.
217
+
218
+ const { data: candidateSubs, error: subsErr } = await subsQuery;
219
+ if (subsErr) {
220
+ await admin.from('notification_sends').update({ status: 'failed' }).eq('id', sendId);
221
+ return json(500, { ok: false, error: 'recipients_lookup_failed', detail: subsErr.message });
222
+ }
223
+
224
+ const profileIds = Array.from(new Set((candidateSubs ?? []).map((s: any) => s.fraidays_profile_id as string)));
225
+ type PrefRow = { fraidays_profile_id: string; notify_recaps: boolean; notify_event_reminders: boolean };
226
+ const { data: prefsRows, error: prefsErr } = profileIds.length
227
+ ? await admin
228
+ .from('fraidays_notification_prefs')
229
+ .select('fraidays_profile_id,notify_recaps,notify_event_reminders')
230
+ .in('fraidays_profile_id', profileIds)
231
+ : { data: [] as PrefRow[], error: null };
232
+ if (prefsErr) {
233
+ await admin.from('notification_sends').update({ status: 'failed' }).eq('id', sendId);
234
+ return json(500, { ok: false, error: 'prefs_lookup_failed', detail: prefsErr.message });
235
+ }
236
+ const prefsByProfile = new Map(((prefsRows ?? []) as PrefRow[]).map((p) => [p.fraidays_profile_id, p]));
237
+
238
+ const recipients: SubscriptionForSend[] = (candidateSubs ?? [])
239
+ .filter((s: any) => {
240
+ const pref = prefsByProfile.get(s.fraidays_profile_id);
241
+ const allowed = topic === 'recaps' ? (pref?.notify_recaps ?? true) : (pref?.notify_event_reminders ?? true);
242
+ return allowed;
243
+ })
244
+ .map((s: any) => ({
245
+ id: s.id,
246
+ endpoint: s.endpoint,
247
+ p256dh: s.p256dh,
248
+ auth_secret: s.auth_secret,
249
+ fraidays_profile_id: s.fraidays_profile_id,
250
+ failure_count: s.failure_count,
251
+ }));
252
+
253
+ await admin.from('notification_sends').update({ recipients_targeted: recipients.length }).eq('id', sendId);
254
+
255
+ if (dryRun) {
256
+ return json(200, { ok: true, dry_run: true, send_id: sendId, recipients_targeted: recipients.length });
257
+ }
258
+
259
+ // --- Step 4: real send.
260
+ const startedAt = new Date().toISOString();
261
+ await admin.from('notification_sends').update({ status: 'sending', started_at: startedAt }).eq('id', sendId);
262
+
263
+ const vapidPublicKey = Deno.env.get('VAPID_PUBLIC_KEY');
264
+ const vapidPrivateKey = Deno.env.get('VAPID_PRIVATE_KEY');
265
+ if (!vapidPublicKey || !vapidPrivateKey) {
266
+ await admin.from('notification_sends').update({ status: 'failed', finished_at: new Date().toISOString() }).eq('id', sendId);
267
+ return json(500, { ok: false, error: 'vapid_not_configured' });
268
+ }
269
+ webpush.setVapidDetails(operator.vapidContact, vapidPublicKey, vapidPrivateKey);
270
+
271
+ let delivered = 0;
272
+ let failed = 0;
273
+ let expired = 0;
274
+
275
+ for (const sub of recipients) {
276
+ // Claim this (send_id, subscription_id) slot BEFORE sending, with a
277
+ // pessimistic 'failed' placeholder — if the function dies between this
278
+ // insert and the update below, the row is left as a safe, retryable
279
+ // 'failed' rather than a false 'sent'. UNIQUE(send_id, subscription_id):
280
+ // a conflict here means this pair already has a delivery row for this
281
+ // send; skip rather than erroring the whole run (retry-safety).
282
+ const { error: deliveryInsertErr } = await admin.from('notification_deliveries').insert({
283
+ send_id: sendId,
284
+ subscription_id: sub.id,
285
+ endpoint_snapshot: sub.endpoint,
286
+ status: 'failed',
287
+ error: 'send_in_progress',
288
+ });
289
+ if (deliveryInsertErr) {
290
+ if ((deliveryInsertErr as { code?: string }).code === '23505') continue;
291
+ failed++;
292
+ continue;
293
+ }
294
+
295
+ try {
296
+ await webpush.sendNotification(
297
+ { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth_secret } },
298
+ JSON.stringify({ topic, title, body: bodyText, url, tag: postId ?? undefined }),
299
+ );
300
+ delivered++;
301
+ await admin.from('notification_deliveries')
302
+ .update({ status: 'sent', http_status: null, error: null, attempted_at: new Date().toISOString() })
303
+ .eq('send_id', sendId).eq('subscription_id', sub.id);
304
+ await admin.from('push_subscriptions')
305
+ .update({ last_success_at: new Date().toISOString() })
306
+ .eq('id', sub.id);
307
+ } catch (e) {
308
+ const statusCode = (e as { statusCode?: number })?.statusCode;
309
+ const message = e instanceof Error ? e.message : String(e);
310
+ if (statusCode === 404 || statusCode === 410) {
311
+ expired++;
312
+ await admin.from('notification_deliveries')
313
+ .update({ status: 'expired', http_status: statusCode, error: message, attempted_at: new Date().toISOString() })
314
+ .eq('send_id', sendId).eq('subscription_id', sub.id);
315
+ await admin.from('push_subscriptions')
316
+ .update({ disabled_at: new Date().toISOString() })
317
+ .eq('id', sub.id);
318
+ } else {
319
+ failed++;
320
+ await admin.from('notification_deliveries')
321
+ .update({ status: 'failed', http_status: statusCode ?? null, error: message, attempted_at: new Date().toISOString() })
322
+ .eq('send_id', sendId).eq('subscription_id', sub.id);
323
+ await admin.from('push_subscriptions')
324
+ .update({ failure_count: (sub.failure_count ?? 0) + 1, last_failure_at: new Date().toISOString() })
325
+ .eq('id', sub.id);
326
+ }
327
+ }
328
+ }
329
+
330
+ const finalStatus = delivered === recipients.length ? 'sent' : delivered === 0 ? 'failed' : 'partial';
331
+ await admin.from('notification_sends').update({
332
+ delivered,
333
+ failed,
334
+ expired,
335
+ status: finalStatus,
336
+ finished_at: new Date().toISOString(),
337
+ }).eq('id', sendId);
338
+
339
+ return json(200, {
340
+ ok: true,
341
+ send_id: sendId,
342
+ status: finalStatus,
343
+ recipients_targeted: recipients.length,
344
+ delivered,
345
+ failed,
346
+ expired,
347
+ });
348
+ }