@simplelayer/graniteer-core 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -1,128 +1,128 @@
1
- // Guest-facing: called by the frontend right after Stripe.js confirms the
2
- // SetupIntent client-side (confirmCardSetup). We never trust that client
3
- // report on its own -- see the ownership check below and
4
- // confirmGuestPrintSetup's own re-retrieve-from-Stripe discipline.
5
- import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
6
- import { createClient } from 'npm:@supabase/supabase-js@2';
7
- import Stripe from 'npm:stripe@17.5.0';
8
- import { z } from 'npm:zod@3.23.8';
9
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
10
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
11
- import {
12
- confirmGuestPrintSetup,
13
- type GuestPrintDbLike,
14
- type GuestPrintStripeLike,
15
- } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
16
-
17
- const Body = z.object({
18
- submission_id: z.string().uuid(),
19
- setup_intent_id: z.string().min(1).max(200),
20
- });
21
-
22
- function json(status: number, body: unknown) {
23
- return new Response(JSON.stringify(body), {
24
- status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
25
- });
26
- }
27
-
28
- export async function handle(req: Request): Promise<Response> {
29
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
30
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
31
-
32
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
33
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
34
- const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
35
- auth: { persistSession: false, autoRefreshToken: false },
36
- });
37
-
38
- let raw: unknown;
39
- try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
40
- const parsed = Body.safeParse(raw);
41
- if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
42
- const { submission_id, setup_intent_id } = parsed.data;
43
-
44
- const ip = clientIp(req);
45
- const ipOk = await checkRateLimit(supabase, 'guest-print-setup-confirm-ip', ip, 30, 600);
46
- if (!ipOk) return json(429, { ok: false, error: 'rate_limited' });
47
-
48
- // Ownership check BEFORE touching Stripe: the submission_id + setup_intent_id
49
- // pair must belong to the same row, or a guessed submission_id + an
50
- // attacker's own real setup_intent_id could mark someone else's row
51
- // 'card_saved' with the attacker's payment method. This check plus
52
- // confirmGuestPrintSetup's own re-retrieve-from-Stripe are BOTH required --
53
- // this proves the pair is bound to one row; that proves what Stripe itself
54
- // says about it.
55
- const { data: row, error: rowErr } = await supabase
56
- .from('print_guest_submissions')
57
- .select('id,status,stripe_setup_intent_id')
58
- .eq('id', submission_id)
59
- .maybeSingle();
60
- if (rowErr) return json(500, { ok: false, error: 'lookup_failed' });
61
- if (!row || row.stripe_setup_intent_id !== setup_intent_id) {
62
- return json(404, { ok: false, error: 'not_found' });
63
- }
64
- if (row.status === 'card_saved') {
65
- // Idempotent: the frontend can safely call this twice.
66
- return json(200, { ok: true, status: 'card_saved' });
67
- }
68
- if (row.status !== 'pending_card') {
69
- return json(409, { ok: false, error: 'not_confirmable', status: row.status });
70
- }
71
-
72
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
73
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
74
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
75
-
76
- const stripeLike: GuestPrintStripeLike = {
77
- customers: {
78
- search: (p) => stripe.customers.search(p),
79
- list: (p) => stripe.customers.list(p),
80
- create: (p) => stripe.customers.create(p),
81
- },
82
- setupIntents: {
83
- create: (p, o) => stripe.setupIntents.create(p, o),
84
- retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
85
- },
86
- paymentIntents: {
87
- // See guest-print-submit/index.ts for why this cast is needed.
88
- create: (p, o) => stripe.paymentIntents.create(p as never, o),
89
- retrieve: (id) => stripe.paymentIntents.retrieve(id),
90
- },
91
- };
92
-
93
- const dbLike: GuestPrintDbLike = {
94
- async insertPending() { throw new Error('not used by setup-confirm'); },
95
- async attachStripeIds() { throw new Error('not used by setup-confirm'); },
96
- async markCardSaved(id, paymentMethodId) {
97
- const { error } = await supabase
98
- .from('print_guest_submissions')
99
- .update({ status: 'card_saved', stripe_payment_method_id: paymentMethodId })
100
- .eq('id', id);
101
- if (error) throw error;
102
- },
103
- async markFailed(id, reason) {
104
- const { error } = await supabase
105
- .from('print_guest_submissions')
106
- .update({ last_error: reason.slice(0, 2000) })
107
- .eq('id', id);
108
- if (error) console.error('[guest-print-setup-confirm] markFailed write failed', error);
109
- },
110
- async getById() { throw new Error('not used by setup-confirm'); },
111
- async claimForCharge() { throw new Error('not used by setup-confirm'); },
112
- async writebackCharged() { throw new Error('not used by setup-confirm'); },
113
- async writebackChargeFailed() { throw new Error('not used by setup-confirm'); },
114
- };
115
-
116
- try {
117
- const outcome = await confirmGuestPrintSetup(stripeLike, dbLike, submission_id, setup_intent_id);
118
- if (!outcome.ok) {
119
- return json(409, { ok: false, error: outcome.detail ?? 'not_succeeded', status: outcome.status });
120
- }
121
- return json(200, { ok: true, status: outcome.status });
122
- } catch (e) {
123
- console.error('guest-print-setup-confirm error', e);
124
- await logOps(supabase, 'guest_print_setup_confirm_error',
125
- { submission_id, message: e instanceof Error ? e.message : String(e) }, { severity: 'error' });
126
- return json(500, { ok: false, error: 'unexpected_error' });
127
- }
128
- }
1
+ // Guest-facing: called by the frontend right after Stripe.js confirms the
2
+ // SetupIntent client-side (confirmCardSetup). We never trust that client
3
+ // report on its own -- see the ownership check below and
4
+ // confirmGuestPrintSetup's own re-retrieve-from-Stripe discipline.
5
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
6
+ import { createClient } from 'npm:@supabase/supabase-js@2';
7
+ import Stripe from 'npm:stripe@17.5.0';
8
+ import { z } from 'npm:zod@3.23.8';
9
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
10
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
11
+ import {
12
+ confirmGuestPrintSetup,
13
+ type GuestPrintDbLike,
14
+ type GuestPrintStripeLike,
15
+ } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
16
+
17
+ const Body = z.object({
18
+ submission_id: z.string().uuid(),
19
+ setup_intent_id: z.string().min(1).max(200),
20
+ });
21
+
22
+ function json(status: number, body: unknown) {
23
+ return new Response(JSON.stringify(body), {
24
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
25
+ });
26
+ }
27
+
28
+ export async function handle(req: Request): Promise<Response> {
29
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
30
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
31
+
32
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
33
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
34
+ const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
35
+ auth: { persistSession: false, autoRefreshToken: false },
36
+ });
37
+
38
+ let raw: unknown;
39
+ try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
40
+ const parsed = Body.safeParse(raw);
41
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
42
+ const { submission_id, setup_intent_id } = parsed.data;
43
+
44
+ const ip = clientIp(req);
45
+ const ipOk = await checkRateLimit(supabase, 'guest-print-setup-confirm-ip', ip, 30, 600);
46
+ if (!ipOk) return json(429, { ok: false, error: 'rate_limited' });
47
+
48
+ // Ownership check BEFORE touching Stripe: the submission_id + setup_intent_id
49
+ // pair must belong to the same row, or a guessed submission_id + an
50
+ // attacker's own real setup_intent_id could mark someone else's row
51
+ // 'card_saved' with the attacker's payment method. This check plus
52
+ // confirmGuestPrintSetup's own re-retrieve-from-Stripe are BOTH required --
53
+ // this proves the pair is bound to one row; that proves what Stripe itself
54
+ // says about it.
55
+ const { data: row, error: rowErr } = await supabase
56
+ .from('print_guest_submissions')
57
+ .select('id,status,stripe_setup_intent_id')
58
+ .eq('id', submission_id)
59
+ .maybeSingle();
60
+ if (rowErr) return json(500, { ok: false, error: 'lookup_failed' });
61
+ if (!row || row.stripe_setup_intent_id !== setup_intent_id) {
62
+ return json(404, { ok: false, error: 'not_found' });
63
+ }
64
+ if (row.status === 'card_saved') {
65
+ // Idempotent: the frontend can safely call this twice.
66
+ return json(200, { ok: true, status: 'card_saved' });
67
+ }
68
+ if (row.status !== 'pending_card') {
69
+ return json(409, { ok: false, error: 'not_confirmable', status: row.status });
70
+ }
71
+
72
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
73
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
74
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
75
+
76
+ const stripeLike: GuestPrintStripeLike = {
77
+ customers: {
78
+ search: (p) => stripe.customers.search(p),
79
+ list: (p) => stripe.customers.list(p),
80
+ create: (p) => stripe.customers.create(p),
81
+ },
82
+ setupIntents: {
83
+ create: (p, o) => stripe.setupIntents.create(p, o),
84
+ retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
85
+ },
86
+ paymentIntents: {
87
+ // See guest-print-submit/index.ts for why this cast is needed.
88
+ create: (p, o) => stripe.paymentIntents.create(p as never, o),
89
+ retrieve: (id) => stripe.paymentIntents.retrieve(id),
90
+ },
91
+ };
92
+
93
+ const dbLike: GuestPrintDbLike = {
94
+ async insertPending() { throw new Error('not used by setup-confirm'); },
95
+ async attachStripeIds() { throw new Error('not used by setup-confirm'); },
96
+ async markCardSaved(id, paymentMethodId) {
97
+ const { error } = await supabase
98
+ .from('print_guest_submissions')
99
+ .update({ status: 'card_saved', stripe_payment_method_id: paymentMethodId })
100
+ .eq('id', id);
101
+ if (error) throw error;
102
+ },
103
+ async markFailed(id, reason) {
104
+ const { error } = await supabase
105
+ .from('print_guest_submissions')
106
+ .update({ last_error: reason.slice(0, 2000) })
107
+ .eq('id', id);
108
+ if (error) console.error('[guest-print-setup-confirm] markFailed write failed', error);
109
+ },
110
+ async getById() { throw new Error('not used by setup-confirm'); },
111
+ async claimForCharge() { throw new Error('not used by setup-confirm'); },
112
+ async writebackCharged() { throw new Error('not used by setup-confirm'); },
113
+ async writebackChargeFailed() { throw new Error('not used by setup-confirm'); },
114
+ };
115
+
116
+ try {
117
+ const outcome = await confirmGuestPrintSetup(stripeLike, dbLike, submission_id, setup_intent_id);
118
+ if (!outcome.ok) {
119
+ return json(409, { ok: false, error: outcome.detail ?? 'not_succeeded', status: outcome.status });
120
+ }
121
+ return json(200, { ok: true, status: outcome.status });
122
+ } catch (e) {
123
+ console.error('guest-print-setup-confirm error', e);
124
+ await logOps(supabase, 'guest_print_setup_confirm_error',
125
+ { submission_id, message: e instanceof Error ? e.message : String(e) }, { severity: 'error' });
126
+ return json(500, { ok: false, error: 'unexpected_error' });
127
+ }
128
+ }
@@ -1,149 +1,149 @@
1
- // Guest-facing: submit a print job and get a Stripe SetupIntent client_secret
2
- // back so the frontend can save a card via Stripe Elements before the job's
3
- // actual cost is known. See _shared/guestPrintCapture.ts for the design.
4
- //
5
- // This is deliberately a THIN wrapper: all decision logic lives in
6
- // guestPrintCapture.ts and is covered by guestPrintCapture.test.ts against a
7
- // mocked Stripe transport. This file only wires the real Supabase/Stripe
8
- // clients and handles HTTP/validation/rate-limiting concerns.
9
- import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
10
- import { createClient } from 'npm:@supabase/supabase-js@2';
11
- import Stripe from 'npm:stripe@17.5.0';
12
- import { z } from 'npm:zod@3.23.8';
13
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
14
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
15
- import {
16
- generateGuestBillingCode,
17
- submitGuestPrintJob,
18
- type GuestPrintDbLike,
19
- type GuestPrintStripeLike,
20
- } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
21
-
22
- const Body = z.object({
23
- email: z.string().trim().email().max(255),
24
- guest_name: z.string().trim().min(1).max(200).optional(),
25
- });
26
-
27
- function json(status: number, body: unknown) {
28
- return new Response(JSON.stringify(body), {
29
- status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
30
- });
31
- }
32
-
33
- export async function handle(req: Request): Promise<Response> {
34
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
35
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
36
-
37
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
38
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
39
- const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
40
- auth: { persistSession: false, autoRefreshToken: false },
41
- });
42
-
43
- let raw: unknown;
44
- try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
45
- const parsed = Body.safeParse(raw);
46
- if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
47
- const emailKey = parsed.data.email.toLowerCase();
48
- const guestName = parsed.data.guest_name?.trim() || null;
49
-
50
- const ip = clientIp(req);
51
- const [ipOk, emailOk] = await Promise.all([
52
- checkRateLimit(supabase, 'guest-print-submit-ip', ip, 20, 600),
53
- checkRateLimit(supabase, 'guest-print-submit-email', emailKey, 10, 600),
54
- ]);
55
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
56
-
57
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
58
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
59
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
60
-
61
- const stripeLike: GuestPrintStripeLike = {
62
- customers: {
63
- search: (p) => stripe.customers.search(p),
64
- list: (p) => stripe.customers.list(p),
65
- create: (p) => stripe.customers.create(p),
66
- },
67
- setupIntents: {
68
- create: (p, o) => stripe.setupIntents.create(p, o),
69
- retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
70
- },
71
- paymentIntents: {
72
- // Cast: GuestPrintStripeLike's params are intentionally structural
73
- // (Record<string, unknown>) so guestPrintCapture.ts stays free of any
74
- // Stripe SDK import; the real SDK's PaymentIntentCreateParams has
75
- // required fields (amount, currency) that a Record<string, unknown>
76
- // erases statically even though every real caller supplies them.
77
- create: (p, o) => stripe.paymentIntents.create(p as never, o),
78
- retrieve: (id) => stripe.paymentIntents.retrieve(id),
79
- },
80
- };
81
-
82
- const dbLike: GuestPrintDbLike = {
83
- async insertPending({ email, guestName, guestBillingCode }) {
84
- const { data, error } = await supabase
85
- .from('print_guest_submissions')
86
- .insert({ email, guest_name: guestName, guest_billing_code: guestBillingCode, status: 'pending_card' })
87
- .select('id')
88
- .single();
89
- if (error) throw error;
90
- return (data as { id: string }).id;
91
- },
92
- async attachStripeIds(id, customerId, setupIntentId) {
93
- const { error } = await supabase
94
- .from('print_guest_submissions')
95
- .update({ stripe_customer_id: customerId, stripe_setup_intent_id: setupIntentId })
96
- .eq('id', id);
97
- if (error) throw error;
98
- },
99
- async markCardSaved() { throw new Error('not used by submit'); },
100
- async markFailed(id, reason) {
101
- const { error } = await supabase
102
- .from('print_guest_submissions')
103
- .update({ status: 'failed', last_error: reason.slice(0, 2000) })
104
- .eq('id', id);
105
- if (error) console.error('[guest-print-submit] markFailed write failed', error);
106
- },
107
- async getById() { throw new Error('not used by submit'); },
108
- async claimForCharge() { throw new Error('not used by submit'); },
109
- async writebackCharged() { throw new Error('not used by submit'); },
110
- async writebackChargeFailed() { throw new Error('not used by submit'); },
111
- };
112
-
113
- // Retry loop for the (very unlikely) billing-code collision -- the unique
114
- // index is the real guard; this just avoids surfacing a 500 to a guest on
115
- // the rare hit.
116
- let outcome;
117
- for (let attempt = 0; attempt < 5; attempt++) {
118
- const guestBillingCode = generateGuestBillingCode(crypto.getRandomValues(new Uint8Array(16)));
119
- try {
120
- outcome = await submitGuestPrintJob(stripeLike, dbLike, {
121
- email: emailKey, guestName, guestBillingCode,
122
- });
123
- break;
124
- } catch (e) {
125
- const code = (e as { code?: string })?.code;
126
- if (code === '23505' && attempt < 4) continue; // billing_code collision -- retry with a new code
127
- console.error('guest-print-submit error', e);
128
- await logOps(supabase, 'guest_print_submit_error',
129
- { message: e instanceof Error ? e.message : String(e) }, { severity: 'error' });
130
- return json(500, { ok: false, error: 'unexpected_error' });
131
- }
132
- }
133
- if (!outcome) {
134
- return json(500, { ok: false, error: 'billing_code_collision_exhausted' });
135
- }
136
-
137
- if (!outcome.ok) {
138
- await logOps(supabase, 'guest_print_submit_stripe_failed',
139
- { submission_id: outcome.submissionId, detail: outcome.detail }, { severity: 'error' });
140
- return json(502, { ok: false, error: 'setup_failed', submission_id: outcome.submissionId });
141
- }
142
-
143
- return json(200, {
144
- ok: true,
145
- submission_id: outcome.submissionId,
146
- client_secret: outcome.clientSecret,
147
- guest_billing_code: outcome.guestBillingCode,
148
- });
149
- }
1
+ // Guest-facing: submit a print job and get a Stripe SetupIntent client_secret
2
+ // back so the frontend can save a card via Stripe Elements before the job's
3
+ // actual cost is known. See _shared/guestPrintCapture.ts for the design.
4
+ //
5
+ // This is deliberately a THIN wrapper: all decision logic lives in
6
+ // guestPrintCapture.ts and is covered by guestPrintCapture.test.ts against a
7
+ // mocked Stripe transport. This file only wires the real Supabase/Stripe
8
+ // clients and handles HTTP/validation/rate-limiting concerns.
9
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
10
+ import { createClient } from 'npm:@supabase/supabase-js@2';
11
+ import Stripe from 'npm:stripe@17.5.0';
12
+ import { z } from 'npm:zod@3.23.8';
13
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
14
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
15
+ import {
16
+ generateGuestBillingCode,
17
+ submitGuestPrintJob,
18
+ type GuestPrintDbLike,
19
+ type GuestPrintStripeLike,
20
+ } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
21
+
22
+ const Body = z.object({
23
+ email: z.string().trim().email().max(255),
24
+ guest_name: z.string().trim().min(1).max(200).optional(),
25
+ });
26
+
27
+ function json(status: number, body: unknown) {
28
+ return new Response(JSON.stringify(body), {
29
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
30
+ });
31
+ }
32
+
33
+ export async function handle(req: Request): Promise<Response> {
34
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
35
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
36
+
37
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
38
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
39
+ const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
40
+ auth: { persistSession: false, autoRefreshToken: false },
41
+ });
42
+
43
+ let raw: unknown;
44
+ try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
45
+ const parsed = Body.safeParse(raw);
46
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
47
+ const emailKey = parsed.data.email.toLowerCase();
48
+ const guestName = parsed.data.guest_name?.trim() || null;
49
+
50
+ const ip = clientIp(req);
51
+ const [ipOk, emailOk] = await Promise.all([
52
+ checkRateLimit(supabase, 'guest-print-submit-ip', ip, 20, 600),
53
+ checkRateLimit(supabase, 'guest-print-submit-email', emailKey, 10, 600),
54
+ ]);
55
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
56
+
57
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
58
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
59
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
60
+
61
+ const stripeLike: GuestPrintStripeLike = {
62
+ customers: {
63
+ search: (p) => stripe.customers.search(p),
64
+ list: (p) => stripe.customers.list(p),
65
+ create: (p) => stripe.customers.create(p),
66
+ },
67
+ setupIntents: {
68
+ create: (p, o) => stripe.setupIntents.create(p, o),
69
+ retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
70
+ },
71
+ paymentIntents: {
72
+ // Cast: GuestPrintStripeLike's params are intentionally structural
73
+ // (Record<string, unknown>) so guestPrintCapture.ts stays free of any
74
+ // Stripe SDK import; the real SDK's PaymentIntentCreateParams has
75
+ // required fields (amount, currency) that a Record<string, unknown>
76
+ // erases statically even though every real caller supplies them.
77
+ create: (p, o) => stripe.paymentIntents.create(p as never, o),
78
+ retrieve: (id) => stripe.paymentIntents.retrieve(id),
79
+ },
80
+ };
81
+
82
+ const dbLike: GuestPrintDbLike = {
83
+ async insertPending({ email, guestName, guestBillingCode }) {
84
+ const { data, error } = await supabase
85
+ .from('print_guest_submissions')
86
+ .insert({ email, guest_name: guestName, guest_billing_code: guestBillingCode, status: 'pending_card' })
87
+ .select('id')
88
+ .single();
89
+ if (error) throw error;
90
+ return (data as { id: string }).id;
91
+ },
92
+ async attachStripeIds(id, customerId, setupIntentId) {
93
+ const { error } = await supabase
94
+ .from('print_guest_submissions')
95
+ .update({ stripe_customer_id: customerId, stripe_setup_intent_id: setupIntentId })
96
+ .eq('id', id);
97
+ if (error) throw error;
98
+ },
99
+ async markCardSaved() { throw new Error('not used by submit'); },
100
+ async markFailed(id, reason) {
101
+ const { error } = await supabase
102
+ .from('print_guest_submissions')
103
+ .update({ status: 'failed', last_error: reason.slice(0, 2000) })
104
+ .eq('id', id);
105
+ if (error) console.error('[guest-print-submit] markFailed write failed', error);
106
+ },
107
+ async getById() { throw new Error('not used by submit'); },
108
+ async claimForCharge() { throw new Error('not used by submit'); },
109
+ async writebackCharged() { throw new Error('not used by submit'); },
110
+ async writebackChargeFailed() { throw new Error('not used by submit'); },
111
+ };
112
+
113
+ // Retry loop for the (very unlikely) billing-code collision -- the unique
114
+ // index is the real guard; this just avoids surfacing a 500 to a guest on
115
+ // the rare hit.
116
+ let outcome;
117
+ for (let attempt = 0; attempt < 5; attempt++) {
118
+ const guestBillingCode = generateGuestBillingCode(crypto.getRandomValues(new Uint8Array(16)));
119
+ try {
120
+ outcome = await submitGuestPrintJob(stripeLike, dbLike, {
121
+ email: emailKey, guestName, guestBillingCode,
122
+ });
123
+ break;
124
+ } catch (e) {
125
+ const code = (e as { code?: string })?.code;
126
+ if (code === '23505' && attempt < 4) continue; // billing_code collision -- retry with a new code
127
+ console.error('guest-print-submit error', e);
128
+ await logOps(supabase, 'guest_print_submit_error',
129
+ { message: e instanceof Error ? e.message : String(e) }, { severity: 'error' });
130
+ return json(500, { ok: false, error: 'unexpected_error' });
131
+ }
132
+ }
133
+ if (!outcome) {
134
+ return json(500, { ok: false, error: 'billing_code_collision_exhausted' });
135
+ }
136
+
137
+ if (!outcome.ok) {
138
+ await logOps(supabase, 'guest_print_submit_stripe_failed',
139
+ { submission_id: outcome.submissionId, detail: outcome.detail }, { severity: 'error' });
140
+ return json(502, { ok: false, error: 'setup_failed', submission_id: outcome.submissionId });
141
+ }
142
+
143
+ return json(200, {
144
+ ok: true,
145
+ submission_id: outcome.submissionId,
146
+ client_secret: outcome.clientSecret,
147
+ guest_billing_code: outcome.guestBillingCode,
148
+ });
149
+ }