@simplelayer/graniteer-core 0.1.2 → 0.2.1

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 +334 -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 +217 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,168 @@
1
+ // Staff-triggered Stripe billing-portal link for a specific member.
2
+ //
3
+ // Mints the same kind of Billing Portal session create-portal-session gives
4
+ // a signed-in member -- staff never see or handle a card number, they only
5
+ // get (and optionally email) a Stripe-hosted link the member uses themselves.
6
+ //
7
+ // Auth/allowlist/rate-limit scaffold copied from admin-resend-payment-link-email.
8
+
9
+ import { createClient } from 'npm:@supabase/supabase-js@2';
10
+ import Stripe from 'npm:stripe@17.5.0';
11
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
12
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
13
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
14
+ import { getOrCreateCoworkingPortalConfig } from 'npm:@simplelayer/graniteer-core/stripeCoworkingPortal';
15
+ import { sendBillingPortalLinkEmail } from 'npm:@simplelayer/graniteer-core/billingPortalLinkEmail';
16
+
17
+ const corsHeaders = {
18
+ 'Access-Control-Allow-Origin': '*',
19
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
20
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
21
+ };
22
+
23
+ interface CallerClaims {
24
+ sub: string;
25
+ email?: string;
26
+ aal?: string;
27
+ }
28
+
29
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
30
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
31
+ function getJwks(supabaseUrl: string) {
32
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
33
+ return jwksCache;
34
+ }
35
+
36
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
37
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
38
+ const token = authHeader.slice(7).trim();
39
+ try {
40
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
41
+ const claims = payload as unknown as CallerClaims;
42
+ if (!claims.sub) return null;
43
+ return claims;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ function json(status: number, body: unknown) {
50
+ return new Response(JSON.stringify(body), {
51
+ status,
52
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
53
+ });
54
+ }
55
+
56
+ export async function handle(
57
+ req: Request,
58
+ operator: { operatorName: string; operatorShortName: string; domain: string; supportEmail: string },
59
+ ): Promise<Response> {
60
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
61
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
62
+
63
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
64
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
65
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
66
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
67
+
68
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
69
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
70
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
71
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
72
+ const callerEmail = (caller.email ?? '').toLowerCase();
73
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
74
+
75
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
76
+ auth: { persistSession: false, autoRefreshToken: false },
77
+ });
78
+
79
+ const [ipOk, emailOk] = await Promise.all([
80
+ checkRateLimit(admin, 'admin-mint-billing-portal-ip', clientIp(req), 60, 300),
81
+ checkRateLimit(admin, 'admin-mint-billing-portal-email', callerEmail, 40, 300),
82
+ ]);
83
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
84
+
85
+ const { data: allow, error: allowErr } = await admin
86
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
87
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
88
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
89
+
90
+ let body: { membership_id?: string; send_email?: boolean };
91
+ try {
92
+ body = await req.json();
93
+ } catch {
94
+ return json(400, { ok: false, error: 'invalid_json' });
95
+ }
96
+
97
+ const membershipId = (body.membership_id ?? '').trim();
98
+ if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
99
+ return json(400, { ok: false, error: 'invalid_membership_id' });
100
+ }
101
+ const sendEmail = body.send_email === true;
102
+
103
+ const { data: row, error: rowErr } = await admin
104
+ .from('memberships')
105
+ .select('id,email,customer_name,status,stripe_customer_id')
106
+ .eq('id', membershipId)
107
+ .maybeSingle();
108
+ if (rowErr) return json(500, { ok: false, error: 'lookup_failed' });
109
+ if (!row) return json(404, { ok: false, error: 'not_found' });
110
+ if (!row.stripe_customer_id) return json(400, { ok: false, error: 'no_stripe_customer' });
111
+
112
+ let portalUrl: string;
113
+ try {
114
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
115
+ const cfgId = await getOrCreateCoworkingPortalConfig(stripe, admin, {
116
+ headline: `Manage your ${operator.operatorName} membership`,
117
+ defaultReturnUrl: `https://${operator.domain}/membership`,
118
+ });
119
+ const session = await stripe.billingPortal.sessions.create({
120
+ customer: row.stripe_customer_id as string,
121
+ configuration: cfgId,
122
+ return_url: `https://${operator.domain}/membership`,
123
+ });
124
+ if (!session.url) throw new Error('stripe_session_missing_url');
125
+ portalUrl = session.url;
126
+ } catch (e) {
127
+ const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
128
+ await logOps(admin, 'admin_billing_portal_link_failed',
129
+ { membership_id: membershipId, actor_email: callerEmail, message: detail },
130
+ { severity: 'error' }).catch(() => {});
131
+ return json(502, { ok: false, error: 'portal_unavailable', detail });
132
+ }
133
+
134
+ let emailed = false;
135
+ if (sendEmail) {
136
+ if (!row.email) {
137
+ return json(400, { ok: false, error: 'no_member_email', url: portalUrl });
138
+ }
139
+ const result = await sendBillingPortalLinkEmail(admin, {
140
+ email: row.email as string,
141
+ name: row.customer_name as string | null,
142
+ portalUrl,
143
+ }, {
144
+ name: operator.operatorName,
145
+ shortName: operator.operatorShortName,
146
+ domain: operator.domain,
147
+ supportEmail: operator.supportEmail,
148
+ });
149
+ emailed = result === 'sent';
150
+ if (!emailed) {
151
+ // Link was minted successfully; only the email leg failed. Return it
152
+ // anyway so staff can still copy/send it by hand.
153
+ return json(200, { ok: true, url: portalUrl, emailed: false, email_error: result });
154
+ }
155
+ }
156
+
157
+ await admin.from('membership_admin_actions').insert({
158
+ membership_id: membershipId,
159
+ action: sendEmail ? 'billing_portal_link_emailed' : 'billing_portal_link_minted',
160
+ actor_email: callerEmail,
161
+ reason: sendEmail ? `Emailed to ${row.email ?? 'unknown'}` : 'Link copied by staff',
162
+ idempotency_key: crypto.randomUUID(),
163
+ }).then(({ error }) => {
164
+ if (error) console.warn('[admin-mint-billing-portal-link] audit insert failed', error);
165
+ });
166
+
167
+ return json(200, { ok: true, url: portalUrl, emailed });
168
+ }
@@ -0,0 +1,62 @@
1
+ // Internal ops tool: re-mint the agreement portal URL for an existing
2
+ // signature_documents row. Read-only against the DB; reuses MANAGE_TOKEN_SECRET
3
+ // and the same buildAgreementPortalUrl helper as create-agreement.
4
+
5
+ import { createClient } from 'npm:@supabase/supabase-js@2';
6
+ import { buildAgreementPortalUrl } from 'npm:@simplelayer/graniteer-core/manageToken';
7
+
8
+ const corsHeaders = {
9
+ 'Access-Control-Allow-Origin': '*',
10
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
11
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
12
+ };
13
+
14
+ function json(status: number, body: unknown) {
15
+ return new Response(JSON.stringify(body), {
16
+ status,
17
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
18
+ });
19
+ }
20
+
21
+ export async function handle(req: Request, operator: { domain: string }): Promise<Response> {
22
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
23
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
24
+
25
+ let body: { signature_document_id?: unknown; signer_email?: unknown };
26
+ try {
27
+ body = await req.json();
28
+ } catch {
29
+ return json(400, { ok: false, error: 'invalid_json' });
30
+ }
31
+
32
+ const id = typeof body.signature_document_id === 'string' ? body.signature_document_id.trim() : '';
33
+ const email = typeof body.signer_email === 'string' ? body.signer_email.trim() : '';
34
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return json(400, { ok: false, error: 'invalid_signature_document_id' });
35
+ if (!email) return json(400, { ok: false, error: 'invalid_signer_email' });
36
+
37
+ const admin = createClient(
38
+ Deno.env.get('SUPABASE_URL')!,
39
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
40
+ { auth: { persistSession: false, autoRefreshToken: false } },
41
+ );
42
+
43
+ const { data: row, error } = await admin
44
+ .from('signature_documents')
45
+ .select('id,signer_email')
46
+ .eq('id', id)
47
+ .maybeSingle();
48
+
49
+ if (error) return json(500, { ok: false, error: 'lookup_failed' });
50
+ if (!row) return json(404, { ok: false, error: 'not_found' });
51
+
52
+ const rowEmail = String(row.signer_email ?? '').toLowerCase();
53
+ if (!rowEmail || rowEmail !== email.toLowerCase()) {
54
+ return json(404, { ok: false, error: 'not_found' });
55
+ }
56
+
57
+ const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
58
+ if (!secret) return json(500, { ok: false, error: 'not_configured' });
59
+
60
+ const url = await buildAgreementPortalUrl(`https://${operator.domain}`, String(row.id), rowEmail, secret);
61
+ return json(200, { ok: true, url });
62
+ }
@@ -1,128 +1,128 @@
1
- // Server-to-server room photo upload. Same effect as the admin UI's upload in
2
- // src/pages/admin/AdminRoomEdit.tsx (handleUpload): pushes the file into the
3
- // "room-photos" Storage bucket and appends { path, alt, url } onto that room's
4
- // rooms.images jsonb array. Auth here is a single shared-secret header
5
- // (x-upload-key) instead of a logged-in browser session, since this is meant
6
- // to be called machine-to-machine over plain HTTPS.
7
- import { createClient } from 'npm:@supabase/supabase-js@2';
8
-
9
- const corsHeaders = {
10
- 'Access-Control-Allow-Origin': '*',
11
- 'Access-Control-Allow-Headers': 'content-type,x-upload-key',
12
- 'Access-Control-Allow-Methods': 'POST,OPTIONS',
13
- };
14
-
15
- function json(status: number, body: unknown) {
16
- return new Response(JSON.stringify(body), {
17
- status,
18
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
19
- });
20
- }
21
-
22
- // Constant-time-ish string compare so a mismatching key doesn't leak timing
23
- // info about how many leading characters matched.
24
- function safeEqual(a: string, b: string): boolean {
25
- if (a.length !== b.length) return false;
26
- let diff = 0;
27
- for (let i = 0; i < a.length; i++) {
28
- diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
29
- }
30
- return diff === 0;
31
- }
32
-
33
- interface UploadBody {
34
- room_id?: unknown;
35
- filename?: unknown;
36
- content_type?: unknown;
37
- image_base64?: unknown;
38
- alt?: unknown;
39
- }
40
-
41
- interface ImageRef {
42
- path: string;
43
- alt: string;
44
- url: string;
45
- }
46
-
47
- export async function handle(req: Request): Promise<Response> {
48
- try {
49
- if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders });
50
- if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
51
-
52
- const expectedKey = Deno.env.get('PHOTO_UPLOAD_KEY');
53
- const providedKey = req.headers.get('x-upload-key');
54
- if (!expectedKey || !providedKey || !safeEqual(providedKey, expectedKey)) {
55
- return json(401, { error: 'unauthorized' });
56
- }
57
-
58
- let body: UploadBody;
59
- try {
60
- body = await req.json();
61
- } catch {
62
- return json(400, { error: 'invalid_json' });
63
- }
64
-
65
- const roomId = typeof body.room_id === 'string' ? body.room_id.trim() : '';
66
- if (!roomId) return json(400, { error: 'invalid_field', field: 'room_id' });
67
-
68
- const filename = typeof body.filename === 'string' ? body.filename.trim() : '';
69
- if (!filename) return json(400, { error: 'invalid_field', field: 'filename' });
70
-
71
- const contentType = typeof body.content_type === 'string' ? body.content_type.trim() : '';
72
- if (!contentType) return json(400, { error: 'invalid_field', field: 'content_type' });
73
-
74
- const imageBase64 = typeof body.image_base64 === 'string' ? body.image_base64 : '';
75
- if (!imageBase64) return json(400, { error: 'invalid_field', field: 'image_base64' });
76
-
77
- const alt = typeof body.alt === 'string' ? body.alt : '';
78
-
79
- let bytes: Uint8Array;
80
- try {
81
- bytes = Uint8Array.from(atob(imageBase64.replace(/\s/g, '')), (c) => c.charCodeAt(0));
82
- } catch {
83
- return json(400, { error: 'invalid_field', field: 'image_base64' });
84
- }
85
-
86
- const admin = createClient(
87
- Deno.env.get('SUPABASE_URL')!,
88
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
89
- { auth: { persistSession: false, autoRefreshToken: false } },
90
- );
91
-
92
- // Same sanitize + path convention as AdminRoomEdit.tsx's handleUpload, so
93
- // files from both paths coexist cleanly in the same bucket/folder.
94
- const safeFilename = filename.replace(/[^a-zA-Z0-9._-]/g, '_');
95
- const path = `${roomId}/${Date.now()}-${safeFilename}`;
96
-
97
- const { error: upErr } = await admin.storage
98
- .from('room-photos')
99
- .upload(path, bytes, { upsert: false, contentType });
100
- if (upErr) return json(500, { error: upErr.message });
101
-
102
- const url = admin.storage.from('room-photos').getPublicUrl(path).data.publicUrl;
103
-
104
- const { data: room, error: roomErr } = await admin
105
- .from('rooms')
106
- .select('images')
107
- .eq('id', roomId)
108
- .single();
109
- if (roomErr) {
110
- if (roomErr.code === 'PGRST116') return json(404, { error: 'room_not_found' });
111
- return json(500, { error: roomErr.message });
112
- }
113
- if (!room) return json(404, { error: 'room_not_found' });
114
-
115
- const existing = Array.isArray((room as { images: unknown }).images)
116
- ? ((room as { images: ImageRef[] }).images)
117
- : [];
118
- const image: ImageRef = { path, alt, url };
119
- const next = [...existing, image];
120
-
121
- const { error: updErr } = await admin.from('rooms').update({ images: next }).eq('id', roomId);
122
- if (updErr) return json(500, { error: updErr.message });
123
-
124
- return json(200, { ok: true, image, images_count: next.length });
125
- } catch (e) {
126
- return json(500, { error: String(e) });
127
- }
128
- }
1
+ // Server-to-server room photo upload. Same effect as the admin UI's upload in
2
+ // src/pages/admin/AdminRoomEdit.tsx (handleUpload): pushes the file into the
3
+ // "room-photos" Storage bucket and appends { path, alt, url } onto that room's
4
+ // rooms.images jsonb array. Auth here is a single shared-secret header
5
+ // (x-upload-key) instead of a logged-in browser session, since this is meant
6
+ // to be called machine-to-machine over plain HTTPS.
7
+ import { createClient } from 'npm:@supabase/supabase-js@2';
8
+
9
+ const corsHeaders = {
10
+ 'Access-Control-Allow-Origin': '*',
11
+ 'Access-Control-Allow-Headers': 'content-type,x-upload-key',
12
+ 'Access-Control-Allow-Methods': 'POST,OPTIONS',
13
+ };
14
+
15
+ function json(status: number, body: unknown) {
16
+ return new Response(JSON.stringify(body), {
17
+ status,
18
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
19
+ });
20
+ }
21
+
22
+ // Constant-time-ish string compare so a mismatching key doesn't leak timing
23
+ // info about how many leading characters matched.
24
+ function safeEqual(a: string, b: string): boolean {
25
+ if (a.length !== b.length) return false;
26
+ let diff = 0;
27
+ for (let i = 0; i < a.length; i++) {
28
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
29
+ }
30
+ return diff === 0;
31
+ }
32
+
33
+ interface UploadBody {
34
+ room_id?: unknown;
35
+ filename?: unknown;
36
+ content_type?: unknown;
37
+ image_base64?: unknown;
38
+ alt?: unknown;
39
+ }
40
+
41
+ interface ImageRef {
42
+ path: string;
43
+ alt: string;
44
+ url: string;
45
+ }
46
+
47
+ export async function handle(req: Request): Promise<Response> {
48
+ try {
49
+ if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders });
50
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
51
+
52
+ const expectedKey = Deno.env.get('PHOTO_UPLOAD_KEY');
53
+ const providedKey = req.headers.get('x-upload-key');
54
+ if (!expectedKey || !providedKey || !safeEqual(providedKey, expectedKey)) {
55
+ return json(401, { error: 'unauthorized' });
56
+ }
57
+
58
+ let body: UploadBody;
59
+ try {
60
+ body = await req.json();
61
+ } catch {
62
+ return json(400, { error: 'invalid_json' });
63
+ }
64
+
65
+ const roomId = typeof body.room_id === 'string' ? body.room_id.trim() : '';
66
+ if (!roomId) return json(400, { error: 'invalid_field', field: 'room_id' });
67
+
68
+ const filename = typeof body.filename === 'string' ? body.filename.trim() : '';
69
+ if (!filename) return json(400, { error: 'invalid_field', field: 'filename' });
70
+
71
+ const contentType = typeof body.content_type === 'string' ? body.content_type.trim() : '';
72
+ if (!contentType) return json(400, { error: 'invalid_field', field: 'content_type' });
73
+
74
+ const imageBase64 = typeof body.image_base64 === 'string' ? body.image_base64 : '';
75
+ if (!imageBase64) return json(400, { error: 'invalid_field', field: 'image_base64' });
76
+
77
+ const alt = typeof body.alt === 'string' ? body.alt : '';
78
+
79
+ let bytes: Uint8Array;
80
+ try {
81
+ bytes = Uint8Array.from(atob(imageBase64.replace(/\s/g, '')), (c) => c.charCodeAt(0));
82
+ } catch {
83
+ return json(400, { error: 'invalid_field', field: 'image_base64' });
84
+ }
85
+
86
+ const admin = createClient(
87
+ Deno.env.get('SUPABASE_URL')!,
88
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
89
+ { auth: { persistSession: false, autoRefreshToken: false } },
90
+ );
91
+
92
+ // Same sanitize + path convention as AdminRoomEdit.tsx's handleUpload, so
93
+ // files from both paths coexist cleanly in the same bucket/folder.
94
+ const safeFilename = filename.replace(/[^a-zA-Z0-9._-]/g, '_');
95
+ const path = `${roomId}/${Date.now()}-${safeFilename}`;
96
+
97
+ const { error: upErr } = await admin.storage
98
+ .from('room-photos')
99
+ .upload(path, bytes, { upsert: false, contentType });
100
+ if (upErr) return json(500, { error: upErr.message });
101
+
102
+ const url = admin.storage.from('room-photos').getPublicUrl(path).data.publicUrl;
103
+
104
+ const { data: room, error: roomErr } = await admin
105
+ .from('rooms')
106
+ .select('images')
107
+ .eq('id', roomId)
108
+ .single();
109
+ if (roomErr) {
110
+ if (roomErr.code === 'PGRST116') return json(404, { error: 'room_not_found' });
111
+ return json(500, { error: roomErr.message });
112
+ }
113
+ if (!room) return json(404, { error: 'room_not_found' });
114
+
115
+ const existing = Array.isArray((room as { images: unknown }).images)
116
+ ? ((room as { images: ImageRef[] }).images)
117
+ : [];
118
+ const image: ImageRef = { path, alt, url };
119
+ const next = [...existing, image];
120
+
121
+ const { error: updErr } = await admin.from('rooms').update({ images: next }).eq('id', roomId);
122
+ if (updErr) return json(500, { error: updErr.message });
123
+
124
+ return json(200, { ok: true, image, images_count: next.length });
125
+ } catch (e) {
126
+ return json(500, { error: String(e) });
127
+ }
128
+ }