From e1d603aeb28b9acf7a32af9a7bcfc9dc00fd94b6 Mon Sep 17 00:00:00 2001 From: Abhay Doss Date: Fri, 13 Nov 2026 13:15:31 -0500 Subject: [PATCH 01/15] feat: add SvelteKit frontend, frequency caps, and single-use booking links --- API_CHANGES_FOR_FRONTEND.md | 125 +++++++ frontend/src/app.css | 28 +- frontend/src/app.html | 10 + frontend/src/lib/api.ts | 24 ++ frontend/src/lib/theme.svelte.ts | 89 +++++ frontend/src/routes/+layout.svelte | 42 +++ frontend/src/routes/calendar/+page.svelte | 23 +- frontend/src/routes/event-types/+page.svelte | 221 ++++++++++- .../routes/event-types/[slug]/+page.svelte | 30 ++ frontend/src/routes/login/+page.svelte | 34 +- internal/booking/booking.go | 8 + internal/booking/caps.go | 161 +++++++++ internal/booking/service.go | 25 ++ internal/booking/service_test.go | 88 +++++ internal/calendar/microsoft/microsoft.go | 1 + internal/config/config.go | 8 +- internal/config/config_test.go | 30 ++ .../00072_event_type_frequency_caps.sql | 7 + .../db/migrations/00073_single_use_tokens.sql | 21 ++ internal/handler/auth_microsoft.go | 1 + internal/handler/auth_microsoft_test.go | 39 ++ internal/handler/auth_oauth.go | 64 +++- internal/handler/auth_oauth_internal_test.go | 98 +++++ internal/handler/book.go | 49 ++- internal/handler/booking_handler.go | 51 ++- internal/handler/event_type.go | 98 ++++- internal/handler/event_type_duplicate.go | 6 +- internal/handler/event_type_duplicate_test.go | 2 + internal/handler/handler.go | 37 +- internal/handler/mcp.go | 18 +- internal/handler/single_use_handler.go | 342 ++++++++++++++++++ internal/handler/single_use_test.go | 329 +++++++++++++++++ internal/handler/slots_handler.go | 49 ++- internal/handler/templates/_shared.html | 57 ++- internal/handler/templates/book.html | 39 +- internal/handler/templates/booking.css | 202 +++++++++++ internal/handler/templates/directory.html | 2 + internal/handler/templates/manage.html | 2 + internal/server/server.go | 24 +- 39 files changed, 2395 insertions(+), 89 deletions(-) create mode 100644 API_CHANGES_FOR_FRONTEND.md create mode 100644 frontend/src/lib/theme.svelte.ts create mode 100644 internal/booking/caps.go create mode 100644 internal/db/migrations/00072_event_type_frequency_caps.sql create mode 100644 internal/db/migrations/00073_single_use_tokens.sql create mode 100644 internal/handler/auth_oauth_internal_test.go create mode 100644 internal/handler/single_use_handler.go create mode 100644 internal/handler/single_use_test.go diff --git a/API_CHANGES_FOR_FRONTEND.md b/API_CHANGES_FOR_FRONTEND.md new file mode 100644 index 00000000..3cac31cf --- /dev/null +++ b/API_CHANGES_FOR_FRONTEND.md @@ -0,0 +1,125 @@ +# API Changes for Frontend (Forma Prime Fork) + +This document describes the backend API additions for the SvelteKit 5 admin UI (`frontend/src/`) and public booking flows. + +--- + +## 1. Event Type Daily & Weekly Frequency Caps + +### Event Type Schema (`GET /v1/event-types`, `GET /v1/event-types/{slug}`, `POST /v1/event-types`, `PATCH /v1/event-types/{slug}`) + +Two optional nullable integer fields are exposed on every event type payload: + +```json +{ + "id": "...", + "slug": "founder-intro", + "name": "Founder Intro", + "max_per_day": 2, + "max_per_week": 6 +} +``` + +- **Types:** `number | null` +- **Semantics:** + - `null` or omitted: unlimited for that period. + - Positive integer (`> 0`): maximum number of non-cancelled (`status != 'cancelled'`) confirmed bookings allowed per calendar day (`YYYY-MM-DD`) or ISO week (Monday–Sunday) in the event type owner's configured IANA timezone (`users.iana_timezone`). + - `0` on `POST` or `PATCH`: normalized to `null` (unlimited). + - Negative integer (`< 0`): rejected with `400 Bad Request` (`"max_per_day cannot be negative (null or 0 = unlimited)"` / `"max_per_week cannot be negative (null or 0 = unlimited)"`). + - Omitting `max_per_day` / `max_per_week` in `PATCH` leaves the existing value unchanged; sending explicit `null` or `0` clears the cap to `null`. +- **Conflict Behavior:** + - `GET /v1/event-types/{slug}/slots` omits any slots whose day or ISO week has already reached its cap. + - `POST /v1/bookings` returns `409 Conflict` (`{"error": "daily or weekly booking limit reached for this event type"}`) if a concurrent booking fills the cap. + +--- + +## 2. Native Single-Use (Ephemeral) Booking Links + +All admin endpoints require standard session or API key authentication (`RequireAuth`). `{id}` in `/v1/event-types/{id}/single-use-links` accepts either the event type's UUID `id` or `slug`, scoped to admins, the event type owner, or assigned hosts. + +### `POST /v1/event-types/{id}/single-use-links` + +Generates a cryptographically random URL-safe single-use link for the event type. + +**Request Body:** +```json +{ + "prefill_name": "Jane Founder", + "prefill_email": "jane@startup.io", + "deal_id": "deal_123", + "expires_in_hours": 168 +} +``` +- All fields are optional. +- `expires_in_hours`: defaults to `168` (7 days) when omitted. `0` creates a non-expiring single-use link (`expires_at: null`). Negative values return `400 Bad Request`. + +**Response (`201 Created`):** +```json +{ + "id": "01J...", + "token": "xYz...", + "url": "https://cal.example.com/t/xYz...", + "event_type_id": "01J...", + "created_by_user_id": "01J...", + "prefill_name": "Jane Founder", + "prefill_email": "jane@startup.io", + "deal_id": "deal_123", + "expires_at": "2026-11-20T12:00:00Z", + "used_at": null, + "booking_id": null, + "created_at": "2026-11-13T12:00:00Z" +} +``` +- `url` uses `/t/` (or `/t/` if no base URL is configured). + +### `GET /v1/event-types/{id}/single-use-links` + +Lists tokens generated for the event type ordered newest-first (`created_at DESC`). + +**Response (`200 OK`):** +```json +{ + "single_use_links": [ + { + "id": "01J...", + "token": "xYz...", + "url": "https://cal.example.com/t/xYz...", + "event_type_id": "01J...", + "created_by_user_id": "01J...", + "prefill_name": "Jane Founder", + "prefill_email": "jane@startup.io", + "deal_id": "deal_123", + "expires_at": "2026-11-20T12:00:00Z", + "used_at": null, + "booking_id": null, + "created_at": "2026-11-13T12:00:00Z" + } + ] +} +``` + +### `DELETE /v1/single-use-links/{token}` + +Revokes an unused single-use token. + +- `204 No Content`: token deleted. +- `404 Not Found`: token does not exist or caller lacks access to its event type. +- `409 Conflict`: token has already been used to create a booking. + +### Public Token Entry & Booking Flow + +- **`GET /t/{token}`** + - Renders the public booking page (`book.html`) with `#f-name` and `#f-email` prefilled, `SINGLE_USE_TOKEN` injected, and any matching `dealId` / `deal_id` intake question prefilled (explicit `?name=`, `?email=`, `?dealId=`/`?deal_id=` URL query params override token defaults). + - Works for both public and private (`is_public = false`) active event types. + - Returns `410 Gone` HTML (`"This booking link has expired or has already been used"`) if the token is missing, revoked, already used, expired, or its event type is inactive. +- **`POST /v1/bookings`** + - Accepts optional `"single_use_token": ""` in the JSON body. + - Atomically marks the token used (`used_at`, `booking_id`) inside the SQLite booking creation transaction, or rolls back with `410 Gone` if already used/expired. + - Resulting bookings use their own manage token on `/manage/{token}` and `/v1/bookings/{id}/reschedule` without modifying `single_use_tokens`. + +--- + +## 3. Environment Variables (Auth & OAuth) + +- `MICROSOFT_TENANT_ID`: Microsoft Entra tenant authority (`"common"` by default when unset; falls back to `MICROSOFT_TENANT` if only that legacy var is set). +- `ALLOWED_SIGNUP_DOMAINS`: Comma-separated list of domains (e.g., `formaprime.vc`) permitted to auto-provision `"member"` accounts on OAuth login. Matching domains succeed with a session; non-matching domains are rejected with `403 Forbidden`. When empty/unset, self-provisioning stays disabled (`/admin/login?error=no_account`). diff --git a/frontend/src/app.css b/frontend/src/app.css index e0921169..ba4c6260 100644 --- a/frontend/src/app.css +++ b/frontend/src/app.css @@ -1,7 +1,7 @@ @import "tailwindcss"; @import "tw-animate-css"; -@custom-variant dark (&:is(.dark *)); +@custom-variant dark (&:where(.dark, .dark *)); /* * Tailwind v4 has built-in data-* variants: `data-foo:` targets `[data-foo]`. @@ -139,4 +139,30 @@ body { line-height: 1.5; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; + transition: background-color 180ms cubic-bezier(0.2, 0.8, 0.2, 1), color 180ms cubic-bezier(0.2, 0.8, 0.2, 1); +} + +button, +a, +input, +select, +textarea { + transition-duration: 160ms; + transition-timing-function: cubic-bezier(0.2, 0.8, 0.2, 1); +} + +:focus-visible { + outline: 2px solid var(--ring); + outline-offset: 2px; +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } } diff --git a/frontend/src/app.html b/frontend/src/app.html index 4fdc6b00..4f69454c 100644 --- a/frontend/src/app.html +++ b/frontend/src/app.html @@ -5,6 +5,16 @@ + diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index cd6c8723..26986d20 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -54,6 +54,8 @@ export type EventType = { min_notice_minutes: number; max_future_days: number; max_active_bookings: number; + max_per_day?: number | null; + max_per_week?: number | null; price_cents: number; // 0 = free currency: string; // ISO 4217, lowercase (e.g. "usd") created_at: string; @@ -93,6 +95,28 @@ export type EventTypeHost = { archived: boolean; }; +export type SingleUseLink = { + id: string; + token: string; + url: string; + event_type_id: string; + created_by_user_id: string; + prefill_name: string; + prefill_email: string; + deal_id: string; + expires_at: string | null; + used_at: string | null; + booking_id: string | null; + created_at: string; +}; + +export type CreateSingleUseLinkPayload = { + prefill_name?: string; + prefill_email?: string; + deal_id?: string; + expires_in_hours?: number; +}; + export type Question = { id: string; event_type_id: string; diff --git a/frontend/src/lib/theme.svelte.ts b/frontend/src/lib/theme.svelte.ts new file mode 100644 index 00000000..20d762ef --- /dev/null +++ b/frontend/src/lib/theme.svelte.ts @@ -0,0 +1,89 @@ +export type ThemeMode = 'light' | 'dark' | 'system'; + +const STORAGE_KEY = 'fp-theme'; +const DARK_QUERY = '(prefers-color-scheme: dark)'; + +function readStoredMode(): ThemeMode { + if (typeof window === 'undefined') return 'system'; + try { + const raw = window.localStorage.getItem(STORAGE_KEY); + if (raw === 'light' || raw === 'dark' || raw === 'system') return raw; + } catch { + // Ignore storage access errors. + } + return 'system'; +} + +function readSystemDark(): boolean { + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false; + return window.matchMedia(DARK_QUERY).matches; +} + +class ThemeStore { + mode = $state(readStoredMode()); + systemDark = $state(readSystemDark()); + resolved = $derived<'light' | 'dark'>( + this.mode === 'system' ? (this.systemDark ? 'dark' : 'light') : this.mode + ); + + private initialized = false; + private mediaCleanup: (() => void) | null = null; + + init() { + if (typeof window === 'undefined') return; + this.mode = readStoredMode(); + this.systemDark = readSystemDark(); + this.apply(); + + if (this.initialized || typeof window.matchMedia !== 'function') return; + this.initialized = true; + + const mq = window.matchMedia(DARK_QUERY); + const onChange = (e: MediaQueryListEvent) => { + this.systemDark = e.matches; + this.apply(); + }; + mq.addEventListener('change', onChange); + + const onStorage = (e: StorageEvent) => { + if (e.key === STORAGE_KEY) { + this.mode = readStoredMode(); + this.apply(); + } + }; + window.addEventListener('storage', onStorage); + + this.mediaCleanup = () => { + mq.removeEventListener('change', onChange); + window.removeEventListener('storage', onStorage); + }; + } + + destroy() { + this.mediaCleanup?.(); + this.mediaCleanup = null; + this.initialized = false; + } + + set(next: ThemeMode) { + this.mode = next; + if (typeof window !== 'undefined') { + try { + window.localStorage.setItem(STORAGE_KEY, next); + } catch { + // Ignore storage access errors. + } + } + this.apply(); + } + + apply() { + if (typeof document === 'undefined') return; + const isDark = this.resolved === 'dark'; + const root = document.documentElement; + root.classList.toggle('dark', isDark); + root.style.colorScheme = isDark ? 'dark' : 'light'; + } +} + +export const theme = new ThemeStore(); diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte index 8c48c731..0cf4f0fb 100644 --- a/frontend/src/routes/+layout.svelte +++ b/frontend/src/routes/+layout.svelte @@ -6,6 +6,7 @@ import { api, type User } from '$lib/api'; import { currentUser, authStatus, type AuthStatus } from '$lib/stores'; import { prefs, prefsFromUser } from '$lib/prefs'; + import { theme, type ThemeMode } from '$lib/theme.svelte'; import { t } from '$lib/i18n'; import { Toaster } from '$lib/components/ui/sonner'; import { buttonVariants } from '$lib/components/ui/button'; @@ -173,6 +174,7 @@ }); onMount(async () => { + theme.init(); // Close the drawer if the viewport grows past md while it is open, so it cannot // linger as an active overlay over the desktop layout. Specified in rem, not px: // every `md:` class compiles to 48rem, which only equals 768px at the 16px @@ -242,6 +244,21 @@ {#if isPublicRoute} +
+
+ {#each (['light', 'dark', 'system'] as ThemeMode[]) as modeOption} + + {/each} +
+
{@render children()} {:else if checking}
@@ -337,6 +354,31 @@
+
+
+ {#each (['light', 'dark', 'system'] as ThemeMode[]) as modeOption} + + {/each} +
+
diff --git a/frontend/src/routes/event-types/+page.svelte b/frontend/src/routes/event-types/+page.svelte index 9a1df60f..19409d8f 100644 --- a/frontend/src/routes/event-types/+page.svelte +++ b/frontend/src/routes/event-types/+page.svelte @@ -1,10 +1,11 @@ {ownerLabel(et)}{/if} {$t('common.minutesShort', { n: et.duration_minutes })} - - - window.open(bookLink(et.slug), '_blank')} - > - - - - {bookLink(et.slug)} - - +
+ + + window.open(bookLink(et.slug), '_blank')} + > + + + + {bookLink(et.slug)} + + + +
saveActive(et, v)} disabled={et.can_edit === false || et.archived} /> @@ -326,3 +437,87 @@
{/if} {/if} + + + + + 1-Time Booking Link{linkEventType ? ` — ${linkEventType.name}` : ''} + + Generate an ephemeral link that expires automatically after a single booking. + + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+

Recent 1-Time Links

