@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,229 +1,229 @@
1
- // supabase/functions/admin-charge-guest-print/index.ts
2
- //
3
- // Staff-facing: charge a guest's saved card once their print job's actual
4
- // usage/cost is known. Same auth shape as admin-issue-day-pass/
5
- // admin-create-booking: JWKS-verified caller JWT, aal2 required,
6
- // admin_users allowlist re-checked server-side, rate limited.
7
- //
8
- // Automatic ezeep-webhook correlation (looking the cost up from print_jobs
9
- // by guest_billing_code, rather than a staff member typing it in) is
10
- // deliberately NOT built in this pass -- see the D5 build report for why.
11
- // This function's `amount_cents` input is staff-entered.
12
- import { createClient } from 'npm:@supabase/supabase-js@2';
13
- import Stripe from 'npm:stripe@17.5.0';
14
- import { z } from 'npm:zod@3.23.8';
15
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
16
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
17
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
18
- import {
19
- chargeGuestPrintJob,
20
- CLAIMABLE_CHARGE_STATUSES,
21
- type GuestPrintDbLike,
22
- type GuestPrintStripeLike,
23
- type SubmissionRow,
24
- } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
25
-
26
- const corsHeaders = {
27
- 'Access-Control-Allow-Origin': '*',
28
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
29
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
30
- };
31
-
32
- interface CallerClaims { sub: string; email?: string; aal?: string }
33
-
34
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
35
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
36
- function getJwks(supabaseUrl: string) {
37
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
38
- return jwksCache;
39
- }
40
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
41
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
42
- const token = authHeader.slice(7).trim();
43
- try {
44
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
45
- const claims = payload as unknown as CallerClaims;
46
- if (!claims.sub) return null;
47
- return claims;
48
- } catch { return null; }
49
- }
50
-
51
- function json(status: number, body: unknown) {
52
- return new Response(JSON.stringify(body), {
53
- status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
54
- });
55
- }
56
-
57
- const Body = z.object({
58
- submission_id: z.string().uuid(),
59
- amount_cents: z.number().int().positive().max(500_00), // sanity ceiling: $500
60
- });
61
-
62
- export async function handle(req: Request): Promise<Response> {
63
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
64
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
65
-
66
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
67
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
68
-
69
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
70
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
71
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
72
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
73
- const callerEmail = (caller.email ?? '').toLowerCase();
74
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
75
-
76
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
77
- auth: { persistSession: false, autoRefreshToken: false },
78
- });
79
-
80
- const [ipOk, emailOk] = await Promise.all([
81
- checkRateLimit(admin, 'admin-charge-guest-print-ip', clientIp(req), 30, 300),
82
- checkRateLimit(admin, 'admin-charge-guest-print-email', callerEmail, 20, 300),
83
- ]);
84
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
85
-
86
- const { data: allow, error: allowErr } = await admin
87
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
88
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
89
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
90
-
91
- let raw: unknown;
92
- try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
93
- const parsed = Body.safeParse(raw);
94
- if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
95
- const { submission_id, amount_cents } = parsed.data;
96
-
97
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
98
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
99
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
100
-
101
- const stripeLike: GuestPrintStripeLike = {
102
- customers: {
103
- search: (p) => stripe.customers.search(p),
104
- list: (p) => stripe.customers.list(p),
105
- create: (p) => stripe.customers.create(p),
106
- },
107
- setupIntents: {
108
- create: (p, o) => stripe.setupIntents.create(p, o),
109
- retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
110
- },
111
- paymentIntents: {
112
- // See guest-print-submit/index.ts for why this cast is needed.
113
- create: (p, o) => stripe.paymentIntents.create(p as never, o),
114
- // B4 (round 2 review): chargeGuestPrintJob must be able to check the
115
- // status of a PRIOR PaymentIntent on this row before ever creating a
116
- // second one -- see that function's own comment.
117
- retrieve: (id) => stripe.paymentIntents.retrieve(id),
118
- },
119
- };
120
-
121
- const dbLike: GuestPrintDbLike = {
122
- async insertPending() { throw new Error('not used by charge'); },
123
- async attachStripeIds() { throw new Error('not used by charge'); },
124
- async markCardSaved() { throw new Error('not used by charge'); },
125
- async markFailed() { throw new Error('not used by charge'); },
126
- async getById(id) {
127
- const { data, error } = await admin
128
- .from('print_guest_submissions')
129
- .select('id,email,status,stripe_customer_id,stripe_setup_intent_id,stripe_payment_method_id,stripe_payment_intent_id,guest_billing_code')
130
- .eq('id', id)
131
- .maybeSingle();
132
- if (error) throw error;
133
- return (data as SubmissionRow) ?? null;
134
- },
135
- async claimForCharge(id) {
136
- // Atomic compare-and-swap: this UPDATE's WHERE clause can only ever
137
- // match the row while it is in CLAIMABLE_CHARGE_STATUSES (currently
138
- // 'card_saved' or 'charge_failed' -- a previously-failed charge
139
- // attempt is a legitimate retry source, D5 adversarial review round
140
- // 1, B3). Imported from guestPrintCapture.ts rather than hardcoded
141
- // here so this filter and the module's own documentation of it can
142
- // never silently drift apart -- see round 2 review's test-vacuity
143
- // finding on the original hardcoded pair. Two concurrent calls for
144
- // the same id: Postgres serializes them on the row lock, and the
145
- // second re-evaluates WHERE against the already-advanced row and
146
- // matches zero rows. That -- not application code -- is the guard.
147
- const { data, error } = await admin
148
- .from('print_guest_submissions')
149
- .update({ status: 'charging' })
150
- .eq('id', id)
151
- .in('status', CLAIMABLE_CHARGE_STATUSES)
152
- .select('id');
153
- if (error) throw error;
154
- return (data ?? []).length === 1;
155
- },
156
- async writebackCharged(id, amountCents, paymentIntentId) {
157
- const { error } = await admin
158
- .from('print_guest_submissions')
159
- .update({
160
- status: 'charged',
161
- charge_cents: amountCents,
162
- stripe_payment_intent_id: paymentIntentId,
163
- charged_at: new Date().toISOString(),
164
- })
165
- .eq('id', id);
166
- if (error) throw error;
167
- },
168
- async writebackChargeFailed(id, reason, paymentIntentId) {
169
- // status = 'charge_failed' (NOT the pre-card 'failed') -- this row IS
170
- // retryable via claimForCharge above. Persist paymentIntentId whenever
171
- // Stripe returned one (even non-succeeded), so a live-but-stuck PI is
172
- // always findable from this row afterward. See D5 adversarial review
173
- // round 1, B2/B3.
174
- const update: Record<string, unknown> = { status: 'charge_failed', last_error: reason.slice(0, 2000) };
175
- if (paymentIntentId) update.stripe_payment_intent_id = paymentIntentId;
176
- const { error } = await admin
177
- .from('print_guest_submissions')
178
- .update(update)
179
- .eq('id', id);
180
- if (error) throw error;
181
- },
182
- };
183
-
184
- try {
185
- const outcome = await chargeGuestPrintJob(stripeLike, dbLike, submission_id, amount_cents);
186
- // Only 'charged' is a real success. In particular, 'not_claimed' comes
187
- // back with outcome.ok === true (it's "not an error" at the decision-core
188
- // level -- see chargeGuestPrintJob's own comment) but MUST NOT be
189
- // reported to staff/UI as HTTP 200/ok:true: that would silently hide a
190
- // concurrent duplicate-charge attempt, or a not-yet-chargeable row, as a
191
- // success with no logOps trail. See D5 adversarial review round 1, B1.
192
- if (outcome.status !== 'charged') {
193
- await logOps(admin, 'admin_charge_guest_print_failed',
194
- {
195
- submission_id, status: outcome.status, detail: outcome.detail, actor: callerEmail,
196
- payment_intent_id: outcome.paymentIntentId,
197
- },
198
- { severity: 'error' });
199
- return json(409, {
200
- ok: false, error: outcome.status, detail: outcome.detail, payment_intent_id: outcome.paymentIntentId,
201
- });
202
- }
203
- // S9: a 'charged' outcome from the already-succeeded-prior-PaymentIntent
204
- // recovery branch can legitimately record a DIFFERENT amount than what
205
- // staff typed here (outcome.amountCents is the TRUE, ledger-recorded
206
- // amount -- see that branch's comment in guestPrintCapture.ts). The
207
- // ledger itself is correct either way, but staff must never be silently
208
- // left believing amount_cents (what they typed) is what was actually
209
- // charged -- log it as its own event even though the charge succeeded.
210
- if (outcome.amountCents !== undefined && outcome.amountCents !== amount_cents) {
211
- await logOps(admin, 'admin_charge_guest_print_amount_mismatch',
212
- {
213
- submission_id, actor: callerEmail, payment_intent_id: outcome.paymentIntentId,
214
- requested_amount_cents: amount_cents, charged_amount_cents: outcome.amountCents,
215
- },
216
- { severity: 'error' });
217
- }
218
- return json(200, {
219
- ok: true, status: outcome.status, payment_intent_id: outcome.paymentIntentId,
220
- amount_cents: outcome.amountCents,
221
- });
222
- } catch (e) {
223
- console.error('admin-charge-guest-print error', e);
224
- await logOps(admin, 'admin_charge_guest_print_error',
225
- { submission_id, message: e instanceof Error ? e.message : String(e), actor: callerEmail },
226
- { severity: 'error' });
227
- return json(500, { ok: false, error: 'unexpected_error' });
228
- }
229
- }
1
+ // supabase/functions/admin-charge-guest-print/index.ts
2
+ //
3
+ // Staff-facing: charge a guest's saved card once their print job's actual
4
+ // usage/cost is known. Same auth shape as admin-issue-day-pass/
5
+ // admin-create-booking: JWKS-verified caller JWT, aal2 required,
6
+ // admin_users allowlist re-checked server-side, rate limited.
7
+ //
8
+ // Automatic ezeep-webhook correlation (looking the cost up from print_jobs
9
+ // by guest_billing_code, rather than a staff member typing it in) is
10
+ // deliberately NOT built in this pass -- see the D5 build report for why.
11
+ // This function's `amount_cents` input is staff-entered.
12
+ import { createClient } from 'npm:@supabase/supabase-js@2';
13
+ import Stripe from 'npm:stripe@17.5.0';
14
+ import { z } from 'npm:zod@3.23.8';
15
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
16
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
17
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
18
+ import {
19
+ chargeGuestPrintJob,
20
+ CLAIMABLE_CHARGE_STATUSES,
21
+ type GuestPrintDbLike,
22
+ type GuestPrintStripeLike,
23
+ type SubmissionRow,
24
+ } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
25
+
26
+ const corsHeaders = {
27
+ 'Access-Control-Allow-Origin': '*',
28
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
29
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
30
+ };
31
+
32
+ interface CallerClaims { sub: string; email?: string; aal?: string }
33
+
34
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
35
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
36
+ function getJwks(supabaseUrl: string) {
37
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
38
+ return jwksCache;
39
+ }
40
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
41
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
42
+ const token = authHeader.slice(7).trim();
43
+ try {
44
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
45
+ const claims = payload as unknown as CallerClaims;
46
+ if (!claims.sub) return null;
47
+ return claims;
48
+ } catch { return null; }
49
+ }
50
+
51
+ function json(status: number, body: unknown) {
52
+ return new Response(JSON.stringify(body), {
53
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
54
+ });
55
+ }
56
+
57
+ const Body = z.object({
58
+ submission_id: z.string().uuid(),
59
+ amount_cents: z.number().int().positive().max(500_00), // sanity ceiling: $500
60
+ });
61
+
62
+ export async function handle(req: Request): Promise<Response> {
63
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
64
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
65
+
66
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
67
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
68
+
69
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
70
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
71
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
72
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
73
+ const callerEmail = (caller.email ?? '').toLowerCase();
74
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
75
+
76
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
77
+ auth: { persistSession: false, autoRefreshToken: false },
78
+ });
79
+
80
+ const [ipOk, emailOk] = await Promise.all([
81
+ checkRateLimit(admin, 'admin-charge-guest-print-ip', clientIp(req), 30, 300),
82
+ checkRateLimit(admin, 'admin-charge-guest-print-email', callerEmail, 20, 300),
83
+ ]);
84
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
85
+
86
+ const { data: allow, error: allowErr } = await admin
87
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
88
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
89
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
90
+
91
+ let raw: unknown;
92
+ try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
93
+ const parsed = Body.safeParse(raw);
94
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
95
+ const { submission_id, amount_cents } = parsed.data;
96
+
97
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
98
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
99
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
100
+
101
+ const stripeLike: GuestPrintStripeLike = {
102
+ customers: {
103
+ search: (p) => stripe.customers.search(p),
104
+ list: (p) => stripe.customers.list(p),
105
+ create: (p) => stripe.customers.create(p),
106
+ },
107
+ setupIntents: {
108
+ create: (p, o) => stripe.setupIntents.create(p, o),
109
+ retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
110
+ },
111
+ paymentIntents: {
112
+ // See guest-print-submit/index.ts for why this cast is needed.
113
+ create: (p, o) => stripe.paymentIntents.create(p as never, o),
114
+ // B4 (round 2 review): chargeGuestPrintJob must be able to check the
115
+ // status of a PRIOR PaymentIntent on this row before ever creating a
116
+ // second one -- see that function's own comment.
117
+ retrieve: (id) => stripe.paymentIntents.retrieve(id),
118
+ },
119
+ };
120
+
121
+ const dbLike: GuestPrintDbLike = {
122
+ async insertPending() { throw new Error('not used by charge'); },
123
+ async attachStripeIds() { throw new Error('not used by charge'); },
124
+ async markCardSaved() { throw new Error('not used by charge'); },
125
+ async markFailed() { throw new Error('not used by charge'); },
126
+ async getById(id) {
127
+ const { data, error } = await admin
128
+ .from('print_guest_submissions')
129
+ .select('id,email,status,stripe_customer_id,stripe_setup_intent_id,stripe_payment_method_id,stripe_payment_intent_id,guest_billing_code')
130
+ .eq('id', id)
131
+ .maybeSingle();
132
+ if (error) throw error;
133
+ return (data as SubmissionRow) ?? null;
134
+ },
135
+ async claimForCharge(id) {
136
+ // Atomic compare-and-swap: this UPDATE's WHERE clause can only ever
137
+ // match the row while it is in CLAIMABLE_CHARGE_STATUSES (currently
138
+ // 'card_saved' or 'charge_failed' -- a previously-failed charge
139
+ // attempt is a legitimate retry source, D5 adversarial review round
140
+ // 1, B3). Imported from guestPrintCapture.ts rather than hardcoded
141
+ // here so this filter and the module's own documentation of it can
142
+ // never silently drift apart -- see round 2 review's test-vacuity
143
+ // finding on the original hardcoded pair. Two concurrent calls for
144
+ // the same id: Postgres serializes them on the row lock, and the
145
+ // second re-evaluates WHERE against the already-advanced row and
146
+ // matches zero rows. That -- not application code -- is the guard.
147
+ const { data, error } = await admin
148
+ .from('print_guest_submissions')
149
+ .update({ status: 'charging' })
150
+ .eq('id', id)
151
+ .in('status', CLAIMABLE_CHARGE_STATUSES)
152
+ .select('id');
153
+ if (error) throw error;
154
+ return (data ?? []).length === 1;
155
+ },
156
+ async writebackCharged(id, amountCents, paymentIntentId) {
157
+ const { error } = await admin
158
+ .from('print_guest_submissions')
159
+ .update({
160
+ status: 'charged',
161
+ charge_cents: amountCents,
162
+ stripe_payment_intent_id: paymentIntentId,
163
+ charged_at: new Date().toISOString(),
164
+ })
165
+ .eq('id', id);
166
+ if (error) throw error;
167
+ },
168
+ async writebackChargeFailed(id, reason, paymentIntentId) {
169
+ // status = 'charge_failed' (NOT the pre-card 'failed') -- this row IS
170
+ // retryable via claimForCharge above. Persist paymentIntentId whenever
171
+ // Stripe returned one (even non-succeeded), so a live-but-stuck PI is
172
+ // always findable from this row afterward. See D5 adversarial review
173
+ // round 1, B2/B3.
174
+ const update: Record<string, unknown> = { status: 'charge_failed', last_error: reason.slice(0, 2000) };
175
+ if (paymentIntentId) update.stripe_payment_intent_id = paymentIntentId;
176
+ const { error } = await admin
177
+ .from('print_guest_submissions')
178
+ .update(update)
179
+ .eq('id', id);
180
+ if (error) throw error;
181
+ },
182
+ };
183
+
184
+ try {
185
+ const outcome = await chargeGuestPrintJob(stripeLike, dbLike, submission_id, amount_cents);
186
+ // Only 'charged' is a real success. In particular, 'not_claimed' comes
187
+ // back with outcome.ok === true (it's "not an error" at the decision-core
188
+ // level -- see chargeGuestPrintJob's own comment) but MUST NOT be
189
+ // reported to staff/UI as HTTP 200/ok:true: that would silently hide a
190
+ // concurrent duplicate-charge attempt, or a not-yet-chargeable row, as a
191
+ // success with no logOps trail. See D5 adversarial review round 1, B1.
192
+ if (outcome.status !== 'charged') {
193
+ await logOps(admin, 'admin_charge_guest_print_failed',
194
+ {
195
+ submission_id, status: outcome.status, detail: outcome.detail, actor: callerEmail,
196
+ payment_intent_id: outcome.paymentIntentId,
197
+ },
198
+ { severity: 'error' });
199
+ return json(409, {
200
+ ok: false, error: outcome.status, detail: outcome.detail, payment_intent_id: outcome.paymentIntentId,
201
+ });
202
+ }
203
+ // S9: a 'charged' outcome from the already-succeeded-prior-PaymentIntent
204
+ // recovery branch can legitimately record a DIFFERENT amount than what
205
+ // staff typed here (outcome.amountCents is the TRUE, ledger-recorded
206
+ // amount -- see that branch's comment in guestPrintCapture.ts). The
207
+ // ledger itself is correct either way, but staff must never be silently
208
+ // left believing amount_cents (what they typed) is what was actually
209
+ // charged -- log it as its own event even though the charge succeeded.
210
+ if (outcome.amountCents !== undefined && outcome.amountCents !== amount_cents) {
211
+ await logOps(admin, 'admin_charge_guest_print_amount_mismatch',
212
+ {
213
+ submission_id, actor: callerEmail, payment_intent_id: outcome.paymentIntentId,
214
+ requested_amount_cents: amount_cents, charged_amount_cents: outcome.amountCents,
215
+ },
216
+ { severity: 'error' });
217
+ }
218
+ return json(200, {
219
+ ok: true, status: outcome.status, payment_intent_id: outcome.paymentIntentId,
220
+ amount_cents: outcome.amountCents,
221
+ });
222
+ } catch (e) {
223
+ console.error('admin-charge-guest-print error', e);
224
+ await logOps(admin, 'admin_charge_guest_print_error',
225
+ { submission_id, message: e instanceof Error ? e.message : String(e), actor: callerEmail },
226
+ { severity: 'error' });
227
+ return json(500, { ok: false, error: 'unexpected_error' });
228
+ }
229
+ }