@simplelayer/graniteer-core 0.0.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 (175) hide show
  1. package/package.json +169 -15
  2. package/src/adminBookingCredit.test.ts +451 -0
  3. package/src/adminBookingCredit.ts +239 -0
  4. package/src/agreementCheckout.ts +250 -0
  5. package/src/agreementPortalEmail.ts +128 -0
  6. package/src/availability.test.ts +25 -0
  7. package/src/availability.ts +201 -0
  8. package/src/billingPortalLinkEmail.ts +117 -0
  9. package/src/bookingAgreementEmail.ts +149 -0
  10. package/src/bookingEffects.ts +388 -0
  11. package/src/bookingHoldReclaim.ts +94 -0
  12. package/src/busClient.ts +268 -0
  13. package/src/busSignature.ts +71 -0
  14. package/src/checkoutCoupon.test.ts +675 -0
  15. package/src/checkoutCoupon.ts +455 -0
  16. package/src/checkoutSessionParams.ts +56 -0
  17. package/src/commonsContract.ts +175 -0
  18. package/src/commonsDeposit.ts +298 -0
  19. package/src/commonsDepositWebhook.ts +237 -0
  20. package/src/conductorAdmin.ts +141 -0
  21. package/src/dayPassConfirmation.ts +230 -0
  22. package/src/dunningEmails.test.ts +263 -0
  23. package/src/dunningEmails.ts +203 -0
  24. package/src/email-templates/brand.ts +93 -0
  25. package/src/email-templates/email-change.tsx +92 -0
  26. package/src/email-templates/invite.tsx +79 -0
  27. package/src/email-templates/magic-link.tsx +59 -0
  28. package/src/email-templates/reauthentication.tsx +60 -0
  29. package/src/email-templates/recovery.tsx +59 -0
  30. package/src/email-templates/signup.tsx +67 -0
  31. package/src/functions/admin-cancel-membership.ts +311 -0
  32. package/src/functions/admin-change-membership-plan.ts +312 -0
  33. package/src/functions/admin-charge-guest-print.ts +229 -0
  34. package/src/functions/admin-correct-booking.ts +333 -0
  35. package/src/functions/admin-create-booking.ts +460 -0
  36. package/src/functions/admin-create-commons-event.ts +244 -0
  37. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  38. package/src/functions/admin-door-write.ts +272 -0
  39. package/src/functions/admin-issue-day-pass.ts +231 -0
  40. package/src/functions/admin-mark-booking-paid.ts +203 -0
  41. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  42. package/src/functions/admin-mint-portal-link.ts +62 -0
  43. package/src/functions/admin-photo-upload.ts +128 -0
  44. package/src/functions/admin-remove-team-member.ts +150 -0
  45. package/src/functions/admin-request-trial.ts +366 -0
  46. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  47. package/src/functions/admin-reset-mfa.ts +138 -0
  48. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  49. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  50. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  51. package/src/functions/admin-revoke-agreement.ts +467 -0
  52. package/src/functions/admin-send-commons-agreement.ts +214 -0
  53. package/src/functions/admin-set-credit-amount.ts +123 -0
  54. package/src/functions/admin-skip-commons-contract.ts +165 -0
  55. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  56. package/src/functions/admin-wall-photo-write.ts +141 -0
  57. package/src/functions/auth-email-hook.ts +259 -0
  58. package/src/functions/boldsign-sender-identity.ts +114 -0
  59. package/src/functions/booking-availability.ts +419 -0
  60. package/src/functions/booking-member-preview.ts +136 -0
  61. package/src/functions/booking-status.ts +149 -0
  62. package/src/functions/conductor.ts +505 -0
  63. package/src/functions/create-agreement.ts +537 -0
  64. package/src/functions/create-booking.ts +648 -0
  65. package/src/functions/create-day-pass-checkout.ts +218 -0
  66. package/src/functions/create-portal-session.ts +142 -0
  67. package/src/functions/create-subscription-checkout.test.ts +222 -0
  68. package/src/functions/create-subscription-checkout.ts +440 -0
  69. package/src/functions/day-pass-status.ts +89 -0
  70. package/src/functions/dayStatus.ts +71 -0
  71. package/src/functions/diag-webpush-test.ts +45 -0
  72. package/src/functions/event-access-admin.ts +277 -0
  73. package/src/functions/event-access-store.ts +309 -0
  74. package/src/functions/ezeep-print-webhook.ts +213 -0
  75. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  76. package/src/functions/fetch-avatar-original.ts +457 -0
  77. package/src/functions/get-provider-sign-link.ts +155 -0
  78. package/src/functions/get-signing-link.ts +211 -0
  79. package/src/functions/guest-print-setup-confirm.ts +128 -0
  80. package/src/functions/guest-print-submit.ts +149 -0
  81. package/src/functions/luma-webhook.ts +165 -0
  82. package/src/functions/manage-booking.ts +472 -0
  83. package/src/functions/mcp.ts +67 -0
  84. package/src/functions/member-door-action.test.ts +1248 -0
  85. package/src/functions/member-door-action.ts +863 -0
  86. package/src/functions/member-unifi-mapping.test.ts +516 -0
  87. package/src/functions/member-unifi-mapping.ts +206 -0
  88. package/src/functions/membership-door-sync.ts +956 -0
  89. package/src/functions/migration-collision-alert.copy.ts +232 -0
  90. package/src/functions/migration-collision-alert.test.ts +349 -0
  91. package/src/functions/migration-collision-alert.ts +232 -0
  92. package/src/functions/office-assignment-end.ts +146 -0
  93. package/src/functions/portal-booking-access.ts +95 -0
  94. package/src/functions/portal-list-invoices.ts +99 -0
  95. package/src/functions/portal-request-login.ts +192 -0
  96. package/src/functions/portal-resend-invite.ts +248 -0
  97. package/src/functions/portal-submit-event.ts +168 -0
  98. package/src/functions/print-billing-recover.ts +97 -0
  99. package/src/functions/print-billing-run.ts +183 -0
  100. package/src/functions/public-facts.ts +168 -0
  101. package/src/functions/push-send.ts +348 -0
  102. package/src/functions/push-test.ts +234 -0
  103. package/src/functions/request-portal-link.ts +211 -0
  104. package/src/functions/reschedule-booking.ts +649 -0
  105. package/src/functions/review-ratings.ts +113 -0
  106. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  107. package/src/functions/space-availability-range.ts +142 -0
  108. package/src/functions/stripe-db-reconcile.ts +319 -0
  109. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  110. package/src/functions/stripe-webhook.ts +2595 -0
  111. package/src/functions/sync-gcal-blackouts.ts +298 -0
  112. package/src/functions/timetable-event-register.ts +162 -0
  113. package/src/functions/timetable-event-status.ts +90 -0
  114. package/src/functions/timetable-spaces.ts +219 -0
  115. package/src/functions/touch-pass-reconciler.ts +689 -0
  116. package/src/functions/touch-pass-signup.ts +478 -0
  117. package/src/functions/upload-booking-display-image.ts +179 -0
  118. package/src/functions/virtual-onboarding-purge.ts +134 -0
  119. package/src/functions/virtual-onboarding-submit.ts +315 -0
  120. package/src/functions/voice-booking.ts +453 -0
  121. package/src/functions/voice-day-pass.ts +346 -0
  122. package/src/functions/voice-inquiry.test.ts +301 -0
  123. package/src/functions/voice-inquiry.ts +198 -0
  124. package/src/functions/voice-membership-signup.ts +355 -0
  125. package/src/functions/voice-tour-availability.ts +204 -0
  126. package/src/functions/voice-tour-booking.ts +429 -0
  127. package/src/gcalSync.ts +142 -0
  128. package/src/ghlEventInquiry.ts +143 -0
  129. package/src/ghlNote.ts +34 -0
  130. package/src/ghlTask.ts +48 -0
  131. package/src/ghlVoiceInquiry.ts +90 -0
  132. package/src/guestPrintCapture.test.ts +722 -0
  133. package/src/guestPrintCapture.ts +538 -0
  134. package/src/lumaGhl.ts +195 -0
  135. package/src/mailArrivalEmail.ts +121 -0
  136. package/src/manageToken.ts +363 -0
  137. package/src/membership.ts +109 -0
  138. package/src/membershipBusClient.ts +537 -0
  139. package/src/membershipWelcome.ts +683 -0
  140. package/src/migrationCheckout.ts +366 -0
  141. package/src/money.ts +36 -0
  142. package/src/ops.ts +97 -0
  143. package/src/pacificDate.ts +88 -0
  144. package/src/paymentLinkEmail.ts +123 -0
  145. package/src/policyAcknowledgment.test.ts +50 -0
  146. package/src/policyAcknowledgment.ts +96 -0
  147. package/src/portalSession.ts +46 -0
  148. package/src/pricing.test.ts +660 -0
  149. package/src/pricing.ts +1025 -0
  150. package/src/printBilling.test.ts +750 -0
  151. package/src/printBilling.ts +891 -0
  152. package/src/printBillingAdapters.ts +169 -0
  153. package/src/printCorrections.test.ts +348 -0
  154. package/src/printCorrections.ts +496 -0
  155. package/src/rateLimit.ts +82 -0
  156. package/src/referralCredits.test.ts +31 -0
  157. package/src/referralCredits.ts +34 -0
  158. package/src/referralGrant.ts +321 -0
  159. package/src/rescheduleCredit.test.ts +521 -0
  160. package/src/rescheduleCredit.ts +337 -0
  161. package/src/reservationWifiCode.test.ts +69 -0
  162. package/src/reservationWifiCode.ts +81 -0
  163. package/src/retellCallAnalyzed.test.ts +167 -0
  164. package/src/retellCallAnalyzed.ts +113 -0
  165. package/src/retellSignature.test.ts +137 -0
  166. package/src/retellSignature.ts +82 -0
  167. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  168. package/src/signedUnpaidReminderEmail.ts +132 -0
  169. package/src/slackAlert.ts +38 -0
  170. package/src/stripeCoworkingPortal.ts +91 -0
  171. package/src/supabaseTestFakes.ts +131 -0
  172. package/src/supportTicketEmail.ts +119 -0
  173. package/src/tier1Agreement.ts +125 -0
  174. package/src/unifiAccessPolicies.ts +228 -0
  175. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,123 @@
