@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +562 -0
  2. package/LICENSE +21 -0
  3. package/README.md +18 -2
  4. package/THIRD_PARTY_NOTICES.md +41 -0
  5. package/bin/booking-engine.mjs +575 -0
  6. package/bin/connect.mjs +408 -0
  7. package/bin/photos.mjs +82 -0
  8. package/dist/admin/BookingAdmin.d.ts +22 -0
  9. package/dist/admin/BookingAdmin.js +337 -0
  10. package/dist/admin/admin.css +1423 -0
  11. package/dist/admin/alerts.d.ts +10 -0
  12. package/dist/admin/alerts.js +11 -0
  13. package/dist/admin/booking-detail.d.ts +37 -0
  14. package/dist/admin/booking-detail.js +149 -0
  15. package/dist/admin/content-inputs.d.ts +15 -0
  16. package/dist/admin/content-inputs.js +105 -0
  17. package/dist/admin/context.d.ts +37 -0
  18. package/dist/admin/context.js +8 -0
  19. package/dist/admin/drawer.d.ts +14 -0
  20. package/dist/admin/drawer.js +56 -0
  21. package/dist/admin/feedback.d.ts +32 -0
  22. package/dist/admin/feedback.js +70 -0
  23. package/dist/admin/fields.d.ts +27 -0
  24. package/dist/admin/fields.js +146 -0
  25. package/dist/admin/fonts/OFL-Geist-Mono.txt +93 -0
  26. package/dist/admin/fonts/OFL-Geist.txt +93 -0
  27. package/dist/admin/fonts/geist-latin-wght-normal.woff2 +0 -0
  28. package/dist/admin/fonts/geist-mono-latin-wght-normal.woff2 +0 -0
  29. package/dist/admin/icons.d.ts +66 -0
  30. package/dist/admin/icons.js +72 -0
  31. package/dist/admin/image-upload.d.ts +58 -0
  32. package/dist/admin/image-upload.js +111 -0
  33. package/dist/admin/index.d.ts +6 -0
  34. package/dist/admin/index.js +6 -0
  35. package/dist/admin/lucide.generated.d.ts +521 -0
  36. package/dist/admin/lucide.generated.js +76 -0
  37. package/dist/admin/sections/BookingsSection.d.ts +1 -0
  38. package/dist/admin/sections/BookingsSection.js +137 -0
  39. package/dist/admin/sections/EmailSection.d.ts +8 -0
  40. package/dist/admin/sections/EmailSection.js +182 -0
  41. package/dist/admin/sections/HoursSection.d.ts +1 -0
  42. package/dist/admin/sections/HoursSection.js +110 -0
  43. package/dist/admin/sections/OverviewSection.d.ts +1 -0
  44. package/dist/admin/sections/OverviewSection.js +427 -0
  45. package/dist/admin/sections/ServicesSection.d.ts +1 -0
  46. package/dist/admin/sections/ServicesSection.js +236 -0
  47. package/dist/admin/sections/SettingsSection.d.ts +10 -0
  48. package/dist/admin/sections/SettingsSection.js +96 -0
  49. package/dist/admin/sections/WebsiteSection.d.ts +1 -0
  50. package/dist/admin/sections/WebsiteSection.js +228 -0
  51. package/dist/admin/sections.d.ts +22 -0
  52. package/dist/admin/sections.js +29 -0
  53. package/dist/admin/setup.d.ts +1 -0
  54. package/dist/admin/setup.js +45 -0
  55. package/dist/admin/today.d.ts +43 -0
  56. package/dist/admin/today.js +115 -0
  57. package/dist/admin/ui.d.ts +134 -0
  58. package/dist/admin/ui.js +220 -0
  59. package/dist/calendar.d.ts +64 -0
  60. package/dist/calendar.js +139 -0
  61. package/dist/client.d.ts +147 -0
  62. package/dist/client.js +507 -0
  63. package/dist/config.d.ts +25 -0
  64. package/dist/config.js +120 -0
  65. package/dist/content/image.d.ts +20 -0
  66. package/dist/content/image.js +90 -0
  67. package/dist/content/resolve.d.ts +12 -0
  68. package/dist/content/resolve.js +73 -0
  69. package/dist/content/schema.d.ts +119 -0
  70. package/dist/content/schema.js +53 -0
  71. package/dist/content/store.d.ts +48 -0
  72. package/dist/content/store.js +123 -0
  73. package/dist/content/validate.d.ts +33 -0
  74. package/dist/content/validate.js +177 -0
  75. package/dist/errors.d.ts +19 -0
  76. package/dist/errors.js +94 -0
  77. package/dist/generated/manifest.d.ts +6 -0
  78. package/dist/generated/manifest.js +7 -0
  79. package/dist/index.d.ts +20 -0
  80. package/dist/index.js +20 -0
  81. package/dist/presets/hair-salon.d.ts +8 -0
  82. package/dist/presets/hair-salon.js +94 -0
  83. package/dist/presets/index.d.ts +5 -0
  84. package/dist/presets/index.js +6 -0
  85. package/dist/preview.d.ts +18 -0
  86. package/dist/preview.js +134 -0
  87. package/dist/semver.d.ts +16 -0
  88. package/dist/semver.js +55 -0
  89. package/dist/time.d.ts +31 -0
  90. package/dist/time.js +138 -0
  91. package/dist/types.d.ts +477 -0
  92. package/dist/types.js +3 -0
  93. package/dist/vite.d.ts +52 -0
  94. package/dist/vite.js +150 -0
  95. package/docs/BUILD-A-SITE.md +203 -0
  96. package/docs/EMAIL-SETUP.md +224 -0
  97. package/docs/INTEGRATION.md +1109 -0
  98. package/engine.manifest.json +90 -0
  99. package/functions/booking-mailer/deno.json +6 -0
  100. package/functions/booking-mailer/index.ts +44 -0
  101. package/functions/booking-mailer/mailer.js +156 -0
  102. package/functions/booking-mailer/providers/index.js +42 -0
  103. package/functions/booking-mailer/providers/resend.js +75 -0
  104. package/functions/booking-mailer/templates.js +345 -0
  105. package/migrations/0001_core.sql +1673 -0
  106. package/migrations/0002_security_hardening.sql +711 -0
  107. package/migrations/0003_private_definers_and_holds.sql +808 -0
  108. package/migrations/0004_verified_requests.sql +1702 -0
  109. package/migrations/0005_scoped_mailer_credential.sql +347 -0
  110. package/migrations/0006_trusted_client_ip.sql +56 -0
  111. package/migrations/0007_site_content.sql +380 -0
  112. package/migrations/0008_service_images_opening_times.sql +328 -0
  113. package/package.json +85 -4
  114. package/templates/BOOKING_ENGINE.md +61 -0
