@simplelayer/graniteer-core 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,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,98 +1,98 @@
1
- import { createClient } from 'npm:@supabase/supabase-js@2';
2
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
3
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
4
-
5
- const corsHeaders = {
6
- 'Access-Control-Allow-Origin': '*',
7
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
8
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
9
- };
10
-
11
- interface CallerClaims {
12
- sub: string;
13
- email?: string;
14
- aal?: string;
15
- }
16
-
17
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
18
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
19
- function getJwks(supabaseUrl: string) {
20
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
21
- return jwksCache;
22
- }
23
-
24
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
25
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
26
- const token = authHeader.slice(7).trim();
27
- try {
28
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
29
- const claims = payload as unknown as CallerClaims;
30
- if (!claims.sub) return null;
31
- return claims;
32
- } catch {
33
- return null;
34
- }
35
- }
36
-
37
- function json(status: number, body: unknown) {
38
- return new Response(JSON.stringify(body), {
39
- status,
40
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
41
- });
42
- }
43
-
44
- export async function handle(req: Request): Promise<Response> {
45
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
46
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
47
-
48
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
49
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
50
-
51
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
52
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
53
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
54
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
55
- const callerEmail = (caller.email ?? '').toLowerCase();
56
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
57
-
58
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
59
- auth: { persistSession: false, autoRefreshToken: false },
60
- });
61
-
62
- const [ipOk, emailOk] = await Promise.all([
63
- checkRateLimit(admin, 'admin-coupon-reverse-ip', clientIp(req), 30, 300),
64
- checkRateLimit(admin, 'admin-coupon-reverse-email', callerEmail, 20, 300),
65
- ]);
66
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
67
-
68
- const { data: allow, error: allowErr } = await admin
69
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
70
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
71
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
72
-
73
- let body: { redemption_id?: string; reason?: string };
74
- try {
75
- body = await req.json();
76
- } catch {
77
- return json(400, { ok: false, error: 'invalid_json' });
78
- }
79
-
80
- const redemptionId = (body.redemption_id ?? '').trim();
81
- if (!/^[0-9a-f-]{36}$/i.test(redemptionId)) {
82
- return json(400, { ok: false, error: 'invalid_redemption_id' });
83
- }
84
- const reason = (body.reason ?? '').trim().slice(0, 500);
85
- if (!reason) return json(400, { ok: false, error: 'reason_required' });
86
-
87
- const { data, error } = await admin.rpc('coupon_reverse', {
88
- p_redemption_id: redemptionId,
89
- p_reason: reason,
90
- p_actor_email: callerEmail,
91
- });
92
-
93
- if (error) {
94
- return json(400, { ok: false, error: error.message });
95
- }
96
-
97
- return json(200, { ok: true, redemption: data });
98
- }
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
3
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
4
+
5
+ const corsHeaders = {
6
+ 'Access-Control-Allow-Origin': '*',
7
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
8
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
9
+ };
10
+
11
+ interface CallerClaims {
12
+ sub: string;
13
+ email?: string;
14
+ aal?: string;
15
+ }
16
+
17
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
18
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
19
+ function getJwks(supabaseUrl: string) {
20
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
21
+ return jwksCache;
22
+ }
23
+
24
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
25
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
26
+ const token = authHeader.slice(7).trim();
27
+ try {
28
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
29
+ const claims = payload as unknown as CallerClaims;
30
+ if (!claims.sub) return null;
31
+ return claims;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ function json(status: number, body: unknown) {
38
+ return new Response(JSON.stringify(body), {
39
+ status,
40
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
41
+ });
42
+ }
43
+
44
+ export async function handle(req: Request): Promise<Response> {
45
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
46
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
47
+
48
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
49
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
50
+
51
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
52
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
53
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
54
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
55
+ const callerEmail = (caller.email ?? '').toLowerCase();
56
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
57
+
58
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
59
+ auth: { persistSession: false, autoRefreshToken: false },
60
+ });
61
+
62
+ const [ipOk, emailOk] = await Promise.all([
63
+ checkRateLimit(admin, 'admin-coupon-reverse-ip', clientIp(req), 30, 300),
64
+ checkRateLimit(admin, 'admin-coupon-reverse-email', callerEmail, 20, 300),
65
+ ]);
66
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
67
+
68
+ const { data: allow, error: allowErr } = await admin
69
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
70
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
71
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
72
+
73
+ let body: { redemption_id?: string; reason?: string };
74
+ try {
75
+ body = await req.json();
76
+ } catch {
77
+ return json(400, { ok: false, error: 'invalid_json' });
78
+ }
79
+
80
+ const redemptionId = (body.redemption_id ?? '').trim();
81
+ if (!/^[0-9a-f-]{36}$/i.test(redemptionId)) {
82
+ return json(400, { ok: false, error: 'invalid_redemption_id' });
83
+ }
84
+ const reason = (body.reason ?? '').trim().slice(0, 500);
85
+ if (!reason) return json(400, { ok: false, error: 'reason_required' });
86
+
87
+ const { data, error } = await admin.rpc('coupon_reverse', {
88
+ p_redemption_id: redemptionId,
89
+ p_reason: reason,
90
+ p_actor_email: callerEmail,
91
+ });
92
+
93
+ if (error) {
94
+ return json(400, { ok: false, error: error.message });
95
+ }
96
+
97
+ return json(200, { ok: true, redemption: data });
98
+ }