@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,312 +1,312 @@
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
- // Only these statuses may have their plan changed. past_due is excluded
47
- // deliberately — dunning must resolve (or the member must be cancelled)
48
- // before a plan change is attempted, to avoid stacking a proration on top
49
- // of an already-failing payment method.
50
- const CHANGEABLE = new Set(['active', 'trialing']);
51
-
52
- type PlanRow = {
53
- id: string;
54
- slug: string;
55
- name: string;
56
- category: string;
57
- is_private_office: boolean;
58
- active: boolean;
59
- billable: boolean;
60
- billing_interval: string | null;
61
- price_cents: number | null;
62
- stripe_price_id: string | null;
63
- stripe_product_id: string | null;
64
- };
65
-
66
- export async function handle(req: Request): Promise<Response> {
67
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
68
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
69
-
70
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
71
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
72
-
73
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
74
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
75
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
76
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
77
- const callerEmail = (caller.email ?? '').toLowerCase();
78
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
79
-
80
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
81
- auth: { persistSession: false, autoRefreshToken: false },
82
- });
83
-
84
- const [ipOk, emailOk] = await Promise.all([
85
- checkRateLimit(admin, 'admin-change-membership-plan-ip', clientIp(req), 30, 300),
86
- checkRateLimit(admin, 'admin-change-membership-plan-email', callerEmail, 20, 300),
87
- ]);
88
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
89
-
90
- const { data: allow, error: allowErr } = await admin
91
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
92
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
93
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
94
-
95
- let body: {
96
- membership_id?: string;
97
- new_plan_id?: string;
98
- reason?: string;
99
- idempotency_key?: string;
100
- dry_run?: boolean;
101
- };
102
- try {
103
- body = await req.json();
104
- } catch {
105
- return json(400, { ok: false, error: 'invalid_json' });
106
- }
107
-
108
- const membershipId = (body.membership_id ?? '').trim();
109
- if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
110
- return json(400, { ok: false, error: 'invalid_membership_id' });
111
- }
112
- const newPlanId = (body.new_plan_id ?? '').trim();
113
- if (!/^[0-9a-f-]{36}$/i.test(newPlanId)) {
114
- return json(400, { ok: false, error: 'invalid_new_plan_id' });
115
- }
116
- const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
117
- const idempotencyKey = (body.idempotency_key ?? '').trim();
118
- if (!idempotencyKey || idempotencyKey.length > 100) {
119
- return json(400, { ok: false, error: 'invalid_idempotency_key' });
120
- }
121
- const dryRun = !!body.dry_run;
122
-
123
- // 1. Live membership state.
124
- const { data: membership, error: mErr } = await admin
125
- .from('memberships')
126
- .select('id,email,status,stripe_subscription_id,plan_id,cancel_at')
127
- .eq('id', membershipId)
128
- .maybeSingle();
129
- if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
130
- if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
131
- if (membership.cancel_at) return json(400, { ok: false, error: 'pending_cancellation' });
132
- if (!CHANGEABLE.has(membership.status)) {
133
- return json(400, { ok: false, error: 'not_changeable', detail: `status is ${membership.status}` });
134
- }
135
- const subscriptionId = membership.stripe_subscription_id;
136
- if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
137
- if (newPlanId === membership.plan_id) return json(400, { ok: false, error: 'same_plan' });
138
-
139
- // 2. Load both plan rows in one query.
140
- const { data: planRows, error: planErr } = await admin
141
- .from('membership_plans')
142
- .select('id,slug,name,category,is_private_office,active,billable,billing_interval,price_cents,stripe_price_id,stripe_product_id')
143
- .in('id', [membership.plan_id, newPlanId]);
144
- if (planErr) return json(500, { ok: false, error: 'load_plans_failed', detail: planErr.message });
145
- const currentPlan = (planRows ?? []).find((p) => p.id === membership.plan_id) as PlanRow | undefined;
146
- const newPlan = (planRows ?? []).find((p) => p.id === newPlanId) as PlanRow | undefined;
147
- if (!currentPlan) return json(500, { ok: false, error: 'current_plan_not_found' });
148
- if (!newPlan) return json(400, { ok: false, error: 'plan_not_found' });
149
-
150
- // 3. Plan-change eligibility guards. Private-office plans are sign-before-pay
151
- // (BoldSign agreement precedes any charge) and must never be reachable from
152
- // this self-serve-adjacent admin path, as either the source or destination.
153
- // is_private_office is a capability flag (D33 Phase 0.5 Phase 7), not the
154
- // catalog 'category' column — a resale operator's own category taxonomy
155
- // need not include 'office' at all for this guard to still apply correctly.
156
- if (currentPlan.is_private_office || newPlan.is_private_office) {
157
- return json(400, { ok: false, error: 'office_plan_blocked' });
158
- }
159
- if (!newPlan.active) return json(400, { ok: false, error: 'plan_inactive' });
160
- if (!newPlan.billable) return json(400, { ok: false, error: 'plan_not_billable' });
161
- // Scope limited to monthly plans for now, matching the site's own
162
- // `subscribable` definition (build-pricing-bootstrap.mjs) — annual plans
163
- // are out of scope for this feature.
164
- if ((newPlan.billing_interval ?? '').toLowerCase() !== 'month') {
165
- return json(400, { ok: false, error: 'unsupported_billing_interval' });
166
- }
167
-
168
- // 4. Resolve what to actually send Stripe for the new price. Mirrors the
169
- // ad-hoc checkout path: a stored stripe_price_id is preferred, but a plan
170
- // with only price_cents + a Stripe product can still be priced inline.
171
- let priceUpdate: { price: string } | { price_data: Record<string, unknown> };
172
- if (newPlan.stripe_price_id) {
173
- priceUpdate = { price: newPlan.stripe_price_id };
174
- } else if (newPlan.stripe_product_id && typeof newPlan.price_cents === 'number' && newPlan.price_cents > 0) {
175
- priceUpdate = {
176
- price_data: {
177
- currency: 'usd',
178
- unit_amount: newPlan.price_cents,
179
- recurring: { interval: 'month' },
180
- product: newPlan.stripe_product_id,
181
- },
182
- };
183
- } else {
184
- return json(400, { ok: false, error: 'plan_not_chargeable' });
185
- }
186
-
187
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
188
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
189
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
190
-
191
- // 5. Retrieve subscription (read-only) for the item id + current period bounds.
192
- let sub: Stripe.Subscription;
193
- try {
194
- sub = await stripe.subscriptions.retrieve(subscriptionId);
195
- } catch (e) {
196
- const msg = e instanceof Error ? e.message : String(e);
197
- return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
198
- }
199
- if (sub.items.data.length !== 1) {
200
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
201
- }
202
- const item = sub.items.data[0] as unknown as {
203
- id: string;
204
- current_period_start: number;
205
- current_period_end: number;
206
- };
207
- const periodStart = item.current_period_start;
208
- const periodEnd = item.current_period_end;
209
- const nowUnix = Math.floor(Date.now() / 1000);
210
-
211
- // 6. Estimate-only proration math (same time-remaining-fraction approach as
212
- // admin-cancel-membership's refund estimate) — a heads-up for the admin.
213
- // The REAL amount is always read back from the invoice Stripe actually
214
- // creates in step 8, never trusted from this estimate.
215
- const span = periodEnd - periodStart;
216
- const remaining = Math.max(0, periodEnd - nowUnix);
217
- const fraction = span > 0 ? remaining / span : 0;
218
- const creditForOldPlan = Math.round((currentPlan.price_cents ?? 0) * fraction);
219
- const chargeForNewPlan = Math.round((newPlan.price_cents ?? 0) * fraction);
220
- const estimatedNetCents = chargeForNewPlan - creditForOldPlan;
221
-
222
- if (dryRun) {
223
- return json(200, {
224
- ok: true,
225
- estimated_net_cents: estimatedNetCents,
226
- current_plan_name: currentPlan.name,
227
- new_plan_name: newPlan.name,
228
- });
229
- }
230
-
231
- // 7. Idempotent audit insert — claims the idempotency key immediately
232
- // before the Stripe mutation, same discipline as admin-cancel-membership.
233
- const { error: insErr } = await admin.from('membership_admin_actions').insert({
234
- membership_id: membershipId,
235
- action: 'plan_changed',
236
- old_plan_id: membership.plan_id,
237
- new_plan_id: newPlanId,
238
- actor_email: callerEmail,
239
- idempotency_key: idempotencyKey,
240
- reason: reasonInput,
241
- effective_at: new Date().toISOString(),
242
- });
243
- if (insErr) {
244
- if ((insErr as { code?: string }).code === '23505') {
245
- return json(200, { ok: true, duplicate: true });
246
- }
247
- return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
248
- }
249
-
250
- // 8. Apply the plan change in Stripe. proration_behavior: 'always_invoice'
251
- // bills/credits the difference immediately rather than deferring it to the
252
- // next regular invoice, matching the "settle now, not later" precedent set
253
- // by admin-cancel-membership's immediate scheduled-cancellation refunds.
254
- let updatedSub: Stripe.Subscription;
255
- try {
256
- updatedSub = await stripe.subscriptions.update(
257
- subscriptionId,
258
- {
259
- items: [{ id: item.id, ...priceUpdate } as any],
260
- proration_behavior: 'always_invoice',
261
- metadata: { plan_id: newPlanId, plan_slug: newPlan.slug },
262
- },
263
- { idempotencyKey },
264
- );
265
- } catch (e) {
266
- const msg = e instanceof Error ? e.message : String(e);
267
- return json(500, { ok: false, error: 'stripe_update_failed', detail: msg });
268
- }
269
-
270
- // 9. Read back the real invoice 'always_invoice' just created — this is
271
- // the authoritative amount/status, never the pre-update estimate.
272
- let invoiceId: string | null = null;
273
- let invoiceAmountCents: number | null = null;
274
- let invoiceStatus: string | null = null;
275
- try {
276
- const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
277
- const latest = invoices.data[0];
278
- if (latest) {
279
- invoiceId = latest.id ?? null;
280
- invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
281
- invoiceStatus = latest.status ?? null;
282
- }
283
- } catch (e) {
284
- const msg = e instanceof Error ? e.message : String(e);
285
- await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
286
- message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
287
- }, { severity: 'warning' });
288
- }
289
-
290
- // 10. Authoritative membership write, done immediately after the Stripe
291
- // mutation that produced it.
292
- const { error: updErr } = await admin
293
- .from('memberships')
294
- .update({ plan_id: newPlanId, status: updatedSub.status })
295
- .eq('id', membershipId);
296
- if (updErr) {
297
- await logOps(admin, 'membership_plan_change_db_write_failed', {
298
- message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
299
- }, { severity: 'error' });
300
- return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
301
- }
302
-
303
- return json(200, {
304
- ok: true,
305
- status: updatedSub.status,
306
- new_plan_id: newPlanId,
307
- invoice_id: invoiceId,
308
- invoice_amount_cents: invoiceAmountCents,
309
- invoice_status: invoiceStatus,
310
- estimated_net_cents: estimatedNetCents,
311
- });
312
- }
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
+ // Only these statuses may have their plan changed. past_due is excluded
47
+ // deliberately — dunning must resolve (or the member must be cancelled)
48
+ // before a plan change is attempted, to avoid stacking a proration on top
49
+ // of an already-failing payment method.
50
+ const CHANGEABLE = new Set(['active', 'trialing']);
51
+
52
+ type PlanRow = {
53
+ id: string;
54
+ slug: string;
55
+ name: string;
56
+ category: string;
57
+ is_private_office: boolean;
58
+ active: boolean;
59
+ billable: boolean;
60
+ billing_interval: string | null;
61
+ price_cents: number | null;
62
+ stripe_price_id: string | null;
63
+ stripe_product_id: string | null;
64
+ };
65
+
66
+ export async function handle(req: Request): Promise<Response> {
67
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
68
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
69
+
70
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
71
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
72
+
73
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
74
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
75
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
76
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
77
+ const callerEmail = (caller.email ?? '').toLowerCase();
78
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
79
+
80
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
81
+ auth: { persistSession: false, autoRefreshToken: false },
82
+ });
83
+
84
+ const [ipOk, emailOk] = await Promise.all([
85
+ checkRateLimit(admin, 'admin-change-membership-plan-ip', clientIp(req), 30, 300),
86
+ checkRateLimit(admin, 'admin-change-membership-plan-email', callerEmail, 20, 300),
87
+ ]);
88
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
89
+
90
+ const { data: allow, error: allowErr } = await admin
91
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
92
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
93
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
94
+
95
+ let body: {
96
+ membership_id?: string;
97
+ new_plan_id?: string;
98
+ reason?: string;
99
+ idempotency_key?: string;
100
+ dry_run?: boolean;
101
+ };
102
+ try {
103
+ body = await req.json();
104
+ } catch {
105
+ return json(400, { ok: false, error: 'invalid_json' });
106
+ }
107
+
108
+ const membershipId = (body.membership_id ?? '').trim();
109
+ if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
110
+ return json(400, { ok: false, error: 'invalid_membership_id' });
111
+ }
112
+ const newPlanId = (body.new_plan_id ?? '').trim();
113
+ if (!/^[0-9a-f-]{36}$/i.test(newPlanId)) {
114
+ return json(400, { ok: false, error: 'invalid_new_plan_id' });
115
+ }
116
+ const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
117
+ const idempotencyKey = (body.idempotency_key ?? '').trim();
118
+ if (!idempotencyKey || idempotencyKey.length > 100) {
119
+ return json(400, { ok: false, error: 'invalid_idempotency_key' });
120
+ }
121
+ const dryRun = !!body.dry_run;
122
+
123
+ // 1. Live membership state.
124
+ const { data: membership, error: mErr } = await admin
125
+ .from('memberships')
126
+ .select('id,email,status,stripe_subscription_id,plan_id,cancel_at')
127
+ .eq('id', membershipId)
128
+ .maybeSingle();
129
+ if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
130
+ if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
131
+ if (membership.cancel_at) return json(400, { ok: false, error: 'pending_cancellation' });
132
+ if (!CHANGEABLE.has(membership.status)) {
133
+ return json(400, { ok: false, error: 'not_changeable', detail: `status is ${membership.status}` });
134
+ }
135
+ const subscriptionId = membership.stripe_subscription_id;
136
+ if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
137
+ if (newPlanId === membership.plan_id) return json(400, { ok: false, error: 'same_plan' });
138
+
139
+ // 2. Load both plan rows in one query.
140
+ const { data: planRows, error: planErr } = await admin
141
+ .from('membership_plans')
142
+ .select('id,slug,name,category,is_private_office,active,billable,billing_interval,price_cents,stripe_price_id,stripe_product_id')
143
+ .in('id', [membership.plan_id, newPlanId]);
144
+ if (planErr) return json(500, { ok: false, error: 'load_plans_failed', detail: planErr.message });
145
+ const currentPlan = (planRows ?? []).find((p) => p.id === membership.plan_id) as PlanRow | undefined;
146
+ const newPlan = (planRows ?? []).find((p) => p.id === newPlanId) as PlanRow | undefined;
147
+ if (!currentPlan) return json(500, { ok: false, error: 'current_plan_not_found' });
148
+ if (!newPlan) return json(400, { ok: false, error: 'plan_not_found' });
149
+
150
+ // 3. Plan-change eligibility guards. Private-office plans are sign-before-pay
151
+ // (BoldSign agreement precedes any charge) and must never be reachable from
152
+ // this self-serve-adjacent admin path, as either the source or destination.
153
+ // is_private_office is a capability flag (D33 Phase 0.5 Phase 7), not the
154
+ // catalog 'category' column — a resale operator's own category taxonomy
155
+ // need not include 'office' at all for this guard to still apply correctly.
156
+ if (currentPlan.is_private_office || newPlan.is_private_office) {
157
+ return json(400, { ok: false, error: 'office_plan_blocked' });
158
+ }
159
+ if (!newPlan.active) return json(400, { ok: false, error: 'plan_inactive' });
160
+ if (!newPlan.billable) return json(400, { ok: false, error: 'plan_not_billable' });
161
+ // Scope limited to monthly plans for now, matching the site's own
162
+ // `subscribable` definition (build-pricing-bootstrap.mjs) — annual plans
163
+ // are out of scope for this feature.
164
+ if ((newPlan.billing_interval ?? '').toLowerCase() !== 'month') {
165
+ return json(400, { ok: false, error: 'unsupported_billing_interval' });
166
+ }
167
+
168
+ // 4. Resolve what to actually send Stripe for the new price. Mirrors the
169
+ // ad-hoc checkout path: a stored stripe_price_id is preferred, but a plan
170
+ // with only price_cents + a Stripe product can still be priced inline.
171
+ let priceUpdate: { price: string } | { price_data: Record<string, unknown> };
172
+ if (newPlan.stripe_price_id) {
173
+ priceUpdate = { price: newPlan.stripe_price_id };
174
+ } else if (newPlan.stripe_product_id && typeof newPlan.price_cents === 'number' && newPlan.price_cents > 0) {
175
+ priceUpdate = {
176
+ price_data: {
177
+ currency: 'usd',
178
+ unit_amount: newPlan.price_cents,
179
+ recurring: { interval: 'month' },
180
+ product: newPlan.stripe_product_id,
181
+ },
182
+ };
183
+ } else {
184
+ return json(400, { ok: false, error: 'plan_not_chargeable' });
185
+ }
186
+
187
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
188
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
189
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
190
+
191
+ // 5. Retrieve subscription (read-only) for the item id + current period bounds.
192
+ let sub: Stripe.Subscription;
193
+ try {
194
+ sub = await stripe.subscriptions.retrieve(subscriptionId);
195
+ } catch (e) {
196
+ const msg = e instanceof Error ? e.message : String(e);
197
+ return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
198
+ }
199
+ if (sub.items.data.length !== 1) {
200
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
201
+ }
202
+ const item = sub.items.data[0] as unknown as {
203
+ id: string;
204
+ current_period_start: number;
205
+ current_period_end: number;
206
+ };
207
+ const periodStart = item.current_period_start;
208
+ const periodEnd = item.current_period_end;
209
+ const nowUnix = Math.floor(Date.now() / 1000);
210
+
211
+ // 6. Estimate-only proration math (same time-remaining-fraction approach as
212
+ // admin-cancel-membership's refund estimate) — a heads-up for the admin.
213
+ // The REAL amount is always read back from the invoice Stripe actually
214
+ // creates in step 8, never trusted from this estimate.
215
+ const span = periodEnd - periodStart;
216
+ const remaining = Math.max(0, periodEnd - nowUnix);
217
+ const fraction = span > 0 ? remaining / span : 0;
218
+ const creditForOldPlan = Math.round((currentPlan.price_cents ?? 0) * fraction);
219
+ const chargeForNewPlan = Math.round((newPlan.price_cents ?? 0) * fraction);
220
+ const estimatedNetCents = chargeForNewPlan - creditForOldPlan;
221
+
222
+ if (dryRun) {
223
+ return json(200, {
224
+ ok: true,
225
+ estimated_net_cents: estimatedNetCents,
226
+ current_plan_name: currentPlan.name,
227
+ new_plan_name: newPlan.name,
228
+ });
229
+ }
230
+
231
+ // 7. Idempotent audit insert — claims the idempotency key immediately
232
+ // before the Stripe mutation, same discipline as admin-cancel-membership.
233
+ const { error: insErr } = await admin.from('membership_admin_actions').insert({
234
+ membership_id: membershipId,
235
+ action: 'plan_changed',
236
+ old_plan_id: membership.plan_id,
237
+ new_plan_id: newPlanId,
238
+ actor_email: callerEmail,
239
+ idempotency_key: idempotencyKey,
240
+ reason: reasonInput,
241
+ effective_at: new Date().toISOString(),
242
+ });
243
+ if (insErr) {
244
+ if ((insErr as { code?: string }).code === '23505') {
245
+ return json(200, { ok: true, duplicate: true });
246
+ }
247
+ return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
248
+ }
249
+
250
+ // 8. Apply the plan change in Stripe. proration_behavior: 'always_invoice'
251
+ // bills/credits the difference immediately rather than deferring it to the
252
+ // next regular invoice, matching the "settle now, not later" precedent set
253
+ // by admin-cancel-membership's immediate scheduled-cancellation refunds.
254
+ let updatedSub: Stripe.Subscription;
255
+ try {
256
+ updatedSub = await stripe.subscriptions.update(
257
+ subscriptionId,
258
+ {
259
+ items: [{ id: item.id, ...priceUpdate } as any],
260
+ proration_behavior: 'always_invoice',
261
+ metadata: { plan_id: newPlanId, plan_slug: newPlan.slug },
262
+ },
263
+ { idempotencyKey },
264
+ );
265
+ } catch (e) {
266
+ const msg = e instanceof Error ? e.message : String(e);
267
+ return json(500, { ok: false, error: 'stripe_update_failed', detail: msg });
268
+ }
269
+
270
+ // 9. Read back the real invoice 'always_invoice' just created — this is
271
+ // the authoritative amount/status, never the pre-update estimate.
272
+ let invoiceId: string | null = null;
273
+ let invoiceAmountCents: number | null = null;
274
+ let invoiceStatus: string | null = null;
275
+ try {
276
+ const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
277
+ const latest = invoices.data[0];
278
+ if (latest) {
279
+ invoiceId = latest.id ?? null;
280
+ invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
281
+ invoiceStatus = latest.status ?? null;
282
+ }
283
+ } catch (e) {
284
+ const msg = e instanceof Error ? e.message : String(e);
285
+ await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
286
+ message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
287
+ }, { severity: 'warning' });
288
+ }
289
+
290
+ // 10. Authoritative membership write, done immediately after the Stripe
291
+ // mutation that produced it.
292
+ const { error: updErr } = await admin
293
+ .from('memberships')
294
+ .update({ plan_id: newPlanId, status: updatedSub.status })
295
+ .eq('id', membershipId);
296
+ if (updErr) {
297
+ await logOps(admin, 'membership_plan_change_db_write_failed', {
298
+ message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
299
+ }, { severity: 'error' });
300
+ return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
301
+ }
302
+
303
+ return json(200, {
304
+ ok: true,
305
+ status: updatedSub.status,
306
+ new_plan_id: newPlanId,
307
+ invoice_id: invoiceId,
308
+ invoice_amount_cents: invoiceAmountCents,
309
+ invoice_status: invoiceStatus,
310
+ estimated_net_cents: estimatedNetCents,
311
+ });
312
+ }