@simplelayer/graniteer-core 0.1.2 → 0.2.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 (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  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 -0
  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 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  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 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +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
+ }
@@ -0,0 +1,234 @@
1
+ // frAIdays Community v2, Feature B — member self-service "send me a test
2
+ // push" endpoint. Auth is the calling member's own JWT only (verifyCaller,
3
+ // no aal2/admin_users check) — copied from the verifyCaller half of
4
+ // admin-cancel-booking/index.ts, minus the admin gate.
5
+ import { createClient } from 'npm:@supabase/supabase-js@2';
6
+ import webpush from 'npm:web-push@3.6.7';
7
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
8
+ import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
9
+
10
+ const corsHeaders = {
11
+ 'Access-Control-Allow-Origin': '*',
12
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
13
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
14
+ };
15
+
16
+ interface CallerClaims {
17
+ sub: string;
18
+ email?: string;
19
+ }
20
+
21
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
22
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
23
+ function getJwks(supabaseUrl: string) {
24
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
25
+ return jwksCache;
26
+ }
27
+
28
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
29
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
30
+ const token = authHeader.slice(7).trim();
31
+ try {
32
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
33
+ const claims = payload as unknown as CallerClaims;
34
+ if (!claims.sub) return null;
35
+ return claims;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ function json(status: number, body: unknown) {
42
+ return new Response(JSON.stringify(body), {
43
+ status,
44
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
45
+ });
46
+ }
47
+
48
+ interface TestBody {
49
+ subscription_id?: string;
50
+ }
51
+
52
+ interface SubscriptionRow {
53
+ id: string;
54
+ endpoint: string;
55
+ p256dh: string;
56
+ auth_secret: string;
57
+ }
58
+
59
+ const TEST_TITLE = 'Test notification';
60
+ const TEST_BODY = 'If you can see this, push notifications are working.';
61
+ const TEST_URL = '/fraidays/community';
62
+
63
+ export async function handle(req: Request, operator: { vapidContact: string }): Promise<Response> {
64
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
65
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
66
+
67
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
68
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
69
+
70
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
71
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
72
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
73
+
74
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
75
+ auth: { persistSession: false, autoRefreshToken: false },
76
+ });
77
+
78
+ // Resolve the caller's own fraidays_profile server-side — never trust a
79
+ // client-supplied profile/user id.
80
+ const { data: profileRow, error: profileErr } = await admin
81
+ .from('fraidays_profiles')
82
+ .select('id')
83
+ .eq('auth_user_id', caller.sub)
84
+ .maybeSingle();
85
+ if (profileErr) return json(500, { ok: false, error: 'profile_lookup_failed' });
86
+ if (!profileRow) return json(404, { ok: false, error: 'profile_not_found' });
87
+ const profileId = profileRow.id as string;
88
+
89
+ if (!(await checkRateLimit(admin, 'push-test-profile', profileId, 3, 3600))) {
90
+ return json(429, { ok: false, error: 'rate_limited' });
91
+ }
92
+
93
+ let raw: TestBody = {};
94
+ try {
95
+ const text = await req.text();
96
+ if (text.trim()) raw = JSON.parse(text);
97
+ } catch {
98
+ return json(400, { ok: false, error: 'invalid_json' });
99
+ }
100
+
101
+ let subs: SubscriptionRow[];
102
+ if (raw.subscription_id) {
103
+ const subId = raw.subscription_id.trim();
104
+ if (!/^[0-9a-f-]{36}$/i.test(subId)) return json(400, { ok: false, error: 'invalid_subscription_id' });
105
+ // Scoped to the caller's own verified id — a subscription_id belonging to
106
+ // someone else resolves to no rows, never a leak of its existence.
107
+ const { data, error } = await admin
108
+ .from('push_subscriptions')
109
+ .select('id,endpoint,p256dh,auth_secret')
110
+ .eq('id', subId)
111
+ .eq('auth_user_id', caller.sub)
112
+ .is('disabled_at', null)
113
+ .maybeSingle();
114
+ if (error) return json(500, { ok: false, error: 'subscription_lookup_failed' });
115
+ if (!data) return json(404, { ok: false, error: 'subscription_not_found' });
116
+ subs = [data as SubscriptionRow];
117
+ } else {
118
+ const { data, error } = await admin
119
+ .from('push_subscriptions')
120
+ .select('id,endpoint,p256dh,auth_secret')
121
+ .eq('auth_user_id', caller.sub)
122
+ .is('disabled_at', null);
123
+ if (error) return json(500, { ok: false, error: 'subscription_lookup_failed' });
124
+ subs = (data ?? []) as SubscriptionRow[];
125
+ }
126
+
127
+ if (subs.length === 0) return json(400, { ok: false, error: 'no_subscriptions' });
128
+
129
+ const vapidPublicKey = Deno.env.get('VAPID_PUBLIC_KEY');
130
+ const vapidPrivateKey = Deno.env.get('VAPID_PRIVATE_KEY');
131
+ if (!vapidPublicKey || !vapidPrivateKey) return json(500, { ok: false, error: 'vapid_not_configured' });
132
+ webpush.setVapidDetails(operator.vapidContact, vapidPublicKey, vapidPrivateKey);
133
+
134
+ let delivered = 0;
135
+ let failed = 0;
136
+ let skipped = 0;
137
+
138
+ for (const sub of subs) {
139
+ if (!(await checkRateLimit(admin, 'push-test-subscription', sub.id, 1, 60))) {
140
+ skipped++;
141
+ continue;
142
+ }
143
+
144
+ // Each targeted subscription gets its own notification_sends +
145
+ // notification_deliveries row (unlike push-send's one-to-many). The
146
+ // dedupe key namespace (test:<subscription_id>:<epoch_ms>) is disjoint
147
+ // from push-send's real-send dedupe_key formats, so it never collides
148
+ // with the unique index on dedupe_key WHERE dry_run=false.
149
+ const dedupeKey = `test:${sub.id}:${Date.now()}`;
150
+ const { data: sendRow, error: sendInsertErr } = await admin
151
+ .from('notification_sends')
152
+ .insert({
153
+ kind: 'test',
154
+ topic: 'recaps',
155
+ title: TEST_TITLE,
156
+ body: TEST_BODY,
157
+ url: TEST_URL,
158
+ // 'audience' is NOT NULL on notification_sends (a broadcast row
159
+ // should always be able to say what it targeted). A single-member
160
+ // test send has no real audience concept, so this sentinel value
161
+ // records what it actually is for the admin sends-history view --
162
+ // it is never one of push-send's three real audience values and is
163
+ // never read as one.
164
+ audience: 'self_test',
165
+ dedupe_key: dedupeKey,
166
+ status: 'sending',
167
+ dry_run: false,
168
+ recipients_targeted: 1,
169
+ created_by: caller.sub,
170
+ started_at: new Date().toISOString(),
171
+ })
172
+ .select('id')
173
+ .single();
174
+ if (sendInsertErr || !sendRow) {
175
+ failed++;
176
+ continue;
177
+ }
178
+ const sendId = sendRow.id as string;
179
+
180
+ try {
181
+ await webpush.sendNotification(
182
+ { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth_secret } },
183
+ JSON.stringify({ topic: 'recaps', title: TEST_TITLE, body: TEST_BODY, url: TEST_URL }),
184
+ );
185
+ delivered++;
186
+ await admin.from('notification_deliveries').insert({
187
+ send_id: sendId,
188
+ subscription_id: sub.id,
189
+ endpoint_snapshot: sub.endpoint,
190
+ status: 'sent',
191
+ attempted_at: new Date().toISOString(),
192
+ });
193
+ await admin.from('notification_sends')
194
+ .update({ status: 'sent', delivered: 1, failed: 0, expired: 0, finished_at: new Date().toISOString() })
195
+ .eq('id', sendId);
196
+ await admin.from('push_subscriptions').update({ last_success_at: new Date().toISOString() }).eq('id', sub.id);
197
+ } catch (e) {
198
+ const statusCode = (e as { statusCode?: number })?.statusCode;
199
+ const message = e instanceof Error ? e.message : String(e);
200
+ const isExpired = statusCode === 404 || statusCode === 410;
201
+ failed++;
202
+ await admin.from('notification_deliveries').insert({
203
+ send_id: sendId,
204
+ subscription_id: sub.id,
205
+ endpoint_snapshot: sub.endpoint,
206
+ status: isExpired ? 'expired' : 'failed',
207
+ http_status: statusCode ?? null,
208
+ error: message,
209
+ attempted_at: new Date().toISOString(),
210
+ });
211
+ // notification_sends.status has no 'expired' member (only
212
+ // notification_deliveries.status does) — an expired single delivery
213
+ // still resolves the send as 'failed' (0 delivered).
214
+ await admin.from('notification_sends')
215
+ .update({
216
+ status: 'failed',
217
+ delivered: 0,
218
+ failed: isExpired ? 0 : 1,
219
+ expired: isExpired ? 1 : 0,
220
+ finished_at: new Date().toISOString(),
221
+ })
222
+ .eq('id', sendId);
223
+ if (isExpired) {
224
+ await admin.from('push_subscriptions').update({ disabled_at: new Date().toISOString() }).eq('id', sub.id);
225
+ } else {
226
+ await admin.from('push_subscriptions')
227
+ .update({ last_failure_at: new Date().toISOString() })
228
+ .eq('id', sub.id);
229
+ }
230
+ }
231
+ }
232
+
233
+ return json(200, { ok: true, delivered, failed, skipped });
234
+ }