@simplelayer/graniteer-core 0.0.2 → 0.1.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 (100) hide show
  1. package/index.js +2 -2
  2. package/package.json +98 -15
  3. package/src/adminBookingCredit.test.ts +451 -0
  4. package/src/adminBookingCredit.ts +239 -0
  5. package/src/availability.test.ts +25 -0
  6. package/src/availability.ts +201 -0
  7. package/src/bookingHoldReclaim.ts +94 -0
  8. package/src/checkoutSessionParams.ts +56 -0
  9. package/src/commonsContract.ts +175 -0
  10. package/src/conductorAdmin.ts +141 -0
  11. package/src/email-templates/email-change.tsx +92 -0
  12. package/src/email-templates/invite.tsx +79 -0
  13. package/src/email-templates/reauthentication.tsx +60 -0
  14. package/src/functions/admin-cancel-membership.ts +311 -0
  15. package/src/functions/admin-change-membership-plan.ts +308 -0
  16. package/src/functions/admin-charge-guest-print.ts +229 -0
  17. package/src/functions/admin-correct-booking.ts +333 -0
  18. package/src/functions/admin-create-commons-event.ts +244 -0
  19. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  20. package/src/functions/admin-door-write.ts +272 -0
  21. package/src/functions/admin-mark-booking-paid.ts +203 -0
  22. package/src/functions/admin-photo-upload.ts +128 -0
  23. package/src/functions/admin-remove-team-member.ts +150 -0
  24. package/src/functions/admin-reset-mfa.ts +138 -0
  25. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  26. package/src/functions/admin-send-commons-agreement.ts +214 -0
  27. package/src/functions/admin-set-credit-amount.ts +123 -0
  28. package/src/functions/admin-skip-commons-contract.ts +165 -0
  29. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  30. package/src/functions/admin-wall-photo-write.ts +141 -0
  31. package/src/functions/boldsign-sender-identity.ts +114 -0
  32. package/src/functions/booking-availability.ts +419 -0
  33. package/src/functions/booking-member-preview.ts +136 -0
  34. package/src/functions/day-pass-status.ts +89 -0
  35. package/src/functions/dayStatus.ts +71 -0
  36. package/src/functions/diag-webpush-test.ts +45 -0
  37. package/src/functions/event-access-store.ts +309 -0
  38. package/src/functions/ezeep-print-webhook.ts +213 -0
  39. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  40. package/src/functions/get-signing-link.ts +211 -0
  41. package/src/functions/guest-print-setup-confirm.ts +128 -0
  42. package/src/functions/guest-print-submit.ts +149 -0
  43. package/src/functions/luma-webhook.ts +165 -0
  44. package/src/functions/migration-collision-alert.copy.ts +232 -0
  45. package/src/functions/migration-collision-alert.test.ts +349 -0
  46. package/src/functions/migration-collision-alert.ts +232 -0
  47. package/src/functions/office-assignment-end.ts +146 -0
  48. package/src/functions/portal-booking-access.ts +95 -0
  49. package/src/functions/portal-list-invoices.ts +99 -0
  50. package/src/functions/print-billing-recover.ts +97 -0
  51. package/src/functions/print-billing-run.ts +183 -0
  52. package/src/functions/public-facts.ts +168 -0
  53. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  54. package/src/functions/space-availability-range.ts +142 -0
  55. package/src/functions/sync-gcal-blackouts.ts +298 -0
  56. package/src/functions/timetable-event-register.ts +162 -0
  57. package/src/functions/timetable-event-status.ts +90 -0
  58. package/src/functions/timetable-spaces.ts +219 -0
  59. package/src/functions/touch-pass-reconciler.ts +689 -0
  60. package/src/functions/virtual-onboarding-purge.ts +134 -0
  61. package/src/functions/virtual-onboarding-submit.ts +315 -0
  62. package/src/functions/voice-inquiry.test.ts +301 -0
  63. package/src/functions/voice-inquiry.ts +198 -0
  64. package/src/functions/voice-tour-availability.ts +204 -0
  65. package/src/gcalSync.ts +142 -0
  66. package/src/ghlNote.ts +34 -0
  67. package/src/ghlTask.ts +48 -0
  68. package/src/ghlVoiceInquiry.ts +90 -0
  69. package/src/guestPrintCapture.test.ts +722 -0
  70. package/src/guestPrintCapture.ts +538 -0
  71. package/src/lumaGhl.ts +195 -0
  72. package/src/membership.ts +109 -0
  73. package/src/money.ts +36 -0
  74. package/src/ops.ts +97 -0
  75. package/src/pacificDate.ts +34 -0
  76. package/src/policyAcknowledgment.test.ts +50 -0
  77. package/src/policyAcknowledgment.ts +96 -0
  78. package/src/portalSession.ts +46 -0
  79. package/src/pricing.test.ts +660 -0
  80. package/src/pricing.ts +1025 -0
  81. package/src/printBilling.test.ts +750 -0
  82. package/src/printBilling.ts +891 -0
  83. package/src/printBillingAdapters.ts +169 -0
  84. package/src/printCorrections.test.ts +348 -0
  85. package/src/printCorrections.ts +496 -0
  86. package/src/rateLimit.ts +82 -0
  87. package/src/referralCredits.test.ts +31 -0
  88. package/src/referralCredits.ts +34 -0
  89. package/src/referralGrant.ts +321 -0
  90. package/src/rescheduleCredit.test.ts +521 -0
  91. package/src/rescheduleCredit.ts +337 -0
  92. package/src/reservationWifiCode.test.ts +69 -0
  93. package/src/reservationWifiCode.ts +81 -0
  94. package/src/retellCallAnalyzed.test.ts +167 -0
  95. package/src/retellCallAnalyzed.ts +113 -0
  96. package/src/retellSignature.test.ts +137 -0
  97. package/src/retellSignature.ts +82 -0
  98. package/src/slackAlert.ts +38 -0
  99. package/src/supabaseTestFakes.ts +131 -0
  100. package/src/tier1Agreement.ts +125 -0