@@ -0,0 +1,347 @@
1
+ -- ============================================================================
2
+ -- Profit Studio Booking Engine — migration 0005_scoped_mailer_credential
3
+ -- Engine schema version: 2.0.0-alpha.5
4
+ --
5
+ -- ENGINE-OWNED FILE. Do not edit. `booking-engine doctor` reports changes.
6
+ --
7
+ -- Phase 2C hardening (docs/adr/0003-scoped-mailer-credential.md):
8
+ -- 1. The database starts the booking-mailer with a MAILER-ONLY token instead
9
+ -- of a Supabase secret key. The token lives in the private table
10
+ -- booking.mailer_config; the function compares it in constant time. It can
11
+ -- only start the mailer, which can only send emails the database queued.
12
+ -- No Supabase key is stored in the database any more (Vault not needed).
13
+ -- 2. Each start of the mailer is recorded, so the dashboard can show the
14
+ -- last result (e.g. HTTP 401 = the token does not match the function).
15
+ -- 3. Owners can retry emails that failed in the last 23 hours (inside
16
+ -- Resend's 24-hour idempotency window: a retry never duplicates).
17
+ --
18
+ -- After upgrading: run the new `npx booking-engine mailer-sql` once, set the
19
+ -- Edge Function secret BOOKING_MAILER_TOKEN, redeploy booking-mailer, and
20
+ -- delete the `booking_mailer` secret key alpha.4 asked for (see CHANGELOG).
21
+ -- ============================================================================
22
+
23
+ do $$
24
+ declare
25
+ v text;
26
+ begin
27
+ select e.schema_version into v from booking.engine_info e where e.id;
28
+ if v is distinct from '2.0.0-alpha.4' then
29
+ raise exception 'Booking Engine 0005_scoped_mailer_credential expects schema 2.0.0-alpha.4, found %', coalesce(v, 'none');
30
+ end if;
31
+ end
32
+ $$;
33
+
34
+ -- ----------------------------------------------------------------------------
35
+ -- Schema
36
+ -- ----------------------------------------------------------------------------
37
+
38
+ create table booking.mailer_config (
39
+ id boolean primary key default true check (id),
40
+ function_url text check (function_url is null or char_length(function_url) <= 300),
41
+ -- 64 hex characters from the CSPRNG behind gen_random_uuid().
42
+ token text not null default encode(uuid_send(gen_random_uuid()) || uuid_send(gen_random_uuid()), 'hex'),
43
+ token_created_at timestamptz not null default now(),
44
+ configured_at timestamptz
45
+ );
46
+ insert into booking.mailer_config default values;
47
+ comment on table booking.mailer_config is
48
+ 'Where the booking-mailer Edge Function is, and the mailer-only token it accepts (Edge Function secret BOOKING_MAILER_TOKEN). The token can only start the mailer. Never readable through the API.';
49
+
50
+ create table booking.mailer_starts (
51
+ request_id bigint primary key,
52
+ started_at timestamptz not null default now()
53
+ );
54
+ comment on table booking.mailer_starts is
55
+ 'One row per pg_net request that started the mailer (its id in net._http_response); kept one day, for the dashboard''s "last start" result.';
56
+
57
+ -- ----------------------------------------------------------------------------
58
+ -- Owner setup (SQL Editor only — not executable by any API role)
59
+ -- ----------------------------------------------------------------------------
60
+
61
+ -- Store the function address and return the token to copy into the Edge
62
+ -- Function secret BOOKING_MAILER_TOKEN. Safe to run again: the token stays the
63
+ -- same unless p_rotate is true (then update the secret too).
64
+ create function booking.configure_mailer(p_function_url text, p_rotate boolean default false)
65
+ returns table (booking_mailer_token text, setup_check text)
66
+ language plpgsql
67
+ volatile
68
+ set search_path = ''
69
+ as $$
70
+ declare
71
+ v_url text := btrim(coalesce(p_function_url, ''));
72
+ w jsonb;
73
+ v_missing text[] := '{}';
74
+ begin
75
+ if v_url !~ '^https://[^[:space:]/]+(/[^[:space:]]*)?$'
76
+ and v_url !~ '^http://(127\.0\.0\.1|localhost)(:[0-9]+)?(/[^[:space:]]*)?$' then
77
+ raise exception 'Give the function address, e.g. https://<project-ref>.supabase.co/functions/v1/booking-mailer';
78
+ end if;
79
+ update booking.mailer_config
80
+ set function_url = v_url,
81
+ configured_at = now(),
82
+ token = case when coalesce(p_rotate, false)
83
+ then encode(uuid_send(gen_random_uuid()) || uuid_send(gen_random_uuid()), 'hex') else token end,
84
+ token_created_at = case when coalesce(p_rotate, false) then now() else token_created_at end
85
+ where id;
86
+ w := booking.mailer_wiring();
87
+ if not (w ->> 'pgNet')::boolean then v_missing := v_missing || 'the pg_net extension'::text; end if;
88
+ if not (w ->> 'schedule')::boolean then v_missing := v_missing || 'the every-minute job (cron.schedule)'::text; end if;
89
+ return query
90
+ select c.token,
91
+ case when cardinality(v_missing) = 0
92
+ then 'OK — now add this token as the Edge Function secret BOOKING_MAILER_TOKEN, then send a test email from the dashboard.'
93
+ else 'Missing: ' || array_to_string(v_missing, ', ') || '. Run the whole mailer-sql output.' end
94
+ from booking.mailer_config c where c.id;
95
+ end;
96
+ $$;
97
+ comment on function booking.configure_mailer(text, boolean) is
98
+ 'Owner only (SQL Editor). Stores the booking-mailer address and returns the mailer token for the Edge Function secret BOOKING_MAILER_TOKEN; p_rotate => true issues a new token.';
99
+
100
+ -- ----------------------------------------------------------------------------
101
+ -- Starting the mailer with the scoped token
102
+ -- ----------------------------------------------------------------------------
103
+
104
+ -- Never raises (it runs inside the transaction that queued an email): a
105
+ -- wiring problem must not block a booking. At most once per transaction.
106
+ create or replace function booking.kick_mailer()
107
+ returns boolean
108
+ language plpgsql
109
+ volatile
110
+ security definer
111
+ set search_path = ''
112
+ as $$
113
+ declare
114
+ v_url text;
115
+ v_token text;
116
+ v_id bigint;
117
+ begin
118
+ if coalesce(current_setting('booking_engine.mailer_kicked', true), '') = 'on' then
119
+ return false;
120
+ end if;
121
+ begin
122
+ select c.function_url, c.token into v_url, v_token from booking.mailer_config c where c.id;
123
+ if v_url is null or to_regprocedure('net.http_post(text,jsonb,jsonb,jsonb,integer)') is null then
124
+ return false;
125
+ end if;
126
+ execute 'select net.http_post(url => $1, body => $2, params => $3, headers => $4, timeout_milliseconds => $5)'
127
+ into v_id
128
+ using v_url, '{}'::jsonb, '{}'::jsonb,
129
+ jsonb_build_object('Content-Type', 'application/json', 'x-booking-mailer-token', v_token), 30000;
130
+ insert into booking.mailer_starts (request_id) values (v_id) on conflict (request_id) do nothing;
131
+ exception when others then
132
+ return false;
133
+ end;
134
+ perform set_config('booking_engine.mailer_kicked', 'on', true);
135
+ return true;
136
+ end;
137
+ $$;
138
+ comment on function booking.kick_mailer() is
139
+ 'PRIVILEGED (SECURITY DEFINER), private schema. Starts the booking-mailer Edge Function through pg_net with the mailer-only token (header x-booking-mailer-token). Never raises.';
140
+
141
+ -- Is automatic sending wired up, and how did the last start go? Booleans and
142
+ -- an HTTP status only; never the token or the address.
143
+ create or replace function booking.mailer_wiring()
144
+ returns jsonb
145
+ language plpgsql
146
+ stable
147
+ security definer
148
+ set search_path = ''
149
+ as $$
150
+ declare
151
+ v_configured boolean;
152
+ v_schedule boolean := false;
153
+ v_net boolean := false;
154
+ v_start booking.mailer_starts%rowtype;
155
+ v_status int;
156
+ v_error text;
157
+ v_last jsonb := null;
158
+ begin
159
+ select c.function_url is not null into v_configured from booking.mailer_config c where c.id;
160
+ begin
161
+ if to_regclass('cron.job') is not null then
162
+ execute 'select exists (select 1 from cron.job j where j.jobname = $1 and j.active)'
163
+ into v_schedule
164
+ using 'booking-engine-mailer';
165
+ end if;
166
+ exception when others then
167
+ v_schedule := false;
168
+ end;
169
+ begin
170
+ v_net := to_regprocedure('net.http_post(text,jsonb,jsonb,jsonb,integer)') is not null;
171
+ exception when others then
172
+ v_net := false;
173
+ end;
174
+ select * into v_start from booking.mailer_starts s order by s.started_at desc, s.request_id desc limit 1;
175
+ if found then
176
+ begin
177
+ if to_regclass('net._http_response') is not null then
178
+ execute 'select r.status_code, r.error_msg from net._http_response r where r.id = $1'
179
+ into v_status, v_error
180
+ using v_start.request_id;
181
+ end if;
182
+ exception when others then
183
+ v_status := null;
184
+ v_error := null;
185
+ end;
186
+ v_last := jsonb_build_object(
187
+ 'at', booking.iso(v_start.started_at),
188
+ 'status', v_status,
189
+ 'error', left(v_error, 200)
190
+ );
191
+ end if;
192
+ return jsonb_build_object('pgNet', v_net, 'configured', coalesce(v_configured, false), 'schedule', v_schedule, 'lastStart', v_last);
193
+ end;
194
+ $$;
195
+
196
+ -- Retention for the start log, with the rest of the housekeeping.
197
+ create or replace function booking.run_maintenance()
198
+ returns jsonb
199
+ language plpgsql
200
+ volatile
201
+ security definer
202
+ set search_path = ''
203
+ as $$
204
+ declare
205
+ v_released int;
206
+ v_withdrawn int;
207
+ begin
208
+ v_released := booking.expire_lapsed();
209
+
210
+ update booking.email_outbox o
211
+ set status = 'cancelled', payload = o.payload - 'code', locked_until = null
212
+ where o.kind = 'verification_code'
213
+ and o.status in ('pending', 'sending')
214
+ and (o.locked_until is null or o.locked_until <= now())
215
+ and ((o.payload ->> 'expiresAt')::timestamptz <= now()
216
+ or not exists (select 1 from booking.bookings b where b.id = o.booking_id and b.status = 'unverified'));
217
+ get diagnostics v_withdrawn = row_count;
218
+
219
+ update booking.email_outbox o
220
+ set status = 'failed', locked_until = null,
221
+ payload = case when o.kind = 'verification_code' then o.payload - 'code' else o.payload end,
222
+ last_error = coalesce(o.last_error, 'Sending was interrupted repeatedly')
223
+ where o.status = 'sending' and o.locked_until <= now() and o.attempts >= 5;
224
+
225
+ delete from booking.email_outbox o
226
+ where o.status in ('sent', 'failed', 'cancelled')
227
+ and o.created_at < now() - case when o.kind = 'verification_code' then interval '2 days' else interval '30 days' end;
228
+ delete from booking.verifications v where v.created_at < now() - interval '1 day';
229
+ delete from booking.mailer_starts s where s.started_at < now() - interval '1 day';
230
+
231
+ return jsonb_build_object('released', v_released, 'withdrawn', v_withdrawn);
232
+ end;
233
+ $$;
234
+
235
+ -- ----------------------------------------------------------------------------
236
+ -- Admin: delivery health incl. the oldest waiting email; retry failed emails
237
+ -- ----------------------------------------------------------------------------
238
+
239
+ create or replace function public.booking_admin_email_status()
240
+ returns jsonb
241
+ language plpgsql
242
+ stable
243
+ security invoker
244
+ set search_path = ''
245
+ as $$
246
+ declare
247
+ v_result jsonb;
248
+ begin
249
+ perform booking.require_admin();
250
+ select jsonb_build_object(
251
+ 'mailer', (select jsonb_build_object(
252
+ 'lastAttemptAt', booking.iso(m.last_attempt_at),
253
+ 'lastSuccessAt', booking.iso(m.last_success_at),
254
+ 'lastFailureAt', booking.iso(m.last_failure_at),
255
+ 'lastError', m.last_error)
256
+ from booking.mailer_state m where m.id),
257
+ 'wiring', booking.mailer_wiring(),
258
+ 'counts', (select jsonb_build_object(
259
+ 'queued', count(*) filter (where o.status in ('pending', 'sending')),
260
+ 'oldestQueuedAt', booking.iso(min(o.created_at) filter (where o.status in ('pending', 'sending'))),
261
+ 'failedLast7Days', count(*) filter (where o.status = 'failed' and o.created_at > now() - interval '7 days'),
262
+ 'retryable', count(*) filter (where o.status = 'failed' and o.kind <> 'verification_code'
263
+ and o.created_at > now() - interval '23 hours'),
264
+ 'sentLast24h', count(*) filter (where o.status = 'sent' and o.sent_at > now() - interval '1 day'),
265
+ 'codesLast24h', count(*) filter (where o.kind = 'verification_code' and o.created_at > now() - interval '1 day'))
266
+ from booking.email_outbox o),
267
+ 'recent', coalesce((
268
+ select jsonb_agg(x.j order by x.created_at desc)
269
+ from (
270
+ select o.created_at, jsonb_build_object(
271
+ 'id', o.id, 'kind', o.kind, 'status', o.status, 'recipient', booking.mask_email(o.recipient),
272
+ 'attempts', o.attempts, 'createdAt', booking.iso(o.created_at), 'sentAt', booking.iso(o.sent_at),
273
+ 'lastError', o.last_error) as j
274
+ from booking.email_outbox o
275
+ order by o.created_at desc
276
+ limit 20
277
+ ) as x), '[]'::jsonb)
278
+ ) into v_result;
279
+ return v_result;
280
+ end;
281
+ $$;
282
+
283
+ -- Failed emails from the last 23 hours go back into the queue (codes are not
284
+ -- retried: they have expired). Resend keeps an idempotency key for 24 hours,
285
+ -- so an email whose first attempt did reach Resend is not sent twice.
286
+ create function public.booking_admin_retry_failed_emails()
287
+ returns jsonb
288
+ language plpgsql
289
+ volatile
290
+ security invoker
291
+ set search_path = ''
292
+ as $$
293
+ declare
294
+ n int;
295
+ begin
296
+ perform booking.require_admin();
297
+ update booking.email_outbox o
298
+ set status = 'pending', attempts = 0, next_attempt_at = now(), locked_until = null, last_error = null
299
+ where o.status = 'failed'
300
+ and o.kind <> 'verification_code'
301
+ and o.created_at > now() - interval '23 hours';
302
+ get diagnostics n = row_count;
303
+ return jsonb_build_object('requeued', n);
304
+ end;
305
+ $$;
306
+ comment on function public.booking_admin_retry_failed_emails() is
307
+ 'Admin only. Puts emails that failed in the last 23 hours back in the queue (the every-minute job sends them; idempotent within Resend''s 24-hour window).';
308
+
309
+ -- ----------------------------------------------------------------------------
310
+ -- Obsolete alpha.4 wiring: the Vault entries held a full Supabase secret key.
311
+ -- Remove them where possible (the key itself must be deleted in the dashboard).
312
+ -- ----------------------------------------------------------------------------
313
+
314
+ do $$
315
+ begin
316
+ if to_regclass('vault.secrets') is not null then
317
+ execute 'delete from vault.secrets where name in (''booking_engine_mailer_url'', ''booking_engine_mailer_key'')';
318
+ end if;
319
+ exception when others then
320
+ raise notice 'Booking Engine: could not remove the old booking_engine_mailer_* Vault secrets (%). Delete them in the dashboard.', sqlerrm;
321
+ end
322
+ $$;
323
+
324
+ -- ----------------------------------------------------------------------------
325
+ -- RLS and privileges
326
+ -- ----------------------------------------------------------------------------
327
+
328
+ alter table booking.mailer_config enable row level security;
329
+ alter table booking.mailer_starts enable row level security;
330
+ create policy mailer_config_no_api_access on booking.mailer_config
331
+ for all to anon, authenticated using (false) with check (false);
332
+ create policy mailer_starts_no_api_access on booking.mailer_starts
333
+ for all to anon, authenticated using (false) with check (false);
334
+ create policy email_outbox_admin_retry on booking.email_outbox
335
+ for update to authenticated using ((select booking.is_admin())) with check ((select booking.is_admin()));
336
+
337
+ revoke all on booking.mailer_config, booking.mailer_starts from public, anon, authenticated, service_role;
338
+ grant update (status, attempts, next_attempt_at, locked_until, last_error) on booking.email_outbox to authenticated;
339
+
340
+ revoke execute on all functions in schema booking from public;
341
+ revoke all on function
342
+ booking.configure_mailer(text, boolean),
343
+ public.booking_admin_retry_failed_emails()
344
+ from public, anon, authenticated, service_role;
345
+ grant execute on function public.booking_admin_retry_failed_emails() to authenticated;
346
+
347
+ update booking.engine_info set schema_version = '2.0.0-alpha.5', updated_at = now() where id;
@@ -0,0 +1,56 @@
1
+ -- ============================================================================
2
+ -- Profit Studio Booking Engine — migration 0006_trusted_client_ip
3
+ -- Engine schema version: 2.0.0-alpha.6
4
+ --
5
+ -- ENGINE-OWNED FILE. Do not edit. `booking-engine doctor` reports changes.
6
+ --
7
+ -- Security patch (verified need: hosted run of 2026-11-01, docs/SECURITY.md §3).
8
+ -- A client's address for per-client limits now comes ONLY from the header the
9
+ -- platform's edge sets: `cf-connecting-ip` (Cloudflare, in front of every
10
+ -- hosted Supabase project, refuses requests that send their own). `x-real-ip`
11
+ -- and `x-forwarded-for` are never used any more: on hosted Supabase the first
12
+ -- `x-forwarded-for` entry is whatever the client sent. Without a usable
13
+ -- `cf-connecting-ip` the request falls into the shared `unknown` bucket, which
14
+ -- the site-wide hourly cap limits — fail-closed: no header a client controls
15
+ -- can open a fresh bucket.
16
+ --
17
+ -- Same function signatures; no data change; nothing to do after upgrading.
18
+ -- ============================================================================
19
+
20
+ do $$
21
+ declare
22
+ v text;
23
+ begin
24
+ select e.schema_version into v from booking.engine_info e where e.id;
25
+ if v is distinct from '2.0.0-alpha.5' then
26
+ raise exception 'Booking Engine 0006_trusted_client_ip expects schema 2.0.0-alpha.5, found %', coalesce(v, 'none');
27
+ end if;
28
+ end
29
+ $$;
30
+
31
+ -- The client's address as set by the platform's edge, or null.
32
+ create or replace function booking.client_ip()
33
+ returns text
34
+ language plpgsql
35
+ stable
36
+ set search_path = ''
37
+ as $$
38
+ declare
39
+ h jsonb;
40
+ begin
41
+ begin
42
+ h := nullif(current_setting('request.headers', true), '')::jsonb;
43
+ exception when others then
44
+ return null;
45
+ end;
46
+ if h is null or jsonb_typeof(h) <> 'object' then
47
+ return null;
48
+ end if;
49
+ -- Only the edge's header. Never x-real-ip or x-forwarded-for: a client can write those.
50
+ return left(nullif(btrim(h ->> 'cf-connecting-ip'), ''), 64);
51
+ end;
52
+ $$;
53
+ comment on function booking.client_ip() is
54
+ 'The client address from cf-connecting-ip (set by the platform edge; clients cannot send it). Null when absent: the caller then shares the unknown bucket.';
55
+
56
+ update booking.engine_info set schema_version = '2.0.0-alpha.6', updated_at = now() where id;