@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,234 +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
- }
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
+ }