@@ -0,0 +1,149 @@
1
+ // Guest-facing: submit a print job and get a Stripe SetupIntent client_secret
2
+ // back so the frontend can save a card via Stripe Elements before the job's
3
+ // actual cost is known. See _shared/guestPrintCapture.ts for the design.
4
+ //
5
+ // This is deliberately a THIN wrapper: all decision logic lives in
6
+ // guestPrintCapture.ts and is covered by guestPrintCapture.test.ts against a
7
+ // mocked Stripe transport. This file only wires the real Supabase/Stripe
8
+ // clients and handles HTTP/validation/rate-limiting concerns.
9
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
10
+ import { createClient } from 'npm:@supabase/supabase-js@2';
11
+ import Stripe from 'npm:stripe@17.5.0';
12
+ import { z } from 'npm:zod@3.23.8';
13
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
14
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
15
+ import {
16
+ generateGuestBillingCode,
17
+ submitGuestPrintJob,
18
+ type GuestPrintDbLike,
19
+ type GuestPrintStripeLike,
20
+ } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
21
+
22
+ const Body = z.object({
23
+ email: z.string().trim().email().max(255),
24
+ guest_name: z.string().trim().min(1).max(200).optional(),
25
+ });
26
+
27
+ function json(status: number, body: unknown) {
28
+ return new Response(JSON.stringify(body), {
29
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
30
+ });
31
+ }
32
+
33
+ export async function handle(req: Request): Promise<Response> {
34
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
35
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
36
+
37
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
38
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
39
+ const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
40
+ auth: { persistSession: false, autoRefreshToken: false },
41
+ });
42
+
43
+ let raw: unknown;
44
+ try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
45
+ const parsed = Body.safeParse(raw);
46
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
47
+ const emailKey = parsed.data.email.toLowerCase();
48
+ const guestName = parsed.data.guest_name?.trim() || null;
49
+
50
+ const ip = clientIp(req);
51
+ const [ipOk, emailOk] = await Promise.all([
52
+ checkRateLimit(supabase, 'guest-print-submit-ip', ip, 20, 600),
53
+ checkRateLimit(supabase, 'guest-print-submit-email', emailKey, 10, 600),
54
+ ]);
55
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
56
+
57
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
58
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
59
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
60
+
61
+ const stripeLike: GuestPrintStripeLike = {
62
+ customers: {
63
+ search: (p) => stripe.customers.search(p),
64
+ list: (p) => stripe.customers.list(p),
65
+ create: (p) => stripe.customers.create(p),
66
+ },
67
+ setupIntents: {
68
+ create: (p, o) => stripe.setupIntents.create(p, o),
69
+ retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
70
+ },
71
+ paymentIntents: {
72
+ // Cast: GuestPrintStripeLike's params are intentionally structural
73
+ // (Record<string, unknown>) so guestPrintCapture.ts stays free of any
74
+ // Stripe SDK import; the real SDK's PaymentIntentCreateParams has
75
+ // required fields (amount, currency) that a Record<string, unknown>
76
+ // erases statically even though every real caller supplies them.
77
+ create: (p, o) => stripe.paymentIntents.create(p as never, o),
78
+ retrieve: (id) => stripe.paymentIntents.retrieve(id),
79
+ },
80
+ };
81
+
82
+ const dbLike: GuestPrintDbLike = {
83
+ async insertPending({ email, guestName, guestBillingCode }) {
84
+ const { data, error } = await supabase
85
+ .from('print_guest_submissions')
86
+ .insert({ email, guest_name: guestName, guest_billing_code: guestBillingCode, status: 'pending_card' })
87
+ .select('id')
88
+ .single();
89
+ if (error) throw error;
90
+ return (data as { id: string }).id;
91
+ },
92
+ async attachStripeIds(id, customerId, setupIntentId) {
93
+ const { error } = await supabase
94
+ .from('print_guest_submissions')
95
+ .update({ stripe_customer_id: customerId, stripe_setup_intent_id: setupIntentId })
96
+ .eq('id', id);
97
+ if (error) throw error;
98
+ },
99
+ async markCardSaved() { throw new Error('not used by submit'); },
100
+ async markFailed(id, reason) {
101
+ const { error } = await supabase
102
+ .from('print_guest_submissions')
103
+ .update({ status: 'failed', last_error: reason.slice(0, 2000) })
104
+ .eq('id', id);
105
+ if (error) console.error('[guest-print-submit] markFailed write failed', error);
106
+ },
107
+ async getById() { throw new Error('not used by submit'); },
108
+ async claimForCharge() { throw new Error('not used by submit'); },
109
+ async writebackCharged() { throw new Error('not used by submit'); },
110
+ async writebackChargeFailed() { throw new Error('not used by submit'); },
111
+ };
112
+
113
+ // Retry loop for the (very unlikely) billing-code collision -- the unique
114
+ // index is the real guard; this just avoids surfacing a 500 to a guest on
115
+ // the rare hit.
116
+ let outcome;
117
+ for (let attempt = 0; attempt < 5; attempt++) {
118
+ const guestBillingCode = generateGuestBillingCode(crypto.getRandomValues(new Uint8Array(16)));
119
+ try {
120
+ outcome = await submitGuestPrintJob(stripeLike, dbLike, {
121
+ email: emailKey, guestName, guestBillingCode,
122
+ });
123
+ break;
124
+ } catch (e) {
125
+ const code = (e as { code?: string })?.code;
126
+ if (code === '23505' && attempt < 4) continue; // billing_code collision -- retry with a new code
127
+ console.error('guest-print-submit error', e);
128
+ await logOps(supabase, 'guest_print_submit_error',
129
+ { message: e instanceof Error ? e.message : String(e) }, { severity: 'error' });
130
+ return json(500, { ok: false, error: 'unexpected_error' });
131
+ }
132
+ }
133
+ if (!outcome) {
134
+ return json(500, { ok: false, error: 'billing_code_collision_exhausted' });
135
+ }
136
+
137
+ if (!outcome.ok) {
138
+ await logOps(supabase, 'guest_print_submit_stripe_failed',
139
+ { submission_id: outcome.submissionId, detail: outcome.detail }, { severity: 'error' });
140
+ return json(502, { ok: false, error: 'setup_failed', submission_id: outcome.submissionId });
141
+ }
142
+
143
+ return json(200, {
144
+ ok: true,
145
+ submission_id: outcome.submissionId,
146
+ client_secret: outcome.clientSecret,
147
+ guest_billing_code: outcome.guestBillingCode,
148
+ });
149
+ }
@@ -0,0 +1,165 @@
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
3
+ import { syncLumaGuestToGhl } from 'npm:@simplelayer/graniteer-core/lumaGhl';
4
+
5
+ /**
6
+ * Inbound Lu.ma webhook receiver.
7
+ *
8
+ * Receive → verify → log. No downstream dispatch yet: rows land in
9
+ * `luma_webhook_events` with `processed = false` for a follow-up task to read.
10
+ *
11
+ * Signature scheme (https://help.luma.com/p/webhooks):
12
+ * Webhook-Signature: t=<unix_ts>,v1=<hex_hmac_sha256>
13
+ * HMAC-SHA256 over `${t}.${rawBody}` keyed with LUMA_WEBHOOK_SECRET.
14
+ * Verified with Web Crypto (Deno has no Node `crypto` module).
15
+ */
16
+
17
+ const MAX_SKEW_SECONDS = 5 * 60;
18
+
19
+ function json(status: number, body: unknown) {
20
+ return new Response(JSON.stringify(body), {
21
+ status,
22
+ headers: { 'Content-Type': 'application/json' },
23
+ });
24
+ }
25
+
26
+ function toHex(buf: ArrayBuffer): string {
27
+ return Array.from(new Uint8Array(buf))
28
+ .map((b) => b.toString(16).padStart(2, '0'))
29
+ .join('');
30
+ }
31
+
32
+ /** Constant-time string compare (Web Crypto exposes no timingSafeEqual). */
33
+ function timingSafeEqualHex(a: string, b: string): boolean {
34
+ if (a.length !== b.length) return false;
35
+ let acc = 0;
36
+ for (let i = 0; i < a.length; i++) acc |= a.charCodeAt(i) ^ b.charCodeAt(i);
37
+ return acc === 0;
38
+ }
39
+
40
+ // No CORS — this is called by Lu.ma, not the browser.
41
+ export async function handle(req: Request): Promise<Response> {
42
+ if (req.method !== 'POST') {
43
+ return new Response('Method not allowed', { status: 405 });
44
+ }
45
+
46
+ // Raw text first: signature verification needs the exact bytes Lu.ma signed.
47
+ const rawBody = await req.text();
48
+
49
+ // Cast: the supabase-js generic defaults differ from logOps' inferred
50
+ // client type; the same shim other functions use.
51
+ const supabase = createClient(
52
+ Deno.env.get('SUPABASE_URL')!,
53
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
54
+ { auth: { persistSession: false, autoRefreshToken: false } },
55
+ ) as unknown as Parameters<typeof logOps>[0];
56
+
57
+ const webhookId = req.headers.get('Webhook-Id');
58
+ const signatureHeader = req.headers.get('Webhook-Signature');
59
+ const timestampHeader = req.headers.get('Webhook-Timestamp');
60
+
61
+ const secret = Deno.env.get('LUMA_WEBHOOK_SECRET');
62
+ if (!secret) {
63
+ // Fail closed — never process an unverifiable request.
64
+ await logOps(supabase, 'luma_webhook_not_configured', {}, { severity: 'error' });
65
+ return json(500, { error: 'not_configured' });
66
+ }
67
+
68
+ const rejectSignature = async (reason: string) => {
69
+ // Never log the secret or the computed/expected signature values.
70
+ await logOps(
71
+ supabase,
72
+ 'luma_webhook_signature_invalid',
73
+ { webhook_id: webhookId, reason },
74
+ { severity: 'warning' },
75
+ );
76
+ return json(401, { error: 'invalid_signature' });
77
+ };
78
+
79
+ if (!signatureHeader || !webhookId) return await rejectSignature('missing_header');
80
+
81
+ let t: string | null = null;
82
+ let v1: string | null = null;
83
+ for (const part of signatureHeader.split(',')) {
84
+ const idx = part.indexOf('=');
85
+ if (idx === -1) continue;
86
+ const key = part.slice(0, idx).trim();
87
+ const value = part.slice(idx + 1).trim();
88
+ if (key === 't') t = value;
89
+ else if (key === 'v1') v1 = value;
90
+ }
91
+ if (!t || !v1) return await rejectSignature('malformed_header');
92
+
93
+ // Replay protection: reject stale or far-future timestamps.
94
+ const tsRaw = timestampHeader ?? t;
95
+ const ts = Number(tsRaw);
96
+ if (!Number.isFinite(ts)) return await rejectSignature('bad_timestamp');
97
+ const skew = Math.abs(Math.floor(Date.now() / 1000) - ts);
98
+ if (skew > MAX_SKEW_SECONDS) return await rejectSignature('timestamp_out_of_window');
99
+
100
+ const key = await crypto.subtle.importKey(
101
+ 'raw',
102
+ new TextEncoder().encode(secret),
103
+ { name: 'HMAC', hash: 'SHA-256' },
104
+ false,
105
+ ['sign'],
106
+ );
107
+ const macBuf = await crypto.subtle.sign(
108
+ 'HMAC',
109
+ key,
110
+ new TextEncoder().encode(`${t}.${rawBody}`),
111
+ );
112
+ const expected = toHex(macBuf);
113
+
114
+ if (!timingSafeEqualHex(expected, v1.toLowerCase())) {
115
+ return await rejectSignature('signature_mismatch');
116
+ }
117
+
118
+ // ---- Verified past this point ----
119
+
120
+ let body: Record<string, unknown>;
121
+ try {
122
+ body = JSON.parse(rawBody) as Record<string, unknown>;
123
+ } catch (e) {
124
+ await logOps(
125
+ supabase,
126
+ 'luma_webhook_malformed_payload',
127
+ { webhook_id: webhookId, message: (e instanceof Error ? e.message : String(e)).slice(0, 500) },
128
+ { severity: 'error' },
129
+ );
130
+ return json(400, { error: 'malformed_payload' });
131
+ }
132
+
133
+ const eventType = typeof body.type === 'string' && body.type.length > 0 ? body.type : 'unknown';
134
+
135
+ // Idempotency ledger — dedupe Lu.ma redeliveries (mirrors stripe_events).
136
+ const { error: insertErr } = await supabase
137
+ .from('luma_webhook_events')
138
+ .insert({ webhook_id: webhookId, event_type: eventType, payload: body } as never);
139
+
140
+ const code = (insertErr as { code?: string } | null)?.code;
141
+ if (code === '23505') {
142
+ return json(200, { received: true, duplicate: true });
143
+ }
144
+ if (insertErr) {
145
+ await logOps(
146
+ supabase,
147
+ 'luma_webhook_insert_failed',
148
+ { webhook_id: webhookId, event_type: eventType, message: insertErr.message },
149
+ { severity: 'error' },
150
+ );
151
+ return json(500, { error: 'insert_failed' });
152
+ }
153
+
154
+ // Data-sync only: create/tag the CRM contact. Never sends a message; GHL
155
+ // workflows fire off these tags. Only guest records reach GHL. Runs after
156
+ // the idempotency insert so redeliveries (23505 above) never re-sync.
157
+ if (eventType === 'guest.registered' || eventType === 'guest.updated') {
158
+ await syncLumaGuestToGhl(body.data, eventType, supabase);
159
+ }
160
+
161
+ return new Response(JSON.stringify({ received: true }), {
162
+ status: 200,
163
+ headers: { 'Content-Type': 'application/json' },
164
+ });
165
+ }
@@ -0,0 +1,232 @@
1
+ // supabase/functions/migration-collision-alert/index.ts
2
+ //
3
+ // TEMPORARY, SECRET-GATED poller that Slack-alerts on
4
+ // `membership_email_collision_flagged` ops_events for emails on the 61-person
5
+ // legacy-migration roster, for the duration of the migration window only.
6
+ //
7
+ // WHY THIS EXISTS (plan v13 §4): stripe-webhook's existing, unmodified
8
+ // adopt/insert logic (§9.4) emits that event at severity 'warning' when
9
+ // `allSameCustomer` is true — two independently-completed Checkout Sessions
10
+ // for one email produce two membership rows, one warning-severity collision
11
+ // event, and two live subscriptions. That behavior is out of scope to change
12
+ // ("zero webhook changes"), and it is the CORRECT behavior to leave alone.
13
+ // What was missing is that nobody finds out: _shared/ops.ts only fans an event
14
+ // out to Slack at severity 'error', so a 'warning' collision lands in
15
+ // ops_events and stops there. This function closes the notification gap
16
+ // WITHOUT touching the emitter.
17
+ //
18
+ // WHY A POLLER RATHER THAN A CALL-SITE ALERT: the natural place for this is
19
+ // one `sendSlackAlert(...)` next to the `logOps(... 'membership_email_
20
+ // collision_flagged' ...)` call in stripe-webhook. That file is explicitly
21
+ // off-limits — the plan's own §4 commitment is zero webhook changes — so the
22
+ // alert is attached from the outside, by reading the event stream the webhook
23
+ // already writes.
24
+ //
25
+ // PATTERNS FOLLOWED (nothing new invented):
26
+ // - auth: x-reconcile-secret + constant-time compare against a secret read
27
+ // via an RPC, copied from dunning-email-check/index.ts (which copied it
28
+ // from ezeep-usage-reconcile/index.ts).
29
+ // - alerting: sendSlackAlert(OPS_ALERTS_CHANNEL_ID, ...) from
30
+ // _shared/slackAlert.ts, as retell-call-webhook/index.ts uses it.
31
+ // - once-only delivery: an ops_events dedupe_key marker row, read before
32
+ // alerting, exactly as retell-call-webhook checks
33
+ // `voice_inquiry_captured:<id>` before doing its backfill.
34
+ //
35
+ // SCOPE, both halves enforced in code below:
36
+ // - people: only emails present in `migration_checkout_state`. That table IS
37
+ // the 61-person roster, so the scoping needs no second hardcoded list and
38
+ // cannot drift from it.
39
+ // - window: only events newer than LOOKBACK_HOURS. When the migration is
40
+ // done, unschedule the cron — see the migration that creates it.
41
+ //
42
+ // This function reads ops_events and migration_checkout_state and writes only
43
+ // its own marker rows. It never reads or writes `memberships`, never touches
44
+ // Stripe, and cannot alter what stripe-webhook did.
45
+
46
+ import { createClient } from 'npm:@supabase/supabase-js@2';
47
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
48
+ import { sendSlackAlert, OPS_ALERTS_CHANNEL_ID } from 'npm:@simplelayer/graniteer-core/slackAlert';
49
+
50
+ const COLLISION_KIND = 'membership_email_collision_flagged';
51
+ const ALERTED_KIND = 'migration_collision_alerted';
52
+
53
+ /**
54
+ * Generous relative to the 5-minute cron: an alert that fires twice is
55
+ * prevented by the dedupe marker, but an alert that never fires because the
56
+ * window was too tight is unrecoverable. Overlap is the safe direction.
57
+ */
58
+ const LOOKBACK_HOURS = 48;
59
+
60
+ function safeEqual(a: string, b: string): boolean {
61
+ const enc = new TextEncoder();
62
+ const ab = enc.encode(a), bb = enc.encode(b);
63
+ if (ab.length !== bb.length) return false;
64
+ let diff = 0;
65
+ for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
66
+ return diff === 0;
67
+ }
68
+
69
+ /** Same normalization §1's reconciliation query established: lower(trim(...)). */
70
+ function normalizeEmail(v: unknown): string | null {
71
+ if (typeof v !== 'string') return null;
72
+ const n = v.trim().toLowerCase();
73
+ return n.length > 0 ? n : null;
74
+ }
75
+
76
+ interface CollisionEventRow {
77
+ id: string;
78
+ created_at: string;
79
+ severity: string | null;
80
+ detail: Record<string, unknown> | null;
81
+ }
82
+
83
+ export interface CollisionAlertDeps {
84
+ supabase: ReturnType<typeof createClient>;
85
+ alert: (channelId: string, text: string) => Promise<void>;
86
+ now: () => Date;
87
+ }
88
+
89
+ export async function handleMigrationCollisionAlert(
90
+ req: Request,
91
+ injected?: CollisionAlertDeps,
92
+ ): Promise<Response> {
93
+ if (req.method !== 'POST' && req.method !== 'GET') {
94
+ return new Response('Method not allowed', { status: 405 });
95
+ }
96
+
97
+ const deps: CollisionAlertDeps = injected ?? {
98
+ supabase: createClient(
99
+ Deno.env.get('SUPABASE_URL')!,
100
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
101
+ ),
102
+ alert: sendSlackAlert,
103
+ now: () => new Date(),
104
+ };
105
+ const supabase = deps.supabase;
106
+
107
+ // Auth is skipped ONLY when dependencies are injected, i.e. under test.
108
+ // In production `injected` is always undefined, so the gate always runs.
109
+ if (!injected) {
110
+ const provided = req.headers.get('x-reconcile-secret');
111
+ if (!provided) return new Response('Unauthorized', { status: 401 });
112
+
113
+ const { data: gate, error: gateErr } = await supabase.rpc('get_migration_collision_alert_secret');
114
+ const expected = typeof gate === 'string' ? gate : null;
115
+ if (gateErr || !expected || !safeEqual(provided, expected)) {
116
+ return new Response('Unauthorized', { status: 401 });
117
+ }
118
+ }
119
+
120
+ try {
121
+ const sinceIso = new Date(deps.now().getTime() - LOOKBACK_HOURS * 3600_000).toISOString();
122
+
123
+ // 1. The roster. This table is the 61-person migration list; an empty
124
+ // roster means the migration is over (or not seeded yet) and there is
125
+ // by definition nothing in scope to alert on.
126
+ const { data: rosterRows, error: rosterErr } = await supabase
127
+ .from('migration_checkout_state')
128
+ .select('email');
129
+ if (rosterErr) throw new Error('migration_checkout_state read failed: ' + rosterErr.message);
130
+ const roster = new Set<string>();
131
+ for (const r of (rosterRows ?? []) as Array<{ email: string }>) {
132
+ const n = normalizeEmail(r.email);
133
+ if (n) roster.add(n);
134
+ }
135
+ if (roster.size === 0) {
136
+ return json({ ok: true, roster_size: 0, in_scope: 0, alerted: 0, skipped: 0 });
137
+ }
138
+
139
+ // 2. Collision events in the window. Deliberately NOT filtered by
140
+ // severity: 'warning' is the same-customer case §4 describes and
141
+ // 'error' is the cross-customer case, and a migrant hitting the second
142
+ // one needs an alert at least as urgently as the first.
143
+ const { data: events, error: evErr } = await supabase
144
+ .from('ops_events')
145
+ .select('id,created_at,severity,detail')
146
+ .eq('kind', COLLISION_KIND)
147
+ .gte('created_at', sinceIso)
148
+ .order('created_at', { ascending: true });
149
+ if (evErr) throw new Error('ops_events read failed: ' + evErr.message);
150
+
151
+ let inScope = 0, alerted = 0, skipped = 0;
152
+
153
+ for (const ev of (events ?? []) as CollisionEventRow[]) {
154
+ const detail = ev.detail ?? {};
155
+ const email = normalizeEmail(detail.attempted_email);
156
+ if (!email || !roster.has(email)) { skipped++; continue; }
157
+ inScope++;
158
+
159
+ const subscriptionId = typeof detail.subscription_id === 'string' ? detail.subscription_id : null;
160
+ // Keyed on the event row id, which is unique per emission, so one alert
161
+ // per collision event rather than per (email, subscription) guess.
162
+ const dedupeKey = `${ALERTED_KIND}:${ev.id}`;
163
+
164
+ const { data: already, error: alreadyErr } = await supabase
165
+ .from('ops_events')
166
+ .select('id')
167
+ .eq('dedupe_key', dedupeKey)
168
+ .maybeSingle();
169
+ // A failed dedupe read must not cause a duplicate alert storm on every
170
+ // 5-minute tick — treat "can't tell" as "already alerted" and let the
171
+ // next run retry once the read works.
172
+ if (alreadyErr) { skipped++; continue; }
173
+ if (already) { skipped++; continue; }
174
+
175
+ const collidingIds = Array.isArray(detail.colliding_ids) ? detail.colliding_ids : [];
176
+ const membershipId = typeof detail.membership_id === 'string' ? detail.membership_id : null;
177
+
178
+ await deps.alert(
179
+ OPS_ALERTS_CHANNEL_ID,
180
+ `:rotating_light: MIGRATION email collision — *${email}* is on the legacy-migration roster ` +
181
+ `and just tripped stripe-webhook's duplicate-membership guard.\n` +
182
+ `• severity: ${ev.severity ?? 'unknown'} • at: ${ev.created_at}\n` +
183
+ `• new subscription: ${subscriptionId ?? 'unknown'} • new membership: ${membershipId ?? 'none'}\n` +
184
+ `• colliding membership rows: ${collidingIds.length > 0 ? collidingIds.join(', ') : 'none reported'}\n` +
185
+ `Expected shape: TWO membership rows and TWO live subscriptions. Cancel the duplicate ` +
186
+ `subscription in Stripe and reconcile the rows by hand — nothing does this automatically.`,
187
+ );
188
+
189
+ // Marker row. logOps returns ok:true on a dedupe_key collision (that is
190
+ // the success case for a once-ever emission), so this is idempotent
191
+ // under a concurrent second tick.
192
+ const res = await logOps(supabase, ALERTED_KIND, {
193
+ collision_event_id: ev.id,
194
+ email,
195
+ subscription_id: subscriptionId,
196
+ severity: ev.severity,
197
+ }, { severity: 'info', dedupeKey });
198
+ if (!res.ok) {
199
+ // Unchecked emission is indistinguishable from "no problem found"
200
+ // (_shared/ops.ts's hard contract), and here it specifically means the
201
+ // next tick will alert again. Say so loudly rather than silently.
202
+ console.error('[migration-collision-alert] marker write failed', {
203
+ collision_event_id: ev.id, error: res.error,
204
+ });
205
+ }
206
+ alerted++;
207
+ }
208
+
209
+ return json({ ok: true, roster_size: roster.size, in_scope: inScope, alerted, skipped });
210
+ } catch (e) {
211
+ try {
212
+ // Cast: the generated Database types are not wired into edge functions,
213
+ // so the insert payload widens to `never` without it (same as ops.ts).
214
+ await supabase.from('ops_events').insert({
215
+ kind: 'migration_collision_alert_error',
216
+ severity: 'error',
217
+ detail: { error: String(e) },
218
+ } as never);
219
+ } catch { /* ignore */ }
220
+ return json({ ok: false, error: String(e) }, 500);
221
+ }
222
+ }
223
+
224
+ function json(body: unknown, status = 200): Response {
225
+ return new Response(JSON.stringify(body), {
226
+ headers: { 'Content-Type': 'application/json' }, status,
227
+ });
228
+ }
229
+
230
+ // Arrow wrapper: the handler's optional second parameter (injected deps) makes
231
+ // Deno.serve resolve to its options overload otherwise.
232
+ if (import.meta.main) Deno.serve((req) => handleMigrationCollisionAlert(req));