1
+ // Payment-link email for a completed private office agreement.
2
+ //
3
+ // Mirrors the GHL request shape, headers, timeouts, escaping and error
4
+ // classification of sendMembershipWelcome in ./membershipWelcome.ts.
5
+
6
+ import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
7
+ import { logOps } from './ops.ts';
8
+
9
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
10
+
11
+ export type PaymentLinkEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
12
+
13
+ /** Escape untrusted values interpolated into outbound HTML. */
14
+ function esc(v: unknown): string {
15
+ return String(v ?? '')
16
+ .replace(/&/g, '&amp;')
17
+ .replace(/</g, '&lt;')
18
+ .replace(/>/g, '&gt;')
19
+ .replace(/"/g, '&quot;')
20
+ .replace(/'/g, '&#39;');
21
+ }
22
+
23
+ /** Classify a caught error as transient (worth another event) or hopeless. */
24
+ function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
25
+ const name = e instanceof Error ? e.name : '';
26
+ if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
27
+ const msg = e instanceof Error ? e.message : String(e);
28
+ const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
29
+ if (m) {
30
+ const code = Number(m[1]);
31
+ if (code === 429 || code >= 500) return 'failed_retryable';
32
+ }
33
+ return 'failed_permanent';
34
+ }
35
+
36
+ export async function sendPaymentLinkEmail(
37
+ supabase: SupabaseLike,
38
+ { email, name, checkoutUrl, officeNumber }: {
39
+ email: string;
40
+ name?: string | null;
41
+ checkoutUrl: string;
42
+ officeNumber?: string | null;
43
+ },
44
+ operator: { name: string; shortName: string; domain: string; supportEmail: string },
45
+ ): Promise<PaymentLinkEmailResult> {
46
+ try {
47
+ const apiKey = Deno.env.get('GHL_API_KEY');
48
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
49
+ if (!apiKey || !locationId) {
50
+ await logOps(supabase, 'payment_link_email_skipped',
51
+ { email, reason: 'ghl_not_configured' }, { severity: 'warning' }).catch(() => {});
52
+ return 'skipped';
53
+ }
54
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
55
+ const headers = {
56
+ Authorization: `Bearer ${apiKey}`,
57
+ Version: '2021-07-28',
58
+ 'Content-Type': 'application/json',
59
+ Accept: 'application/json',
60
+ };
61
+
62
+ const trimmed = (name || '').trim();
63
+ const parts = trimmed.split(/\s+/).filter(Boolean);
64
+ // Greeting is display-only. The CRM name is OMITTED when we have no name —
65
+ // never defaulted, or we would overwrite a real contact with "there".
66
+ const greetingName = parts[0] || 'there';
67
+ const crmName: { firstName?: string; lastName?: string } = {};
68
+ if (parts[0]) crmName.firstName = parts[0];
69
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
70
+
71
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
72
+ method: 'POST', headers,
73
+ signal: AbortSignal.timeout(8000),
74
+ body: JSON.stringify({
75
+ locationId, ...crmName, email,
76
+ source: `${operator.shortName} Website — Office Agreement`,
77
+ tags: ['Office Agreement', operator.domain],
78
+ }),
79
+ });
80
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
81
+ const upJson = await upRes.json();
82
+ const contactId = upJson.contact?.id || upJson.id || null;
83
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
84
+
85
+ const p = (t: string) =>
86
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
87
+
88
+ const office = (officeNumber || '').trim();
89
+ const officeClause = office ? ` for office ${esc(office)}` : '';
90
+
91
+ const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
92
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Your ${operator.shortName} office agreement is signed — set up payment</h2>
93
+ ${p(`Hi ${esc(greetingName)},`)}
94
+ ${p(`Thanks for signing your ${operator.name} office agreement${officeClause} — you're one step from locked in.`)}
95
+ ${p('The last step is setting up your monthly payment. Use the link below to add a payment method and start your subscription:')}
96
+ ${p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Set up payment →</a>`)}
97
+ ${p('This link is unique to your agreement, so please don\'t forward it. Once checkout is complete, we\'ll follow up with move-in details and everything else you need to get started.')}
98
+ ${p(`Questions in the meantime? Just reply to this email or reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
99
+ ${p(`Welcome aboard,<br />The ${operator.name} team`)}
100
+ </td></tr></table></td></tr></table></div>`;
101
+
102
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
103
+ method: 'POST', headers,
104
+ signal: AbortSignal.timeout(8000),
105
+ body: JSON.stringify({
106
+ type: 'Email',
107
+ contactId,
108
+ subject: `Your ${operator.shortName} office agreement is signed — set up payment`,
109
+ html,
110
+ }),
111
+ });
112
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
113
+
114
+ await logOps(supabase, 'payment_link_email_sent', { email }, { severity: 'info' }).catch(() => {});
115
+ return 'sent';
116
+ } catch (e) {
117
+ const classification = classifyError(e);
118
+ await logOps(supabase, 'payment_link_email_failed',
119
+ { email, message: e instanceof Error ? e.message : String(e) },
120
+ { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
121
+ return classification;
122
+ }
123
+ }
@@ -0,0 +1,50 @@
1
+ import { assertEquals } from 'https://deno.land/std@0.224.0/assert/mod.ts';
2
+ import { checkPolicyAcceptance, policyTextSha256 } from './policyAcknowledgment.ts';
3
+
4
+ // (a) No policy text on the room => never required, always ok, whatever the
5
+ // client sent. This is the OFF switch for every room that has not been given a
6
+ // checkout agreement.
7
+ Deno.test('checkPolicyAcceptance: null policy text is never required, ok regardless of the flag', () => {
8
+ for (const accepted of [undefined, false, true] as const) {
9
+ assertEquals(
10
+ checkPolicyAcceptance({ checkout_agreement_text: null }, accepted),
11
+ { required: false, ok: true },
12
+ );
13
+ }
14
+ });
15
+
16
+ // (b) Policy text present, acknowledgment missing or refused => gated.
17
+ Deno.test('checkPolicyAcceptance: policy text with a missing or false flag is required and not ok', () => {
18
+ assertEquals(
19
+ checkPolicyAcceptance({ checkout_agreement_text: 'No pets. Clean up.' }, undefined),
20
+ { required: true, ok: false },
21
+ );
22
+ assertEquals(
23
+ checkPolicyAcceptance({ checkout_agreement_text: 'No pets. Clean up.' }, false),
24
+ { required: true, ok: false },
25
+ );
26
+ });
27
+
28
+ // (c) Policy text present and explicitly accepted => gated but satisfied.
29
+ Deno.test('checkPolicyAcceptance: policy text with agreementAccepted=true is required and ok', () => {
30
+ assertEquals(
31
+ checkPolicyAcceptance({ checkout_agreement_text: 'No pets. Clean up.' }, true),
32
+ { required: true, ok: true },
33
+ );
34
+ });
35
+
36
+ // A whitespace-only column is an empty policy, not a policy nobody can satisfy.
37
+ Deno.test('checkPolicyAcceptance: whitespace-only policy text behaves like NULL', () => {
38
+ assertEquals(
39
+ checkPolicyAcceptance({ checkout_agreement_text: ' \n\t ' }, undefined),
40
+ { required: false, ok: true },
41
+ );
42
+ });
43
+
44
+ // Known-answer vector: `printf 'abc' | sha256sum`.
45
+ Deno.test('policyTextSha256: lowercase hex SHA-256 of the exact text bytes', async () => {
46
+ assertEquals(
47
+ await policyTextSha256('abc'),
48
+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
49
+ );
50
+ });
@@ -0,0 +1,96 @@
1
+ // Per-room checkout agreement ("room use policy") acknowledgment.
2
+ //
3
+ // SEPARATE MECHANISM from _shared/tier1Agreement.ts / public.booking_agreements
4
+ // (Tier 1 click-through, Tier 2-3 BoldSign) and from the Commons Event Contract
5
+ // tier-3 flow. Nothing in this file reads or writes booking_agreements,
6
+ // booking_contract_violations, or any BoldSign state, and nothing here gates
7
+ // door provisioning. It records one plain fact: at booking time the customer
8
+ // was shown this room's own free-text `rooms.checkout_agreement_text` and
9
+ // ticked the box. Do not merge the two mechanisms.
10
+ //
11
+ // The feature's off switch is NULL: a room with checkout_agreement_text IS NULL
12
+ // requires nothing and produces no acknowledgment row.
13
+
14
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
15
+
16
+ // Loose generics, matching _shared/ops.ts and _shared/bookingEffects.ts — a
17
+ // real createClient(url, key) call is not assignable to the un-inferred
18
+ // ReturnType<typeof createClient> default.
19
+ // deno-lint-ignore no-explicit-any
20
+ type SupabaseLike = SupabaseClient<any, any, any>;
21
+
22
+ export interface RoomForPolicyAcknowledgment {
23
+ checkout_agreement_text: string | null;
24
+ }
25
+
26
+ export interface PolicyAcceptanceCheck {
27
+ /** True when this room has a policy at all, i.e. the box must be shown. */
28
+ required: boolean;
29
+ /** True when the request may proceed: not required, or required and accepted. */
30
+ ok: boolean;
31
+ }
32
+
33
+ /**
34
+ * Pure. The single authority on "does this booking need the room use policy
35
+ * ticked, and was it". A room with no policy text is never gated, whatever the
36
+ * client sent; a room with policy text is gated on an explicit `true` — an
37
+ * omitted, false, or non-boolean truthy value is a refusal, so a client that
38
+ * simply forgets the field can never book past the policy.
39
+ */
40
+ export function checkPolicyAcceptance(
41
+ room: RoomForPolicyAcknowledgment,
42
+ agreementAccepted: boolean | undefined,
43
+ ): PolicyAcceptanceCheck {
44
+ const text = room.checkout_agreement_text;
45
+ const required = typeof text === 'string' && text.trim().length > 0;
46
+ if (!required) return { required: false, ok: true };
47
+ return { required: true, ok: agreementAccepted === true };
48
+ }
49
+
50
+ /** Customer-facing 400 message for a failed check. */
51
+ export const POLICY_NOT_ACCEPTED_ERROR =
52
+ 'You must accept the room use policy to book this room.';
53
+
54
+ /**
55
+ * Hex SHA-256 of the policy text the customer actually ticked. Same Web Crypto
56
+ * pattern as tier1Agreement.ts's own content_sha256 (crypto.subtle.digest over
57
+ * the exact bytes, lowercase hex) so the two hashes are directly comparable by
58
+ * eye, even though the tables are unrelated.
59
+ */
60
+ export async function policyTextSha256(text: string): Promise<string> {
61
+ const bytes = new TextEncoder().encode(text);
62
+ const digest = await crypto.subtle.digest('SHA-256', bytes as unknown as BufferSource);
63
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('');
64
+ }
65
+
66
+ export interface PolicyAcknowledgmentInput {
67
+ bookingId: string;
68
+ roomId: string;
69
+ /** The room's CURRENT checkout_agreement_text, hashed here — never client-supplied. */
70
+ agreementText: string;
71
+ acceptedEmail: string | null;
72
+ acceptedIp: string | null;
73
+ }
74
+
75
+ /**
76
+ * Records the acknowledgment. Returns the error message instead of throwing so
77
+ * the caller decides whether a failure is fatal — the booking itself is not
78
+ * legally dependent on this row (that is booking_agreements' job), so callers
79
+ * log rather than roll back.
80
+ */
81
+ export async function insertPolicyAcknowledgment(
82
+ supabase: SupabaseLike,
83
+ input: PolicyAcknowledgmentInput,
84
+ ): Promise<{ error: string | null }> {
85
+ const { error } = await supabase.from('booking_policy_acknowledgments').insert({
86
+ booking_id: input.bookingId,
87
+ room_id: input.roomId,
88
+ agreement_text_sha256: await policyTextSha256(input.agreementText),
89
+ accepted_at: new Date().toISOString(),
90
+ accepted_email: input.acceptedEmail,
91
+ // inet rejects the 'unknown' sentinel _shared/rateLimit.ts's clientIp()
92
+ // returns when no forwarding header is present — store NULL instead.
93
+ accepted_ip: input.acceptedIp && input.acceptedIp !== 'unknown' ? input.acceptedIp : null,
94
+ } as never);
95
+ return { error: error ? error.message : null };
96
+ }
@@ -0,0 +1,46 @@
1
+ // Second accepted auth mode for the customer-facing booking functions.
2
+ //
3
+ // The original mode — the HMAC manage token (`_shared/manageToken.ts`) — is
4
+ // unchanged and remains the emailed-link credential. This adds a parallel
5
+ // mode for signed-in member-portal sessions: an `Authorization: Bearer <jwt>`
6
+ // header verified against Supabase Auth with a service-role client. The
7
+ // verified email is then fed into the SAME contact_email equality check the
8
+ // token path already performs; no side-effect logic is forked.
9
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
10
+
11
+ type SupabaseLike = SupabaseClient<any, any, any>;
12
+
13
+ /**
14
+ * Returns the verified auth user id AND email of the caller's portal session,
15
+ * or null when there is no bearer token or it doesn't validate.
16
+ */
17
+ export async function resolvePortalSession(
18
+ req: Request,
19
+ admin: SupabaseLike,
20
+ ): Promise<{ id: string; email: string } | null> {
21
+ const header = req.headers.get('Authorization') ?? '';
22
+ const m = header.match(/^Bearer\s+(.+)$/i);
23
+ if (!m) return null;
24
+ const jwt = m[1].trim();
25
+ if (!jwt) return null;
26
+ // The anon/publishable key is also sent as a bearer by supabase-js clients
27
+ // in some call shapes; getUser simply fails on it, which is what we want.
28
+ try {
29
+ const { data, error } = await admin.auth.getUser(jwt);
30
+ if (error || !data?.user?.email) return null;
31
+ return { id: data.user.id, email: data.user.email.toLowerCase() };
32
+ } catch (e) {
33
+ console.warn('[portalSession] getUser threw', e);
34
+ return null;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Back-compat wrapper: verified email only. Unchanged signature/behaviour.
40
+ */
41
+ export async function resolvePortalSessionEmail(
42
+ req: Request,
43
+ admin: SupabaseLike,
44
+ ): Promise<string | null> {
45
+ return (await resolvePortalSession(req, admin))?.email ?? null;
46
+ }