@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,144 +1,144 @@
1
- import { createClient } from 'npm:@supabase/supabase-js@2';
2
- import Stripe from 'npm:stripe@17.5.0';
3
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
-
6
- const corsHeaders = {
7
- 'Access-Control-Allow-Origin': '*',
8
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
9
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
10
- };
11
-
12
- interface CallerClaims {
13
- sub: string;
14
- email?: string;
15
- aal?: string;
16
- }
17
-
18
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
19
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
20
- function getJwks(supabaseUrl: string) {
21
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
22
- return jwksCache;
23
- }
24
-
25
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
26
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
27
- const token = authHeader.slice(7).trim();
28
- try {
29
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
30
- const claims = payload as unknown as CallerClaims;
31
- if (!claims.sub) return null;
32
- return claims;
33
- } catch {
34
- return null;
35
- }
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
- export async function handle(req: Request): Promise<Response> {
46
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
47
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
48
-
49
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
50
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
51
-
52
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
53
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
54
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
55
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
56
- const callerEmail = (caller.email ?? '').toLowerCase();
57
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
58
-
59
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
60
- auth: { persistSession: false, autoRefreshToken: false },
61
- });
62
-
63
- const [ipOk, emailOk] = await Promise.all([
64
- checkRateLimit(admin, 'admin-undo-membership-cancel-ip', clientIp(req), 30, 300),
65
- checkRateLimit(admin, 'admin-undo-membership-cancel-email', callerEmail, 20, 300),
66
- ]);
67
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
68
-
69
- const { data: allow, error: allowErr } = await admin
70
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
71
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
72
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
73
-
74
- let body: { membership_id?: string; idempotency_key?: string };
75
- try {
76
- body = await req.json();
77
- } catch {
78
- return json(400, { ok: false, error: 'invalid_json' });
79
- }
80
-
81
- const membershipId = (body.membership_id ?? '').trim();
82
- if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
83
- return json(400, { ok: false, error: 'invalid_membership_id' });
84
- }
85
- const idempotencyKey = (body.idempotency_key ?? '').trim();
86
- if (!idempotencyKey || idempotencyKey.length > 100) {
87
- return json(400, { ok: false, error: 'invalid_idempotency_key' });
88
- }
89
-
90
- // 1. Live state re-check.
91
- const { data: membership, error: mErr } = await admin
92
- .from('memberships')
93
- .select('id,status,stripe_subscription_id,cancel_at')
94
- .eq('id', membershipId)
95
- .maybeSingle();
96
- if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
97
- if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
98
- if (!membership.cancel_at) return json(400, { ok: false, error: 'no_scheduled_cancellation' });
99
- const subscriptionId = membership.stripe_subscription_id;
100
- if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
101
-
102
- // 2. Idempotent audit insert.
103
- const { error: insErr } = await admin.from('membership_admin_actions').insert({
104
- membership_id: membershipId,
105
- action: 'cancel_undone',
106
- actor_email: callerEmail,
107
- idempotency_key: idempotencyKey,
108
- effective_at: new Date().toISOString(),
109
- });
110
- if (insErr) {
111
- if ((insErr as { code?: string }).code === '23505') {
112
- return json(200, { ok: true, duplicate: true });
113
- }
114
- return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
115
- }
116
-
117
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
118
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
119
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
120
-
121
- // 3. Clear the scheduled cancellation in Stripe.
122
- let updatedSub: Stripe.Subscription;
123
- try {
124
- updatedSub = await stripe.subscriptions.update(
125
- subscriptionId,
126
- { cancel_at: null },
127
- { idempotencyKey },
128
- );
129
- } catch (e) {
130
- const msg = e instanceof Error ? e.message : String(e);
131
- return json(500, { ok: false, error: 'stripe_undo_failed', detail: msg });
132
- }
133
-
134
- // 4. Authoritative membership write.
135
- const { error: updErr } = await admin
136
- .from('memberships')
137
- .update({ status: updatedSub.status, cancel_at: null })
138
- .eq('id', membershipId);
139
- if (updErr) {
140
- return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
141
- }
142
-
143
- return json(200, { ok: true, status: updatedSub.status });
144
- }
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import Stripe from 'npm:stripe@17.5.0';
3
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
+
6
+ const corsHeaders = {
7
+ 'Access-Control-Allow-Origin': '*',
8
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
9
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
10
+ };
11
+
12
+ interface CallerClaims {
13
+ sub: string;
14
+ email?: string;
15
+ aal?: string;
16
+ }
17
+
18
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
19
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
20
+ function getJwks(supabaseUrl: string) {
21
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
22
+ return jwksCache;
23
+ }
24
+
25
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
26
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
27
+ const token = authHeader.slice(7).trim();
28
+ try {
29
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
30
+ const claims = payload as unknown as CallerClaims;
31
+ if (!claims.sub) return null;
32
+ return claims;
33
+ } catch {
34
+ return null;
35
+ }
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
+ export async function handle(req: Request): Promise<Response> {
46
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
47
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
48
+
49
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
50
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
51
+
52
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
53
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
54
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
55
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
56
+ const callerEmail = (caller.email ?? '').toLowerCase();
57
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
58
+
59
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
60
+ auth: { persistSession: false, autoRefreshToken: false },
61
+ });
62
+
63
+ const [ipOk, emailOk] = await Promise.all([
64
+ checkRateLimit(admin, 'admin-undo-membership-cancel-ip', clientIp(req), 30, 300),
65
+ checkRateLimit(admin, 'admin-undo-membership-cancel-email', callerEmail, 20, 300),
66
+ ]);
67
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
68
+
69
+ const { data: allow, error: allowErr } = await admin
70
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
71
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
72
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
73
+
74
+ let body: { membership_id?: string; idempotency_key?: string };
75
+ try {
76
+ body = await req.json();
77
+ } catch {
78
+ return json(400, { ok: false, error: 'invalid_json' });
79
+ }
80
+
81
+ const membershipId = (body.membership_id ?? '').trim();
82
+ if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
83
+ return json(400, { ok: false, error: 'invalid_membership_id' });
84
+ }
85
+ const idempotencyKey = (body.idempotency_key ?? '').trim();
86
+ if (!idempotencyKey || idempotencyKey.length > 100) {
87
+ return json(400, { ok: false, error: 'invalid_idempotency_key' });
88
+ }
89
+
90
+ // 1. Live state re-check.
91
+ const { data: membership, error: mErr } = await admin
92
+ .from('memberships')
93
+ .select('id,status,stripe_subscription_id,cancel_at')
94
+ .eq('id', membershipId)
95
+ .maybeSingle();
96
+ if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
97
+ if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
98
+ if (!membership.cancel_at) return json(400, { ok: false, error: 'no_scheduled_cancellation' });
99
+ const subscriptionId = membership.stripe_subscription_id;
100
+ if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
101
+
102
+ // 2. Idempotent audit insert.
103
+ const { error: insErr } = await admin.from('membership_admin_actions').insert({
104
+ membership_id: membershipId,
105
+ action: 'cancel_undone',
106
+ actor_email: callerEmail,
107
+ idempotency_key: idempotencyKey,
108
+ effective_at: new Date().toISOString(),
109
+ });
110
+ if (insErr) {
111
+ if ((insErr as { code?: string }).code === '23505') {
112
+ return json(200, { ok: true, duplicate: true });
113
+ }
114
+ return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
115
+ }
116
+
117
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
118
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
119
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
120
+
121
+ // 3. Clear the scheduled cancellation in Stripe.
122
+ let updatedSub: Stripe.Subscription;
123
+ try {
124
+ updatedSub = await stripe.subscriptions.update(
125
+ subscriptionId,
126
+ { cancel_at: null },
127
+ { idempotencyKey },
128
+ );
129
+ } catch (e) {
130
+ const msg = e instanceof Error ? e.message : String(e);
131
+ return json(500, { ok: false, error: 'stripe_undo_failed', detail: msg });
132
+ }
133
+
134
+ // 4. Authoritative membership write.
135
+ const { error: updErr } = await admin
136
+ .from('memberships')
137
+ .update({ status: updatedSub.status, cancel_at: null })
138
+ .eq('id', membershipId);
139
+ if (updErr) {
140
+ return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
141
+ }
142
+
143
+ return json(200, { ok: true, status: updatedSub.status });
144
+ }
@@ -1,141 +1,141 @@
1
- // Member wall photo -- the ONLY write path (and the only way to mint a
2
- // signed download URL) for the Wall Photos admin console. Auth mirrors
3
- // admin-door-write exactly (JWKS verify -> aal2 -> admin_users allowlist
4
- // re-check server-side -> rate limit), per member-wall-photo-plan-v1.md §3.6.
5
- // Every mutation lands an ops_events audit row via the shared logOps helper,
6
- // same as every other admin-*-write function in this codebase.
7
-
8
- import { createClient } from 'npm:@supabase/supabase-js@2';
9
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
10
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
11
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
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
- interface CallerClaims { sub: string; email?: string; aal?: string }
20
-
21
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
22
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
23
- function getJwks(supabaseUrl: string) {
24
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
25
- return jwksCache;
26
- }
27
-
28
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
29
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
30
- try {
31
- const { payload } = await jwtVerify(authHeader.slice(7).trim(), getJwks(supabaseUrl));
32
- const claims = payload as unknown as CallerClaims;
33
- return claims.sub ? claims : null;
34
- } catch {
35
- return null;
36
- }
37
- }
38
-
39
- function json(status: number, body: unknown) {
40
- return new Response(JSON.stringify(body), {
41
- status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
42
- });
43
- }
44
-
45
- const UUID = /^[0-9a-f-]{36}$/i;
46
- const SIGNED_URL_TTL_SECONDS = 300; // 5 minutes, per plan §3.6
47
-
48
- export async function handle(req: Request): Promise<Response> {
49
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
51
-
52
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
53
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
54
-
55
- const caller = await verifyCaller(req.headers.get('Authorization') ?? req.headers.get('authorization'), SUPABASE_URL);
56
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
57
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
58
- const actorEmail = (caller.email ?? '').toLowerCase();
59
- if (!actorEmail) return json(403, { ok: false, error: 'no_email' });
60
-
61
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
62
- auth: { persistSession: false, autoRefreshToken: false },
63
- });
64
-
65
- const [ipOk, emailOk] = await Promise.all([
66
- checkRateLimit(admin, 'admin-wall-photo-write-ip', clientIp(req), 120, 300),
67
- checkRateLimit(admin, 'admin-wall-photo-write-email', actorEmail, 80, 300),
68
- ]);
69
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
70
-
71
- const { data: allow, error: allowErr } = await admin
72
- .from('admin_users').select('email').eq('email', actorEmail).maybeSingle();
73
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
74
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
75
-
76
- let body: Record<string, unknown>;
77
- try { body = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
78
- const action = String(body.action ?? '');
79
-
80
- const audit = async (detail: Record<string, unknown>) => {
81
- const { error: auditErr } = await admin.from('ops_events').insert({
82
- kind: 'wall_photo_admin_write', severity: 'info', booking_id: null,
83
- detail: { actor_email: actorEmail, action, ...detail },
84
- });
85
- if (auditErr) {
86
- await logOps(
87
- admin,
88
- 'wall_photo_admin_audit_failed',
89
- { intended_action: action, audit_error: auditErr.message, actor_email: actorEmail, ...detail },
90
- { severity: 'error' },
91
- );
92
- }
93
- };
94
-
95
- try {
96
- const id = String(body.id ?? '');
97
- if (!UUID.test(id)) return json(400, { ok: false, error: 'invalid_id' });
98
-
99
- const { data: row, error: rowErr } = await admin
100
- .from('member_wall_photo_queue')
101
- .select('id, auth_user_id, original_object_path, content_type, status')
102
- .eq('id', id)
103
- .maybeSingle();
104
- if (rowErr) return json(500, { ok: false, error: 'read_failed' });
105
- if (!row) return json(404, { ok: false, error: 'not_found' });
106
-
107
- if (action === 'get_signed_url') {
108
- if (!row.original_object_path) return json(400, { ok: false, error: 'no_original_captured' });
109
- const ext = (row.content_type as string | null)?.split('/')[1] ?? 'jpg';
110
- const { data: signed, error: signErr } = await admin.storage
111
- .from('member-photo-originals')
112
- .createSignedUrl(row.original_object_path as string, SIGNED_URL_TTL_SECONDS, {
113
- download: `wall-photo-${row.auth_user_id}.${ext}`,
114
- });
115
- if (signErr || !signed) return json(500, { ok: false, error: signErr?.message ?? 'sign_failed' });
116
- // Read-only -- no audit row. Every write action below still lands one.
117
- return json(200, { ok: true, signed_url: signed.signedUrl, expires_in: SIGNED_URL_TTL_SECONDS });
118
- }
119
-
120
- if (action === 'mark_printed' || action === 'mark_skipped') {
121
- const nextStatus = action === 'mark_printed' ? 'printed' : 'skipped';
122
- const patch: Record<string, unknown> =
123
- action === 'mark_printed'
124
- ? { status: 'printed', printed_at: new Date().toISOString(), printed_by: actorEmail }
125
- : { status: 'skipped', printed_at: null, printed_by: null };
126
- const { data: after, error } = await admin
127
- .from('member_wall_photo_queue')
128
- .update(patch)
129
- .eq('id', id)
130
- .select('id, status')
131
- .single();
132
- if (error) return json(400, { ok: false, error: error.message });
133
- await audit({ queue_id: id, auth_user_id: row.auth_user_id, from_status: row.status, to_status: nextStatus });
134
- return json(200, { ok: true, row: after });
135
- }
136
-
137
- return json(400, { ok: false, error: 'unknown_action' });
138
- } catch (e) {
139
- return json(500, { ok: false, error: String(e) });
140
- }
141
- }
1
+ // Member wall photo -- the ONLY write path (and the only way to mint a
2
+ // signed download URL) for the Wall Photos admin console. Auth mirrors
3
+ // admin-door-write exactly (JWKS verify -> aal2 -> admin_users allowlist
4
+ // re-check server-side -> rate limit), per member-wall-photo-plan-v1.md §3.6.
5
+ // Every mutation lands an ops_events audit row via the shared logOps helper,
6
+ // same as every other admin-*-write function in this codebase.
7
+
8
+ import { createClient } from 'npm:@supabase/supabase-js@2';
9
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
10
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
11
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
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
+ interface CallerClaims { sub: string; email?: string; aal?: string }
20
+
21
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
22
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
23
+ function getJwks(supabaseUrl: string) {
24
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
25
+ return jwksCache;
26
+ }
27
+
28
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
29
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
30
+ try {
31
+ const { payload } = await jwtVerify(authHeader.slice(7).trim(), getJwks(supabaseUrl));
32
+ const claims = payload as unknown as CallerClaims;
33
+ return claims.sub ? claims : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function json(status: number, body: unknown) {
40
+ return new Response(JSON.stringify(body), {
41
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
42
+ });
43
+ }
44
+
45
+ const UUID = /^[0-9a-f-]{36}$/i;
46
+ const SIGNED_URL_TTL_SECONDS = 300; // 5 minutes, per plan §3.6
47
+
48
+ export async function handle(req: Request): Promise<Response> {
49
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
51
+
52
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
53
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
54
+
55
+ const caller = await verifyCaller(req.headers.get('Authorization') ?? req.headers.get('authorization'), SUPABASE_URL);
56
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
57
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
58
+ const actorEmail = (caller.email ?? '').toLowerCase();
59
+ if (!actorEmail) return json(403, { ok: false, error: 'no_email' });
60
+
61
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
62
+ auth: { persistSession: false, autoRefreshToken: false },
63
+ });
64
+
65
+ const [ipOk, emailOk] = await Promise.all([
66
+ checkRateLimit(admin, 'admin-wall-photo-write-ip', clientIp(req), 120, 300),
67
+ checkRateLimit(admin, 'admin-wall-photo-write-email', actorEmail, 80, 300),
68
+ ]);
69
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
70
+
71
+ const { data: allow, error: allowErr } = await admin
72
+ .from('admin_users').select('email').eq('email', actorEmail).maybeSingle();
73
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
74
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
75
+
76
+ let body: Record<string, unknown>;
77
+ try { body = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
78
+ const action = String(body.action ?? '');
79
+
80
+ const audit = async (detail: Record<string, unknown>) => {
81
+ const { error: auditErr } = await admin.from('ops_events').insert({
82
+ kind: 'wall_photo_admin_write', severity: 'info', booking_id: null,
83
+ detail: { actor_email: actorEmail, action, ...detail },
84
+ });
85
+ if (auditErr) {
86
+ await logOps(
87
+ admin,
88
+ 'wall_photo_admin_audit_failed',
89
+ { intended_action: action, audit_error: auditErr.message, actor_email: actorEmail, ...detail },
90
+ { severity: 'error' },
91
+ );
92
+ }
93
+ };
94
+
95
+ try {
96
+ const id = String(body.id ?? '');
97
+ if (!UUID.test(id)) return json(400, { ok: false, error: 'invalid_id' });
98
+
99
+ const { data: row, error: rowErr } = await admin
100
+ .from('member_wall_photo_queue')
101
+ .select('id, auth_user_id, original_object_path, content_type, status')
102
+ .eq('id', id)
103
+ .maybeSingle();
104
+ if (rowErr) return json(500, { ok: false, error: 'read_failed' });
105
+ if (!row) return json(404, { ok: false, error: 'not_found' });
106
+
107
+ if (action === 'get_signed_url') {
108
+ if (!row.original_object_path) return json(400, { ok: false, error: 'no_original_captured' });
109
+ const ext = (row.content_type as string | null)?.split('/')[1] ?? 'jpg';
110
+ const { data: signed, error: signErr } = await admin.storage
111
+ .from('member-photo-originals')
112
+ .createSignedUrl(row.original_object_path as string, SIGNED_URL_TTL_SECONDS, {
113
+ download: `wall-photo-${row.auth_user_id}.${ext}`,
114
+ });
115
+ if (signErr || !signed) return json(500, { ok: false, error: signErr?.message ?? 'sign_failed' });
116
+ // Read-only -- no audit row. Every write action below still lands one.
117
+ return json(200, { ok: true, signed_url: signed.signedUrl, expires_in: SIGNED_URL_TTL_SECONDS });
118
+ }
119
+
120
+ if (action === 'mark_printed' || action === 'mark_skipped') {
121
+ const nextStatus = action === 'mark_printed' ? 'printed' : 'skipped';
122
+ const patch: Record<string, unknown> =
123
+ action === 'mark_printed'
124
+ ? { status: 'printed', printed_at: new Date().toISOString(), printed_by: actorEmail }
125
+ : { status: 'skipped', printed_at: null, printed_by: null };
126
+ const { data: after, error } = await admin
127
+ .from('member_wall_photo_queue')
128
+ .update(patch)
129
+ .eq('id', id)
130
+ .select('id, status')
131
+ .single();
132
+ if (error) return json(400, { ok: false, error: error.message });
133
+ await audit({ queue_id: id, auth_user_id: row.auth_user_id, from_status: row.status, to_status: nextStatus });
134
+ return json(200, { ok: true, row: after });
135
+ }
136
+
137
+ return json(400, { ok: false, error: 'unknown_action' });
138
+ } catch (e) {
139
+ return json(500, { ok: false, error: String(e) });
140
+ }
141
+ }