+ {#if linksLoading} +

Loading links...

+ {:else if singleUseLinks.length === 0} +

No single-use links created for this event type yet.

+ {:else} +
+ {#each singleUseLinks as link (link.id)} + {@const st = linkStatus(link)} +
+
+
+ + {st} + + + {link.prefill_name || link.prefill_email || link.token.slice(0, 10) + '…'} + + {#if link.deal_id} + {link.deal_id} + {/if} +
+

/t/{link.token}

+
+
+ {#if st === 'active'} + + {/if} + {#if !link.used_at} + + {/if} +
+
+ {/each} +
+ {/if} +
+
+
+
diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index 6f5c49eb..0c61960b 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -92,6 +92,8 @@ buffer_before_minutes: 0, buffer_after_minutes: 0, min_notice_minutes: 0, max_future_days: 60, max_active_bookings: 1, + max_per_day: '' as number | '' | null, + max_per_week: '' as number | '' | null, price_cents: 0, currency: 'usd', }); @@ -343,6 +345,8 @@ min_notice_minutes: et.min_notice_minutes, max_future_days: et.max_future_days, max_active_bookings: et.max_active_bookings, + max_per_day: et.max_per_day ?? '', + max_per_week: et.max_per_week ?? '', price_cents: et.price_cents ?? 0, currency: et.currency ?? 'usd', }; @@ -378,6 +382,16 @@ // including when the person is editing something else entirely. if (form.slot_interval_minutes < 1) { toast.error(tr('eventTypeEditor.validation.slotInterval')); return; } if (form.max_active_bookings < 0) { toast.error(tr('eventTypeEditor.validation.maxActive')); return; } + const maxPerDay = form.max_per_day === '' || form.max_per_day === null ? null : Number(form.max_per_day); + const maxPerWeek = form.max_per_week === '' || form.max_per_week === null ? null : Number(form.max_per_week); + if (maxPerDay !== null && (!Number.isFinite(maxPerDay) || maxPerDay < 0)) { + toast.error('Max bookings per day cannot be negative.'); + return; + } + if (maxPerWeek !== null && (!Number.isFinite(maxPerWeek) || maxPerWeek < 0)) { + toast.error('Max bookings per week cannot be negative.'); + return; + } if (routingMode === 'round_robin' && rotationHosts.length === 0) { toast.error(tr('eventTypeEditor.validation.rotation')); return; } @@ -405,6 +419,8 @@ min_notice_minutes: Number(form.min_notice_minutes), max_future_days: Number(form.max_future_days), max_active_bookings: Number(form.max_active_bookings), + max_per_day: maxPerDay === 0 ? null : maxPerDay, + max_per_week: maxPerWeek === 0 ? null : maxPerWeek, price_cents: Math.max(0, Math.round(Number(priceMajor) * 100)) || 0, currency: form.currency.trim().toLowerCase() || 'usd', routing_mode: routingMode, @@ -895,6 +911,20 @@

{$t('eventTypeEditor.scheduling.maxActiveHint')}

+
+

Frequency Caps

+

Limit total confirmed bookings for this event type in your timezone. Leave blank or 0 for unlimited.

+
+
+ + +
+
+ + +
+
+
diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte index 00f354e3..90395356 100644 --- a/frontend/src/routes/login/+page.svelte +++ b/frontend/src/routes/login/+page.svelte @@ -30,6 +30,8 @@ oauth: $t('auth.login.oauth.oauth'), userinfo: $t('auth.login.oauth.userinfo'), no_account: $t('auth.login.oauth.noAccount'), + forbidden: 'Access denied. Your email domain is not authorized for this workspace.', + domain_not_allowed: 'Access denied. Your email domain is not authorized for this workspace.', archived: $t('auth.login.oauth.archived'), session: $t('auth.login.oauth.session'), link: $t('auth.login.oauth.link') @@ -66,7 +68,11 @@ window.location.href = '/admin'; } else { const data = await res.json().catch(() => ({})); - loginError = data.error || tr('auth.login.error.loginFailed'); + if (res.status === 403) { + loginError = data.error || 'Access denied. Your account or email domain is not authorized.'; + } else { + loginError = data.error || tr('auth.login.error.loginFailed'); + } } } finally { submitting = false; @@ -135,20 +141,8 @@ {status?.demo_mode ? $t('auth.login.enteringDemo') : $t('auth.login.loading')} {:else} - {#if showGoogle} - - {/if} - {#if showMicrosoft} - {/if} + {#if showGoogle} + + {/if} + {#if showDivider}
diff --git a/internal/booking/booking.go b/internal/booking/booking.go index 1df41ebc..8a0d8d7b 100644 --- a/internal/booking/booking.go +++ b/internal/booking/booking.go @@ -12,6 +12,8 @@ var ( ErrTokenNotFound = errors.New("booking: manage token not found or expired") ErrBookingLimitReached = errors.New("booking: active booking limit reached for this invitee") ErrEmailThrottled = errors.New("booking: too many bookings from this email address") + ErrFrequencyCapReached = errors.New("booking: event type frequency cap reached") + ErrSingleUseTokenGone = errors.New("booking: single-use booking link has expired or has already been used") // ErrHostAlreadyAssigned: a reassign targeted a host who already attends the booking // (e.g. a collective's co-host). Moving the primary seat onto them would collapse two // seats into one, which booking_hosts' UNIQUE(booking_id, user_id) rightly refuses. @@ -110,6 +112,12 @@ type CreateParams struct { // creation transaction, next to the active cap, so concurrent submissions // can't both slip past a read-then-write check. MaxBookingsPerHour int + // MaxPerDay and MaxPerWeek optionally override the event type's daily/weekly + // confirmed booking caps (evaluated in EventTimezone / the owner's IANA timezone). + MaxPerDay *int + MaxPerWeek *int + EventTimezone string + SingleUseToken string // InviteDelivery records who sends the booker's calendar invite for this booking: // InviteByCalendar (the hosts' connected calendars; the default when empty) or // InviteByCalnode (Calnode's own .ics, with the hosts' events created guestless) or diff --git a/internal/booking/caps.go b/internal/booking/caps.go new file mode 100644 index 00000000..55aeb114 --- /dev/null +++ b/internal/booking/caps.go @@ -0,0 +1,161 @@ +package booking + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" +) + +// QueryRower is satisfied by both *sql.DB and *sql.Tx. +type QueryRower interface { + QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row +} + +// ISOWeek identifies an ISO 8601 week (Monday-Sunday). +type ISOWeek struct { + Year int + Week int +} + +// FrequencyCounts holds confirmed booking counts bucketed by local calendar date +// ("2006-01-02") and local ISO week. +type FrequencyCounts struct { + ByDay map[string]int + ByWeek map[ISOWeek]int +} + +// Exceeded reports whether adding a booking at instant `at` in `loc` would meet or +// exceed either configured frequency cap. +func (c FrequencyCounts) Exceeded(at time.Time, loc *time.Location, maxPerDay, maxPerWeek *int) bool { + if loc == nil { + loc = time.UTC + } + local := at.In(loc) + if maxPerDay != nil && *maxPerDay > 0 { + if c.ByDay[local.Format("2006-01-02")] >= *maxPerDay { + return true + } + } + if maxPerWeek != nil && *maxPerWeek > 0 { + y, w := local.ISOWeek() + if c.ByWeek[ISOWeek{Year: y, Week: w}] >= *maxPerWeek { + return true + } + } + return false +} + +// LoadLocationOrUTC resolves an IANA timezone name, falling back to UTC on empty or invalid input. +func LoadLocationOrUTC(ianaTZ string) *time.Location { + if ianaTZ == "" { + return time.UTC + } + loc, err := time.LoadLocation(ianaTZ) + if err != nil || loc == nil { + return time.UTC + } + return loc +} + +// ISOWeekWindow returns the UTC [start, end) bounds of the Monday-Sunday ISO week +// containing `at` when evaluated in `loc`. +func ISOWeekWindow(at time.Time, loc *time.Location) (time.Time, time.Time) { + if loc == nil { + loc = time.UTC + } + local := at.In(loc) + dayMidnight := time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, loc) + // Go Weekday(): Sunday=0, Monday=1, ..., Saturday=6. Shift so Monday=0..Sunday=6. + wd := (int(local.Weekday()) + 6) % 7 + weekStart := dayMidnight.AddDate(0, 0, -wd) + weekEnd := weekStart.AddDate(0, 0, 7) + return weekStart.UTC(), weekEnd.UTC() +} + +// CountFrequencyBookings counts all non-cancelled bookings for eventTypeID whose start_at +// falls near [rangeStartUTC, rangeEndUTC) (padded cleanly so timezone conversions never miss +// boundary events) and buckets them into loc's calendar days and ISO weeks. +func CountFrequencyBookings(ctx context.Context, q QueryRower, eventTypeID string, rangeStartUTC, rangeEndUTC time.Time, loc *time.Location) (FrequencyCounts, error) { + if loc == nil { + loc = time.UTC + } + counts := FrequencyCounts{ + ByDay: make(map[string]int), + ByWeek: make(map[ISOWeek]int), + } + padStart := rangeStartUTC.UTC().Add(-24 * time.Hour).Format(time.RFC3339) + padEnd := rangeEndUTC.UTC().Add(24 * time.Hour).Format(time.RFC3339) + + rows, err := q.QueryContext(ctx, ` + SELECT start_at FROM bookings + WHERE event_type_id = ? + AND status != 'cancelled' + AND datetime(start_at) >= datetime(?) + AND datetime(start_at) < datetime(?)`, + eventTypeID, padStart, padEnd) + if err != nil { + return counts, err + } + defer rows.Close() + + for rows.Next() { + var raw string + if err := rows.Scan(&raw); err != nil { + return counts, err + } + t, err := time.Parse(time.RFC3339Nano, raw) + if err != nil { + continue + } + local := t.In(loc) + counts.ByDay[local.Format("2006-01-02")]++ + y, w := local.ISOWeek() + counts.ByWeek[ISOWeek{Year: y, Week: w}]++ + } + return counts, rows.Err() +} + +func enforceFrequencyCaps(ctx context.Context, tx *sql.Tx, p CreateParams) error { + var dbDay, dbWeek sql.NullInt64 + var dbTZ string + err := tx.QueryRowContext(ctx, ` + SELECT et.max_per_day, et.max_per_week, COALESCE(u.iana_timezone, 'UTC') + FROM event_types et + LEFT JOIN users u ON u.id = et.user_id + WHERE et.id = ?`, p.EventTypeID).Scan(&dbDay, &dbWeek, &dbTZ) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("booking: load frequency caps: %w", err) + } + + maxPerDay := p.MaxPerDay + if maxPerDay == nil && dbDay.Valid { + v := int(dbDay.Int64) + maxPerDay = &v + } + maxPerWeek := p.MaxPerWeek + if maxPerWeek == nil && dbWeek.Valid { + v := int(dbWeek.Int64) + maxPerWeek = &v + } + if (maxPerDay == nil || *maxPerDay <= 0) && (maxPerWeek == nil || *maxPerWeek <= 0) { + return nil + } + + tzName := p.EventTimezone + if tzName == "" { + tzName = dbTZ + } + loc := LoadLocationOrUTC(tzName) + weekStart, weekEnd := ISOWeekWindow(p.StartAt, loc) + counts, err := CountFrequencyBookings(ctx, tx, p.EventTypeID, weekStart, weekEnd, loc) + if err != nil { + return fmt.Errorf("booking: frequency cap check: %w", err) + } + if counts.Exceeded(p.StartAt, loc, maxPerDay, maxPerWeek) { + return ErrFrequencyCapReached + } + return nil +} diff --git a/internal/booking/service.go b/internal/booking/service.go index aae6c77d..234cb8f1 100644 --- a/internal/booking/service.go +++ b/internal/booking/service.go @@ -151,6 +151,10 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Booking, error) } } + if err := enforceFrequencyCaps(ctx, tx, p); err != nil { + return nil, err + } + bookingID := uid.New() inviteDelivery := p.InviteDelivery if inviteDelivery == "" { @@ -211,6 +215,27 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Booking, error) } } + if token := strings.TrimSpace(p.SingleUseToken); token != "" { + res, err := tx.ExecContext(ctx, ` + UPDATE single_use_tokens + SET used_at = ?, booking_id = ? + WHERE token = ? + AND event_type_id = ? + AND used_at IS NULL + AND (expires_at IS NULL OR datetime(expires_at) > datetime(?))`, + now, bookingID, token, p.EventTypeID, now) + if err != nil { + return nil, fmt.Errorf("booking: burn single-use token: %w", err) + } + affected, err := res.RowsAffected() + if err != nil { + return nil, fmt.Errorf("booking: burn single-use token rows affected: %w", err) + } + if affected == 0 { + return nil, ErrSingleUseTokenGone + } + } + if err := tx.Commit(); err != nil { return nil, fmt.Errorf("booking: commit: %w", err) } diff --git a/internal/booking/service_test.go b/internal/booking/service_test.go index 9f656a02..bb195b79 100644 --- a/internal/booking/service_test.go +++ b/internal/booking/service_test.go @@ -676,3 +676,91 @@ func TestListByHost_empty(t *testing.T) { t.Errorf("ListByHost empty: got %d bookings; want 0", len(bookings)) } } + +func TestCreate_frequencyCapsDailyAndWeeklyTimezoneAware(t *testing.T) { + database := newTestDB(t) + ctx := context.Background() + svc := booking.New(database) + + hostID := uid.New() + if _, err := database.ExecContext(ctx, ` + INSERT INTO users (id, email, name, iana_timezone) + VALUES (?, ?, 'NY Host', 'America/New_York')`, + hostID, hostID+"@test.com"); err != nil { + t.Fatalf("seed host: %v", err) + } + + etID := uid.New() + if _, err := database.ExecContext(ctx, ` + INSERT INTO event_types (id, user_id, slug, name, duration_minutes, max_per_day, max_per_week) + VALUES (?, ?, ?, 'Capped Call', 30, 1, 2)`, + etID, hostID, etID+"-slug"); err != nil { + t.Fatalf("seed event type: %v", err) + } + + // Monday 2026-06-15 23:00 EDT = Tuesday 2026-06-16 03:00 UTC. + // Counts toward Monday 2026-06-15 in America/New_York. + ny, _ := time.LoadLocation("America/New_York") + monNight := time.Date(2026, 6, 15, 23, 0, 0, 0, ny).UTC() + b1, err := svc.Create(ctx, booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: monNight, + EndAt: monNight.Add(30 * time.Minute), + Organizer: booking.Attendee{Name: "A", Email: "a@example.com"}, + }) + if err != nil { + t.Fatalf("first booking on Monday NY: %v", err) + } + + // Same NY Monday morning (09:00 EDT = 13:00 UTC on 2026-06-15): hits max_per_day=1. + monMorning := time.Date(2026, 6, 15, 9, 0, 0, 0, ny).UTC() + if _, err := svc.Create(ctx, booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: monMorning, + EndAt: monMorning.Add(30 * time.Minute), + Organizer: booking.Attendee{Name: "B", Email: "b@example.com"}, + }); err != booking.ErrFrequencyCapReached { + t.Fatalf("same NY day err = %v; want ErrFrequencyCapReached", err) + } + + // Next NY day (Tuesday 2026-06-16 10:00 EDT = 14:00 UTC): succeeds even though + // b1 was also on 2026-06-16 in UTC! + tueMorning := time.Date(2026, 6, 16, 10, 0, 0, 0, ny).UTC() + if _, err := svc.Create(ctx, booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: tueMorning, + EndAt: tueMorning.Add(30 * time.Minute), + Organizer: booking.Attendee{Name: "C", Email: "c@example.com"}, + }); err != nil { + t.Fatalf("Tuesday NY booking failed unexpectedly: %v", err) + } + + // Wednesday same ISO week: hits max_per_week=2. + wedMorning := time.Date(2026, 6, 17, 10, 0, 0, 0, ny).UTC() + if _, err := svc.Create(ctx, booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: wedMorning, + EndAt: wedMorning.Add(30 * time.Minute), + Organizer: booking.Attendee{Name: "D", Email: "d@example.com"}, + }); err != booking.ErrFrequencyCapReached { + t.Fatalf("Wednesday same week err = %v; want ErrFrequencyCapReached", err) + } + + // Cancelling b1 frees Monday AND lowers weekly count to 1, allowing Wednesday! + if err := svc.CancelByID(ctx, b1.ID, "cancelled by test"); err != nil { + t.Fatalf("cancel b1: %v", err) + } + if _, err := svc.Create(ctx, booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: wedMorning, + EndAt: wedMorning.Add(30 * time.Minute), + Organizer: booking.Attendee{Name: "D", Email: "d@example.com"}, + }); err != nil { + t.Fatalf("Wednesday after cancelling b1: %v", err) + } +} diff --git a/internal/calendar/microsoft/microsoft.go b/internal/calendar/microsoft/microsoft.go index 849dc6d6..23fbc9a5 100644 --- a/internal/calendar/microsoft/microsoft.go +++ b/internal/calendar/microsoft/microsoft.go @@ -54,6 +54,7 @@ func New(db *sql.DB, clientID, clientSecret, tenant, redirectURL, encKeyHex stri if err != nil || len(b) != 32 { return nil, fmt.Errorf("microsoft: invalid encryption key") } + tenant = strings.TrimSpace(tenant) if tenant == "" { tenant = "common" } diff --git a/internal/config/config.go b/internal/config/config.go index 6cb178e3..d9a6a6c2 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -35,10 +35,12 @@ type Config struct { GoogleClientID string GoogleClientSecret string - // Microsoft 365 / Outlook (calendar) — env-only; tenant defaults to "common". + // Microsoft 365 / Outlook (calendar & OAuth login) — env-only; tenant defaults to "common". MicrosoftClientID string MicrosoftClientSecret string MicrosoftTenant string + MicrosoftTenantID string + AllowedSignupDomains []string // Zoom OAuth app (per-host meeting links) — DB settings take priority over these. ZoomClientID string @@ -126,7 +128,9 @@ func Load() *Config { MicrosoftClientID: getEnv("MICROSOFT_CLIENT_ID", ""), MicrosoftClientSecret: getEnv("MICROSOFT_CLIENT_SECRET", ""), - MicrosoftTenant: getEnv("MICROSOFT_TENANT", "common"), + MicrosoftTenant: getEnv("MICROSOFT_TENANT_ID", getEnv("MICROSOFT_TENANT", "common")), + MicrosoftTenantID: getEnv("MICROSOFT_TENANT_ID", getEnv("MICROSOFT_TENANT", "common")), + AllowedSignupDomains: splitCSV(getEnv("ALLOWED_SIGNUP_DOMAINS", "")), ZoomClientID: getEnv("ZOOM_CLIENT_ID", ""), ZoomClientSecret: getEnv("ZOOM_CLIENT_SECRET", ""), diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 4b727c42..879c8e8f 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -208,3 +208,33 @@ func TestValidate_acceptsAPortAndATrailingSlash(t *testing.T) { t.Errorf("Validate() = %v; want nil", err) } } + +func TestLoad_microsoftTenantIDAndAllowedSignupDomains(t *testing.T) { + os.Unsetenv("MICROSOFT_TENANT_ID") + os.Unsetenv("MICROSOFT_TENANT") + os.Unsetenv("ALLOWED_SIGNUP_DOMAINS") + cfg := config.Load() + if cfg.MicrosoftTenantID != "common" { + t.Errorf("MicrosoftTenantID default = %q; want common", cfg.MicrosoftTenantID) + } + if cfg.MicrosoftTenant != "common" { + t.Errorf("MicrosoftTenant default = %q; want common", cfg.MicrosoftTenant) + } + if len(cfg.AllowedSignupDomains) != 0 { + t.Errorf("AllowedSignupDomains default = %v; want empty", cfg.AllowedSignupDomains) + } + + t.Setenv("MICROSOFT_TENANT", "legacy-tenant") + t.Setenv("MICROSOFT_TENANT_ID", "11111111-2222-3333-4444-555555555555") + t.Setenv("ALLOWED_SIGNUP_DOMAINS", "formaprime.vc, example.org ") + cfg = config.Load() + if cfg.MicrosoftTenantID != "11111111-2222-3333-4444-555555555555" { + t.Errorf("MicrosoftTenantID = %q; want MICROSOFT_TENANT_ID", cfg.MicrosoftTenantID) + } + if cfg.MicrosoftTenant != cfg.MicrosoftTenantID { + t.Errorf("MicrosoftTenant = %q; want %q", cfg.MicrosoftTenant, cfg.MicrosoftTenantID) + } + if len(cfg.AllowedSignupDomains) != 2 || cfg.AllowedSignupDomains[0] != "formaprime.vc" || cfg.AllowedSignupDomains[1] != "example.org" { + t.Errorf("AllowedSignupDomains = %v; want [formaprime.vc example.org]", cfg.AllowedSignupDomains) + } +} diff --git a/internal/db/migrations/00072_event_type_frequency_caps.sql b/internal/db/migrations/00072_event_type_frequency_caps.sql new file mode 100644 index 00000000..e0ebbe70 --- /dev/null +++ b/internal/db/migrations/00072_event_type_frequency_caps.sql @@ -0,0 +1,7 @@ +-- +goose Up +-- Nullable per-event-type frequency caps evaluated in the host/event-type timezone. +ALTER TABLE event_types ADD COLUMN max_per_day INTEGER; +ALTER TABLE event_types ADD COLUMN max_per_week INTEGER; + +-- +goose Down +-- Leave additive columns in place, consistent with other column migrations. diff --git a/internal/db/migrations/00073_single_use_tokens.sql b/internal/db/migrations/00073_single_use_tokens.sql new file mode 100644 index 00000000..6eecac45 --- /dev/null +++ b/internal/db/migrations/00073_single_use_tokens.sql @@ -0,0 +1,21 @@ +-- +goose Up +CREATE TABLE IF NOT EXISTS single_use_tokens ( + id TEXT PRIMARY KEY, + token TEXT NOT NULL UNIQUE, + event_type_id TEXT NOT NULL REFERENCES event_types(id) ON DELETE CASCADE, + created_by_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + prefill_name TEXT NOT NULL DEFAULT '', + prefill_email TEXT NOT NULL DEFAULT '', + deal_id TEXT NOT NULL DEFAULT '', + expires_at DATETIME, + used_at DATETIME, + booking_id TEXT, + created_at DATETIME NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_single_use_tokens_event_created + ON single_use_tokens(event_type_id, created_at DESC); + +-- +goose Down +DROP INDEX IF EXISTS idx_single_use_tokens_event_created; +DROP TABLE IF EXISTS single_use_tokens; diff --git a/internal/handler/auth_microsoft.go b/internal/handler/auth_microsoft.go index 817bc557..0d56697a 100644 --- a/internal/handler/auth_microsoft.go +++ b/internal/handler/auth_microsoft.go @@ -16,6 +16,7 @@ import ( // own scopes. Called from server.New when Microsoft credentials are configured. // secure should be true when BASE_URL starts with https://. func (h *Handler) SetMicrosoftAuth(clientID, clientSecret, tenant, redirectURL string, secure bool) { + tenant = strings.TrimSpace(tenant) if tenant == "" { tenant = "common" } diff --git a/internal/handler/auth_microsoft_test.go b/internal/handler/auth_microsoft_test.go index 69626af7..0080a384 100644 --- a/internal/handler/auth_microsoft_test.go +++ b/internal/handler/auth_microsoft_test.go @@ -47,3 +47,42 @@ func TestLoginMicrosoft_setsStateCookieAndRedirects(t *testing.T) { t.Fatal("calnode_oauth_state cookie not set") } } + +func TestLoginMicrosoft_tenantScopedAuthority(t *testing.T) { + t.Run("explicit tenant id", func(t *testing.T) { + h, _, _ := authTestSetup(t) + const tenant = "99999999-aaaa-bbbb-cccc-dddddddddddd" + h.SetMicrosoftAuth("client-id", "client-secret", tenant, "http://localhost/v1/auth/microsoft/callback", false) + + req := httptest.NewRequest(http.MethodGet, "/v1/auth/microsoft/login", nil) + rec := httptest.NewRecorder() + h.LoginMicrosoft(rec, req) + + if rec.Code != http.StatusFound { + t.Fatalf("status = %d; want 302", rec.Code) + } + loc := rec.Header().Get("Location") + wantPrefix := "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/authorize" + if !strings.HasPrefix(loc, wantPrefix) { + t.Errorf("Location = %q; want prefix %q", loc, wantPrefix) + } + }) + + t.Run("empty falls back to common", func(t *testing.T) { + h, _, _ := authTestSetup(t) + h.SetMicrosoftAuth("client-id", "client-secret", "", "http://localhost/v1/auth/microsoft/callback", false) + + req := httptest.NewRequest(http.MethodGet, "/v1/auth/microsoft/login", nil) + rec := httptest.NewRecorder() + h.LoginMicrosoft(rec, req) + + if rec.Code != http.StatusFound { + t.Fatalf("status = %d; want 302", rec.Code) + } + loc := rec.Header().Get("Location") + wantPrefix := "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" + if !strings.HasPrefix(loc, wantPrefix) { + t.Errorf("Location = %q; want prefix %q", loc, wantPrefix) + } + }) +} diff --git a/internal/handler/auth_oauth.go b/internal/handler/auth_oauth.go index bc8f9d05..83b55c55 100644 --- a/internal/handler/auth_oauth.go +++ b/internal/handler/auth_oauth.go @@ -4,7 +4,11 @@ import ( "crypto/rand" "database/sql" "encoding/hex" + "errors" "net/http" + "strings" + + "github.com/calnode/calnode/internal/uid" ) // newOAuthState generates a CSRF state token, sets it as a short-lived cookie, and @@ -46,15 +50,50 @@ func (h *Handler) verifyOAuthState(w http.ResponseWriter, r *http.Request) bool } // finishOAuthLogin resolves an OAuth-verified email to an existing, non-archived -// user and starts a session, redirecting to /admin on success or /admin/login with -// an error otherwise. Self-registration is not allowed — only known emails sign in. +// user and starts a session. When allowedSignupDomains is empty, self-registration +// is blocked and unknown emails redirect to /admin/login?error=no_account. When +// allowedSignupDomains is configured, matching domains auto-provision a "member" +// user and non-matching domains are rejected with 403 Forbidden. func (h *Handler) finishOAuthLogin(w http.ResponseWriter, r *http.Request, email string) { + email = strings.ToLower(strings.TrimSpace(email)) var userID string var archivedAt sql.NullString - if err := h.db.QueryRowContext(r.Context(), - `SELECT id, archived_at FROM users WHERE email = ?`, email).Scan(&userID, &archivedAt); err != nil { - h.logger.WarnContext(r.Context(), "auth: no account for email", "email", email) - http.Redirect(w, r, "/admin/login?error=no_account", http.StatusFound) + err := h.db.QueryRowContext(r.Context(), + `SELECT id, archived_at FROM users WHERE email = ?`, email).Scan(&userID, &archivedAt) + if errors.Is(err, sql.ErrNoRows) { + allowed := h.getAllowedSignupDomains() + if len(allowed) == 0 { + h.logger.WarnContext(r.Context(), "auth: no account for email", "email", email) + http.Redirect(w, r, "/admin/login?error=no_account", http.StatusFound) + return + } + if !emailDomainAllowed(email, allowed) { + h.logger.WarnContext(r.Context(), "auth: email domain not in allowed signup domains", "email", email) + h.writeError(w, http.StatusForbidden, "email domain is not allowed") + return + } + userID = uid.New() + name, _, _ := strings.Cut(email, "@") + if name == "" { + name = email + } + if _, insErr := h.db.ExecContext(r.Context(), ` + INSERT INTO users (id, email, name, iana_timezone, is_admin, is_owner, email_login) + VALUES (?, ?, ?, 'UTC', 0, 0, 0)`, + userID, email, name); insErr != nil { + // Handle concurrent login race if another request inserted the same email first. + if reErr := h.db.QueryRowContext(r.Context(), + `SELECT id, archived_at FROM users WHERE email = ?`, email).Scan(&userID, &archivedAt); reErr != nil { + h.logger.ErrorContext(r.Context(), "auth: auto-provision user", "email", email, "error", insErr) + http.Redirect(w, r, "/admin/login?error=session", http.StatusFound) + return + } + } else { + h.logger.InfoContext(r.Context(), "auth: auto-provisioned member user", "user_id", userID, "email", email) + } + } else if err != nil { + h.logger.ErrorContext(r.Context(), "auth: lookup user", "email", email, "error", err) + http.Redirect(w, r, "/admin/login?error=session", http.StatusFound) return } if archivedAt.Valid { @@ -74,3 +113,16 @@ func (h *Handler) finishOAuthLogin(w http.ResponseWriter, r *http.Request, email } http.Redirect(w, r, "/admin", http.StatusFound) } + +func emailDomainAllowed(email string, allowed []string) bool { + _, domain, ok := strings.Cut(strings.ToLower(strings.TrimSpace(email)), "@") + if !ok || domain == "" { + return false + } + for _, a := range allowed { + if domain == a { + return true + } + } + return false +} diff --git a/internal/handler/auth_oauth_internal_test.go b/internal/handler/auth_oauth_internal_test.go new file mode 100644 index 00000000..5ab56ddc --- /dev/null +++ b/internal/handler/auth_oauth_internal_test.go @@ -0,0 +1,98 @@ +package handler + +import ( + "log/slog" + "net/http" + "net/http/httptest" + "testing" + + "github.com/calnode/calnode/internal/db" +) + +func newInternalHandler(t *testing.T) *Handler { + t.Helper() + database, err := db.Open("sqlite://:memory:") + if err != nil { + t.Fatalf("db.Open: %v", err) + } + if err := db.Migrate(database); err != nil { + t.Fatalf("db.Migrate: %v", err) + } + t.Cleanup(func() { database.Close() }) + return New(database, slog.Default()) +} + +func TestFinishOAuthLogin_allowedSignupDomainsJITProvisioning(t *testing.T) { + t.Run("empty allowed domains preserves default redirect", func(t *testing.T) { + h := newInternalHandler(t) + req := httptest.NewRequest(http.MethodGet, "/v1/auth/microsoft/callback", nil) + rec := httptest.NewRecorder() + + h.finishOAuthLogin(rec, req, "newuser@formaprime.vc") + if rec.Code != http.StatusFound { + t.Fatalf("status = %d; want 302", rec.Code) + } + if got := rec.Header().Get("Location"); got != "/admin/login?error=no_account" { + t.Errorf("Location = %q; want /admin/login?error=no_account", got) + } + }) + + t.Run("matching domain provisions member and creates session", func(t *testing.T) { + h := newInternalHandler(t) + h.SetAllowedSignupDomains([]string{"FormaPrime.VC"}) + + req := httptest.NewRequest(http.MethodGet, "/v1/auth/microsoft/callback", nil) + rec := httptest.NewRecorder() + h.finishOAuthLogin(rec, req, "Partner@formaprime.vc") + + if rec.Code != http.StatusFound { + t.Fatalf("status = %d; want 302 — body: %s", rec.Code, rec.Body.String()) + } + if got := rec.Header().Get("Location"); got != "/admin" { + t.Errorf("Location = %q; want /admin", got) + } + + var hasSession bool + for _, c := range rec.Result().Cookies() { + if c.Name == sessionCookieName && c.Value != "" { + hasSession = true + } + } + if !hasSession { + t.Fatal("expected calnode_session cookie after JIT provisioning") + } + + var name string + var isAdmin, isOwner int + if err := h.db.QueryRow(`SELECT name, is_admin, is_owner FROM users WHERE email = ?`, "partner@formaprime.vc"). + Scan(&name, &isAdmin, &isOwner); err != nil { + t.Fatalf("query provisioned user: %v", err) + } + if name != "partner" { + t.Errorf("name = %q; want partner", name) + } + if isAdmin != 0 || isOwner != 0 { + t.Errorf("role flags = (%d, %d); want (0, 0) for member", isAdmin, isOwner) + } + }) + + t.Run("non-matching domain returns 403 Forbidden", func(t *testing.T) { + h := newInternalHandler(t) + h.SetAllowedSignupDomains([]string{"formaprime.vc"}) + + req := httptest.NewRequest(http.MethodGet, "/v1/auth/microsoft/callback", nil) + rec := httptest.NewRecorder() + h.finishOAuthLogin(rec, req, "intruder@gmail.com") + + if rec.Code != http.StatusForbidden { + t.Fatalf("status = %d; want 403", rec.Code) + } + var count int + if err := h.db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ?`, "intruder@gmail.com").Scan(&count); err != nil { + t.Fatalf("count users: %v", err) + } + if count != 0 { + t.Errorf("count = %d; want 0 for rejected domain", count) + } + }) +} diff --git a/internal/handler/book.go b/internal/handler/book.go index 3f80ee42..6b24d255 100644 --- a/internal/handler/book.go +++ b/internal/handler/book.go @@ -108,6 +108,18 @@ type bookPageData struct { TermsURL string // operator Terms URL; "" hides the footer link // DemoMode shows the "public demo" banner + a noindex meta tag (see internal/demo). DemoMode bool + // Single-use link token and optional prefill values (empty on normal /book/{slug} pages). + SingleUseToken string + PrefillName string + PrefillEmail string + PrefillDealID string +} + +type bookPrefill struct { + SingleUseToken string + Name string + Email string + DealID string } // hostDisplay is one host's identity for the public booking page. @@ -445,7 +457,22 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) { // BookPage renders the public booking page for a given event type slug. func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { - slug := r.PathValue("slug") + h.renderBookPage(w, r, r.PathValue("slug"), false, bookPrefill{}) +} + +func (h *Handler) renderBookPage(w http.ResponseWriter, r *http.Request, slug string, allowPrivate bool, prefill bookPrefill) { + qp := r.URL.Query() + if qp.Has("name") { + prefill.Name = qp.Get("name") + } + if qp.Has("email") { + prefill.Email = qp.Get("email") + } + if qp.Has("dealId") { + prefill.DealID = qp.Get("dealId") + } else if qp.Has("deal_id") { + prefill.DealID = qp.Get("deal_id") + } var ( etID string @@ -465,15 +492,19 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { allowPhoneCall bool accentColor string ) - err := h.db.QueryRowContext(r.Context(), ` + query := ` SELECT et.id, et.name, COALESCE(et.description, ''), et.duration_minutes, et.location_type, COALESCE(et.location_value, ''), et.max_future_days, et.min_notice_minutes, et.routing_mode, u.name, COALESCE(u.avatar_url, ''), et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent FROM event_types et JOIN users u ON u.id = et.user_id - WHERE et.slug = ? AND et.is_active = 1 AND et.is_public = 1`, - slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor) + WHERE et.slug = ? AND et.is_active = 1` + if !allowPrivate { + query += ` AND et.is_public = 1` + } + err := h.db.QueryRowContext(r.Context(), query, slug). + Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor) if errors.Is(err, sql.ErrNoRows) { http.Error(w, "Page not found", http.StatusNotFound) @@ -579,9 +610,13 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { LogoOpacity: opacityCSS(brand.LogoOpacity), BannerURL: brand.BannerURL, BannerOpacity: opacityCSS(brand.BannerOpacity), - PrivacyURL: brand.PrivacyURL, - TermsURL: brand.TermsURL, - DemoMode: h.demoMode, + PrivacyURL: brand.PrivacyURL, + TermsURL: brand.TermsURL, + DemoMode: h.demoMode, + SingleUseToken: prefill.SingleUseToken, + PrefillName: prefill.Name, + PrefillEmail: prefill.Email, + PrefillDealID: prefill.DealID, } h.persistLangOverride(w, r) diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index f7a09f26..307ecf55 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -503,6 +503,9 @@ type bookableEventType struct { MinNoticeMinutes int MaxFutureDays int MaxActiveBookings int + MaxPerDay *int + MaxPerWeek *int + OwnerTimezone string PriceCents int Currency string // ShowTakenSlots opts this event type into returning the starts a booking removed, @@ -520,24 +523,33 @@ type bookableEventType struct { // BookPage), so an operator who unpublishes an event type stops it from being bookable // everywhere, not just hidden from its own page. func (h *Handler) loadBookableEventType(ctx context.Context, slug string) (*bookableEventType, error) { + return h.loadBookableEventTypeWithVisibility(ctx, slug, false) +} + +func (h *Handler) loadBookableEventTypeWithVisibility(ctx context.Context, slug string, allowPrivate bool) (*bookableEventType, error) { var et bookableEventType var isActive, isPublic, showTaken int + var maxPerDay, maxPerWeek sql.NullInt64 err := h.db.QueryRowContext(ctx, ` - SELECT id, user_id, name, duration_minutes, slot_interval_minutes, - location_type, location_value, allow_phone_call, routing_mode, rr_strategy, - buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, - is_active, is_public, show_taken_slots, max_active_bookings, price_cents, currency, - invite_delivery - FROM event_types WHERE slug = ?`, slug). + SELECT et.id, et.user_id, et.name, et.duration_minutes, et.slot_interval_minutes, + et.location_type, et.location_value, et.allow_phone_call, et.routing_mode, et.rr_strategy, + et.buffer_before_minutes, et.buffer_after_minutes, et.min_notice_minutes, et.max_future_days, + et.is_active, et.is_public, et.show_taken_slots, et.max_active_bookings, et.price_cents, et.currency, + et.invite_delivery, et.max_per_day, et.max_per_week, COALESCE(u.iana_timezone, 'UTC') + FROM event_types et + LEFT JOIN users u ON u.id = et.user_id + WHERE et.slug = ?`, slug). Scan(&et.ID, &et.UserID, &et.Name, &et.DurationMinutes, &et.SlotIntervalMinutes, &et.LocationType, &et.LocationValue, &et.AllowPhoneCall, &et.RoutingMode, &et.RRStrategy, &et.BufferBeforeMinutes, &et.BufferAfterMinutes, &et.MinNoticeMinutes, &et.MaxFutureDays, &isActive, &isPublic, &showTaken, &et.MaxActiveBookings, &et.PriceCents, &et.Currency, - &et.InviteDelivery) - if err != nil || isActive == 0 || isPublic == 0 { + &et.InviteDelivery, &maxPerDay, &maxPerWeek, &et.OwnerTimezone) + if err != nil || isActive == 0 || (!allowPrivate && isPublic == 0) { return nil, errEventTypeNotFound } et.ShowTakenSlots = showTaken != 0 + et.MaxPerDay = nullIntPtr(maxPerDay) + et.MaxPerWeek = nullIntPtr(maxPerWeek) return &et, nil } @@ -615,6 +627,9 @@ func (h *Handler) createBookingForSlug(ctx context.Context, slug string, startAt Answers: answers, MaxActivePerInvitee: et.MaxActiveBookings, MaxBookingsPerHour: maxBookingsPerEmailPerHour, + MaxPerDay: et.MaxPerDay, + MaxPerWeek: et.MaxPerWeek, + EventTimezone: et.OwnerTimezone, InviteDelivery: et.InviteDelivery, }) if err != nil { @@ -764,8 +779,9 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) { // Deliberately NOT named "company": browsers map that to the organization // autofill entry (ignoring autocomplete="off") and fill this invisible field // for real humans, who are then rejected as bots (#33). - Honeypot string `json:"hp_extra"` - Answers []struct { + Honeypot string `json:"hp_extra"` + SingleUseToken string `json:"single_use_token"` + Answers []struct { QuestionID string `json:"question_id"` Value string `json:"value"` } `json:"answers"` @@ -856,7 +872,8 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) { return } - et, err := h.loadBookableEventType(r.Context(), req.EventTypeSlug) + singleUseToken := strings.TrimSpace(req.SingleUseToken) + et, err := h.loadBookableEventTypeWithVisibility(r.Context(), req.EventTypeSlug, singleUseToken != "") if err != nil { h.writeError(w, http.StatusNotFound, "event type not found") return @@ -962,9 +979,21 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) { Answers: answers, MaxActivePerInvitee: et.MaxActiveBookings, MaxBookingsPerHour: maxBookingsPerEmailPerHour, + MaxPerDay: et.MaxPerDay, + MaxPerWeek: et.MaxPerWeek, + EventTimezone: et.OwnerTimezone, + SingleUseToken: singleUseToken, InviteDelivery: et.InviteDelivery, }) if err != nil { + if errors.Is(err, booking.ErrSingleUseTokenGone) { + h.writeError(w, http.StatusGone, "This booking link has expired or has already been used") + return + } + if errors.Is(err, booking.ErrFrequencyCapReached) { + h.writeError(w, http.StatusConflict, "daily or weekly booking limit reached for this event type") + return + } if errors.Is(err, booking.ErrDoubleBooked) { h.writeError(w, http.StatusConflict, "this slot is no longer available") return diff --git a/internal/handler/event_type.go b/internal/handler/event_type.go index dc8eff8e..99e90ab1 100644 --- a/internal/handler/event_type.go +++ b/internal/handler/event_type.go @@ -1,6 +1,7 @@ package handler import ( + "bytes" "context" "database/sql" "encoding/json" @@ -37,6 +38,8 @@ type eventTypeJSON struct { MinNoticeMinutes int `json:"min_notice_minutes"` MaxFutureDays int `json:"max_future_days"` MaxActiveBookings int `json:"max_active_bookings"` + MaxPerDay *int `json:"max_per_day"` + MaxPerWeek *int `json:"max_per_week"` IsActive bool `json:"is_active"` // ShowTakenSlots renders already-booked times greyed out on the booking page // instead of omitting them. Off by default: the slots endpoint is public, so this @@ -106,6 +109,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { var et eventTypeJSON var desc, locVal, msgConf, msgCancel, msgResched, msgRemind, msgGreeting sql.NullString var subjConf, subjCancel, subjResched, subjRemind sql.NullString + var maxPerDay, maxPerWeek sql.NullInt64 var isActive, isPublic, showTaken int dests := []any{ @@ -119,6 +123,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { &msgConf, &msgCancel, &msgResched, &msgRemind, &msgGreeting, &subjConf, &subjCancel, &subjResched, &subjRemind, &et.PriceCents, &et.Currency, &et.InviteDelivery, &et.DisplayOrder, + &maxPerDay, &maxPerWeek, } dests = append(dests, trailing...) err := s.Scan(dests...) @@ -164,10 +169,54 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { if subjRemind.Valid { et.SubjReminder = &subjRemind.String } + et.MaxPerDay = nullIntPtr(maxPerDay) + et.MaxPerWeek = nullIntPtr(maxPerWeek) et.Reminders = []int{} // initialise to non-nil so JSON encodes as [] not null return &et, nil } +func nullIntPtr(v sql.NullInt64) *int { + if !v.Valid { + return nil + } + n := int(v.Int64) + return &n +} + +// nullableInt distinguishes an omitted JSON field from an explicit null or integer in PATCH payloads. +type nullableInt struct { + set bool + value *int +} + +func (n *nullableInt) UnmarshalJSON(data []byte) error { + n.set = true + if bytes.Equal(bytes.TrimSpace(data), []byte("null")) { + n.value = nil + return nil + } + var v int + if err := json.Unmarshal(data, &v); err != nil { + return err + } + n.value = &v + return nil +} + +// normalizeCap normalizes a nullable frequency cap (0 or nil clears to SQL NULL). +func normalizeCap(v *int, field string) (any, string) { + if v == nil { + return nil, "" + } + if *v < 0 { + return nil, field + " cannot be negative (null or 0 = unlimited)" + } + if *v == 0 { + return nil, "" + } + return *v, "" +} + const etColumns = `id, slug, name, description, duration_minutes, slot_interval_minutes, location_type, location_value, allow_phone_call, @@ -177,7 +226,8 @@ const etColumns = `id, slug, name, description, is_active, is_public, show_taken_slots, created_at, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, - price_cents, currency, invite_delivery, display_order` + price_cents, currency, invite_delivery, display_order, + max_per_day, max_per_week` // selectETCols fetches a single event type without the caller-relative columns. const selectETCols = "SELECT " + etColumns + " FROM event_types" @@ -280,6 +330,8 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { MinNoticeMinutes *int `json:"min_notice_minutes"` MaxFutureDays *int `json:"max_future_days"` MaxActiveBookings *int `json:"max_active_bookings"` + MaxPerDay *int `json:"max_per_day"` + MaxPerWeek *int `json:"max_per_week"` AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` InviteDelivery *string `json:"invite_delivery"` @@ -296,6 +348,16 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { h.writeError(w, http.StatusBadRequest, "max_active_bookings cannot be negative (0 = unlimited)") return } + maxPerDayVal, capErr := normalizeCap(req.MaxPerDay, "max_per_day") + if capErr != "" { + h.writeError(w, http.StatusBadRequest, capErr) + return + } + maxPerWeekVal, capErr := normalizeCap(req.MaxPerWeek, "max_per_week") + if capErr != "" { + h.writeError(w, http.StatusBadRequest, capErr) + return + } if req.DurationMinutes <= 0 { h.writeError(w, http.StatusBadRequest, "duration_minutes must be positive") return @@ -386,12 +448,14 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { slot_interval_minutes, location_type, location_value, allow_phone_call, routing_mode, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, show_taken_slots, invite_delivery, - msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, display_order) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, display_order, + max_per_day, max_per_week) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, user.ID, req.Slug, req.Name, req.Description, req.DurationMinutes, slotInterval, locType, req.LocationValue, req.AllowPhoneCall != nil && *req.AllowPhoneCall, routingMode, bufBefore, bufAfter, minNotice, maxFuture, maxActive, showTaken, inviteDelivery, - defaultMsgConfirmation, defaultMsgCancellation, defaultMsgReschedule, defaultMsgReminder, req.DisplayOrder) + defaultMsgConfirmation, defaultMsgCancellation, defaultMsgReschedule, defaultMsgReminder, req.DisplayOrder, + maxPerDayVal, maxPerWeekVal) if err != nil { if db.IsUniqueViolation(err) { h.writeError(w, http.StatusConflict, "slug already in use") @@ -513,10 +577,12 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { RRStrategy *string `json:"rr_strategy"` BufferBeforeMinutes *int `json:"buffer_before_minutes"` BufferAfterMinutes *int `json:"buffer_after_minutes"` - MinNoticeMinutes *int `json:"min_notice_minutes"` - MaxFutureDays *int `json:"max_future_days"` - MaxActiveBookings *int `json:"max_active_bookings"` - IsActive *bool `json:"is_active"` + MinNoticeMinutes *int `json:"min_notice_minutes"` + MaxFutureDays *int `json:"max_future_days"` + MaxActiveBookings *int `json:"max_active_bookings"` + MaxPerDay nullableInt `json:"max_per_day"` + MaxPerWeek nullableInt `json:"max_per_week"` + IsActive *bool `json:"is_active"` IsPublic *bool `json:"is_public"` AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` @@ -633,6 +699,22 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { } set("max_active_bookings", *req.MaxActiveBookings) } + if req.MaxPerDay.set { + v, capErr := normalizeCap(req.MaxPerDay.value, "max_per_day") + if capErr != "" { + h.writeError(w, http.StatusBadRequest, capErr) + return + } + set("max_per_day", v) + } + if req.MaxPerWeek.set { + v, capErr := normalizeCap(req.MaxPerWeek.value, "max_per_week") + if capErr != "" { + h.writeError(w, http.StatusBadRequest, capErr) + return + } + set("max_per_week", v) + } if req.PriceCents != nil { if *req.PriceCents < 0 { h.writeError(w, http.StatusBadRequest, "price_cents cannot be negative (0 = free)") diff --git a/internal/handler/event_type_duplicate.go b/internal/handler/event_type_duplicate.go index a4d7bff9..ae165c7b 100644 --- a/internal/handler/event_type_duplicate.go +++ b/internal/handler/event_type_duplicate.go @@ -143,7 +143,8 @@ func (h *Handler) DuplicateEventType(w http.ResponseWriter, r *http.Request) { is_active, is_public, show_taken_slots, archived_at, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, - price_cents, currency, invite_delivery, display_order) + price_cents, currency, invite_delivery, display_order, + max_per_day, max_per_week) SELECT ?, user_id, team_id, ?, name, description, duration_minutes, slot_interval_minutes, @@ -154,7 +155,8 @@ func (h *Handler) DuplicateEventType(w http.ResponseWriter, r *http.Request) { 0, is_public, show_taken_slots, NULL, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, - price_cents, currency, invite_delivery, display_order + price_cents, currency, invite_delivery, display_order, + max_per_day, max_per_week FROM event_types WHERE id = ?`, newID, newSlug, srcID); err != nil { h.logger.ErrorContext(r.Context(), "duplicate event type: copy row", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") diff --git a/internal/handler/event_type_duplicate_test.go b/internal/handler/event_type_duplicate_test.go index 581aef3d..7553383c 100644 --- a/internal/handler/event_type_duplicate_test.go +++ b/internal/handler/event_type_duplicate_test.go @@ -606,6 +606,8 @@ func TestDuplicateEventType_handlesEveryEventTypeColumn(t *testing.T) { "price_cents": true, "currency": true, "invite_delivery": true, "display_order": true, + "max_per_day": true, + "max_per_week": true, } // Deliberately not inherited, with the reason. notInherited := map[string]string{ diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 05898e14..d1e71697 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "log/slog" "net/http" + "strings" "sync" "time" @@ -36,10 +37,11 @@ type Handler struct { baseURL string publicBaseURL string dataDir string - authMu sync.RWMutex - googleAuth *oauth2.Config - microsoftAuth *oauth2.Config - secureCookie bool + authMu sync.RWMutex + googleAuth *oauth2.Config + microsoftAuth *oauth2.Config + allowedSignupDomains []string + secureCookie bool llmMu sync.RWMutex llm *llm.Client // nil when the optional LLM layer is off/unconfigured zoomMu sync.RWMutex @@ -237,6 +239,33 @@ func (h *Handler) getMicrosoftAuth() *oauth2.Config { return h.microsoftAuth } +// SetAllowedSignupDomains configures the email domains permitted to auto-provision +// member accounts on OAuth login (case-insensitive). Empty disables JIT provisioning. +func (h *Handler) SetAllowedSignupDomains(domains []string) { + cleaned := make([]string, 0, len(domains)) + for _, d := range domains { + d = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(d)), "@") + if d != "" { + cleaned = append(cleaned, d) + } + } + h.authMu.Lock() + h.allowedSignupDomains = cleaned + h.authMu.Unlock() +} + +// getAllowedSignupDomains returns a copy of the configured OAuth auto-provisioning domains. +func (h *Handler) getAllowedSignupDomains() []string { + h.authMu.RLock() + defer h.authMu.RUnlock() + if len(h.allowedSignupDomains) == 0 { + return nil + } + out := make([]string, len(h.allowedSignupDomains)) + copy(out, h.allowedSignupDomains) + return out +} + // SetWebhookSvc replaces the default ephemeral-key webhook service with one // backed by the configured encryption key. func (h *Handler) SetWebhookSvc(svc *webhook.Service) { diff --git a/internal/handler/mcp.go b/internal/handler/mcp.go index 855844c3..ae2eb3da 100644 --- a/internal/handler/mcp.go +++ b/internal/handler/mcp.go @@ -90,6 +90,8 @@ type eventTypeBrief struct { DurationMinutes int `json:"duration_minutes"` LocationType string `json:"location_type"` Description string `json:"description,omitempty"` + MaxPerDay *int `json:"max_per_day,omitempty"` + MaxPerWeek *int `json:"max_per_week,omitempty"` } type listEventTypesOut struct { @@ -98,7 +100,7 @@ type listEventTypesOut struct { func (h *Handler) mcpListEventTypes(ctx context.Context, _ *mcp.CallToolRequest, _ listEventTypesIn) (*mcp.CallToolResult, listEventTypesOut, error) { rows, err := h.db.QueryContext(ctx, ` - SELECT slug, name, duration_minutes, location_type, COALESCE(description, '') + SELECT slug, name, duration_minutes, location_type, COALESCE(description, ''), max_per_day, max_per_week FROM event_types WHERE is_active = 1 AND is_public = 1 ORDER BY name`) @@ -109,9 +111,12 @@ func (h *Handler) mcpListEventTypes(ctx context.Context, _ *mcp.CallToolRequest, out := listEventTypesOut{EventTypes: []eventTypeBrief{}} for rows.Next() { var e eventTypeBrief - if err := rows.Scan(&e.ID, &e.Name, &e.DurationMinutes, &e.LocationType, &e.Description); err != nil { + var maxDay, maxWeek sql.NullInt64 + if err := rows.Scan(&e.ID, &e.Name, &e.DurationMinutes, &e.LocationType, &e.Description, &maxDay, &maxWeek); err != nil { return nil, listEventTypesOut{}, fmt.Errorf("list event types: scan: %w", err) } + e.MaxPerDay = nullIntPtr(maxDay) + e.MaxPerWeek = nullIntPtr(maxWeek) out.EventTypes = append(out.EventTypes, e) } return nil, out, rows.Err() @@ -142,6 +147,8 @@ type getEventTypeOut struct { Description string `json:"description,omitempty"` DurationMinutes int `json:"duration_minutes"` LocationType string `json:"location_type"` + MaxPerDay *int `json:"max_per_day,omitempty"` + MaxPerWeek *int `json:"max_per_week,omitempty"` Hosts []eventTypeHostBrief `json:"hosts,omitempty"` Questions []eventTypeQuestion `json:"questions"` } @@ -150,13 +157,16 @@ func (h *Handler) mcpGetEventType(ctx context.Context, _ *mcp.CallToolRequest, i out := getEventTypeOut{ID: in.EventTypeID, Questions: []eventTypeQuestion{}} var etID string var isActive int + var maxDay, maxWeek sql.NullInt64 err := h.db.QueryRowContext(ctx, ` - SELECT id, name, COALESCE(description, ''), duration_minutes, location_type, is_active + SELECT id, name, COALESCE(description, ''), duration_minutes, location_type, is_active, max_per_day, max_per_week FROM event_types WHERE slug = ?`, in.EventTypeID). - Scan(&etID, &out.Name, &out.Description, &out.DurationMinutes, &out.LocationType, &isActive) + Scan(&etID, &out.Name, &out.Description, &out.DurationMinutes, &out.LocationType, &isActive, &maxDay, &maxWeek) if err != nil || isActive == 0 { return nil, getEventTypeOut{}, fmt.Errorf("event type not found: %s", in.EventTypeID) } + out.MaxPerDay = nullIntPtr(maxDay) + out.MaxPerWeek = nullIntPtr(maxWeek) // Intake questions, in form order. Materialize fully before the host queries below // — the single-connection pool can't run a second query while this cursor is open. diff --git a/internal/handler/single_use_handler.go b/internal/handler/single_use_handler.go new file mode 100644 index 00000000..a2379e6c --- /dev/null +++ b/internal/handler/single_use_handler.go @@ -0,0 +1,342 @@ +package handler + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/base64" + "encoding/json" + "errors" + "html" + "io" + "net/http" + "strings" + "time" + + "github.com/calnode/calnode/internal/uid" +) + +const defaultSingleUseExpiryHours = 168 + +type singleUseLinkJSON struct { + ID string `json:"id"` + Token string `json:"token"` + URL string `json:"url"` + EventTypeID string `json:"event_type_id"` + CreatedByUserID string `json:"created_by_user_id"` + PrefillName string `json:"prefill_name"` + PrefillEmail string `json:"prefill_email"` + DealID string `json:"deal_id"` + ExpiresAt *string `json:"expires_at"` + UsedAt *string `json:"used_at"` + BookingID *string `json:"booking_id"` + CreatedAt string `json:"created_at"` +} + +func (h *Handler) singleUseURL(token string) string { + base := strings.TrimRight(h.publicURL(), "/") + if base == "" { + return "/t/" + token + } + return base + "/t/" + token +} + +func (h *Handler) resolveEventTypeForSingleUse(ctx context.Context, idOrSlug string, user AuthUser) (etID, etSlug string, err error) { + isAdmin := 0 + if user.IsAdmin { + isAdmin = 1 + } + err = h.db.QueryRowContext(ctx, ` + SELECT id, slug + FROM event_types + WHERE (id = ? OR slug = ?) + AND (? = 1 OR user_id = ? OR id IN (SELECT event_type_id FROM event_type_hosts WHERE user_id = ?))`, + idOrSlug, idOrSlug, isAdmin, user.ID, user.ID).Scan(&etID, &etSlug) + return etID, etSlug, err +} + +func generateSingleUseToken() (string, error) { + b := make([]byte, 24) + if _, err := rand.Read(b); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// CreateSingleUseLink handles POST /v1/event-types/{id}/single-use-links. +func (h *Handler) CreateSingleUseLink(w http.ResponseWriter, r *http.Request) { + user, ok := userFromContext(r.Context()) + if !ok { + h.writeError(w, http.StatusUnauthorized, "unauthorized") + return + } + idOrSlug := r.PathValue("id") + etID, _, err := h.resolveEventTypeForSingleUse(r.Context(), idOrSlug, user) + if errors.Is(err, sql.ErrNoRows) { + h.writeError(w, http.StatusNotFound, "event type not found") + return + } + if err != nil { + h.logger.ErrorContext(r.Context(), "create single-use link: lookup event type", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + + var req struct { + PrefillName string `json:"prefill_name"` + PrefillEmail string `json:"prefill_email"` + DealID string `json:"deal_id"` + ExpiresInHours *int `json:"expires_in_hours"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) { + h.writeError(w, http.StatusBadRequest, "invalid JSON") + return + } + + expHours := defaultSingleUseExpiryHours + if req.ExpiresInHours != nil { + if *req.ExpiresInHours < 0 { + h.writeError(w, http.StatusBadRequest, "expires_in_hours cannot be negative") + return + } + expHours = *req.ExpiresInHours + } + + token, err := generateSingleUseToken() + if err != nil { + h.logger.ErrorContext(r.Context(), "create single-use link: generate token", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + + id := uid.New() + nowT := time.Now().UTC() + nowStr := nowT.Format(time.RFC3339Nano) + var expiresAtSQL sql.NullString + var expiresAtPtr *string + if expHours > 0 { + expStr := nowT.Add(time.Duration(expHours) * time.Hour).Format(time.RFC3339Nano) + expiresAtSQL = sql.NullString{String: expStr, Valid: true} + expiresAtPtr = &expStr + } + + prefillName := strings.TrimSpace(req.PrefillName) + prefillEmail := strings.TrimSpace(req.PrefillEmail) + dealID := strings.TrimSpace(req.DealID) + + if _, err := h.db.ExecContext(r.Context(), ` + INSERT INTO single_use_tokens + (id, token, event_type_id, created_by_user_id, prefill_name, prefill_email, deal_id, expires_at, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + id, token, etID, user.ID, prefillName, prefillEmail, dealID, expiresAtSQL, nowStr); err != nil { + h.logger.ErrorContext(r.Context(), "create single-use link: insert", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + + h.writeJSON(w, http.StatusCreated, singleUseLinkJSON{ + ID: id, + Token: token, + URL: h.singleUseURL(token), + EventTypeID: etID, + CreatedByUserID: user.ID, + PrefillName: prefillName, + PrefillEmail: prefillEmail, + DealID: dealID, + ExpiresAt: expiresAtPtr, + CreatedAt: nowStr, + }) +} + +// ListSingleUseLinks handles GET /v1/event-types/{id}/single-use-links. +func (h *Handler) ListSingleUseLinks(w http.ResponseWriter, r *http.Request) { + user, ok := userFromContext(r.Context()) + if !ok { + h.writeError(w, http.StatusUnauthorized, "unauthorized") + return + } + idOrSlug := r.PathValue("id") + etID, _, err := h.resolveEventTypeForSingleUse(r.Context(), idOrSlug, user) + if errors.Is(err, sql.ErrNoRows) { + h.writeError(w, http.StatusNotFound, "event type not found") + return + } + if err != nil { + h.logger.ErrorContext(r.Context(), "list single-use links: lookup event type", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + + rows, err := h.db.QueryContext(r.Context(), ` + SELECT id, token, event_type_id, created_by_user_id, prefill_name, prefill_email, deal_id, + expires_at, used_at, booking_id, created_at + FROM single_use_tokens + WHERE event_type_id = ? + ORDER BY created_at DESC`, etID) + if err != nil { + h.logger.ErrorContext(r.Context(), "list single-use links: query", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + defer rows.Close() + + links := []singleUseLinkJSON{} + for rows.Next() { + var item singleUseLinkJSON + var expiresAt, usedAt, bookingID sql.NullString + if err := rows.Scan( + &item.ID, &item.Token, &item.EventTypeID, &item.CreatedByUserID, + &item.PrefillName, &item.PrefillEmail, &item.DealID, + &expiresAt, &usedAt, &bookingID, &item.CreatedAt, + ); err != nil { + h.logger.ErrorContext(r.Context(), "list single-use links: scan", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + item.URL = h.singleUseURL(item.Token) + if expiresAt.Valid { + v := expiresAt.String + item.ExpiresAt = &v + } + if usedAt.Valid { + v := usedAt.String + item.UsedAt = &v + } + if bookingID.Valid { + v := bookingID.String + item.BookingID = &v + } + links = append(links, item) + } + if err := rows.Err(); err != nil { + h.logger.ErrorContext(r.Context(), "list single-use links: rows", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + + h.writeJSON(w, http.StatusOK, map[string]any{"single_use_links": links}) +} + +// RevokeSingleUseLink handles DELETE /v1/single-use-links/{token}. +func (h *Handler) RevokeSingleUseLink(w http.ResponseWriter, r *http.Request) { + user, ok := userFromContext(r.Context()) + if !ok { + h.writeError(w, http.StatusUnauthorized, "unauthorized") + return + } + token := strings.TrimSpace(r.PathValue("token")) + if token == "" { + h.writeError(w, http.StatusNotFound, "single-use link not found") + return + } + + isAdmin := 0 + if user.IsAdmin { + isAdmin = 1 + } + + var eventTypeID string + var usedAt sql.NullString + err := h.db.QueryRowContext(r.Context(), ` + SELECT s.event_type_id, s.used_at + FROM single_use_tokens s + JOIN event_types et ON et.id = s.event_type_id + WHERE s.token = ? + AND (? = 1 OR et.user_id = ? OR s.created_by_user_id = ? + OR et.id IN (SELECT event_type_id FROM event_type_hosts WHERE user_id = ?))`, + token, isAdmin, user.ID, user.ID, user.ID).Scan(&eventTypeID, &usedAt) + if errors.Is(err, sql.ErrNoRows) { + h.writeError(w, http.StatusNotFound, "single-use link not found") + return + } + if err != nil { + h.logger.ErrorContext(r.Context(), "revoke single-use link: lookup", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + if usedAt.Valid { + h.writeError(w, http.StatusConflict, "single-use link has already been used") + return + } + + res, err := h.db.ExecContext(r.Context(), + `DELETE FROM single_use_tokens WHERE token = ? AND used_at IS NULL`, token) + if err != nil { + h.logger.ErrorContext(r.Context(), "revoke single-use link: delete", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + n, _ := res.RowsAffected() + if n == 0 { + h.writeError(w, http.StatusConflict, "single-use link has already been used") + return + } + w.WriteHeader(http.StatusNoContent) +} + +// SingleUseBookPage handles GET /t/{token} by validating the ephemeral link and +// rendering the event type booking page prefilled for that token. +func (h *Handler) SingleUseBookPage(w http.ResponseWriter, r *http.Request) { + token := strings.TrimSpace(r.PathValue("token")) + if token == "" { + writeSingleUseGonePage(w) + return + } + + var ( + slug string + isActive int + prefillName string + prefillMail string + dealID string + expiresAt sql.NullString + usedAt sql.NullString + ) + err := h.db.QueryRowContext(r.Context(), ` + SELECT et.slug, et.is_active, s.prefill_name, s.prefill_email, s.deal_id, + s.expires_at, s.used_at + FROM single_use_tokens s + JOIN event_types et ON et.id = s.event_type_id + WHERE s.token = ?`, token). + Scan(&slug, &isActive, &prefillName, &prefillMail, &dealID, &expiresAt, &usedAt) + if errors.Is(err, sql.ErrNoRows) { + writeSingleUseGonePage(w) + return + } + if err != nil { + h.logger.ErrorContext(r.Context(), "single-use book page: lookup", "error", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + if isActive == 0 || usedAt.Valid { + writeSingleUseGonePage(w) + return + } + if expiresAt.Valid && expiresAt.String != "" { + expT, parseErr := time.Parse(time.RFC3339Nano, expiresAt.String) + if parseErr != nil { + expT, parseErr = time.Parse(time.RFC3339, expiresAt.String) + } + if parseErr != nil || !expT.After(time.Now().UTC()) { + writeSingleUseGonePage(w) + return + } + } + + h.renderBookPage(w, r, slug, true, bookPrefill{ + SingleUseToken: token, + Name: prefillName, + Email: prefillMail, + DealID: dealID, + }) +} + +func writeSingleUseGonePage(w http.ResponseWriter) { + const msg = "This booking link has expired or has already been used" + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(http.StatusGone) + _, _ = io.WriteString(w, `Link Unavailable

Booking Link Unavailable

`+html.EscapeString(msg)+`

`) +} diff --git a/internal/handler/single_use_test.go b/internal/handler/single_use_test.go new file mode 100644 index 00000000..d1f17917 --- /dev/null +++ b/internal/handler/single_use_test.go @@ -0,0 +1,329 @@ +package handler_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func seedAvailabilityWindow(t *testing.T, h interface { + RequireAuth(http.HandlerFunc) http.HandlerFunc + CreateAvailabilityRule(http.ResponseWriter, *http.Request) +}, apiKey string, weekday int, startTime, endTime string) { + t.Helper() + body := fmt.Sprintf(`{"day_of_week":%d,"start_time":%q,"end_time":%q}`, weekday, startTime, endTime) + req := authReq(http.MethodPost, "/v1/availability-rules", body, apiKey) + rec := httptest.NewRecorder() + h.RequireAuth(h.CreateAvailabilityRule)(rec, req) + if rec.Code != http.StatusCreated && rec.Code != http.StatusOK { + t.Fatalf("seed availability rule: %d — %s", rec.Code, rec.Body.String()) + } +} + +func TestEventTypeFrequencyCaps_slotsFilteringAnd409Conflict(t *testing.T) { + h, database, apiKey, userID := setupWorkspaceWithDB(t) + h.SetBaseURL("https://cal.formaprime.vc") + ctx := context.Background() + + // Configure host timezone to America/New_York. + if _, err := database.ExecContext(ctx, `UPDATE users SET iana_timezone = 'America/New_York' WHERE id = ?`, userID); err != nil { + t.Fatalf("set user tz: %v", err) + } + + // Pick a future Monday and Tuesday > 7 days from now. + targetDay := time.Now().UTC().Truncate(24*time.Hour).AddDate(0, 0, 10) + for targetDay.Weekday() != time.Monday { + targetDay = targetDay.AddDate(0, 0, 1) + } + tuesday := targetDay.AddDate(0, 0, 1) + nextMonday := targetDay.AddDate(0, 0, 7) + + // Open Monday (1) and Tuesday (2) 09:00-17:00 NY time. + seedAvailabilityWindow(t, h, apiKey, 1, "09:00", "17:00") + seedAvailabilityWindow(t, h, apiKey, 2, "09:00", "17:00") + + // Create event type with max_per_day=1, max_per_week=1. + createBody := `{ + "slug": "founder-intro", + "name": "Founder Intro", + "duration_minutes": 60, + "max_future_days": 0, + "max_per_day": 1, + "max_per_week": 1 + }` + req := authReq(http.MethodPost, "/v1/event-types", createBody, apiKey) + rec := httptest.NewRecorder() + h.RequireAuth(h.CreateEventType)(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("CreateEventType: %d — %s", rec.Code, rec.Body.String()) + } + var etResp map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &etResp); err != nil { + t.Fatalf("decode event type: %v", err) + } + if etResp["max_per_day"] != float64(1) || etResp["max_per_week"] != float64(1) { + t.Fatalf("unexpected caps in CreateEventType response: day=%v week=%v", etResp["max_per_day"], etResp["max_per_week"]) + } + + // Book one slot on Monday 14:00 UTC (10:00 EDT / 09:00 EST). + monSlot := time.Date(targetDay.Year(), targetDay.Month(), targetDay.Day(), 14, 0, 0, 0, time.UTC) + bookBody := fmt.Sprintf(`{ + "event_type_slug": "founder-intro", + "start_at": %q, + "name": "Alice Founder", + "email": "alice@startup.io", + "timezone": "America/New_York" + }`, monSlot.Format(time.RFC3339)) + bReq := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(bookBody)) + bReq.Header.Set("Content-Type", "application/json") + bRec := httptest.NewRecorder() + h.CreateBooking(bRec, bReq) + if bRec.Code != http.StatusCreated { + t.Fatalf("first booking: %d — %s", bRec.Code, bRec.Body.String()) + } + + // Direct booking on Tuesday in the SAME ISO week must fail with 409 Conflict due to max_per_week=1. + tueSlot := time.Date(tuesday.Year(), tuesday.Month(), tuesday.Day(), 14, 0, 0, 0, time.UTC) + tueBody := fmt.Sprintf(`{ + "event_type_slug": "founder-intro", + "start_at": %q, + "name": "Bob Founder", + "email": "bob@startup.io", + "timezone": "America/New_York" + }`, tueSlot.Format(time.RFC3339)) + tueReq := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(tueBody)) + tueReq.Header.Set("Content-Type", "application/json") + tueRec := httptest.NewRecorder() + h.CreateBooking(tueRec, tueReq) + if tueRec.Code != http.StatusConflict { + t.Fatalf("capped Tuesday booking status = %d; want 409 — %s", tueRec.Code, tueRec.Body.String()) + } + + // GetSlots over Mon..Tue (same ISO week) + next Monday (new ISO week): + // capped week slots must be excluded while next Monday stays available. + sReq := httptest.NewRequest(http.MethodGet, + fmt.Sprintf("/v1/event-types/founder-intro/slots?from=%s&to=%s&tz=America/New_York", + targetDay.Format("2006-01-02"), nextMonday.Format("2006-01-02")), + nil) + sReq.SetPathValue("slug", "founder-intro") + sRec := httptest.NewRecorder() + h.GetSlots(sRec, sReq) + if sRec.Code != http.StatusOK { + t.Fatalf("GetSlots: %d — %s", sRec.Code, sRec.Body.String()) + } + var sResp struct { + Slots []struct { + Start string `json:"start"` + } `json:"slots"` + } + if err := json.Unmarshal(sRec.Body.Bytes(), &sResp); err != nil { + t.Fatalf("decode GetSlots: %v", err) + } + ny, _ := time.LoadLocation("America/New_York") + monStr := targetDay.Format("2006-01-02") + tueStr := tuesday.Format("2006-01-02") + nextMonStr := nextMonday.Format("2006-01-02") + var hasNextMon bool + for _, sl := range sResp.Slots { + parsed, err := time.Parse(time.RFC3339, sl.Start) + if err != nil { + t.Fatalf("parse slot start: %v", err) + } + d := parsed.In(ny).Format("2006-01-02") + if d == monStr || d == tueStr { + t.Errorf("unexpected slot on capped week day %s: %s", d, sl.Start) + } + if d == nextMonStr { + hasNextMon = true + } + } + if !hasNextMon { + t.Errorf("expected slots on uncapped next Monday %s, got %d slots total", nextMonStr, len(sResp.Slots)) + } + + // PATCH max_per_week to null clears it cleanly, restoring Tuesday slots. + pReq := authReq(http.MethodPatch, "/v1/event-types/founder-intro", `{"max_per_week":null}`, apiKey) + pReq.SetPathValue("slug", "founder-intro") + pRec := httptest.NewRecorder() + h.RequireAuth(h.PatchEventType)(pRec, pReq) + if pRec.Code != http.StatusOK { + t.Fatalf("PatchEventType null clear: %d — %s", pRec.Code, pRec.Body.String()) + } + var patched map[string]any + _ = json.Unmarshal(pRec.Body.Bytes(), &patched) + if patched["max_per_week"] != nil { + t.Errorf("max_per_week after PATCH null = %v; want nil", patched["max_per_week"]) + } +} + +func TestSingleUseLinks_lifecycleBookReplayAndManageReschedule(t *testing.T) { + h, database, apiKey, _ := setupWorkspaceWithDB(t) + h.SetBaseURL("https://cal.formaprime.vc") + ctx := context.Background() + + // Seed an event type (even make it private to ensure /t/{token} and single_use_token handle private invites cleanly). + slug, etID := seedEventTypeHTTP(t, h, apiKey) + pReq := authReq(http.MethodPatch, "/v1/event-types/"+slug, `{"is_public":false}`, apiKey) + pReq.SetPathValue("slug", slug) + pRec := httptest.NewRecorder() + h.RequireAuth(h.PatchEventType)(pRec, pReq) + if pRec.Code != http.StatusOK { + t.Fatalf("PatchEventType is_public=false: %d", pRec.Code) + } + + targetDay := time.Now().UTC().Truncate(24*time.Hour).AddDate(0, 0, 10) + for i := 0; i < 7; i++ { + seedAvailabilityWindow(t, h, apiKey, i, "08:00", "20:00") + } + + // 1. POST /v1/event-types/{id}/single-use-links + createReq := authReq(http.MethodPost, "/v1/event-types/"+etID+"/single-use-links", `{ + "prefill_name": "Jane Founder", + "prefill_email": "jane@acme.vc", + "deal_id": "deal_123", + "expires_in_hours": 168 + }`, apiKey) + createReq.SetPathValue("id", etID) + createRec := httptest.NewRecorder() + h.RequireAuth(h.CreateSingleUseLink)(createRec, createReq) + if createRec.Code != http.StatusCreated { + t.Fatalf("CreateSingleUseLink: %d — %s", createRec.Code, createRec.Body.String()) + } + var created struct { + ID string `json:"id"` + Token string `json:"token"` + URL string `json:"url"` + } + if err := json.Unmarshal(createRec.Body.Bytes(), &created); err != nil { + t.Fatalf("decode create link: %v", err) + } + if created.Token == "" || created.URL != "https://cal.formaprime.vc/t/"+created.Token { + t.Fatalf("unexpected link response: %+v", created) + } + + // 2. GET /v1/event-types/{id}/single-use-links + listReq := authReq(http.MethodGet, "/v1/event-types/"+etID+"/single-use-links", "", apiKey) + listReq.SetPathValue("id", etID) + listRec := httptest.NewRecorder() + h.RequireAuth(h.ListSingleUseLinks)(listRec, listReq) + if listRec.Code != http.StatusOK || !strings.Contains(listRec.Body.String(), created.Token) { + t.Fatalf("ListSingleUseLinks: %d — %s", listRec.Code, listRec.Body.String()) + } + + // 3. GET /t/{token} renders book.html prefilled + allows URL query param overrides. + pageReq := httptest.NewRequest(http.MethodGet, "/t/"+created.Token+"?name=Override+Name", nil) + pageReq.SetPathValue("token", created.Token) + pageRec := httptest.NewRecorder() + h.SingleUseBookPage(pageRec, pageReq) + if pageRec.Code != http.StatusOK { + t.Fatalf("GET /t/{token}: %d — %s", pageRec.Code, pageRec.Body.String()) + } + htmlBody := pageRec.Body.String() + for _, want := range []string{created.Token, `value="Override Name"`, `value="jane@acme.vc"`, "deal_123"} { + if !strings.Contains(htmlBody, want) { + t.Errorf("GET /t/{token} body missing %q", want) + } + } + + // 4. Book using single_use_token -> creates booking & atomically burns token. + slot1 := time.Date(targetDay.Year(), targetDay.Month(), targetDay.Day(), 10, 0, 0, 0, time.UTC) + bookReq := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(fmt.Sprintf(`{ + "event_type_slug": %q, + "start_at": %q, + "name": "Jane Founder", + "email": "jane@acme.vc", + "timezone": "UTC", + "single_use_token": %q + }`, slug, slot1.Format(time.RFC3339), created.Token))) + bookReq.Header.Set("Content-Type", "application/json") + bookRec := httptest.NewRecorder() + h.CreateBooking(bookRec, bookReq) + if bookRec.Code != http.StatusCreated { + t.Fatalf("CreateBooking with single_use_token: %d — %s", bookRec.Code, bookRec.Body.String()) + } + var booked struct { + ID string `json:"id"` + } + if err := json.Unmarshal(bookRec.Body.Bytes(), &booked); err != nil || booked.ID == "" { + t.Fatalf("decode booking: %v / %s", err, bookRec.Body.String()) + } + + // 5. Replay GET /t/{token} and POST /v1/bookings -> 410 Gone. + replayPageReq := httptest.NewRequest(http.MethodGet, "/t/"+created.Token, nil) + replayPageReq.SetPathValue("token", created.Token) + replayPageRec := httptest.NewRecorder() + h.SingleUseBookPage(replayPageRec, replayPageReq) + if replayPageRec.Code != http.StatusGone { + t.Errorf("replay GET /t/{token} status = %d; want 410", replayPageRec.Code) + } + if !strings.Contains(replayPageRec.Body.String(), "This booking link has expired or has already been used") { + t.Errorf("replay body = %q; want expired/used message", replayPageRec.Body.String()) + } + + slot2 := slot1.Add(2 * time.Hour) + replayBookReq := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(fmt.Sprintf(`{ + "event_type_slug": %q, + "start_at": %q, + "name": "Jane Founder", + "email": "jane@acme.vc", + "timezone": "UTC", + "single_use_token": %q + }`, slug, slot2.Format(time.RFC3339), created.Token))) + replayBookReq.Header.Set("Content-Type", "application/json") + replayBookRec := httptest.NewRecorder() + h.CreateBooking(replayBookRec, replayBookReq) + if replayBookRec.Code != http.StatusGone { + t.Errorf("replay CreateBooking status = %d; want 410 — %s", replayBookRec.Code, replayBookRec.Body.String()) + } + + // 6. Created booking's own /manage/{token} and reschedule continue operating without touching single_use_tokens. + manageToken := issueTestToken(t, database, booked.ID) + mReq := httptest.NewRequest(http.MethodGet, "/manage/"+manageToken, nil) + mReq.SetPathValue("token", manageToken) + mRec := httptest.NewRecorder() + h.ManagePage(mRec, mReq) + if mRec.Code != http.StatusOK { + t.Errorf("GET /manage/{token} status = %d; want 200", mRec.Code) + } + newTime := slot1.Add(4 * time.Hour) + rRec := patchReschedule(t, h, booked.ID, newTime.Format(time.RFC3339), apiKey) + if rRec.Code != http.StatusOK { + t.Fatalf("RescheduleBooking status = %d; want 200 — %s", rRec.Code, rRec.Body.String()) + } + var linkedBookingID string + if err := database.QueryRowContext(ctx, `SELECT booking_id FROM single_use_tokens WHERE token = ?`, created.Token). + Scan(&linkedBookingID); err != nil || linkedBookingID != booked.ID { + t.Errorf("single_use_tokens.booking_id = %q, err=%v; want %q", linkedBookingID, err, booked.ID) + } + + // 7. Create a second unused token, DELETE /v1/single-use-links/{token} revokes it, then GET /t/{token} returns 410. + c2Req := authReq(http.MethodPost, "/v1/event-types/"+etID+"/single-use-links", `{"expires_in_hours": 1}`, apiKey) + c2Req.SetPathValue("id", etID) + c2Rec := httptest.NewRecorder() + h.RequireAuth(h.CreateSingleUseLink)(c2Rec, c2Req) + var c2 struct { + Token string `json:"token"` + } + _ = json.Unmarshal(c2Rec.Body.Bytes(), &c2) + + delReq := authReq(http.MethodDelete, "/v1/single-use-links/"+c2.Token, "", apiKey) + delReq.SetPathValue("token", c2.Token) + delRec := httptest.NewRecorder() + h.RequireAuth(h.RevokeSingleUseLink)(delRec, delReq) + if delRec.Code != http.StatusNoContent { + t.Fatalf("DELETE /v1/single-use-links/{token} status = %d; want 204 — %s", delRec.Code, delRec.Body.String()) + } + + revokedPageReq := httptest.NewRequest(http.MethodGet, "/t/"+c2.Token, nil) + revokedPageReq.SetPathValue("token", c2.Token) + revokedPageRec := httptest.NewRecorder() + h.SingleUseBookPage(revokedPageRec, revokedPageReq) + if revokedPageRec.Code != http.StatusGone { + t.Errorf("revoked GET /t/{token} status = %d; want 410", revokedPageRec.Code) + } +} diff --git a/internal/handler/slots_handler.go b/internal/handler/slots_handler.go index 83a943bf..14f579a0 100644 --- a/internal/handler/slots_handler.go +++ b/internal/handler/slots_handler.go @@ -2,6 +2,7 @@ package handler import ( "context" + "database/sql" "errors" "fmt" "net/http" @@ -9,6 +10,7 @@ import ( "sync" "time" + "github.com/calnode/calnode/internal/booking" "github.com/calnode/calnode/internal/slots" ) @@ -68,7 +70,7 @@ func (h *Handler) GetSlots(w http.ResponseWriter, r *http.Request) { // when the event type opted in; computeSlots enforces the second half. res, err := h.computeSlots(r.Context(), slug, tzName, r.URL.Query().Get("from"), r.URL.Query().Get("to"), - slotsWanted{Taken: true, NoticeGap: true}) + slotsWanted{Taken: true, NoticeGap: true, SingleUseToken: r.URL.Query().Get("single_use_token")}) switch { case errors.Is(err, errEventTypeNotFound): h.writeError(w, http.StatusNotFound, "event type not found") @@ -153,6 +155,8 @@ type slotsWanted struct { Taken bool // NoticeGap asks which days the minimum-notice rule took a bookable start from. NoticeGap bool + // SingleUseToken optionally authorizes slot visibility for a private (is_public=0) event type. + SingleUseToken string } // computeSlots returns the bookable slots (and the candidate hosts' display map) for @@ -162,6 +166,22 @@ type slotsWanted struct { // of the sentinel errors above on bad input, or a wrapped error on internal failure. func (h *Handler) computeSlots(ctx context.Context, slug, tzName, fromStr, toStr string, want slotsWanted) (slotsResult, error) { et, err := h.loadBookableEventType(ctx, slug) + if errors.Is(err, errEventTypeNotFound) && strings.TrimSpace(want.SingleUseToken) != "" { + if candidate, cErr := h.loadBookableEventTypeWithVisibility(ctx, slug, true); cErr == nil { + var dummy string + if tErr := h.db.QueryRowContext(ctx, ` + SELECT id FROM single_use_tokens + WHERE token = ? AND event_type_id = ? + AND used_at IS NULL + AND (expires_at IS NULL OR datetime(expires_at) > datetime(?))`, + strings.TrimSpace(want.SingleUseToken), candidate.ID, time.Now().UTC().Format(time.RFC3339Nano)).Scan(&dummy); tErr == nil { + et = candidate + err = nil + } else if !errors.Is(tErr, sql.ErrNoRows) { + err = tErr + } + } + } if err != nil { return slotsResult{}, err } @@ -271,6 +291,33 @@ func (h *Handler) computeSlots(ctx context.Context, slug, tzName, fromStr, toStr return slotsResult{}, fmt.Errorf("slots generate: %w", err) } + if (et.MaxPerDay != nil && *et.MaxPerDay > 0) || (et.MaxPerWeek != nil && *et.MaxPerWeek > 0) { + capLoc := booking.LoadLocationOrUTC(et.OwnerTimezone) + rangeStart, _ := booking.ISOWeekWindow(dateFrom, capLoc) + _, rangeEnd := booking.ISOWeekWindow(dateTo.Add(24*time.Hour), capLoc) + if len(result.Free) > 0 { + firstStart, _ := booking.ISOWeekWindow(result.Free[0].Start, capLoc) + if firstStart.Before(rangeStart) { + rangeStart = firstStart + } + _, lastEnd := booking.ISOWeekWindow(result.Free[len(result.Free)-1].Start, capLoc) + if lastEnd.After(rangeEnd) { + rangeEnd = lastEnd + } + } + counts, err := booking.CountFrequencyBookings(ctx, h.db, et.ID, rangeStart, rangeEnd, capLoc) + if err != nil { + return slotsResult{}, fmt.Errorf("count frequency caps: %w", err) + } + filtered := make([]slots.Slot, 0, len(result.Free)) + for _, s := range result.Free { + if !counts.Exceeded(s.Start, capLoc, et.MaxPerDay, et.MaxPerWeek) { + filtered = append(filtered, s) + } + } + result.Free = filtered + } + // Host metadata (name + avatar) for the candidate pool, so the booking page can // show whose face goes with each slot's host_ids (round-robin: the priority pick; // group: every required host). diff --git a/internal/handler/templates/_shared.html b/internal/handler/templates/_shared.html index c4855008..972c5e7c 100644 --- a/internal/handler/templates/_shared.html +++ b/internal/handler/templates/_shared.html @@ -16,11 +16,66 @@ {{define "businessHeader"}} {{if or .LogoURL .BusinessName}}
- {{if .LogoURL}}{{if .BusinessName}}{{.BusinessName}}{{else}}Business logo{{end}}{{else}}{{.BusinessName}}{{end}} + {{if .LogoURL}}{{if .BusinessName}}{{.BusinessName}}{{else}}Business logo{{end}}{{else}}{{.BusinessName}}{{end}}
{{end}} {{end}} +{{define "themeHead"}}{{end}} + +{{define "themeSwitcher"}}
+ + + +
+{{end}} + {{define "trackingHead"}}{{if or .GTMContainerID .GA4MeasurementID}} +
+
+
+ + + {$t('eventTypeEditor.back')} + +

{form.name || et?.name || slug}

+
+ + {#if et && et.can_edit !== false} +
+
+ {form.is_active ? 'Active' : 'Inactive'} + +
+ + + + +
+ {/if}
@@ -634,22 +668,28 @@ {:else} {#if editingForOwner} -
+
{$t('eventTypeEditor.adminEditing.banner', { owner: ownerLabel })}
{/if} -
- {#each TABS as tab} - - {/each} -
+
+ + + + +
{#if activeTab === 'general'} @@ -1283,6 +1323,21 @@
{/if} +
+ + + +
fileInput?.click()} disabled={uploadingFlag.active} title={logoUrl ? $t('settings.branding.logo.replaceTitle') : $t('settings.branding.logo.uploadTitle')} - class="group relative flex min-h-[88px] w-full max-w-md cursor-pointer items-center justify-center overflow-hidden rounded-md border bg-white px-4 py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-wait" + class="group relative flex min-h-[88px] w-full max-w-md cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed border-zinc-300 bg-zinc-50 px-4 py-3 transition-colors hover:border-zinc-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-wait dark:border-zinc-700 dark:bg-zinc-900/60 dark:hover:border-zinc-500" > {#if logoUrl} {$t('settings.branding.logo.alt')} @@ -246,7 +246,7 @@ onclick={() => bannerFileInput?.click()} disabled={uploadingFlag.active} title={bannerUrl ? $t('settings.branding.banner.replaceTitle') : $t('settings.branding.banner.uploadTitle')} - class="group relative flex min-h-[88px] w-full max-w-md cursor-pointer items-center justify-center overflow-hidden rounded-md border bg-white px-4 py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-wait" + class="group relative flex min-h-[88px] w-full max-w-md cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed border-zinc-300 bg-zinc-50 px-4 py-3 transition-colors hover:border-zinc-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-wait dark:border-zinc-700 dark:bg-zinc-900/60 dark:hover:border-zinc-500" > {#if bannerUrl} {$t('settings.branding.banner.alt')} diff --git a/frontend/src/routes/settings/microsoft/+page.svelte b/frontend/src/routes/settings/microsoft/+page.svelte new file mode 100644 index 00000000..2b61fc03 --- /dev/null +++ b/frontend/src/routes/settings/microsoft/+page.svelte @@ -0,0 +1,157 @@ + + +Microsoft OAuth — Settings + +
+
+

Microsoft OAuth

+

+ Configure Microsoft Entra ID (Azure AD) for single sign-on and Microsoft 365 calendar sync. +

+
+ + {#if loading} +

Loading...

+ {:else} +
+
+ Connection Status + + + {configured ? 'Configured' : 'Not configured'} + +
+ +
+
+ + +
+ +
+ + +
+ +
+ + +

+ Leave blank or enter common to allow multi-tenant Microsoft accounts. Enter your Directory (Tenant) ID to restrict SSO to a single Entra ID tenant. +

+
+ +
+ + +

+ Comma-separated list of email domains allowed to auto-provision accounts on Microsoft SSO login. +

+
+ +
+

OAuth Redirect URIs

+
+ {authRedirectUri} + +
+
+ {calRedirectUri} + +
+
+ + +
+
+ {/if} +
diff --git a/internal/db/migrations/00073_single_use_tokens.sql b/internal/db/migrations/00073_single_use_tokens.sql index 6eecac45..3e7972cb 100644 --- a/internal/db/migrations/00073_single_use_tokens.sql +++ b/internal/db/migrations/00073_single_use_tokens.sql @@ -4,9 +4,6 @@ CREATE TABLE IF NOT EXISTS single_use_tokens ( token TEXT NOT NULL UNIQUE, event_type_id TEXT NOT NULL REFERENCES event_types(id) ON DELETE CASCADE, created_by_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - prefill_name TEXT NOT NULL DEFAULT '', - prefill_email TEXT NOT NULL DEFAULT '', - deal_id TEXT NOT NULL DEFAULT '', expires_at DATETIME, used_at DATETIME, booking_id TEXT, diff --git a/internal/db/migrations/00074_microsoft_oauth_settings.sql b/internal/db/migrations/00074_microsoft_oauth_settings.sql new file mode 100644 index 00000000..028ea8b4 --- /dev/null +++ b/internal/db/migrations/00074_microsoft_oauth_settings.sql @@ -0,0 +1,11 @@ +-- +goose Up +ALTER TABLE server_settings ADD COLUMN microsoft_client_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE server_settings ADD COLUMN microsoft_client_secret_enc TEXT NOT NULL DEFAULT ''; +ALTER TABLE server_settings ADD COLUMN microsoft_tenant_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE server_settings ADD COLUMN microsoft_allowed_signup_domains TEXT NOT NULL DEFAULT ''; + +-- +goose Down +ALTER TABLE server_settings DROP COLUMN microsoft_allowed_signup_domains; +ALTER TABLE server_settings DROP COLUMN microsoft_tenant_id; +ALTER TABLE server_settings DROP COLUMN microsoft_client_secret_enc; +ALTER TABLE server_settings DROP COLUMN microsoft_client_id; diff --git a/internal/handler/microsoft_settings.go b/internal/handler/microsoft_settings.go new file mode 100644 index 00000000..3a292c20 --- /dev/null +++ b/internal/handler/microsoft_settings.go @@ -0,0 +1,192 @@ +package handler + +import ( + "database/sql" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/calnode/calnode/internal/calendar/microsoft" + "github.com/calnode/calnode/internal/secret" +) + +// MicrosoftOAuthConfig holds decrypted Microsoft OAuth settings loaded from the DB. +type MicrosoftOAuthConfig struct { + ClientID string + ClientSecret string + TenantID string + AllowedSignupDomains []string +} + +func parseDomainsCSV(raw string) []string { + if strings.TrimSpace(raw) == "" { + return nil + } + var out []string + for _, part := range strings.Split(raw, ",") { + d := strings.TrimSpace(strings.ToLower(part)) + if d != "" { + out = append(out, d) + } + } + return out +} + +// LoadMicrosoftSettingsFromDB reads Microsoft OAuth credentials from server_settings. +// Returns nil (not an error) when microsoft_client_id is empty. +func LoadMicrosoftSettingsFromDB(db *sql.DB, encKey [32]byte) (*MicrosoftOAuthConfig, error) { + var clientID, secretEnc, tenantID, domainsCSV string + err := db.QueryRow(` + SELECT microsoft_client_id, microsoft_client_secret_enc, microsoft_tenant_id, microsoft_allowed_signup_domains + FROM server_settings WHERE id = 1`). + Scan(&clientID, &secretEnc, &tenantID, &domainsCSV) + if err == sql.ErrNoRows || clientID == "" { + return nil, nil + } + if err != nil { + return nil, err + } + var clientSecret string + if secretEnc != "" { + clientSecret, err = secret.Decrypt(encKey, secretEnc) + if err != nil { + return nil, fmt.Errorf("decrypt microsoft client secret: %w", err) + } + } + return &MicrosoftOAuthConfig{ + ClientID: strings.TrimSpace(clientID), + ClientSecret: clientSecret, + TenantID: strings.TrimSpace(tenantID), + AllowedSignupDomains: parseDomainsCSV(domainsCSV), + }, nil +} + +// GetMicrosoftSettings handles GET /v1/settings/microsoft (admin only). +func (h *Handler) GetMicrosoftSettings(w http.ResponseWriter, r *http.Request) { + if _, ok := h.requireAdmin(w, r); !ok { + return + } + var clientID, secretEnc, tenantID, domainsCSV string + err := h.db.QueryRowContext(r.Context(), ` + SELECT microsoft_client_id, microsoft_client_secret_enc, microsoft_tenant_id, microsoft_allowed_signup_domains + FROM server_settings WHERE id = 1`). + Scan(&clientID, &secretEnc, &tenantID, &domainsCSV) + if err != nil && err != sql.ErrNoRows { + h.logger.ErrorContext(r.Context(), "microsoft settings: query", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + h.writeJSON(w, http.StatusOK, map[string]any{ + "client_id": clientID, + "client_secret_set": secretEnc != "", + "tenant_id": tenantID, + "allowed_signup_domains": domainsCSV, + "configured": clientID != "" && secretEnc != "", + "base_url": h.baseURL, + }) +} + +// PutMicrosoftSettings handles PUT and PATCH /v1/settings/microsoft (admin only). +func (h *Handler) PutMicrosoftSettings(w http.ResponseWriter, r *http.Request) { + if _, ok := h.requireAdmin(w, r); !ok { + return + } + if h.demoMode { + h.writeError(w, http.StatusServiceUnavailable, "not available in the demo") + return + } + r.Body = http.MaxBytesReader(w, r.Body, 8<<10) + var req struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + TenantID string `json:"tenant_id"` + AllowedSignupDomains string `json:"allowed_signup_domains"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + h.writeError(w, http.StatusBadRequest, "invalid JSON") + return + } + + req.ClientID = strings.TrimSpace(req.ClientID) + req.TenantID = strings.TrimSpace(req.TenantID) + req.AllowedSignupDomains = strings.TrimSpace(req.AllowedSignupDomains) + + if req.ClientID == "" { + if _, err := h.db.ExecContext(r.Context(), ` + UPDATE server_settings SET + microsoft_client_id = '', + microsoft_client_secret_enc = '', + microsoft_tenant_id = '', + microsoft_allowed_signup_domains = ?, + updated_at = datetime('now') + WHERE id = 1`, req.AllowedSignupDomains); err != nil { + h.logger.ErrorContext(r.Context(), "microsoft settings: clear", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + h.SetAllowedSignupDomains(parseDomainsCSV(req.AllowedSignupDomains)) + h.SetMicrosoftAuth("", "", "common", "", h.secureCookie) + h.GetMicrosoftSettings(w, r) + return + } + + var existingEnc string + _ = h.db.QueryRowContext(r.Context(), `SELECT microsoft_client_secret_enc FROM server_settings WHERE id = 1`).Scan(&existingEnc) + + secretEnc := existingEnc + clientSecret := "" + if req.ClientSecret != "" { + var err error + secretEnc, err = secret.Encrypt(h.encKey, req.ClientSecret) + if err != nil { + h.logger.ErrorContext(r.Context(), "microsoft settings: encrypt secret", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + clientSecret = req.ClientSecret + } else if existingEnc != "" { + var err error + clientSecret, err = secret.Decrypt(h.encKey, existingEnc) + if err != nil { + h.logger.ErrorContext(r.Context(), "microsoft settings: decrypt existing secret", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + } + + if _, err := h.db.ExecContext(r.Context(), ` + UPDATE server_settings SET + microsoft_client_id = ?, + microsoft_client_secret_enc = ?, + microsoft_tenant_id = ?, + microsoft_allowed_signup_domains = ?, + updated_at = datetime('now') + WHERE id = 1`, + req.ClientID, secretEnc, req.TenantID, req.AllowedSignupDomains); err != nil { + h.logger.ErrorContext(r.Context(), "microsoft settings: save", "error", err) + h.writeError(w, http.StatusInternalServerError, "internal error") + return + } + + tenant := req.TenantID + if tenant == "" { + tenant = "common" + } + h.SetAllowedSignupDomains(parseDomainsCSV(req.AllowedSignupDomains)) + + if req.ClientID != "" && clientSecret != "" { + authRedirect := strings.TrimRight(h.baseURL, "/") + "/v1/auth/microsoft/callback" + calRedirect := strings.TrimRight(h.baseURL, "/") + "/v1/calendar/microsoft/callback" + h.SetMicrosoftAuth(req.ClientID, clientSecret, tenant, authRedirect, h.secureCookie) + encKeyHex := hex.EncodeToString(h.encKey[:]) + if mc, err := microsoft.New(h.db, req.ClientID, clientSecret, tenant, calRedirect, encKeyHex); err == nil { + if h.cal != nil { + h.cal.Register(mc) + } + } + } + + h.GetMicrosoftSettings(w, r) +} diff --git a/internal/handler/single_use_handler.go b/internal/handler/single_use_handler.go index a2379e6c..7195c01e 100644 --- a/internal/handler/single_use_handler.go +++ b/internal/handler/single_use_handler.go @@ -24,9 +24,6 @@ type singleUseLinkJSON struct { URL string `json:"url"` EventTypeID string `json:"event_type_id"` CreatedByUserID string `json:"created_by_user_id"` - PrefillName string `json:"prefill_name"` - PrefillEmail string `json:"prefill_email"` - DealID string `json:"deal_id"` ExpiresAt *string `json:"expires_at"` UsedAt *string `json:"used_at"` BookingID *string `json:"booking_id"` @@ -83,10 +80,7 @@ func (h *Handler) CreateSingleUseLink(w http.ResponseWriter, r *http.Request) { } var req struct { - PrefillName string `json:"prefill_name"` - PrefillEmail string `json:"prefill_email"` - DealID string `json:"deal_id"` - ExpiresInHours *int `json:"expires_in_hours"` + ExpiresInHours *int `json:"expires_in_hours"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) { h.writeError(w, http.StatusBadRequest, "invalid JSON") @@ -120,15 +114,11 @@ func (h *Handler) CreateSingleUseLink(w http.ResponseWriter, r *http.Request) { expiresAtPtr = &expStr } - prefillName := strings.TrimSpace(req.PrefillName) - prefillEmail := strings.TrimSpace(req.PrefillEmail) - dealID := strings.TrimSpace(req.DealID) - if _, err := h.db.ExecContext(r.Context(), ` INSERT INTO single_use_tokens - (id, token, event_type_id, created_by_user_id, prefill_name, prefill_email, deal_id, expires_at, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, - id, token, etID, user.ID, prefillName, prefillEmail, dealID, expiresAtSQL, nowStr); err != nil { + (id, token, event_type_id, created_by_user_id, expires_at, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, + id, token, etID, user.ID, expiresAtSQL, nowStr); err != nil { h.logger.ErrorContext(r.Context(), "create single-use link: insert", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return @@ -140,9 +130,6 @@ func (h *Handler) CreateSingleUseLink(w http.ResponseWriter, r *http.Request) { URL: h.singleUseURL(token), EventTypeID: etID, CreatedByUserID: user.ID, - PrefillName: prefillName, - PrefillEmail: prefillEmail, - DealID: dealID, ExpiresAt: expiresAtPtr, CreatedAt: nowStr, }) @@ -168,7 +155,7 @@ func (h *Handler) ListSingleUseLinks(w http.ResponseWriter, r *http.Request) { } rows, err := h.db.QueryContext(r.Context(), ` - SELECT id, token, event_type_id, created_by_user_id, prefill_name, prefill_email, deal_id, + SELECT id, token, event_type_id, created_by_user_id, expires_at, used_at, booking_id, created_at FROM single_use_tokens WHERE event_type_id = ? @@ -186,7 +173,6 @@ func (h *Handler) ListSingleUseLinks(w http.ResponseWriter, r *http.Request) { var expiresAt, usedAt, bookingID sql.NullString if err := rows.Scan( &item.ID, &item.Token, &item.EventTypeID, &item.CreatedByUserID, - &item.PrefillName, &item.PrefillEmail, &item.DealID, &expiresAt, &usedAt, &bookingID, &item.CreatedAt, ); err != nil { h.logger.ErrorContext(r.Context(), "list single-use links: scan", "error", err) @@ -284,21 +270,18 @@ func (h *Handler) SingleUseBookPage(w http.ResponseWriter, r *http.Request) { } var ( - slug string - isActive int - prefillName string - prefillMail string - dealID string - expiresAt sql.NullString - usedAt sql.NullString + slug string + isActive int + expiresAt sql.NullString + usedAt sql.NullString ) err := h.db.QueryRowContext(r.Context(), ` - SELECT et.slug, et.is_active, s.prefill_name, s.prefill_email, s.deal_id, + SELECT et.slug, et.is_active, s.expires_at, s.used_at FROM single_use_tokens s JOIN event_types et ON et.id = s.event_type_id WHERE s.token = ?`, token). - Scan(&slug, &isActive, &prefillName, &prefillMail, &dealID, &expiresAt, &usedAt) + Scan(&slug, &isActive, &expiresAt, &usedAt) if errors.Is(err, sql.ErrNoRows) { writeSingleUseGonePage(w) return @@ -326,9 +309,6 @@ func (h *Handler) SingleUseBookPage(w http.ResponseWriter, r *http.Request) { h.renderBookPage(w, r, slug, true, bookPrefill{ SingleUseToken: token, - Name: prefillName, - Email: prefillMail, - DealID: dealID, }) } diff --git a/internal/handler/templates/booking.css b/internal/handler/templates/booking.css index e8775398..42c12d9c 100644 --- a/internal/handler/templates/booking.css +++ b/internal/handler/templates/booking.css @@ -491,9 +491,9 @@ /* ── Theme switcher & Dark mode ─────────────────────────── */ :root { - --fp-bg: #f3f4f6; + --fp-bg: #F7F8FA; --fp-surface: #ffffff; - --fp-surface-muted: #f9fafb; + --fp-surface-muted: #F1F3F5; --fp-border: #e5e7eb; --fp-text: #111827; --fp-text-muted: #6b7280; @@ -588,9 +588,13 @@ html.dark .dir-members li { border-color: var(--fp-border); } html.dark .business-name-text, +html.dark header span, html.dark .event-name, html.dark .month-label, html.dark #month-label, +html.dark .slots-title, +html.dark .slots-date, +html.dark #selected-date, html.dark .section-title, html.dark .scheduled-time, html.dark .dir-title, @@ -634,11 +638,12 @@ html.dark .cookie-btn:hover { color: #ffffff; } html.dark .cd.avail { - background: #27272a; - color: #f4f4f5; + background: #27272A; + color: #F4F4F5; + border: 1px solid #3F3F46; } html.dark .cd.avail:hover { - background: #3f3f46; + background: #3F3F46; } html.dark .cd.past, html.dark .cd.unavail { diff --git a/internal/server/server.go b/internal/server/server.go index f8a65650..0a0b91ce 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -239,19 +239,36 @@ func BuildHandler(ctx context.Context, cfg *config.Config, db *sql.DB, logger *s h.SetAllowedSignupDomains(cfg.AllowedSignupDomains) } - if cfg.MicrosoftClientID != "" && cfg.MicrosoftClientSecret != "" { - msTenant := strings.TrimSpace(cfg.MicrosoftTenantID) - if msTenant == "" { - msTenant = strings.TrimSpace(cfg.MicrosoftTenant) + msClientID := cfg.MicrosoftClientID + msClientSecret := cfg.MicrosoftClientSecret + msTenant := strings.TrimSpace(cfg.MicrosoftTenantID) + if msTenant == "" { + msTenant = strings.TrimSpace(cfg.MicrosoftTenant) + } + if dbMS, err := handler.LoadMicrosoftSettingsFromDB(db, encKey); err == nil && dbMS != nil { + if dbMS.ClientID != "" { + msClientID = dbMS.ClientID + } + if dbMS.ClientSecret != "" { + msClientSecret = dbMS.ClientSecret + } + if dbMS.TenantID != "" { + msTenant = dbMS.TenantID } + if len(dbMS.AllowedSignupDomains) > 0 { + h.SetAllowedSignupDomains(dbMS.AllowedSignupDomains) + } + } + + if msClientID != "" && msClientSecret != "" { if msTenant == "" { msTenant = "common" } msAuthRedirect := cfg.BaseURL + "/v1/auth/microsoft/callback" - h.SetMicrosoftAuth(cfg.MicrosoftClientID, cfg.MicrosoftClientSecret, msTenant, msAuthRedirect, cfg.CookieSecure) + h.SetMicrosoftAuth(msClientID, msClientSecret, msTenant, msAuthRedirect, cfg.CookieSecure) logger.Info("Microsoft OAuth login configured", "redirect_url", msAuthRedirect, "tenant", msTenant) - mc, err := microsoft.New(db, cfg.MicrosoftClientID, cfg.MicrosoftClientSecret, msTenant, calRedirect, cfg.EncryptionKey) + mc, err := microsoft.New(db, msClientID, msClientSecret, msTenant, calRedirect, cfg.EncryptionKey) if err != nil { logger.Error("microsoft: init failed", "error", err) } else { @@ -449,6 +466,9 @@ func New(ctx context.Context, cfg *config.Config, db *sql.DB, logger *slog.Logge mux.HandleFunc("POST /v1/settings/email/rsvp-webhook", settingsRL(h.RequireAuth(h.SetupRSVPWebhook))) mux.HandleFunc("GET /v1/settings/google", h.RequireAuth(h.GetGoogleSettings)) mux.HandleFunc("PATCH /v1/settings/google", settingsRL(h.RequireAuth(h.PatchGoogleSettings))) + mux.HandleFunc("GET /v1/settings/microsoft", h.RequireAuth(h.GetMicrosoftSettings)) + mux.HandleFunc("PUT /v1/settings/microsoft", settingsRL(h.RequireAuth(h.PutMicrosoftSettings))) + mux.HandleFunc("PATCH /v1/settings/microsoft", settingsRL(h.RequireAuth(h.PutMicrosoftSettings))) mux.HandleFunc("GET /v1/settings/zoom", h.RequireAuth(h.GetZoomSettings)) mux.HandleFunc("PATCH /v1/settings/zoom", settingsRL(h.RequireAuth(h.PatchZoomSettings))) mux.HandleFunc("GET /v1/settings/livekit", h.RequireAuth(h.GetLiveKitSettings)) From fda9b86dc808dba869a2a7f6504099e660b62db5 Mon Sep 17 00:00:00 2001 From: Abhay Doss Date: Fri, 13 Nov 2026 14:51:30 -0500 Subject: [PATCH 03/15] feat: add editor page and configuration for event type slug routes --- .gitignore | 1 + .../src/routes/event-types/[slug]/+page.svelte | 14 +++----------- frontend/vite.config.ts | 14 +++++++++++++- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index fb8b6478..f8237de6 100644 --- a/.gitignore +++ b/.gitignore @@ -67,3 +67,4 @@ __screenshots__/ # NS8 Robot Framework test output (output.xml, log.html, report.html, screenshots) packaging/ns8/tests/outputs/ __pycache__/ +calnode.key diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index e6f26ba8..f7e935a0 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -673,9 +673,9 @@
{/if} -
+
-
-{/if}
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 2f222dba..1ad4f088 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -3,5 +3,17 @@ import { defineConfig } from 'vite'; import tailwindcss from '@tailwindcss/vite'; export default defineConfig({ - plugins: [tailwindcss(), sveltekit()] + plugins: [tailwindcss(), sveltekit()], + server: { + proxy: { + '/v1': 'http://localhost:3010', + '/book': 'http://localhost:3010', + '/t': 'http://localhost:3010', + '/manage': 'http://localhost:3010', + '/u': 'http://localhost:3010', + '/team': 'http://localhost:3010', + '/booking.css': 'http://localhost:3010', + '/embed.js': 'http://localhost:3010' + } + } }); From 7bd199459ccfb7e2abafa2f6c5050c36be9321e7 Mon Sep 17 00:00:00 2001 From: Abhay Doss Date: Fri, 13 Nov 2026 18:39:36 -0500 Subject: [PATCH 04/15] feat: add core UI routes, layout, questions panel, and feature roadmap docs --- .gitignore | 1 + .../event-types/QuestionsPanel.svelte | 132 ++++- frontend/src/routes/+layout.svelte | 10 +- frontend/src/routes/availability/+page.svelte | 478 +++++++++++++++--- frontend/src/routes/bookings/+page.svelte | 450 ++++++++++++++++- frontend/src/routes/calendar/+page.svelte | 131 +++-- frontend/src/routes/event-types/+page.svelte | 269 +++++----- .../routes/event-types/[slug]/+page.svelte | 361 +++++++++---- frontend/src/routes/settings/+layout.svelte | 1 - frontend/vite.config.ts | 28 +- 10 files changed, 1483 insertions(+), 378 deletions(-) diff --git a/.gitignore b/.gitignore index f8237de6..af852bee 100644 --- a/.gitignore +++ b/.gitignore @@ -68,3 +68,4 @@ __screenshots__/ packaging/ns8/tests/outputs/ __pycache__/ calnode.key +FUTURE_FEATURES.md diff --git a/frontend/src/lib/components/event-types/QuestionsPanel.svelte b/frontend/src/lib/components/event-types/QuestionsPanel.svelte index 8036ff9b..ad366738 100644 --- a/frontend/src/lib/components/event-types/QuestionsPanel.svelte +++ b/frontend/src/lib/components/event-types/QuestionsPanel.svelte @@ -5,7 +5,7 @@ import { ConfirmDialog } from '$lib/components/ui/confirm-dialog'; import { Input } from '$lib/components/ui/input'; import { Label } from '$lib/components/ui/label'; - import { Checkbox } from '$lib/components/ui/checkbox'; + import { Switch } from '$lib/components/ui/switch'; import { Textarea } from '$lib/components/ui/textarea'; import * as Select from '$lib/components/ui/select'; import * as Tooltip from '$lib/components/ui/tooltip'; @@ -124,6 +124,30 @@ function typeLabel(value: string): string { return QUESTION_TYPES.find((t) => t.value === value)?.label ?? value; } + + let dragIdx = $state(null); + let reordering = $state(false); + + async function reorderQuestions(fromIdx: number, toIdx: number) { + if (fromIdx === toIdx || fromIdx < 0 || toIdx < 0 || toIdx >= questions.length || reordering) return; + const next = [...questions]; + const [moved] = next.splice(fromIdx, 1); + next.splice(toIdx, 0, moved); + questions = next.map((item, idx) => ({ ...item, position: idx })); + reordering = true; + try { + await Promise.all( + questions.map((item, idx) => + api.patch(`/v1/event-types/${slug}/questions/${item.id}`, { position: idx }) + ) + ); + } catch (e: any) { + toast.error(e.message || 'Failed to reorder questions'); + await loadQuestions(); + } finally { + reordering = false; + } + } {$t('eventTypeEditor.questions.title')}

{$t('eventTypeEditor.questions.subtitle')}

-
+
{#if qLoading}

{$t('common.loading')}

{:else if questions.length > 0} - + +
+ {#each questions as q, idx (q.id)} + {#if editingQId === q.id} +
+
+ + +
+
+ + { if (v) editQForm.type = v as 'text'|'select'|'checkbox'; }}> + + {QUESTION_TYPES.find((t) => t.value === editQForm.type)?.label ?? $t('common.select')} + + + {#each QUESTION_TYPES as qt} + {qt.label} + {/each} + + +
+ {#if editQForm.type === 'select'} +
+ +