@simplelayer/graniteer-core 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -460
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -334
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -217
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,333 +1,333 @@
1
- // supabase/functions/admin-retry-invoice-payment/index.ts
2
- //
3
- // Staff-triggered retry of ONE failed Stripe subscription invoice, with an
4
- // automatic fallback: if the retry attempt fails (declined card, card needs
5
- // 3DS, any Stripe error), the same call mints the coworking billing-portal
6
- // link so staff can send the member a payment-update link without a second
7
- // action.
8
- //
9
- // The invoice id comes from the admin UI, which reads it out of the most
10
- // recent `subscription_payment_failed` ops_events row for that subscription
11
- // (stripe-webhook's invoice.payment_failed handler is the only place a real
12
- // Stripe invoice id is recorded — no table has an invoice column).
13
- //
14
- // Auth/allowlist/rate-limit scaffold mirrors admin-mint-billing-portal-link,
15
- // and the fallback link reuses that function's exact portal configuration via
16
- // the shared getOrCreateCoworkingPortalConfig helper — no second portal
17
- // configuration is created here.
18
- //
19
- // NOTE ON THE CORE BLOCK BELOW: everything between the BEGIN/END markers is
20
- // import-free by design and is mirrored byte-for-byte into
21
- // admin-retry-invoice-payment.test.ts, which exercises it against a
22
- // hand-rolled fake Stripe client. That test file asserts the two copies are
23
- // identical, so the tested code cannot drift from the shipped code.
24
-
25
- import { createClient } from 'npm:@supabase/supabase-js@2';
26
- import Stripe from 'npm:stripe@17.5.0';
27
- import { z } from 'npm:zod@3.23.8';
28
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
29
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
30
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
31
- import { getOrCreateCoworkingPortalConfig } from 'npm:@simplelayer/graniteer-core/stripeCoworkingPortal';
32
-
33
- const corsHeaders = {
34
- 'Access-Control-Allow-Origin': '*',
35
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
36
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
37
- };
38
-
39
- interface CallerClaims { sub: string; email?: string; aal?: string }
40
-
41
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
42
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
43
- function getJwks(supabaseUrl: string) {
44
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
45
- return jwksCache;
46
- }
47
-
48
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
49
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
50
- const token = authHeader.slice(7).trim();
51
- try {
52
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
53
- const claims = payload as unknown as CallerClaims;
54
- if (!claims.sub) return null;
55
- return claims;
56
- } catch {
57
- return null;
58
- }
59
- }
60
-
61
- function json(status: number, body: unknown) {
62
- return new Response(JSON.stringify(body), {
63
- status,
64
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
65
- });
66
- }
67
-
68
- const Body = z.object({ invoiceId: z.string().trim().min(1).max(255) });
69
-
70
- // ---8<--- BEGIN retry-core (mirrored verbatim in admin-retry-invoice-payment.test.ts) ---8<---
71
-
72
- export interface RetryCallerClaims { sub?: string; email?: string; aal?: string }
73
-
74
- /** The only invoice fields this path reads. Structural on purpose: the test's
75
- * fake Stripe client satisfies it without pulling in the Stripe SDK. */
76
- export interface RetryStripeInvoice {
77
- id?: string;
78
- status?: string | null;
79
- customer?: string | { id?: string } | null;
80
- subscription?: string | { id?: string } | null;
81
- amount_due?: number | null;
82
- amount_paid?: number | null;
83
- }
84
-
85
- export interface RetryStripeLike {
86
- invoices: {
87
- retrieve(id: string): Promise<RetryStripeInvoice>;
88
- pay(id: string): Promise<RetryStripeInvoice>;
89
- };
90
- billingPortal: {
91
- sessions: {
92
- create(params: Record<string, unknown>): Promise<{ url?: string | null }>;
93
- };
94
- };
95
- }
96
-
97
- export interface RetryDeps {
98
- stripe: RetryStripeLike;
99
- /** admin_users allowlist lookup. `error` set => the lookup itself broke. */
100
- isAllowedAdmin(email: string): Promise<{ allowed: boolean; error?: string }>;
101
- /** Stripe billingPortal configuration id for coworking memberships. */
102
- portalConfigId(): Promise<string>;
103
- portalReturnUrl: string;
104
- log(kind: string, detail: Record<string, unknown>, severity: 'info' | 'warning' | 'error'): Promise<unknown>;
105
- }
106
-
107
- export interface RetryResult { status: number; body: Record<string, unknown> }
108
-
109
- export function stripeIdOf(v: string | { id?: string } | null | undefined): string | null {
110
- if (!v) return null;
111
- return typeof v === 'string' ? v : (v.id ?? null);
112
- }
113
-
114
- /** Short, staff-readable reason from a Stripe error object. */
115
- export function retryFailureReason(e: unknown): string {
116
- const err = e as { message?: unknown; code?: unknown; decline_code?: unknown } | null;
117
- const message = typeof err?.message === 'string' && err.message.trim()
118
- ? err.message.trim()
119
- : String(e);
120
- const code = typeof err?.decline_code === 'string' && err.decline_code
121
- ? err.decline_code
122
- : typeof err?.code === 'string' ? err.code : '';
123
- const suffix = code && !message.toLowerCase().includes(code.toLowerCase()) ? ` (${code})` : '';
124
- return `${message}${suffix}`.slice(0, 300);
125
- }
126
-
127
- /**
128
- * Retry one invoice, falling back to a billing-portal link on failure.
129
- *
130
- * Contract notes:
131
- * - Every authorization gate runs BEFORE `deps.stripe` is touched at all, so
132
- * an unauthorized caller can never cause a Stripe API call.
133
- * - Only an `open` invoice is retried. paid/void/draft/uncollectible
134
- * short-circuit to `status: 'not_payable'` WITHOUT calling invoices.pay --
135
- * re-paying is either an error or a no-op, and on a money path a no-op that
136
- * Stripe might interpret is not worth attempting.
137
- * - A failed retry is HTTP 200 / ok:true with `status: 'retry_failed'`. The
138
- * request succeeded; the card is what declined, and the response carries the
139
- * fallback link the caller needs. Reserving non-2xx for "we could not do the
140
- * work at all" keeps the decline reason out of supabase-js's error.context
141
- * swallowing on the client.
142
- */
143
- export async function handleRetryInvoicePayment(
144
- caller: RetryCallerClaims | null,
145
- input: { invoiceId: string },
146
- deps: RetryDeps,
147
- ): Promise<RetryResult> {
148
- if (!caller?.sub) {
149
- return { status: 401, body: { ok: false, code: 'unauthenticated', error: 'Not signed in.' } };
150
- }
151
- if (caller.aal !== 'aal2') {
152
- return { status: 403, body: { ok: false, code: 'mfa_required', error: 'Two-factor authentication is required.' } };
153
- }
154
- const actorEmail = (caller.email ?? '').toLowerCase();
155
- if (!actorEmail) {
156
- return { status: 403, body: { ok: false, code: 'no_email', error: 'Caller has no email claim.' } };
157
- }
158
- const allow = await deps.isAllowedAdmin(actorEmail);
159
- if (allow.error) {
160
- return { status: 500, body: { ok: false, code: 'allowlist_lookup_failed', error: allow.error } };
161
- }
162
- if (!allow.allowed) {
163
- return { status: 403, body: { ok: false, code: 'not_authorized', error: 'Not authorized.' } };
164
- }
165
-
166
- const invoiceId = (input.invoiceId ?? '').trim();
167
- if (!/^in_[A-Za-z0-9_]+$/.test(invoiceId)) {
168
- return { status: 400, body: { ok: false, code: 'invalid_invoice_id', error: 'That is not a Stripe invoice id.' } };
169
- }
170
-
171
- let invoice: RetryStripeInvoice;
172
- try {
173
- invoice = await deps.stripe.invoices.retrieve(invoiceId);
174
- } catch (e) {
175
- const reason = retryFailureReason(e);
176
- await deps.log('admin_invoice_retry_lookup_failed',
177
- { invoice_id: invoiceId, actor_email: actorEmail, reason }, 'error');
178
- return { status: 502, body: { ok: false, code: 'invoice_lookup_failed', error: reason } };
179
- }
180
-
181
- const customerId = stripeIdOf(invoice.customer);
182
- const subscriptionId = stripeIdOf(invoice.subscription);
183
- const invoiceStatus = invoice.status ?? 'unknown';
184
-
185
- if (!customerId) {
186
- await deps.log('admin_invoice_retry_no_customer',
187
- { invoice_id: invoiceId, actor_email: actorEmail, invoice_status: invoiceStatus }, 'error');
188
- return {
189
- status: 409,
190
- body: { ok: false, code: 'no_customer', error: 'That invoice has no Stripe customer attached.' },
191
- };
192
- }
193
-
194
- if (invoiceStatus !== 'open') {
195
- const reason = invoiceStatus === 'paid'
196
- ? 'This invoice is already paid — there is nothing to retry.'
197
- : `This invoice is "${invoiceStatus}", so Stripe will not accept a payment attempt on it.`;
198
- await deps.log('admin_invoice_retry_skipped', {
199
- invoice_id: invoiceId, actor_email: actorEmail, customer_id: customerId,
200
- subscription_id: subscriptionId, invoice_status: invoiceStatus,
201
- }, 'info');
202
- return {
203
- status: 200,
204
- body: { ok: true, status: 'not_payable', invoiceId, invoiceStatus, reason },
205
- };
206
- }
207
-
208
- let paidInvoice: RetryStripeInvoice | null = null;
209
- let failure: string | null = null;
210
- try {
211
- paidInvoice = await deps.stripe.invoices.pay(invoiceId);
212
- // invoices.pay RESOLVES for a payment that needs member action (3DS): the
213
- // invoice comes back still `open`. Treating a resolved promise as success
214
- // would report a payment that never happened.
215
- if ((paidInvoice?.status ?? null) !== 'paid') {
216
- failure = `Stripe accepted the attempt but the invoice is still "${paidInvoice?.status ?? 'unknown'}" — the card most likely needs the member to authenticate the payment.`;
217
- }
218
- } catch (e) {
219
- failure = retryFailureReason(e);
220
- }
221
-
222
- if (!failure) {
223
- await deps.log('admin_invoice_retry_paid', {
224
- invoice_id: invoiceId, actor_email: actorEmail, customer_id: customerId,
225
- subscription_id: subscriptionId, amount_paid_cents: paidInvoice?.amount_paid ?? null,
226
- }, 'info');
227
- return {
228
- status: 200,
229
- body: {
230
- ok: true,
231
- status: 'paid',
232
- invoiceId,
233
- amountPaidCents: paidInvoice?.amount_paid ?? null,
234
- },
235
- };
236
- }
237
-
238
- let fallbackPortalUrl: string | null = null;
239
- let fallbackError: string | null = null;
240
- try {
241
- const configuration = await deps.portalConfigId();
242
- const session = await deps.stripe.billingPortal.sessions.create({
243
- customer: customerId,
244
- configuration,
245
- return_url: deps.portalReturnUrl,
246
- });
247
- fallbackPortalUrl = session.url ?? null;
248
- if (!fallbackPortalUrl) fallbackError = 'stripe_session_missing_url';
249
- } catch (e) {
250
- fallbackError = retryFailureReason(e);
251
- }
252
-
253
- await deps.log('admin_invoice_retry_failed', {
254
- invoice_id: invoiceId, actor_email: actorEmail, customer_id: customerId,
255
- subscription_id: subscriptionId, amount_due_cents: invoice.amount_due ?? null,
256
- reason: failure, fallback_link_minted: fallbackPortalUrl !== null,
257
- fallback_error: fallbackError,
258
- }, fallbackPortalUrl ? 'warning' : 'error');
259
-
260
- return {
261
- status: 200,
262
- body: {
263
- ok: true,
264
- status: 'retry_failed',
265
- invoiceId,
266
- reason: failure,
267
- fallbackPortalUrl,
268
- fallbackError,
269
- },
270
- };
271
- }
272
-
273
- // ---8<--- END retry-core ---8<---
274
-
275
- export async function handle(
276
- req: Request,
277
- operator: { operatorName: string; domain: string },
278
- ): Promise<Response> {
279
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
280
- if (req.method !== 'POST') return json(405, { ok: false, code: 'method_not_allowed', error: 'Method not allowed.' });
281
-
282
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
283
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
284
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
285
- if (!stripeKey) return json(500, { ok: false, code: 'stripe_not_configured', error: 'Stripe is not configured.' });
286
-
287
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
288
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
289
-
290
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
291
- auth: { persistSession: false, autoRefreshToken: false },
292
- });
293
-
294
- // Rate limiting keys on the IP for an unverified caller so an unauthenticated
295
- // flood is still bounded.
296
- const rateKey = (caller?.email ?? '').toLowerCase() || clientIp(req);
297
- const [ipOk, emailOk] = await Promise.all([
298
- checkRateLimit(admin, 'admin-retry-invoice-payment-ip', clientIp(req), 20, 300),
299
- checkRateLimit(admin, 'admin-retry-invoice-payment-email', rateKey, 20, 300),
300
- ]);
301
- if (!ipOk || !emailOk) return json(429, { ok: false, code: 'rate_limited', error: 'Too many attempts — try again shortly.' });
302
-
303
- let raw: unknown;
304
- try {
305
- raw = await req.json();
306
- } catch {
307
- return json(400, { ok: false, code: 'invalid_json', error: 'Body was not valid JSON.' });
308
- }
309
- const parsed = Body.safeParse(raw);
310
- if (!parsed.success) {
311
- return json(400, { ok: false, code: 'invalid_body', error: JSON.stringify(parsed.error.flatten().fieldErrors) });
312
- }
313
-
314
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
315
-
316
- const result = await handleRetryInvoicePayment(caller, { invoiceId: parsed.data.invoiceId }, {
317
- stripe: stripe as unknown as RetryStripeLike,
318
- isAllowedAdmin: async (email) => {
319
- const { data, error } = await admin
320
- .from('admin_users').select('email').eq('email', email).maybeSingle();
321
- if (error) return { allowed: false, error: error.message };
322
- return { allowed: !!data };
323
- },
324
- portalConfigId: () => getOrCreateCoworkingPortalConfig(stripe, admin, {
325
- headline: `Manage your ${operator.operatorName} membership`,
326
- defaultReturnUrl: `https://${operator.domain}/membership`,
327
- }),
328
- portalReturnUrl: `https://${operator.domain}/membership`,
329
- log: (kind, detail, severity) => logOps(admin, kind, detail, { severity }).catch(() => ({ ok: false })),
330
- });
331
-
332
- return json(result.status, result.body);
333
- }
1
+ // supabase/functions/admin-retry-invoice-payment/index.ts
2
+ //
3
+ // Staff-triggered retry of ONE failed Stripe subscription invoice, with an
4
+ // automatic fallback: if the retry attempt fails (declined card, card needs
5
+ // 3DS, any Stripe error), the same call mints the coworking billing-portal
6
+ // link so staff can send the member a payment-update link without a second
7
+ // action.
8
+ //
9
+ // The invoice id comes from the admin UI, which reads it out of the most
10
+ // recent `subscription_payment_failed` ops_events row for that subscription
11
+ // (stripe-webhook's invoice.payment_failed handler is the only place a real
12
+ // Stripe invoice id is recorded — no table has an invoice column).
13
+ //
14
+ // Auth/allowlist/rate-limit scaffold mirrors admin-mint-billing-portal-link,
15
+ // and the fallback link reuses that function's exact portal configuration via
16
+ // the shared getOrCreateCoworkingPortalConfig helper — no second portal
17
+ // configuration is created here.
18
+ //
19
+ // NOTE ON THE CORE BLOCK BELOW: everything between the BEGIN/END markers is
20
+ // import-free by design and is mirrored byte-for-byte into
21
+ // admin-retry-invoice-payment.test.ts, which exercises it against a
22
+ // hand-rolled fake Stripe client. That test file asserts the two copies are
23
+ // identical, so the tested code cannot drift from the shipped code.
24
+
25
+ import { createClient } from 'npm:@supabase/supabase-js@2';
26
+ import Stripe from 'npm:stripe@17.5.0';
27
+ import { z } from 'npm:zod@3.23.8';
28
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
29
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
30
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
31
+ import { getOrCreateCoworkingPortalConfig } from 'npm:@simplelayer/graniteer-core/stripeCoworkingPortal';
32
+
33
+ const corsHeaders = {
34
+ 'Access-Control-Allow-Origin': '*',
35
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
36
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
37
+ };
38
+
39
+ interface CallerClaims { sub: string; email?: string; aal?: string }
40
+
41
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
42
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
43
+ function getJwks(supabaseUrl: string) {
44
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
45
+ return jwksCache;
46
+ }
47
+
48
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
49
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
50
+ const token = authHeader.slice(7).trim();
51
+ try {
52
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
53
+ const claims = payload as unknown as CallerClaims;
54
+ if (!claims.sub) return null;
55
+ return claims;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ function json(status: number, body: unknown) {
62
+ return new Response(JSON.stringify(body), {
63
+ status,
64
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
65
+ });
66
+ }
67
+
68
+ const Body = z.object({ invoiceId: z.string().trim().min(1).max(255) });
69
+
70
+ // ---8<--- BEGIN retry-core (mirrored verbatim in admin-retry-invoice-payment.test.ts) ---8<---
71
+
72
+ export interface RetryCallerClaims { sub?: string; email?: string; aal?: string }
73
+
74
+ /** The only invoice fields this path reads. Structural on purpose: the test's
75
+ * fake Stripe client satisfies it without pulling in the Stripe SDK. */
76
+ export interface RetryStripeInvoice {
77
+ id?: string;
78
+ status?: string | null;
79
+ customer?: string | { id?: string } | null;
80
+ subscription?: string | { id?: string } | null;
81
+ amount_due?: number | null;
82
+ amount_paid?: number | null;
83
+ }
84
+
85
+ export interface RetryStripeLike {
86
+ invoices: {
87
+ retrieve(id: string): Promise<RetryStripeInvoice>;
88
+ pay(id: string): Promise<RetryStripeInvoice>;
89
+ };
90
+ billingPortal: {
91
+ sessions: {
92
+ create(params: Record<string, unknown>): Promise<{ url?: string | null }>;
93
+ };
94
+ };
95
+ }
96
+
97
+ export interface RetryDeps {
98
+ stripe: RetryStripeLike;
99
+ /** admin_users allowlist lookup. `error` set => the lookup itself broke. */
100
+ isAllowedAdmin(email: string): Promise<{ allowed: boolean; error?: string }>;
101
+ /** Stripe billingPortal configuration id for coworking memberships. */
102
+ portalConfigId(): Promise<string>;
103
+ portalReturnUrl: string;
104
+ log(kind: string, detail: Record<string, unknown>, severity: 'info' | 'warning' | 'error'): Promise<unknown>;
105
+ }
106
+
107
+ export interface RetryResult { status: number; body: Record<string, unknown> }
108
+
109
+ export function stripeIdOf(v: string | { id?: string } | null | undefined): string | null {
110
+ if (!v) return null;
111
+ return typeof v === 'string' ? v : (v.id ?? null);
112
+ }
113
+
114
+ /** Short, staff-readable reason from a Stripe error object. */
115
+ export function retryFailureReason(e: unknown): string {
116
+ const err = e as { message?: unknown; code?: unknown; decline_code?: unknown } | null;
117
+ const message = typeof err?.message === 'string' && err.message.trim()
118
+ ? err.message.trim()
119
+ : String(e);
120
+ const code = typeof err?.decline_code === 'string' && err.decline_code
121
+ ? err.decline_code
122
+ : typeof err?.code === 'string' ? err.code : '';
123
+ const suffix = code && !message.toLowerCase().includes(code.toLowerCase()) ? ` (${code})` : '';
124
+ return `${message}${suffix}`.slice(0, 300);
125
+ }
126
+
127
+ /**
128
+ * Retry one invoice, falling back to a billing-portal link on failure.
129
+ *
130
+ * Contract notes:
131
+ * - Every authorization gate runs BEFORE `deps.stripe` is touched at all, so
132
+ * an unauthorized caller can never cause a Stripe API call.
133
+ * - Only an `open` invoice is retried. paid/void/draft/uncollectible
134
+ * short-circuit to `status: 'not_payable'` WITHOUT calling invoices.pay --
135
+ * re-paying is either an error or a no-op, and on a money path a no-op that
136
+ * Stripe might interpret is not worth attempting.
137
+ * - A failed retry is HTTP 200 / ok:true with `status: 'retry_failed'`. The
138
+ * request succeeded; the card is what declined, and the response carries the
139
+ * fallback link the caller needs. Reserving non-2xx for "we could not do the
140
+ * work at all" keeps the decline reason out of supabase-js's error.context
141
+ * swallowing on the client.
142
+ */
143
+ export async function handleRetryInvoicePayment(
144
+ caller: RetryCallerClaims | null,
145
+ input: { invoiceId: string },
146
+ deps: RetryDeps,
147
+ ): Promise<RetryResult> {
148
+ if (!caller?.sub) {
149
+ return { status: 401, body: { ok: false, code: 'unauthenticated', error: 'Not signed in.' } };
150
+ }
151
+ if (caller.aal !== 'aal2') {
152
+ return { status: 403, body: { ok: false, code: 'mfa_required', error: 'Two-factor authentication is required.' } };
153
+ }
154
+ const actorEmail = (caller.email ?? '').toLowerCase();
155
+ if (!actorEmail) {
156
+ return { status: 403, body: { ok: false, code: 'no_email', error: 'Caller has no email claim.' } };
157
+ }
158
+ const allow = await deps.isAllowedAdmin(actorEmail);
159
+ if (allow.error) {
160
+ return { status: 500, body: { ok: false, code: 'allowlist_lookup_failed', error: allow.error } };
161
+ }
162
+ if (!allow.allowed) {
163
+ return { status: 403, body: { ok: false, code: 'not_authorized', error: 'Not authorized.' } };
164
+ }
165
+
166
+ const invoiceId = (input.invoiceId ?? '').trim();
167
+ if (!/^in_[A-Za-z0-9_]+$/.test(invoiceId)) {
168
+ return { status: 400, body: { ok: false, code: 'invalid_invoice_id', error: 'That is not a Stripe invoice id.' } };
169
+ }
170
+
171
+ let invoice: RetryStripeInvoice;
172
+ try {
173
+ invoice = await deps.stripe.invoices.retrieve(invoiceId);
174
+ } catch (e) {
175
+ const reason = retryFailureReason(e);
176
+ await deps.log('admin_invoice_retry_lookup_failed',
177
+ { invoice_id: invoiceId, actor_email: actorEmail, reason }, 'error');
178
+ return { status: 502, body: { ok: false, code: 'invoice_lookup_failed', error: reason } };
179
+ }
180
+
181
+ const customerId = stripeIdOf(invoice.customer);
182
+ const subscriptionId = stripeIdOf(invoice.subscription);
183
+ const invoiceStatus = invoice.status ?? 'unknown';
184
+
185
+ if (!customerId) {
186
+ await deps.log('admin_invoice_retry_no_customer',
187
+ { invoice_id: invoiceId, actor_email: actorEmail, invoice_status: invoiceStatus }, 'error');
188
+ return {
189
+ status: 409,
190
+ body: { ok: false, code: 'no_customer', error: 'That invoice has no Stripe customer attached.' },
191
+ };
192
+ }
193
+
194
+ if (invoiceStatus !== 'open') {
195
+ const reason = invoiceStatus === 'paid'
196
+ ? 'This invoice is already paid — there is nothing to retry.'
197
+ : `This invoice is "${invoiceStatus}", so Stripe will not accept a payment attempt on it.`;
198
+ await deps.log('admin_invoice_retry_skipped', {
199
+ invoice_id: invoiceId, actor_email: actorEmail, customer_id: customerId,
200
+ subscription_id: subscriptionId, invoice_status: invoiceStatus,
201
+ }, 'info');
202
+ return {
203
+ status: 200,
204
+ body: { ok: true, status: 'not_payable', invoiceId, invoiceStatus, reason },
205
+ };
206
+ }
207
+
208
+ let paidInvoice: RetryStripeInvoice | null = null;
209
+ let failure: string | null = null;
210
+ try {
211
+ paidInvoice = await deps.stripe.invoices.pay(invoiceId);
212
+ // invoices.pay RESOLVES for a payment that needs member action (3DS): the
213
+ // invoice comes back still `open`. Treating a resolved promise as success
214
+ // would report a payment that never happened.
215
+ if ((paidInvoice?.status ?? null) !== 'paid') {
216
+ failure = `Stripe accepted the attempt but the invoice is still "${paidInvoice?.status ?? 'unknown'}" — the card most likely needs the member to authenticate the payment.`;
217
+ }
218
+ } catch (e) {
219
+ failure = retryFailureReason(e);
220
+ }
221
+
222
+ if (!failure) {
223
+ await deps.log('admin_invoice_retry_paid', {
224
+ invoice_id: invoiceId, actor_email: actorEmail, customer_id: customerId,
225
+ subscription_id: subscriptionId, amount_paid_cents: paidInvoice?.amount_paid ?? null,
226
+ }, 'info');
227
+ return {
228
+ status: 200,
229
+ body: {
230
+ ok: true,
231
+ status: 'paid',
232
+ invoiceId,
233
+ amountPaidCents: paidInvoice?.amount_paid ?? null,
234
+ },
235
+ };
236
+ }
237
+
238
+ let fallbackPortalUrl: string | null = null;
239
+ let fallbackError: string | null = null;
240
+ try {
241
+ const configuration = await deps.portalConfigId();
242
+ const session = await deps.stripe.billingPortal.sessions.create({
243
+ customer: customerId,
244
+ configuration,
245
+ return_url: deps.portalReturnUrl,
246
+ });
247
+ fallbackPortalUrl = session.url ?? null;
248
+ if (!fallbackPortalUrl) fallbackError = 'stripe_session_missing_url';
249
+ } catch (e) {
250
+ fallbackError = retryFailureReason(e);
251
+ }
252
+
253
+ await deps.log('admin_invoice_retry_failed', {
254
+ invoice_id: invoiceId, actor_email: actorEmail, customer_id: customerId,
255
+ subscription_id: subscriptionId, amount_due_cents: invoice.amount_due ?? null,
256
+ reason: failure, fallback_link_minted: fallbackPortalUrl !== null,
257
+ fallback_error: fallbackError,
258
+ }, fallbackPortalUrl ? 'warning' : 'error');
259
+
260
+ return {
261
+ status: 200,
262
+ body: {
263
+ ok: true,
264
+ status: 'retry_failed',
265
+ invoiceId,
266
+ reason: failure,
267
+ fallbackPortalUrl,
268
+ fallbackError,
269
+ },
270
+ };
271
+ }
272
+
273
+ // ---8<--- END retry-core ---8<---
274
+
275
+ export async function handle(
276
+ req: Request,
277
+ operator: { operatorName: string; domain: string },
278
+ ): Promise<Response> {
279
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
280
+ if (req.method !== 'POST') return json(405, { ok: false, code: 'method_not_allowed', error: 'Method not allowed.' });
281
+
282
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
283
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
284
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
285
+ if (!stripeKey) return json(500, { ok: false, code: 'stripe_not_configured', error: 'Stripe is not configured.' });
286
+
287
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
288
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
289
+
290
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
291
+ auth: { persistSession: false, autoRefreshToken: false },
292
+ });
293
+
294
+ // Rate limiting keys on the IP for an unverified caller so an unauthenticated
295
+ // flood is still bounded.
296
+ const rateKey = (caller?.email ?? '').toLowerCase() || clientIp(req);
297
+ const [ipOk, emailOk] = await Promise.all([
298
+ checkRateLimit(admin, 'admin-retry-invoice-payment-ip', clientIp(req), 20, 300),
299
+ checkRateLimit(admin, 'admin-retry-invoice-payment-email', rateKey, 20, 300),
300
+ ]);
301
+ if (!ipOk || !emailOk) return json(429, { ok: false, code: 'rate_limited', error: 'Too many attempts — try again shortly.' });
302
+
303
+ let raw: unknown;
304
+ try {
305
+ raw = await req.json();
306
+ } catch {
307
+ return json(400, { ok: false, code: 'invalid_json', error: 'Body was not valid JSON.' });
308
+ }
309
+ const parsed = Body.safeParse(raw);
310
+ if (!parsed.success) {
311
+ return json(400, { ok: false, code: 'invalid_body', error: JSON.stringify(parsed.error.flatten().fieldErrors) });
312
+ }
313
+
314
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
315
+
316
+ const result = await handleRetryInvoicePayment(caller, { invoiceId: parsed.data.invoiceId }, {
317
+ stripe: stripe as unknown as RetryStripeLike,
318
+ isAllowedAdmin: async (email) => {
319
+ const { data, error } = await admin
320
+ .from('admin_users').select('email').eq('email', email).maybeSingle();
321
+ if (error) return { allowed: false, error: error.message };
322
+ return { allowed: !!data };
323
+ },
324
+ portalConfigId: () => getOrCreateCoworkingPortalConfig(stripe, admin, {
325
+ headline: `Manage your ${operator.operatorName} membership`,
326
+ defaultReturnUrl: `https://${operator.domain}/membership`,
327
+ }),
328
+ portalReturnUrl: `https://${operator.domain}/membership`,
329
+ log: (kind, detail, severity) => logOps(admin, kind, detail, { severity }).catch(() => ({ ok: false })),
330
+ });
331
+
332
+ return json(result.status, result.body);
333
+ }