@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,311 +1,311 @@
1
- import { createClient } from 'npm:@supabase/supabase-js@2';
2
- import Stripe from 'npm:stripe@17.5.0';
3
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
6
-
7
- const corsHeaders = {
8
- 'Access-Control-Allow-Origin': '*',
9
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
10
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
11
- };
12
-
13
- interface CallerClaims {
14
- sub: string;
15
- email?: string;
16
- aal?: string;
17
- }
18
-
19
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
20
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
21
- function getJwks(supabaseUrl: string) {
22
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
23
- return jwksCache;
24
- }
25
-
26
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
27
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
28
- const token = authHeader.slice(7).trim();
29
- try {
30
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
31
- const claims = payload as unknown as CallerClaims;
32
- if (!claims.sub) return null;
33
- return claims;
34
- } catch {
35
- return null;
36
- }
37
- }
38
-
39
- function json(status: number, body: unknown) {
40
- return new Response(JSON.stringify(body), {
41
- status,
42
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
43
- });
44
- }
45
-
46
- const CANCELLABLE = new Set(['active', 'trialing', 'past_due']);
47
-
48
- export async function handle(req: Request): Promise<Response> {
49
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
51
-
52
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
53
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
54
-
55
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
56
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
57
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
58
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
59
- const callerEmail = (caller.email ?? '').toLowerCase();
60
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
61
-
62
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
63
- auth: { persistSession: false, autoRefreshToken: false },
64
- });
65
-
66
- const [ipOk, emailOk] = await Promise.all([
67
- checkRateLimit(admin, 'admin-cancel-membership-ip', clientIp(req), 30, 300),
68
- checkRateLimit(admin, 'admin-cancel-membership-email', callerEmail, 20, 300),
69
- ]);
70
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
71
-
72
- const { data: allow, error: allowErr } = await admin
73
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
74
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
75
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
76
-
77
- let body: {
78
- membership_id?: string;
79
- effective?: string;
80
- effective_date?: string;
81
- issue_refund?: boolean;
82
- reason?: string;
83
- idempotency_key?: string;
84
- dry_run?: boolean;
85
- };
86
- try {
87
- body = await req.json();
88
- } catch {
89
- return json(400, { ok: false, error: 'invalid_json' });
90
- }
91
-
92
- const membershipId = (body.membership_id ?? '').trim();
93
- if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
94
- return json(400, { ok: false, error: 'invalid_membership_id' });
95
- }
96
- const effective = body.effective;
97
- if (effective !== 'now' && effective !== 'date') {
98
- return json(400, { ok: false, error: 'invalid_effective' });
99
- }
100
- let effectiveDate: Date | null = null;
101
- if (effective === 'date') {
102
- const raw = (body.effective_date ?? '').trim();
103
- const parsedDate = raw ? new Date(raw) : null;
104
- if (!parsedDate || isNaN(parsedDate.getTime())) {
105
- return json(400, { ok: false, error: 'invalid_effective_date' });
106
- }
107
- const startOfToday = new Date();
108
- startOfToday.setHours(0, 0, 0, 0);
109
- if (parsedDate.getTime() < startOfToday.getTime()) {
110
- return json(400, { ok: false, error: 'effective_date_in_past' });
111
- }
112
- // Use end-of-day (UTC) for the picked date so "today" still resolves to a
113
- // genuinely future instant rather than midnight, which is almost always
114
- // already past by the time this request executes.
115
- parsedDate.setUTCHours(23, 59, 59, 0);
116
- effectiveDate = parsedDate;
117
- }
118
- const issueRefund = !!body.issue_refund;
119
- const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
120
- const idempotencyKey = (body.idempotency_key ?? '').trim();
121
- if (!idempotencyKey || idempotencyKey.length > 100) {
122
- return json(400, { ok: false, error: 'invalid_idempotency_key' });
123
- }
124
- const dryRun = !!body.dry_run;
125
-
126
- // 1. Live state re-check (concurrency guard).
127
- const { data: membership, error: mErr } = await admin
128
- .from('memberships')
129
- .select('id,email,status,stripe_subscription_id,plan_id')
130
- .eq('id', membershipId)
131
- .maybeSingle();
132
- if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
133
- if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
134
- if (membership.status === 'canceled') return json(400, { ok: false, error: 'already_canceled' });
135
- if (!CANCELLABLE.has(membership.status)) {
136
- return json(400, { ok: false, error: 'not_cancellable', detail: `status is ${membership.status}` });
137
- }
138
- const subscriptionId = membership.stripe_subscription_id;
139
- if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
140
-
141
- // 2. Audit action string.
142
- const action = effective === 'now'
143
- ? (issueRefund ? 'cancel_immediate_refunded' : 'cancel_immediate_no_refund')
144
- : (issueRefund ? 'cancel_scheduled_refunded' : 'cancel_scheduled_no_refund');
145
-
146
- // 3. Idempotent audit insert (skipped for dry runs).
147
- if (!dryRun) {
148
- const { error: insErr } = await admin.from('membership_admin_actions').insert({
149
- membership_id: membershipId,
150
- action,
151
- actor_email: callerEmail,
152
- idempotency_key: idempotencyKey,
153
- reason: reasonInput,
154
- effective_at: effective === 'now' ? new Date().toISOString() : effectiveDate!.toISOString(),
155
- });
156
- if (insErr) {
157
- if ((insErr as { code?: string }).code === '23505') {
158
- return json(200, { ok: true, duplicate: true });
159
- }
160
- return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
161
- }
162
- }
163
-
164
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
165
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
166
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
167
-
168
- // 4. Retrieve subscription.
169
- let sub: Stripe.Subscription;
170
- try {
171
- sub = await stripe.subscriptions.retrieve(subscriptionId);
172
- } catch (e) {
173
- const msg = e instanceof Error ? e.message : String(e);
174
- return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
175
- }
176
- if (sub.items.data.length !== 1) {
177
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
178
- }
179
- const item = sub.items.data[0] as unknown as { current_period_start: number; current_period_end: number };
180
- const periodStart = item.current_period_start;
181
- const periodEnd = item.current_period_end;
182
-
183
- // 5. Compute the timestamp to send to Stripe. This MUST always be strictly
184
- // future or Stripe rejects the cancel_at update — the safety floor below is
185
- // the fix for the bug where "today" (midnight) or a clamp to periodStart
186
- // could resolve to a past instant by call time. Refund math further below
187
- // uses a SEPARATE, period-clamped value derived from this one, so the floor
188
- // never distorts the proration amount.
189
- let cancelAtUnix = effective === 'now'
190
- ? Math.floor(Date.now() / 1000)
191
- : Math.floor(effectiveDate!.getTime() / 1000);
192
- const nowUnix = Math.floor(Date.now() / 1000);
193
- cancelAtUnix = Math.max(cancelAtUnix, nowUnix + 60);
194
-
195
- // 6. Refund estimate (read-only; computed for both dry-run and real runs,
196
- // but no money moves and nothing is mutated in Stripe yet).
197
- let refundCents: number | null = null;
198
- let stripeRefundId: string | null = null;
199
- let invoice: Stripe.Invoice | undefined;
200
- let paymentIntent: { id: string; latest_charge?: { amount_refunded?: number } | null } | null = null;
201
- if (issueRefund) {
202
- try {
203
- const list = await stripe.invoices.list({
204
- subscription: subscriptionId,
205
- status: 'paid',
206
- limit: 1,
207
- expand: ['data.payment_intent.latest_charge'],
208
- });
209
- invoice = list.data[0];
210
- } catch (e) {
211
- const msg = e instanceof Error ? e.message : String(e);
212
- return json(500, { ok: false, error: 'stripe_invoice_lookup_failed', detail: msg });
213
- }
214
- if (!invoice) {
215
- if (!dryRun) {
216
- try {
217
- await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
218
- } catch { /* non-fatal */ }
219
- }
220
- return json(400, { ok: false, error: 'no_refundable_invoice' });
221
- }
222
- paymentIntent = invoice.payment_intent as unknown as
223
- { id: string; latest_charge?: { amount_refunded?: number } | null } | null;
224
- const charge = paymentIntent?.latest_charge ?? null;
225
- const refundableCents = (invoice.amount_paid ?? 0) - (charge?.amount_refunded ?? 0);
226
-
227
- const cancelAtForRefund = Math.min(Math.max(cancelAtUnix, periodStart), periodEnd);
228
- const span = periodEnd - periodStart;
229
- const prorated = span > 0
230
- ? Math.round((invoice.amount_paid ?? 0) * (periodEnd - cancelAtForRefund) / span)
231
- : 0;
232
- refundCents = Math.max(0, Math.min(prorated, refundableCents));
233
- }
234
-
235
- if (dryRun) {
236
- return json(200, { ok: true, refund_amount_cents: refundCents ?? 0 });
237
- }
238
-
239
- // 7. Apply cancellation in Stripe FIRST. If this fails, the function returns
240
- // here and no refund is ever created — money never moves ahead of the
241
- // actual cancellation taking effect.
242
- let updatedSub: Stripe.Subscription;
243
- try {
244
- updatedSub = effective === 'now'
245
- ? await stripe.subscriptions.cancel(subscriptionId, {}, { idempotencyKey })
246
- : await stripe.subscriptions.update(
247
- subscriptionId,
248
- { cancel_at: cancelAtUnix, proration_behavior: 'none' },
249
- { idempotencyKey },
250
- );
251
- } catch (e) {
252
- const msg = e instanceof Error ? e.message : String(e);
253
- return json(500, { ok: false, error: 'stripe_cancel_failed', detail: msg });
254
- }
255
-
256
- const cancelAtIso = updatedSub.cancel_at ? new Date(updatedSub.cancel_at * 1000).toISOString() : null;
257
-
258
- // 8. Authoritative membership write, done immediately after the Stripe
259
- // mutation that produced it — so even if the refund step below fails, our
260
- // DB already correctly reflects the real cancellation state.
261
- const { error: updErr } = await admin
262
- .from('memberships')
263
- .update({ status: updatedSub.status, cancel_at: cancelAtIso })
264
- .eq('id', membershipId);
265
- if (updErr) {
266
- await logOps(admin, 'membership_cancel_db_write_failed', {
267
- message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
268
- }, { severity: 'error' });
269
- return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
270
- }
271
-
272
- // 9. Issue the refund only after cancellation succeeded and was persisted.
273
- if (issueRefund && refundCents && refundCents > 0) {
274
- if (!paymentIntent?.id) {
275
- return json(400, { ok: false, error: 'no_payment_intent' });
276
- }
277
- try {
278
- const refund = await stripe.refunds.create({
279
- payment_intent: paymentIntent.id,
280
- amount: refundCents,
281
- reason: 'requested_by_customer',
282
- metadata: { membership_id: membershipId, actor: callerEmail },
283
- }, { idempotencyKey });
284
- stripeRefundId = refund.id;
285
- } catch (e) {
286
- const msg = e instanceof Error ? e.message : String(e);
287
- return json(500, { ok: false, error: 'stripe_refund_failed', detail: msg });
288
- }
289
- }
290
-
291
- // 10. Backfill audit row with refund outcome.
292
- const { error: auditUpdErr } = await admin
293
- .from('membership_admin_actions')
294
- .update({ refund_amount_cents: refundCents ?? null, stripe_refund_id: stripeRefundId })
295
- .eq('idempotency_key', idempotencyKey);
296
- if (auditUpdErr) {
297
- await logOps(admin, 'membership_cancel_audit_update_failed', {
298
- message: auditUpdErr.message, idempotency_key: idempotencyKey,
299
- }, { severity: 'warning' });
300
- }
301
-
302
- // 11. GHL note skipped: `memberships` has no ghl_contact_id-equivalent column.
303
-
304
- return json(200, {
305
- ok: true,
306
- status: updatedSub.status,
307
- refund_amount_cents: refundCents ?? null,
308
- stripe_refund_id: stripeRefundId ?? null,
309
- cancel_at: cancelAtIso,
310
- });
311
- }
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import Stripe from 'npm:stripe@17.5.0';
3
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
6
+
7
+ const corsHeaders = {
8
+ 'Access-Control-Allow-Origin': '*',
9
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
10
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
11
+ };
12
+
13
+ interface CallerClaims {
14
+ sub: string;
15
+ email?: string;
16
+ aal?: string;
17
+ }
18
+
19
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
20
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
21
+ function getJwks(supabaseUrl: string) {
22
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
23
+ return jwksCache;
24
+ }
25
+
26
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
27
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
28
+ const token = authHeader.slice(7).trim();
29
+ try {
30
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
31
+ const claims = payload as unknown as CallerClaims;
32
+ if (!claims.sub) return null;
33
+ return claims;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function json(status: number, body: unknown) {
40
+ return new Response(JSON.stringify(body), {
41
+ status,
42
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
43
+ });
44
+ }
45
+
46
+ const CANCELLABLE = new Set(['active', 'trialing', 'past_due']);
47
+
48
+ export async function handle(req: Request): Promise<Response> {
49
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
51
+
52
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
53
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
54
+
55
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
56
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
57
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
58
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
59
+ const callerEmail = (caller.email ?? '').toLowerCase();
60
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
61
+
62
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
63
+ auth: { persistSession: false, autoRefreshToken: false },
64
+ });
65
+
66
+ const [ipOk, emailOk] = await Promise.all([
67
+ checkRateLimit(admin, 'admin-cancel-membership-ip', clientIp(req), 30, 300),
68
+ checkRateLimit(admin, 'admin-cancel-membership-email', callerEmail, 20, 300),
69
+ ]);
70
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
71
+
72
+ const { data: allow, error: allowErr } = await admin
73
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
74
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
75
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
76
+
77
+ let body: {
78
+ membership_id?: string;
79
+ effective?: string;
80
+ effective_date?: string;
81
+ issue_refund?: boolean;
82
+ reason?: string;
83
+ idempotency_key?: string;
84
+ dry_run?: boolean;
85
+ };
86
+ try {
87
+ body = await req.json();
88
+ } catch {
89
+ return json(400, { ok: false, error: 'invalid_json' });
90
+ }
91
+
92
+ const membershipId = (body.membership_id ?? '').trim();
93
+ if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
94
+ return json(400, { ok: false, error: 'invalid_membership_id' });
95
+ }
96
+ const effective = body.effective;
97
+ if (effective !== 'now' && effective !== 'date') {
98
+ return json(400, { ok: false, error: 'invalid_effective' });
99
+ }
100
+ let effectiveDate: Date | null = null;
101
+ if (effective === 'date') {
102
+ const raw = (body.effective_date ?? '').trim();
103
+ const parsedDate = raw ? new Date(raw) : null;
104
+ if (!parsedDate || isNaN(parsedDate.getTime())) {
105
+ return json(400, { ok: false, error: 'invalid_effective_date' });
106
+ }
107
+ const startOfToday = new Date();
108
+ startOfToday.setHours(0, 0, 0, 0);
109
+ if (parsedDate.getTime() < startOfToday.getTime()) {
110
+ return json(400, { ok: false, error: 'effective_date_in_past' });
111
+ }
112
+ // Use end-of-day (UTC) for the picked date so "today" still resolves to a
113
+ // genuinely future instant rather than midnight, which is almost always
114
+ // already past by the time this request executes.
115
+ parsedDate.setUTCHours(23, 59, 59, 0);
116
+ effectiveDate = parsedDate;
117
+ }
118
+ const issueRefund = !!body.issue_refund;
119
+ const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
120
+ const idempotencyKey = (body.idempotency_key ?? '').trim();
121
+ if (!idempotencyKey || idempotencyKey.length > 100) {
122
+ return json(400, { ok: false, error: 'invalid_idempotency_key' });
123
+ }
124
+ const dryRun = !!body.dry_run;
125
+
126
+ // 1. Live state re-check (concurrency guard).
127
+ const { data: membership, error: mErr } = await admin
128
+ .from('memberships')
129
+ .select('id,email,status,stripe_subscription_id,plan_id')
130
+ .eq('id', membershipId)
131
+ .maybeSingle();
132
+ if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
133
+ if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
134
+ if (membership.status === 'canceled') return json(400, { ok: false, error: 'already_canceled' });
135
+ if (!CANCELLABLE.has(membership.status)) {
136
+ return json(400, { ok: false, error: 'not_cancellable', detail: `status is ${membership.status}` });
137
+ }
138
+ const subscriptionId = membership.stripe_subscription_id;
139
+ if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
140
+
141
+ // 2. Audit action string.
142
+ const action = effective === 'now'
143
+ ? (issueRefund ? 'cancel_immediate_refunded' : 'cancel_immediate_no_refund')
144
+ : (issueRefund ? 'cancel_scheduled_refunded' : 'cancel_scheduled_no_refund');
145
+
146
+ // 3. Idempotent audit insert (skipped for dry runs).
147
+ if (!dryRun) {
148
+ const { error: insErr } = await admin.from('membership_admin_actions').insert({
149
+ membership_id: membershipId,
150
+ action,
151
+ actor_email: callerEmail,
152
+ idempotency_key: idempotencyKey,
153
+ reason: reasonInput,
154
+ effective_at: effective === 'now' ? new Date().toISOString() : effectiveDate!.toISOString(),
155
+ });
156
+ if (insErr) {
157
+ if ((insErr as { code?: string }).code === '23505') {
158
+ return json(200, { ok: true, duplicate: true });
159
+ }
160
+ return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
161
+ }
162
+ }
163
+
164
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
165
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
166
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
167
+
168
+ // 4. Retrieve subscription.
169
+ let sub: Stripe.Subscription;
170
+ try {
171
+ sub = await stripe.subscriptions.retrieve(subscriptionId);
172
+ } catch (e) {
173
+ const msg = e instanceof Error ? e.message : String(e);
174
+ return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
175
+ }
176
+ if (sub.items.data.length !== 1) {
177
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
178
+ }
179
+ const item = sub.items.data[0] as unknown as { current_period_start: number; current_period_end: number };
180
+ const periodStart = item.current_period_start;
181
+ const periodEnd = item.current_period_end;
182
+
183
+ // 5. Compute the timestamp to send to Stripe. This MUST always be strictly
184
+ // future or Stripe rejects the cancel_at update — the safety floor below is
185
+ // the fix for the bug where "today" (midnight) or a clamp to periodStart
186
+ // could resolve to a past instant by call time. Refund math further below
187
+ // uses a SEPARATE, period-clamped value derived from this one, so the floor
188
+ // never distorts the proration amount.
189
+ let cancelAtUnix = effective === 'now'
190
+ ? Math.floor(Date.now() / 1000)
191
+ : Math.floor(effectiveDate!.getTime() / 1000);
192
+ const nowUnix = Math.floor(Date.now() / 1000);
193
+ cancelAtUnix = Math.max(cancelAtUnix, nowUnix + 60);
194
+
195
+ // 6. Refund estimate (read-only; computed for both dry-run and real runs,
196
+ // but no money moves and nothing is mutated in Stripe yet).
197
+ let refundCents: number | null = null;
198
+ let stripeRefundId: string | null = null;
199
+ let invoice: Stripe.Invoice | undefined;
200
+ let paymentIntent: { id: string; latest_charge?: { amount_refunded?: number } | null } | null = null;
201
+ if (issueRefund) {
202
+ try {
203
+ const list = await stripe.invoices.list({
204
+ subscription: subscriptionId,
205
+ status: 'paid',
206
+ limit: 1,
207
+ expand: ['data.payment_intent.latest_charge'],
208
+ });
209
+ invoice = list.data[0];
210
+ } catch (e) {
211
+ const msg = e instanceof Error ? e.message : String(e);
212
+ return json(500, { ok: false, error: 'stripe_invoice_lookup_failed', detail: msg });
213
+ }
214
+ if (!invoice) {
215
+ if (!dryRun) {
216
+ try {
217
+ await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
218
+ } catch { /* non-fatal */ }
219
+ }
220
+ return json(400, { ok: false, error: 'no_refundable_invoice' });
221
+ }
222
+ paymentIntent = invoice.payment_intent as unknown as
223
+ { id: string; latest_charge?: { amount_refunded?: number } | null } | null;
224
+ const charge = paymentIntent?.latest_charge ?? null;
225
+ const refundableCents = (invoice.amount_paid ?? 0) - (charge?.amount_refunded ?? 0);
226
+
227
+ const cancelAtForRefund = Math.min(Math.max(cancelAtUnix, periodStart), periodEnd);
228
+ const span = periodEnd - periodStart;
229
+ const prorated = span > 0
230
+ ? Math.round((invoice.amount_paid ?? 0) * (periodEnd - cancelAtForRefund) / span)
231
+ : 0;
232
+ refundCents = Math.max(0, Math.min(prorated, refundableCents));
233
+ }
234
+
235
+ if (dryRun) {
236
+ return json(200, { ok: true, refund_amount_cents: refundCents ?? 0 });
237
+ }
238
+
239
+ // 7. Apply cancellation in Stripe FIRST. If this fails, the function returns
240
+ // here and no refund is ever created — money never moves ahead of the
241
+ // actual cancellation taking effect.
242
+ let updatedSub: Stripe.Subscription;
243
+ try {
244
+ updatedSub = effective === 'now'
245
+ ? await stripe.subscriptions.cancel(subscriptionId, {}, { idempotencyKey })
246
+ : await stripe.subscriptions.update(
247
+ subscriptionId,
248
+ { cancel_at: cancelAtUnix, proration_behavior: 'none' },
249
+ { idempotencyKey },
250
+ );
251
+ } catch (e) {
252
+ const msg = e instanceof Error ? e.message : String(e);
253
+ return json(500, { ok: false, error: 'stripe_cancel_failed', detail: msg });
254
+ }
255
+
256
+ const cancelAtIso = updatedSub.cancel_at ? new Date(updatedSub.cancel_at * 1000).toISOString() : null;
257
+
258
+ // 8. Authoritative membership write, done immediately after the Stripe
259
+ // mutation that produced it — so even if the refund step below fails, our
260
+ // DB already correctly reflects the real cancellation state.
261
+ const { error: updErr } = await admin
262
+ .from('memberships')
263
+ .update({ status: updatedSub.status, cancel_at: cancelAtIso })
264
+ .eq('id', membershipId);
265
+ if (updErr) {
266
+ await logOps(admin, 'membership_cancel_db_write_failed', {
267
+ message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
268
+ }, { severity: 'error' });
269
+ return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
270
+ }
271
+
272
+ // 9. Issue the refund only after cancellation succeeded and was persisted.
273
+ if (issueRefund && refundCents && refundCents > 0) {
274
+ if (!paymentIntent?.id) {
275
+ return json(400, { ok: false, error: 'no_payment_intent' });
276
+ }
277
+ try {
278
+ const refund = await stripe.refunds.create({
279
+ payment_intent: paymentIntent.id,
280
+ amount: refundCents,
281
+ reason: 'requested_by_customer',
282
+ metadata: { membership_id: membershipId, actor: callerEmail },
283
+ }, { idempotencyKey });
284
+ stripeRefundId = refund.id;
285
+ } catch (e) {
286
+ const msg = e instanceof Error ? e.message : String(e);
287
+ return json(500, { ok: false, error: 'stripe_refund_failed', detail: msg });
288
+ }
289
+ }
290
+
291
+ // 10. Backfill audit row with refund outcome.
292
+ const { error: auditUpdErr } = await admin
293
+ .from('membership_admin_actions')
294
+ .update({ refund_amount_cents: refundCents ?? null, stripe_refund_id: stripeRefundId })
295
+ .eq('idempotency_key', idempotencyKey);
296
+ if (auditUpdErr) {
297
+ await logOps(admin, 'membership_cancel_audit_update_failed', {
298
+ message: auditUpdErr.message, idempotency_key: idempotencyKey,
299
+ }, { severity: 'warning' });
300
+ }
301
+
302
+ // 11. GHL note skipped: `memberships` has no ghl_contact_id-equivalent column.
303
+
304
+ return json(200, {
305
+ ok: true,
306
+ status: updatedSub.status,
307
+ refund_amount_cents: refundCents ?? null,
308
+ stripe_refund_id: stripeRefundId ?? null,
309
+ cancel_at: cancelAtIso,
310
+ });
311
+ }