@simplelayer/graniteer-core 0.2.0 → 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 -309
  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 -95
  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,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
+ }