@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
@@ -1,162 +1,162 @@
1
- // Timetable — Event registration. Lets a signed-in member register for, or
2
- // cancel their registration on, one of our own Commons-calendar Luma events
3
- // without leaving the portal.
4
- //
5
- // SCOPE: only works for events owned by OUR Luma calendar (the same
6
- // LUMA_API_KEY that timetable-events already uses to read them) — Luma's own
7
- // key-scoping means a guest can't be added to (or found on) a calendar this
8
- // key doesn't own, so a community/ICS event id simply fails here. The client
9
- // only shows Register/Cancel for events with `source: null` (Commons-owned).
10
- //
11
- // AUTH: portal bearer session only (resolvePortalSession). The registering/
12
- // cancelling email is ALWAYS the verified session email — never
13
- // client-supplied — so this can't be used as an open relay against
14
- // arbitrary addresses.
15
- //
16
- // CANCEL: looks up the caller's own guest record via guests/list (matching
17
- // on verified session email server-side, never trusting a client-supplied
18
- // guest_id), then flips it to declined with send_email: false — a self
19
- // service undo, not a notified cancellation.
20
- //
21
- // NOT PERSISTED: Luma stays the system of record for RSVPs, same as the read
22
- // side (timetable-events). Nothing is written to Supabase here.
23
- import { createClient } from 'npm:@supabase/supabase-js@2';
24
- import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
25
- import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
26
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
27
-
28
- const corsHeaders = {
29
- 'Access-Control-Allow-Origin': '*',
30
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
31
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
32
- };
33
-
34
- const LUMA_BASE = 'https://api.lu.ma/public/v1';
35
- const BROWSER_UA =
36
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
37
-
38
- function json(status: number, body: unknown) {
39
- return new Response(JSON.stringify(body), {
40
- status,
41
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
42
- });
43
- }
44
-
45
- async function lumaFetch(path: string, apiKey: string, init: RequestInit = {}) {
46
- return fetch(`${LUMA_BASE}${path}`, {
47
- ...init,
48
- headers: {
49
- 'x-luma-api-key': apiKey,
50
- 'User-Agent': BROWSER_UA,
51
- 'Content-Type': 'application/json',
52
- Accept: 'application/json',
53
- ...(init.headers ?? {}),
54
- },
55
- signal: AbortSignal.timeout(10_000),
56
- });
57
- }
58
-
59
- /** Finds the caller's own guest record on an event by verified email — never
60
- * trusts a client-supplied guest_id. Paginates like the read side does. */
61
- async function findOwnGuest(eventId: string, email: string, apiKey: string) {
62
- let cursor: string | null = null;
63
- for (let page = 0; page < 5; page++) {
64
- const qs = new URLSearchParams({ event_id: eventId, pagination_limit: '100' });
65
- if (cursor) qs.set('pagination_cursor', cursor);
66
- const res = await lumaFetch(`/events/guests/list?${qs.toString()}`, apiKey);
67
- if (!res.ok) return { error: res.status };
68
- const data = await res.json();
69
- const entries = data.entries ?? [];
70
- for (const ent of entries) {
71
- const g = ent.guest ?? ent;
72
- if ((g.user_email ?? '').toLowerCase() === email) {
73
- return { guest: g };
74
- }
75
- }
76
- cursor = data.has_more ? data.next_cursor : null;
77
- if (!cursor) break;
78
- }
79
- return { guest: null };
80
- }
81
-
82
- export async function handle(req: Request): Promise<Response> {
83
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
84
- if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
85
-
86
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
87
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
88
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
89
- auth: { persistSession: false, autoRefreshToken: false },
90
- });
91
-
92
- try {
93
- const session = await resolvePortalSession(req, admin);
94
- if (!session) return json(401, { error: 'unauthorized' });
95
-
96
- const ok = await checkRateLimit(admin, 'timetable-event-register', session.email, 15, 600);
97
- if (!ok) return json(429, { error: 'rate_limited' });
98
-
99
- const payload = await req.json().catch(() => ({}));
100
- const eventId = typeof payload?.event_id === 'string' ? payload.event_id.trim() : '';
101
- const action = payload?.action === 'cancel' ? 'cancel' : 'register';
102
- if (!eventId) return json(400, { error: 'missing_event_id' });
103
-
104
- const apiKey = Deno.env.get('LUMA_API_KEY');
105
- if (!apiKey) {
106
- console.error('timetable-event-register: LUMA_API_KEY is not set');
107
- return json(503, { error: 'not_configured' });
108
- }
109
-
110
- if (action === 'cancel') {
111
- const found = await findOwnGuest(eventId, session.email, apiKey);
112
- if ('error' in found) {
113
- console.error('timetable-event-register: guest lookup failed', found.error);
114
- return json(502, { error: 'cancel_failed' });
115
- }
116
- if (!found.guest) {
117
- return json(200, { ok: true, message: "You're not registered for this event." });
118
- }
119
- const res = await lumaFetch('/events/guests/update-status', apiKey, {
120
- method: 'POST',
121
- body: JSON.stringify({
122
- event_id: eventId,
123
- guest_id: found.guest.id,
124
- status: 'declined',
125
- send_email: false,
126
- }),
127
- });
128
- if (!res.ok) {
129
- const detail = await res.text().catch(() => '');
130
- console.error('timetable-event-register: cancel failed', res.status, detail.slice(0, 300));
131
- await logOps(admin, 'timetable_event_cancel_failed', {
132
- event_id: eventId, status: res.status, detail: detail.slice(0, 300),
133
- }, { severity: 'warning' });
134
- return json(502, { error: 'cancel_failed' });
135
- }
136
- return json(200, { ok: true, message: 'Registration cancelled.' });
137
- }
138
-
139
- const res = await lumaFetch('/events/guests/add', apiKey, {
140
- method: 'POST',
141
- body: JSON.stringify({
142
- event_id: eventId,
143
- guests: [{ email: session.email }],
144
- send_email: true,
145
- }),
146
- });
147
-
148
- if (!res.ok) {
149
- const detail = await res.text().catch(() => '');
150
- console.error('timetable-event-register: luma responded', res.status, detail.slice(0, 300));
151
- await logOps(admin, 'timetable_event_register_failed', {
152
- event_id: eventId, status: res.status, detail: detail.slice(0, 300),
153
- }, { severity: 'warning' });
154
- return json(502, { error: 'registration_failed' });
155
- }
156
-
157
- return json(200, { ok: true, message: "You're registered — check your email for details." });
158
- } catch (e) {
159
- console.error('timetable-event-register: failed', e);
160
- return json(502, { error: 'registration_failed' });
161
- }
162
- }
1
+ // Timetable — Event registration. Lets a signed-in member register for, or
2
+ // cancel their registration on, one of our own Commons-calendar Luma events
3
+ // without leaving the portal.
4
+ //
5
+ // SCOPE: only works for events owned by OUR Luma calendar (the same
6
+ // LUMA_API_KEY that timetable-events already uses to read them) — Luma's own
7
+ // key-scoping means a guest can't be added to (or found on) a calendar this
8
+ // key doesn't own, so a community/ICS event id simply fails here. The client
9
+ // only shows Register/Cancel for events with `source: null` (Commons-owned).
10
+ //
11
+ // AUTH: portal bearer session only (resolvePortalSession). The registering/
12
+ // cancelling email is ALWAYS the verified session email — never
13
+ // client-supplied — so this can't be used as an open relay against
14
+ // arbitrary addresses.
15
+ //
16
+ // CANCEL: looks up the caller's own guest record via guests/list (matching
17
+ // on verified session email server-side, never trusting a client-supplied
18
+ // guest_id), then flips it to declined with send_email: false — a self
19
+ // service undo, not a notified cancellation.
20
+ //
21
+ // NOT PERSISTED: Luma stays the system of record for RSVPs, same as the read
22
+ // side (timetable-events). Nothing is written to Supabase here.
23
+ import { createClient } from 'npm:@supabase/supabase-js@2';
24
+ import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
25
+ import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
26
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
27
+
28
+ const corsHeaders = {
29
+ 'Access-Control-Allow-Origin': '*',
30
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
31
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
32
+ };
33
+
34
+ const LUMA_BASE = 'https://api.lu.ma/public/v1';
35
+ const BROWSER_UA =
36
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
37
+
38
+ function json(status: number, body: unknown) {
39
+ return new Response(JSON.stringify(body), {
40
+ status,
41
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
42
+ });
43
+ }
44
+
45
+ async function lumaFetch(path: string, apiKey: string, init: RequestInit = {}) {
46
+ return fetch(`${LUMA_BASE}${path}`, {
47
+ ...init,
48
+ headers: {
49
+ 'x-luma-api-key': apiKey,
50
+ 'User-Agent': BROWSER_UA,
51
+ 'Content-Type': 'application/json',
52
+ Accept: 'application/json',
53
+ ...(init.headers ?? {}),
54
+ },
55
+ signal: AbortSignal.timeout(10_000),
56
+ });
57
+ }
58
+
59
+ /** Finds the caller's own guest record on an event by verified email — never
60
+ * trusts a client-supplied guest_id. Paginates like the read side does. */
61
+ async function findOwnGuest(eventId: string, email: string, apiKey: string) {
62
+ let cursor: string | null = null;
63
+ for (let page = 0; page < 5; page++) {
64
+ const qs = new URLSearchParams({ event_id: eventId, pagination_limit: '100' });
65
+ if (cursor) qs.set('pagination_cursor', cursor);
66
+ const res = await lumaFetch(`/events/guests/list?${qs.toString()}`, apiKey);
67
+ if (!res.ok) return { error: res.status };
68
+ const data = await res.json();
69
+ const entries = data.entries ?? [];
70
+ for (const ent of entries) {
71
+ const g = ent.guest ?? ent;
72
+ if ((g.user_email ?? '').toLowerCase() === email) {
73
+ return { guest: g };
74
+ }
75
+ }
76
+ cursor = data.has_more ? data.next_cursor : null;
77
+ if (!cursor) break;
78
+ }
79
+ return { guest: null };
80
+ }
81
+
82
+ export async function handle(req: Request): Promise<Response> {
83
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
84
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
85
+
86
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
87
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
88
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
89
+ auth: { persistSession: false, autoRefreshToken: false },
90
+ });
91
+
92
+ try {
93
+ const session = await resolvePortalSession(req, admin);
94
+ if (!session) return json(401, { error: 'unauthorized' });
95
+
96
+ const ok = await checkRateLimit(admin, 'timetable-event-register', session.email, 15, 600);
97
+ if (!ok) return json(429, { error: 'rate_limited' });
98
+
99
+ const payload = await req.json().catch(() => ({}));
100
+ const eventId = typeof payload?.event_id === 'string' ? payload.event_id.trim() : '';
101
+ const action = payload?.action === 'cancel' ? 'cancel' : 'register';
102
+ if (!eventId) return json(400, { error: 'missing_event_id' });
103
+
104
+ const apiKey = Deno.env.get('LUMA_API_KEY');
105
+ if (!apiKey) {
106
+ console.error('timetable-event-register: LUMA_API_KEY is not set');
107
+ return json(503, { error: 'not_configured' });
108
+ }
109
+
110
+ if (action === 'cancel') {
111
+ const found = await findOwnGuest(eventId, session.email, apiKey);
112
+ if ('error' in found) {
113
+ console.error('timetable-event-register: guest lookup failed', found.error);
114
+ return json(502, { error: 'cancel_failed' });
115
+ }
116
+ if (!found.guest) {
117
+ return json(200, { ok: true, message: "You're not registered for this event." });
118
+ }
119
+ const res = await lumaFetch('/events/guests/update-status', apiKey, {
120
+ method: 'POST',
121
+ body: JSON.stringify({
122
+ event_id: eventId,
123
+ guest_id: found.guest.id,
124
+ status: 'declined',
125
+ send_email: false,
126
+ }),
127
+ });
128
+ if (!res.ok) {
129
+ const detail = await res.text().catch(() => '');
130
+ console.error('timetable-event-register: cancel failed', res.status, detail.slice(0, 300));
131
+ await logOps(admin, 'timetable_event_cancel_failed', {
132
+ event_id: eventId, status: res.status, detail: detail.slice(0, 300),
133
+ }, { severity: 'warning' });
134
+ return json(502, { error: 'cancel_failed' });
135
+ }
136
+ return json(200, { ok: true, message: 'Registration cancelled.' });
137
+ }
138
+
139
+ const res = await lumaFetch('/events/guests/add', apiKey, {
140
+ method: 'POST',
141
+ body: JSON.stringify({
142
+ event_id: eventId,
143
+ guests: [{ email: session.email }],
144
+ send_email: true,
145
+ }),
146
+ });
147
+
148
+ if (!res.ok) {
149
+ const detail = await res.text().catch(() => '');
150
+ console.error('timetable-event-register: luma responded', res.status, detail.slice(0, 300));
151
+ await logOps(admin, 'timetable_event_register_failed', {
152
+ event_id: eventId, status: res.status, detail: detail.slice(0, 300),
153
+ }, { severity: 'warning' });
154
+ return json(502, { error: 'registration_failed' });
155
+ }
156
+
157
+ return json(200, { ok: true, message: "You're registered — check your email for details." });
158
+ } catch (e) {
159
+ console.error('timetable-event-register: failed', e);
160
+ return json(502, { error: 'registration_failed' });
161
+ }
162
+ }
@@ -1,90 +1,90 @@
1
- // Timetable — Registration status lookup. Given a list of our own Commons
2
- // event ids, tells the caller which ones they're already an approved guest
3
- // on, so the portal can show "Registered" (with a Cancel action) instead of
4
- // always defaulting back to "Register" after a page refresh.
5
- //
6
- // AUTH: portal bearer session only. Reflects the VERIFIED session email —
7
- // never a client-supplied one. Read-only against Luma; nothing written,
8
- // nothing persisted in Supabase.
9
- import { createClient } from 'npm:@supabase/supabase-js@2';
10
- import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
11
- import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
12
-
13
- const corsHeaders = {
14
- 'Access-Control-Allow-Origin': '*',
15
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
16
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
17
- };
18
-
19
- const LUMA_BASE = 'https://api.lu.ma/public/v1';
20
- const BROWSER_UA =
21
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
22
- const MAX_EVENT_IDS = 20;
23
-
24
- function json(status: number, body: unknown) {
25
- return new Response(JSON.stringify(body), {
26
- status,
27
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
28
- });
29
- }
30
-
31
- async function isRegistered(eventId: string, email: string, apiKey: string): Promise<boolean> {
32
- let cursor: string | null = null;
33
- for (let page = 0; page < 5; page++) {
34
- const qs = new URLSearchParams({ event_id: eventId, pagination_limit: '100' });
35
- if (cursor) qs.set('pagination_cursor', cursor);
36
- const res = await fetch(`${LUMA_BASE}/events/guests/list?${qs.toString()}`, {
37
- headers: { 'x-luma-api-key': apiKey, 'User-Agent': BROWSER_UA, Accept: 'application/json' },
38
- signal: AbortSignal.timeout(10_000),
39
- });
40
- if (!res.ok) return false;
41
- const data = await res.json();
42
- const entries = data.entries ?? [];
43
- for (const ent of entries) {
44
- const g = ent.guest ?? ent;
45
- if ((g.user_email ?? '').toLowerCase() === email && g.approval_status === 'approved') {
46
- return true;
47
- }
48
- }
49
- cursor = data.has_more ? data.next_cursor : null;
50
- if (!cursor) break;
51
- }
52
- return false;
53
- }
54
-
55
- export async function handle(req: Request): Promise<Response> {
56
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
57
- if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
58
-
59
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
60
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
61
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
62
- auth: { persistSession: false, autoRefreshToken: false },
63
- });
64
-
65
- try {
66
- const session = await resolvePortalSession(req, admin);
67
- if (!session) return json(401, { error: 'unauthorized' });
68
-
69
- const ok = await checkRateLimit(admin, 'timetable-event-status', session.email, 30, 600);
70
- if (!ok) return json(429, { error: 'rate_limited' });
71
-
72
- const payload = await req.json().catch(() => ({}));
73
- const eventIds: string[] = Array.isArray(payload?.event_ids)
74
- ? payload.event_ids.filter((x: unknown) => typeof x === 'string').slice(0, MAX_EVENT_IDS)
75
- : [];
76
- if (eventIds.length === 0) return json(200, { statuses: {} });
77
-
78
- const apiKey = Deno.env.get('LUMA_API_KEY');
79
- if (!apiKey) return json(503, { error: 'not_configured' });
80
-
81
- const entries = await Promise.all(
82
- eventIds.map(async (id) => [id, await isRegistered(id, session.email, apiKey)] as const),
83
- );
84
- const statuses = Object.fromEntries(entries);
85
- return json(200, { statuses });
86
- } catch (e) {
87
- console.error('timetable-event-status: failed', e);
88
- return json(502, { error: 'status_failed' });
89
- }
90
- }
1
+ // Timetable — Registration status lookup. Given a list of our own Commons
2
+ // event ids, tells the caller which ones they're already an approved guest
3
+ // on, so the portal can show "Registered" (with a Cancel action) instead of
4
+ // always defaulting back to "Register" after a page refresh.
5
+ //
6
+ // AUTH: portal bearer session only. Reflects the VERIFIED session email —
7
+ // never a client-supplied one. Read-only against Luma; nothing written,
8
+ // nothing persisted in Supabase.
9
+ import { createClient } from 'npm:@supabase/supabase-js@2';
10
+ import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
11
+ import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
12
+
13
+ const corsHeaders = {
14
+ 'Access-Control-Allow-Origin': '*',
15
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
16
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
17
+ };
18
+
19
+ const LUMA_BASE = 'https://api.lu.ma/public/v1';
20
+ const BROWSER_UA =
21
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
22
+ const MAX_EVENT_IDS = 20;
23
+
24
+ function json(status: number, body: unknown) {
25
+ return new Response(JSON.stringify(body), {
26
+ status,
27
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
28
+ });
29
+ }
30
+
31
+ async function isRegistered(eventId: string, email: string, apiKey: string): Promise<boolean> {
32
+ let cursor: string | null = null;
33
+ for (let page = 0; page < 5; page++) {
34
+ const qs = new URLSearchParams({ event_id: eventId, pagination_limit: '100' });
35
+ if (cursor) qs.set('pagination_cursor', cursor);
36
+ const res = await fetch(`${LUMA_BASE}/events/guests/list?${qs.toString()}`, {
37
+ headers: { 'x-luma-api-key': apiKey, 'User-Agent': BROWSER_UA, Accept: 'application/json' },
38
+ signal: AbortSignal.timeout(10_000),
39
+ });
40
+ if (!res.ok) return false;
41
+ const data = await res.json();
42
+ const entries = data.entries ?? [];
43
+ for (const ent of entries) {
44
+ const g = ent.guest ?? ent;
45
+ if ((g.user_email ?? '').toLowerCase() === email && g.approval_status === 'approved') {
46
+ return true;
47
+ }
48
+ }
49
+ cursor = data.has_more ? data.next_cursor : null;
50
+ if (!cursor) break;
51
+ }
52
+ return false;
53
+ }
54
+
55
+ export async function handle(req: Request): Promise<Response> {
56
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
57
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
58
+
59
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
60
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
61
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
62
+ auth: { persistSession: false, autoRefreshToken: false },
63
+ });
64
+
65
+ try {
66
+ const session = await resolvePortalSession(req, admin);
67
+ if (!session) return json(401, { error: 'unauthorized' });
68
+
69
+ const ok = await checkRateLimit(admin, 'timetable-event-status', session.email, 30, 600);
70
+ if (!ok) return json(429, { error: 'rate_limited' });
71
+
72
+ const payload = await req.json().catch(() => ({}));
73
+ const eventIds: string[] = Array.isArray(payload?.event_ids)
74
+ ? payload.event_ids.filter((x: unknown) => typeof x === 'string').slice(0, MAX_EVENT_IDS)
75
+ : [];
76
+ if (eventIds.length === 0) return json(200, { statuses: {} });
77
+
78
+ const apiKey = Deno.env.get('LUMA_API_KEY');
79
+ if (!apiKey) return json(503, { error: 'not_configured' });
80
+
81
+ const entries = await Promise.all(
82
+ eventIds.map(async (id) => [id, await isRegistered(id, session.email, apiKey)] as const),
83
+ );
84
+ const statuses = Object.fromEntries(entries);
85
+ return json(200, { statuses });
86
+ } catch (e) {
87
+ console.error('timetable-event-status: failed', e);
88
+ return json(502, { error: 'status_failed' });
89
+ }
90
+ }