29 Commits

Author SHA1 Message Date
f85b90c95e fix(frontend): satisfy phase 2 lint checks
All checks were successful
Mirror to GitHub / mirror (push) Successful in 5s
CI / frontend (pull_request) Successful in 7m18s
CI / backend (pull_request) Successful in 10m23s
CI / e2e (pull_request) Successful in 9m31s
Co-Authored-By: Codex <noreply@openai.com>
2026-05-07 12:02:49 -04:00
5e6541ab92 fix(ci): set up node in gitea workflow
Some checks failed
Mirror to GitHub / mirror (push) Successful in 7s
CI / frontend (pull_request) Failing after 2m48s
CI / backend (pull_request) Successful in 15m5s
CI / e2e (pull_request) Successful in 8m47s
Co-Authored-By: Codex <noreply@openai.com>
2026-05-07 11:45:58 -04:00
4a37a47887 chore(env): standardize backend python on 3.12
Some checks failed
Mirror to GitHub / mirror (push) Successful in 5s
CI / frontend (pull_request) Failing after 1m8s
CI / e2e (pull_request) Successful in 12m9s
CI / backend (pull_request) Successful in 15m24s
Co-Authored-By: Codex <noreply@openai.com>
2026-05-07 11:31:28 -04:00
f31b873459 wip(handoff): record native python status
Co-Authored-By: Codex <noreply@openai.com>
2026-05-07 11:14:59 -04:00
380fcf7bde docs(env): document Stripe env vars in backend/.env.example
Some checks failed
Mirror to GitHub / mirror (push) Successful in 6s
CI / frontend (pull_request) Failing after 1m10s
CI / backend (pull_request) Failing after 1m24s
CI / e2e (pull_request) Failing after 1m25s
STRIPE_SECRET_KEY / STRIPE_PUBLISHABLE_KEY / STRIPE_WEBHOOK_SECRET are
required for the self-serve signup flow's checkout, portal, and webhook
paths. When unset, settings.stripe_enabled returns False and Stripe
code paths short-circuit cleanly.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 01:58:15 -04:00
4b098deac5 docs(handoff): record four post-implementation fixes from external review
OAuth refresh-token storage, OAuth setTokens authenticated flag, Stripe
webhook idempotency atomicity, and the missing /account/billing pages.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 01:45:35 -04:00
502c0a44e8 feat(billing): add /account/billing and /account/billing/select-plan pages
Wires up the missing frontend billing surfaces that TrialPill, UpgradePrompt,
NextStepCard, and SetupChecklist all link to. Trial-expired, canceled,
past-due, and "Pick a plan" CTAs no longer 404.

- BillingPage: subscription summary, status-specific messaging
  (trialing / past_due / canceled / complimentary), Manage billing button
  routed through the Stripe Customer Portal, and a Pick/Change-plan link.
- SelectPlanPage: plan picker with monthly/annual toggle + seat count.
  Starter/Pro hit /billing/checkout-session; Enterprise links to
  /contact-sales. Active current plan is tagged "Current plan" with a
  disabled CTA.
- billingApi.getPortalSession + createCheckoutSession; getPortalSession
  surfaces a typed BillingPortalError (no_stripe_customer / stripe_not_
  configured) so the UI can show the right toast.
- AccountSettingsPage gets a Billing link card so the page is discoverable
  from the account hub.
- 10 new vitest cases covering subscription summary, trial/past-due/
  canceled/complimentary states, portal-session error fallback, plan-card
  rendering, checkout payload, and current-plan badge.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 01:43:48 -04:00
06200fabb1 fix(billing): make Stripe webhook idempotency atomic so failed handlers can retry
Previously `apply_subscription_event` committed the StripeEvent idempotency
row before invoking the handler, then the handlers each committed their own
mutations. If a handler raised mid-flight (transient DB error, network blip,
race), the idempotency mark was already persisted — Stripe's retry would hit
the IntegrityError branch and silently return False, and the subscription
state would permanently desync from Stripe.

Switch to a single atomic transaction:
- Insert the StripeEvent + flush (catch IntegrityError on duplicate event_id).
- Run the handler.
- Commit on success; roll back the entire transaction on failure and re-raise.

Drop the four `db.commit()` calls inside `_handle_*` so the outer caller owns
commit. The webhook endpoint already lets exceptions propagate, so a 500
response now correctly tells Stripe to retry.

Tests: three new regression cases in test_stripe_webhook_handler.py covering
handler failure (no idempotency mark persisted), retry-after-failure success,
and duplicate-event-id skip.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 01:36:13 -04:00
3630dd5a80 fix(auth): mark store authenticated after OAuth setTokens
setTokens() previously only set { token } without flipping
isAuthenticated, so after the OAuth callback exchange the store had
fresh tokens but ProtectedRoute still saw isAuthenticated === false and
bounced the user to /landing before fetchUser() could complete.

Storing tokens implies an active session, so set isAuthenticated: true
inside setTokens. The other caller (refresh interceptor in api/client.ts)
runs from an already-authenticated session, so the flag flip is a no-op
there.

Tests:
- new src/store/authStore.test.ts covers the setTokens contract
- src/pages/__tests__/OAuthCallbackPage.test.tsx adds a successful-
  callback case asserting setTokens + fetchUser are invoked with the
  exchanged tokens

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 01:32:53 -04:00
5e0c9d2de1 fix(auth): store OAuth refresh token JTI to fix /auth/refresh after OAuth signup
OAuth callbacks (POST /auth/google/callback, POST /auth/microsoft/callback)
issued refresh tokens via create_refresh_token() but never persisted the JTI
in the refresh_tokens table. The /auth/refresh rotation logic does a
conditional UPDATE that requires a matching unrevoked row; without it the
first refresh attempt 401s with "Refresh token has been revoked" and OAuth
users get effectively logged out after the ~5 minute access-token expiry.

- Promote _store_refresh_token to module-public store_refresh_token in
  app.api.endpoints.auth (existing callers in /login, /login/json, /refresh
  updated in-place — same module, just renamed).
- OAuth callbacks now call store_refresh_token(...) + db.commit() after
  _sign_in_or_register returns. _sign_in_or_register already commits the
  user/account/identity rows; the refresh-token row gets its own commit.
- Tests:
  - test_oauth_google_callback_stores_refresh_token_jti — asserts the JTI
    hash is in refresh_tokens after a Google callback.
  - test_oauth_refresh_works_after_oauth_signup — full e2e: callback -> use
    returned refresh token at /auth/refresh -> 200 with rotated tokens.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 01:30:14 -04:00
fee4cb5b74 docs(handoff): capture Phase 2 (frontend cutover) code completion
Tasks 27–44 implemented across 18 commits on this branch. Phase O (Stripe
live setup, internal validation, flag flip) is the manual operational
follow-up and is the resume point.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 23:46:15 -04:00
c75ce0c9a3 feat(sales): redirect beta-signup to /register; queue waitlist emails
Phase 2 retires the public beta-signup form in favor of the self-serve
register flow. The /api/v1/beta-signup POST endpoint stays mounted but
now responds with 307 to /register?from=beta so any external links keep
working and analytics can tag signup origin via the from query param.

Note: there is no beta_signup table in the schema — the original
endpoint only fired an email notification, so there is no waitlist to
read and no migration to run for the email-sent_at field. The one-off
admin script in the spec is therefore a no-op and is intentionally not
added here.

- Replace POST /beta-signup handler with RedirectResponse(307)
- Drop the EmailService.send_beta_signup_notification call (the user is
  now redirected into the register flow, which has its own email path)
- Add tests/test_beta_signup_redirect.py covering the 307 + Location

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 23:43:35 -04:00
db2478dd89 feat(sales): add /contact-sales form + landing page CTA
Public Talk-to-Sales surface and a "See pricing" hero CTA on the marketing
landing page. Phase 2 Task 43 of self-serve signup.

- frontend/src/api/sales.ts: salesApi.createLead -> POST /sales-leads.
- ContactSalesPage at /contact-sales (public, gated by self_serve_enabled
  with a 404-style fallback). Form fields: name, work email, company,
  team size (1-2 / 3-5 / 6-10 / 11-25 / 26+), and an optional
  "what brought you here?" textarea -> message. Submit button disabled
  while in flight to block duplicate submissions.
- Confirmation surface replaces the form on success. Calendly block is
  hidden when VITE_CALENDLY_URL is unset.
- detectSource(): 'pricing_page' if document.referrer contains '/pricing',
  else 'landing_page'. Server emits the canonical PostHog
  talk_to_sales_form_submitted event with this source.
- LandingPage: new "See pricing" hero CTA gated by useAppConfig().
  self_serve_enabled.
- frontend/.env.example + Dockerfile: VITE_CALENDLY_URL ARG/ENV.
- Tests: ContactSalesPage submit/confirmation, Calendly hide-when-unset,
  in-flight de-dup, 404 when self-serve off; LandingPage CTA on/off.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 23:31:56 -04:00
67fae91087 feat(pricing): add /pricing page (B-style)
Phase 2 Task 42: public pricing page gated by SELF_SERVE_ENABLED.

Backend:
- New `GET /api/v1/plans/public` (no auth) returns plan_billing rows
  joined with plan_limits.max_users (as `max_seats`), filtered to
  is_public=true AND is_archived=false, ordered by sort_order ASC,
  plan ASC. Uses get_admin_db (cross-tenant catalog read, same pattern
  as /config/public).
- `PublicPlanResponse` schema in app/schemas/billing.py.
- Registered as PUBLIC in api router.

Frontend:
- `plansApi.getPublic()` client (frontend/src/api/plans.ts).
- `PricingPage` at /pricing with hero / 3 plan cards (Pro recommended,
  Enterprise hides price) / hardcoded v1 comparison table / testimonial
  placeholder / soft trust strip.
- Reads `useAppConfig().self_serve_enabled`; renders a 404 fallback
  when disabled, never calls the API in that path.
- Start free trial CTAs link to /register?plan=starter|pro; Talk to sales
  links to /contact-sales (page wired in Task 43).

Tests:
- Backend: only-public-rows + sort-order ordering.
- Frontend (Vitest): three plan cards with API prices, /register?plan=pro
  CTA, /contact-sales CTA, 404 when self_serve_enabled is false, soft
  trust language (no SOC2 claim).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 23:26:27 -04:00
0c326d0616 feat(dashboard): replace checklist with next-step card + unified list
Phase 2 Task 41 — Dashboard redesign.

Backend:
- Extend GET /users/onboarding-status with email_verified and shop_setup_done.
- tried_ai_assistant kept in payload for backward-compat during deploy.

Frontend:
- New NextStepCard: surfaces the highest-priority incomplete onboarding item
  with a primary CTA. Priority order: verify email > set up shop > run first
  FlowPilot session > connect PSA > invite teammate > pick a plan (gated on
  trial stage warning/urgent/expired). Returns null when all done OR
  onboarding_dismissed.
- New SetupChecklist: unified single list (no SOLO/TEAM bifurcation), drops
  the stale tried_ai_assistant / Script Builder item, surfaces "Pick a plan"
  when trial stage is warning or later.
- Mounted on QuickStartPage below the hero with a "Show all setup steps"
  toggle. The whole onboarding section auto-hides when there's nothing left
  to nudge on, so the dashboard goes back to clean once setup is done.
- Removed the orphaned OnboardingChecklist component (was defined but never
  mounted).
- New useOnboardingStatus hook so page + components share one fetch contract.

Tests:
- Backend: test_onboarding_status_includes_email_verified_and_shop_setup_done.
- Frontend (Vitest): 13 new tests across NextStepCard, SetupChecklist, and
  QuickStartPage covering priority ordering, dismissal, the SOLO/TEAM
  removal, the toggle reveal, and the trial-stage gate on Pick a plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 23:19:58 -04:00
99343ab7a9 feat(dashboard): add TrialPill in AppLayout topbar
Mounts a billing-state pill in the topbar that reads useTrialBanner() and
renders the appropriate label / tone / CTA per spec:

- pristine / warning  → "Pro trial · Nd"   (info → warning amber as days drop)
- urgent              → "Pro trial · today" (warning amber, semibold)
- expired             → "Trial expired — pick a plan" → /account/billing/select-plan
- paid                → planBilling.display_name (quiet)
- complimentary       → "Complimentary Pro" (accent, no CTA)
- past_due            → "Payment failed — update card" → /account/billing
- canceled            → "Reactivate" → /account/billing/select-plan
- null                → hidden

Uses existing design-system tokens only (text-info/bg-info-dim,
text-warning/bg-warning-dim, text-danger/bg-danger-dim, text-accent/
bg-accent-dim, text-muted-foreground/bg-elevated). Clickable variants
render as react-router-dom <Link>s and are keyboard-focusable with an
accent focus-visible ring. Mobile collapses the label to a clock icon
with a title attribute carrying the full text.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 23:06:09 -04:00
53dd5f13e5 feat(onboarding): add wizard Steps 2 (PSA) and 3 (Invite team)
Step 2 (`/welcome/step-2`): four PSA tiles (ConnectWise / Autotask /
HaloPSA / No PSA yet). Selecting a real PSA reveals a quiet inline
"Connect now" link to `/account/integrations` — credential entry is
intentionally OUT of the wizard. Continue persists `primary_psa`,
Skip advances without writing.

Step 3 (`/welcome/step-3`): up to 10 email/role rows (default 3,
"+ Add another" extends, role defaults to Tech / engineer with
Viewer alt). "Send invites and continue" filters empty rows, POSTs
`/accounts/me/invites/bulk`, then PATCHes onboarding-step
`{step:3, action:"complete"}` and navigates to `/?welcome=true`.
Per-row `failed[]` errors render inline next to the email and the
wizard does NOT auto-advance — user can fix-and-retry or click
"Continue anyway" to mark step complete. Empty + Skip / empty + Send
both advance without sending.

Adds `accountsApi.bulkInvite` and registers `/welcome/step-{2,3}`
in the router. Vitest: 5 named tests (selecting PSA persists,
Skip advances without primary_psa, valid emails create invites,
partial-failure inline error, empty + Skip no-op) + 5 incidental
coverage tests. tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 23:02:00 -04:00
9b517d3320 feat(onboarding): add welcome wizard scaffold + Step 1 (Your shop)
Lays the groundwork for the post-signup welcome wizard (Phase 2,
Task 38). Authed users hitting /welcome are routed to the next
incomplete step based on users.onboarding_step_completed +
users.onboarding_dismissed; refresh resumes correctly because every
navigation persists state server-side first.

Backend:
- Expose onboarding_step_completed (Optional[int]) and
  onboarding_dismissed (bool) on UserResponse so /auth/me drives
  client-side routing without a separate fetch.

Frontend:
- WelcomeRouter handles the /welcome decision table (dismissed → /,
  completed >=3 → /, else next step).
- WelcomeStep1 renders the "Your shop" form (company name pre-filled
  from accounts.name, team size 1-2/3-5/6-10/11-25/26+, role
  Owner/Lead Tech/Tech/Other). Continue PATCHes /users/me/onboarding-step
  with action=complete; Skip-this-step PATCHes action=skip; Skip-the-rest
  POSTs /users/me/onboarding-dismiss-rest. Each action refreshes the
  auth store before navigating so the router resumes correctly on the
  next visit.
- onboardingApi.updateStep + dismissRest (typed against backend
  OnboardingStepRequest/Response schemas).
- Routes mounted inside AppLayout so EmailVerificationBanner persists
  above each step per spec.
- 11 vitest cases covering the routing decision table + Continue / Skip
  / Skip-the-rest / persist-failure paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 22:54:10 -04:00
7d939a4acf feat(auth): add email verification banner, wall, /verify-email page
Wires up the soft 7-day email-verification grace period UX.

- EmailVerificationBanner now uses the design-system warning tokens
  (bg-warning-dim / text-warning) and hides itself once the grace
  period expires, so the wall takes over without double-messaging.
- EmailVerificationWall picks up data-testids on the resend and
  sign-out CTAs.
- VerifyEmailPage gains a single-fire useRef guard (so React 19
  strict-mode double-invoke doesn't burn the token), an
  already-verified short-circuit that skips the API call, success
  state with auth-store refresh + redirect to /?verified=1, and
  an error state with a resend CTA.

Tests: banner hides past day-7, banner resend triggers API call,
verify success refreshes + redirects, verify short-circuits when
already verified, single-fire guard holds across remount.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 22:46:43 -04:00
39e85c9770 feat(auth): add /accept-invite page + lookup endpoint
Adds the invitee-side flow for self-serve signup Phase 2 (Task 36):

Backend
- Public GET /accounts/invites/{code}/lookup returns
  {account_name, inviter_name, invited_email, role} for a valid invite,
  404 invite_invalid_or_expired_or_revoked otherwise (collapses unknown /
  expired / revoked / used into one anti-enumeration response). Mounted
  in a new account_invite_lookup endpoints module on the public route
  list, uses get_admin_db (BYPASSRLS) since the caller has no tenant.
- OAuthCallbackPayload gains optional account_invite_code + invited_email.
  _sign_in_or_register honors them: a new OAuth user with a valid invite
  joins the invited account (no personal account, no Pro trial), the
  invite is marked used, and OAuth-profile-email vs invite-email mismatch
  raises invite_email_mismatch (matching the email+password register
  contract).

Frontend
- New public route /accept-invite -> AcceptInvitePage. Reads ?code=,
  calls inviteApi.lookupAccountInvite, renders "Join {account} on
  ResolutionFlow" with the invited email locked (rendered as a div, not
  an input), three sign-in options (set password, Google, Microsoft),
  and a clear "ask {inviter} to resend" + mailto: fallback for invalid
  codes.
- OAuth state for invitees is base64url(JSON({csrf, accountInviteCode,
  invitedEmail})). OAuthCallbackPage decodes both shapes, forwards the
  invite fields to the backend, and surfaces invite_email_mismatch /
  invite_invalid_or_expired_or_revoked errors with friendly text.
  Successful invite-OAuth lands on /?welcome=teammate (suppresses the
  welcome wizard for invitees per spec).
- UserCreate type + invite/auth API clients extended for the new fields.

Tests
- Backend: invite lookup happy path + four invalid-state collapse, OAuth
  callback links invite when supplied + rejects on email mismatch.
- Frontend Vitest: AcceptInvitePage renders account name + locked email
  + accept buttons; resend message + mailto on invalid code.

All 43 backend auth/account/invite/email-verification tests green;
frontend Vitest 120/120 green; tsc -b clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 21:34:22 -04:00
70ab1f34d4 feat(auth): redesign /register with OAuth buttons; hide invite-code under flag
Phase 2 Task 35. Adds OAuth Google/Microsoft sign-in to the register flow,
gated on the public SELF_SERVE_ENABLED flag, and hides the legacy invite-code
field when self-serve is on.

- New `useAppConfig` hook + `configApi`. One-shot module-cached fetch of
  `GET /api/v1/config/public`; falls back to `VITE_SELF_SERVE_ENABLED` env
  var (default false) if the endpoint is unreachable.
- New `OAuthCallbackPage` mounted at `/auth/google/callback` and
  `/auth/microsoft/callback` (public, NOT inside ProtectedRoute). Posts the
  authorization code to the backend, persists tokens, hydrates the auth
  store via fetchUser, and redirects to `/welcome` (new) or `/` (returning).
- `RegisterPage` now renders OAuth buttons + email/password divider when
  `self_serve_enabled` is true and only emits buttons for providers the
  backend reports as configured. Invite-code field hidden in that mode.
  Captures `?plan=pro` into `localStorage.rf-intended-plan` on mount.
- `authApi` gains `googleCallback(code)` / `microsoftCallback(code)`.
- `frontend/.env.example` + `frontend/Dockerfile` document and bake the
  three new VITE_* build-time variables (Lesson 60: Vite needs ARG+ENV).
- Vitest coverage for the three required cases plus the plan-param capture.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 21:15:25 -04:00
ece82225f2 feat(billing): add FeatureGate, UpgradePrompt, EmailVerificationGate components
Three drop-in gating components for the self-serve signup flow.

- FeatureGate reads useFeature(flag) and renders children when enabled,
  else a fallback (default UpgradePrompt). UX-only — security boundary
  remains require_feature on the backend.
- UpgradePrompt resolves a feature key to display name + required plan
  via an inline catalog and links to /account/billing/select-plan.
- EmailVerificationGate gates protected content behind a 6-day grace
  period; renders a minimal EmailVerificationWall (resend + sign out)
  on Day 7+ unverified. Wall design will be refined in Task 37.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 21:01:53 -04:00
0b5ed9aa10 feat(billing): add useFeature, useFeatureLimit, useTrialBanner hooks
Phase 2 Task 33. Components can now ask "is this feature on?", "how many
sessions left?", and "what stage is the trial in?" without re-implementing
the read against useBillingStore.

- useFeature(flagKey): boolean — reads enabledFeatures from store
- useFeatureLimit(field): { used, limit, percentage, isAtLimit, isLoading }
  with non-blocking 60s module-level cache and graceful 404 degradation
- useTrialBanner(): derives stage from subscription status + trial countdown,
  returns null on initial load to prevent flicker
- usageApi.getCount(field) — calls /api/v1/usage/{field}; backend endpoint
  is not yet implemented (planned), so the hook degrades to used=0

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 20:55:58 -04:00
7a9cb4b03b feat(billing): add useBillingStore and /billing/state integration
T32: Single frontend source of truth for subscription / plan / feature
state. New Zustand `useBillingStore` fetches `/billing/state` (auto-fetch
on login via authStore, reset on logout), exposes `refetch` for
post-Checkout refresh, and is supported by a `useBillingPoll` hook
that re-fetches every 60s while authenticated. The new `billingApi`
client transforms the snake_case backend payload to camelCase at a
single boundary so the rest of the frontend never sees `plan_billing`
or `enabled_features`.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 20:47:50 -04:00
80baf89b00 feat(config): add SELF_SERVE_ENABLED flag + GET /config/public
Phase 2 Task 31. Single flag now controls whether the public-facing
self-serve flow is exposed.

- New public endpoint GET /api/v1/config/public returns
  {self_serve_enabled, oauth_providers}. oauth_providers includes
  "google" if GOOGLE_CLIENT_ID is set and "microsoft" if MS_CLIENT_ID
  is set. No auth required; consumed once by the frontend at load.
- POST /auth/register: when SELF_SERVE_ENABLED=true the platform
  invite-code requirement is bypassed even with REQUIRE_INVITE_CODE=true.
  invite_code stays in the schema for backward compat and still applies
  when supplied. With the flag off, the gate behaves exactly as before.
- Adds backend/app/schemas/config.py with PublicConfigResponse and
  registers the new router in the public/unauthenticated section.
- Adds 3 integration tests in tests/test_config_public.py covering the
  flag round-trip, the regression case (flag off keeps the 400), and
  the new behavior (flag on bypasses the gate, creates user + Pro trial).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 20:38:50 -04:00
d05b475a41 feat(admin): extend /admin/plan-limits to manage plan_billing fields
Task 30 of self-serve signup Phase 2. Super-admins can now manage Stripe
IDs, display names, prices, and public/archived flags via the existing
admin plan-limits endpoints.

- GET /admin/plan-limits now outer-joins plan_billing and returns
  merged PlanLimitWithBillingResponse rows. Plans without a
  plan_billing row return None for the billing fields.
- PUT /admin/plan-limits accepts the new optional billing fields and
  upserts plan_billing in the same transaction. If no plan_billing
  row exists for the plan and the body includes any billing field, a
  row is created (display_name defaults to plan.capitalize() when
  omitted; display_name is never NULLed out on an existing row).
- After commit, the handler queries account_ids on the affected plan
  and calls BillingService.invalidate_billing_cache(account_ids).
  This is a no-op stub today (logs only) — there's no in-process
  billing cache yet. TODO comment marks the wire-up point.
- 3 new integration tests cover GET-with-billing-present, PUT creating
  a plan_billing row, and the invalidation hook being awaited with a
  list of account_ids.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 20:35:10 -04:00
694279f89e feat(sales): add POST /sales-leads public endpoint
Phase 2 Task 29 — public Talk-to-Sales submission endpoint.

- New POST /api/v1/sales-leads (public, no auth, rate-limited 5/hour per IP).
- Inserts a sales_leads row, fires best-effort notification email and
  PostHog server-side capture; failures are logged but never fail the
  request.
- New EmailService.send_sales_lead_notification static method.
- New SALES_LEAD_RECIPIENT_EMAIL setting (defaults to sales@resolutionflow.com).
- Schemas: SalesLeadCreate / SalesLeadCreateResponse with literal source enum.
- Tests: happy path (row + email), email-failure resilience, and rate-limit
  enforcement (re-enables the slowapi limiter for the rate-limit assertion
  since DEBUG=true disables it by default in tests).

PostHog server-side instrumentation point is wired in but no-ops gracefully
until app.core.analytics.posthog exists — turning it on is a one-line
change when the backend SDK is configured.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 20:12:03 -04:00
16f5e4ce05 feat(onboarding): add PATCH /users/me/onboarding-step + dismiss-rest
Persists welcome-wizard Step 1/2/3 progress for self-serve signup Phase 2.
PATCH validates step cannot decrease, ignores `data` on action="skip", and
is idempotent on re-PATCH of the same step. POST /users/me/onboarding-dismiss-rest
backs the wizard's "Skip the rest" button.

Both routes added to _EMAIL_VERIFICATION_ALLOWLIST and _SUBSCRIPTION_GUARD_ALLOWLIST
so the wizard runs before email verification and during the trial. 4 integration
tests cover field writes, skip semantics, decrease guard, and dismiss-rest.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 20:04:43 -04:00
2f8ec3775e feat(billing): add BillingService.open_customer_portal + GET endpoint
Authed users can now request a Stripe-hosted Customer Portal URL for card
updates and cancellation via GET /api/v1/billing/portal-session. The path is
already in both _SUBSCRIPTION_GUARD_ALLOWLIST and _EMAIL_VERIFICATION_ALLOWLIST
so canceled or unverified-past-grace users can still update billing.

- Returns 503 with {"error": "stripe_not_configured"} when STRIPE_SECRET_KEY unset.
- Returns 400 with {"error": "no_stripe_customer"} when account has no
  stripe_customer_id (must complete checkout first).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-06 20:00:08 -04:00
107 changed files with 233 additions and 4221 deletions

View File

@@ -1,12 +1,10 @@
# CURRENT_TASK.md
**Active task:** Phase O cutover for self-serve signup. PR #164 (`feat/billing-plan-taxonomy`) open in Gitea with 5 commits at head `2c9f5e9`, closing the last code blockers — plan taxonomy reconciliation (`team``enterprise`, add `starter`), `INTERNAL_TESTER_EMAILS` allowlist, `sync_stripe_plan_ids.py` script, page-title `—` JSX-escape bug fix, frontend taxonomy followups, doc refresh. After merge, only manual ops remain: Stripe Dashboard live-mode config, Railway prod env vars, internal validation pass, public flag flip. See `.ai/HANDOFF.md` for the resume point.
**Active task:** Self-serve signup Phase 2 — PR #162 is open on `feat/self-serve-signup-phase-2`. Current focus is resolving its failing Gitea checks. Phase O manual ops (Stripe live setup, internal validation, flag flip) remain pending after review/merge. See `.ai/HANDOFF.md` for the resume point.
## Recently shipped
- **2026-05-08PR #164 (open)** Plan taxonomy reconciliation + `INTERNAL_TESTER_EMAILS` allowlist + Stripe sync script + page-title fix + frontend taxonomy followups + doc refresh. 5 commits on `feat/billing-plan-taxonomy` from main (`dad5e1f`); HEAD `2c9f5e9`. Migration `4ce3e594cb87` renames `plan_limits.plan='team'``'enterprise'` and adds `starter` row (caps interpolated between free and pro: `max_trees=10`, `sessions=75`, `ai=15/mo`). Resource visibility (`Tree.visibility='team'`, `StepLibrary.visibility='team'`) is a separate domain and intentionally untouched. New `backend/scripts/sync_stripe_plan_ids.py` upserts `plan_billing` rows from Stripe products by exact name match — annual fields stay NULL by design (user explicitly skipping annual pricing for exit flexibility). `Settings.is_internal_tester` + `is_self_serve_active_for` centralize the allowlist + global-flag check; new `get_current_user_optional` dep; `/config/public` honors allowlist for authenticated callers; `/auth/register` allows allowlisted emails without invite code. LandingPage page-title bug — `—` inside JSX attribute strings was rendering as 6 literal characters in browser tabs; replaced with literal em dash. PageMeta default tagline updated from "Decision Tree Platform" to "AI-Powered Troubleshooting for MSPs". 86/86 passing across subscription/billing/plan/invite/admin sweep; tsc + lint clean. See `.ai/DECISIONS.md` for the two architectural entries (taxonomy reconciliation, allowlist).
- **2026-05-06 — PR #163** Seed test users marked email-verified. Squash-merged into main as `dad5e1f`.
- **2026-05-06 — PR #162** Self-serve signup Phase 2 (frontend cutover). 18 commits across Tasks 2744 of the plan. Backend remainders + frontend billing foundation + auth surfaces (OAuth + accept-invite + verify-email) + welcome wizard + dashboard redesign (TrialPill, NextStepCard, unified checklist) + public surfaces (`/pricing`, `/contact-sales`) + beta-signup deprecation. Squash-merged into main as `f1be3ab`. Single alembic head was `c6cbfc534fad` (no new migrations in Phase 2; PR #164 adds `4ce3e594cb87`).
- **2026-05-06`feat/self-serve-signup-phase-2`** Phase 2 frontend cutover code (Tasks 2744 of the plan, 18 commits). Backend remainders + frontend billing foundation + auth surfaces (OAuth + accept-invite + verify-email) + welcome wizard + dashboard redesign (TrialPill, NextStepCard, unified checklist) + public surfaces (`/pricing`, `/contact-sales`) + beta-signup deprecation. Phase O (Stripe live setup, internal validation, flag flip) is operational and pending. Single alembic head `c6cbfc534fad` (no new migrations).
- **2026-05-02 — PR #159** In-product User Guides rewrite. Merged into `main`. Replaced 15 feature-dump guides with 43 problem-oriented Diátaxis how-tos grouped under 10 categories. Dropped Maintenance Flows / AI Assistant / Flow Assist Sparkles (UI no longer exists). Renamed Step Library → Solutions Library. Authored 14 net-new how-tos for FlowPilot-era surfaces (tasklane keyboard flow, what-we-know, resolve, escalate, record-fix-outcome, post-docs-to-ticket, share-update, pause-and-leave, build-script-from-scratch, open-suggested-flow, pin-a-flow, invite-teammate, etc.). Schema additions: `category`, optional `relatedSlugs`; hub renders category sections; detail page renders related-guides footer. Fixed rendering bug where `**bold**` in `step.tip` rendered literally. Killed misleading "N sections" subtitle on guide cards. Browser-verified against engineer + owner login (sidebar labels, account sub-pages, pilot-screen header buttons, Tasks panel, integration form). Two unverified items intentionally deferred: change-teammate-role (requires non-owner test member to inspect role-change control) and detailed Resolve / Escalate modal contents (Resolve gated by 6 pending tasks in test data). tsc and Vite build clean.
- **2026-05-01 — PR #158** Session-screen UX impeccable pass + tasklane keyboard flow. Merged into `main` as `5e10005`.
- **Impeccable pass** (5 sub-passes — distill / quieter / layout / typeset / polish): score 24/40 → 33/40. Removed the duplicate "Suggested checks" chip strip; added an inline `Next steps · N pending in Tasks` cue above the latest action-bearing AI bubble; consolidated the desktop session header to Resolve + Escalate + ⋯ kebab (Context / New Ticket / Update Ticket / Pause now under the kebab, mobile kebab gained Context + New Ticket parity); centered the messages column to `max-w-3xl` to match the composer; bubbles dropped to `rounded-xl`. Decoration sweep: dropped 3px side stripes (TaskLane done states, all 6 ProposalBanner modes, WhatWeKnowItem rows), gradient backgrounds (WhatWeKnow + every banner), accent borderTop on TaskLane header, backdrop-blur on handoff overlay, animate-pulse-amber ring in VerifyingBanner, bordered avatar boxes in banners. Type sweep: 14 distinct sizes → 5-step scale (10/11/12/13/14px). Icon disambiguation: `MessageCircleQuestion` split into `Pencil` (Answer CTA) + `HelpCircle` (per-check explainer). Dead `font-sans` audit (12 sites) and double `text-xs` cleanups.

View File

@@ -13,82 +13,6 @@
---
## 2026-05-13 — Session expiration policy: 3d idle / 14d absolute defaults + per-account override
**Context:** User report: "I login to ResolutionFlow and never have to log back in." Investigation found refresh tokens at `REFRESH_TOKEN_EXPIRE_DAYS=7` with JTI rotation (`security.py:36`) — every `/auth/refresh` minted a fresh 7-day window. Net effect: a sliding 7-day session with no absolute cap. Visit once a week, logged in forever. Acceptable for pilot but not for MSP buyers whose SOC2 / cyber-insurance auditors require enforced session timeouts. Required for the same Phase O launch readiness as the other gates already in flight.
**Decision:** Two-window model snapshotted into the refresh JWT at login. Defaults to Strict (3-day idle, 14-day absolute), bounded by env-var system min/max. Per-account override via two new `accounts` columns (NULL = use system default). Owner-only `GET/PATCH /accounts/me/security` endpoint with effective-value validation (partial-override case caught at the app layer because the DB CHECK can't see Settings). Sibling `POST /accounts/me/security/revoke-sessions` for `all|others`-scoped bulk revocation. Frontend: Strict/Standard/Custom presets, active-users list (name + email + last-login-ago), differentiated SessionExpiryToast (idle = warning amber with "Stay signed in" → `/auth/refresh`; absolute = info cyan, informational only), cyan info-tone banner on `/login?reason=session_expired`, auto-redirect after scope=all bulk-revoke. Error-detail taxonomy on the wire: `session_expired_idle`, `session_expired_absolute`, `invalid_refresh_token`. Grandfather path: legacy refresh tokens (no `auth_time` claim) get one free rotation under the new policy. Atomic-revoke-then-check on `/auth/refresh` so absolute-expired tokens can't be replayed.
8 commits on `feat/session-expiration-policy` branch (`92fa3bc``c7cd711`), ~1300 LoC backend + frontend including 28 backend tests. Plan + design review at `docs/plans/2026-05-13-session-expiration-policy.md` (initial design score 4/10 → final 9/10 via `/plan-design-review`; 7 design decisions locked).
**Rejected:**
- **Idle-only or absolute-only enforcement.** Idle without absolute is the current broken state (sliding forever). Absolute without idle is too strict — kicks users out daily.
- **Hard cutover on deploy (SECRET_KEY rotation).** Forces every pilot to log in again immediately; high support cost. Grandfather path is friendlier and adds ~50 lines of code.
- **Distinguish `session_revoked_by_admin` from `invalid_refresh_token` on the wire** for users whose sessions were killed via bulk-revoke. Requires tracking revocation reason per `refresh_tokens` row. Not worth the complexity for v1 — affected users see they're logged out, same as any other revoke.
- **Per-user device list with per-device revoke.** Refresh tokens don't carry device/user-agent metadata today. Account-wide bulk revoke covers the breach-response use case; per-device is a follow-up if pilots ask.
- **"Loose" preset (90d).** Strict default suggests we shouldn't ship a one-click loose option. Owners who want a loose policy can use Custom and own the choice explicitly.
- **Always-required `idle_minutes`+`absolute_minutes` (XOR-NULL invariant).** Forces owners who only want to override idle to also re-declare the absolute window, leaking the system default into account data. Partial overrides allowed; validated at the app layer against current defaults.
- **Reveal-on-Custom UI for the minute inputs.** Hidden-by-default-reveal-on-radio shifts page layout when Custom is selected. Always-visible-but-disabled is more stable and previews the Custom interaction.
- **Modal-stays-open-success-state for scope=all bulk-revoke.** User preferred auto-redirect-with-toast (more standard SaaS pattern); the toast acts as the success acknowledgment before /login loads.
**Consequences:**
- "Logged in forever" is fixed. Every user sees a hard 14-day re-auth at minimum (3-day idle in practice for typical usage).
- Account owners get a complete self-service surface for policy + bulk session control. New `/account/security` route, owner-gated.
- Audit-log entries on both mutations: `account.session_policy_update` and `account.sessions_revoked_bulk`. SOC2-ready.
- Frontend `idle_expires_at` + `absolute_expires_at` flow through the entire auth surface (`Token`, `OAuthCallbackResponse`, `authStore`, persistence). `useAuthSessionExpiry` hook is the single source for "is the session about to end."
- Future improvements (filed as follow-ups in plan §9): per-user device list (requires `refresh_tokens.last_used_at` column), super-admin global ceiling UI, per-user policy. None block current shipping.
- Cyan info-tone banner on `/login` is the first of its kind in the app; sets precedent for future neutral system messages.
---
## 2026-05-07 — Per-email allowlist (`INTERNAL_TESTER_EMAILS`) for self-serve soft cutover
**Context:** Phase O Task 46 ("internal validation pass") needed a way to exercise the full self-serve flow against the prod backend before flipping `SELF_SERVE_ENABLED=true` for everyone. The plan doc described the mechanism but the backend support was never built — flagged in `SESSION_LOG.md` as a code blocker. Stripe live-mode setup is also gated on having a working internal-tester path in prod test mode.
**Decision:** Comma-separated allowlist `INTERNAL_TESTER_EMAILS` parsed by a Pydantic field_validator into a normalized lowercase list. Two helpers on `Settings`: `is_internal_tester(email)` (case-insensitive membership check) and `is_self_serve_active_for(email)` (returns `SELF_SERVE_ENABLED OR is_internal_tester(email)`). Both endpoints that gate on the global flag now call the helper:
- `/config/public` accepts optional auth via new `get_current_user_optional` dep; returns `self_serve_enabled=true` for allowlisted authenticated callers; anonymous calls always see the global flag.
- `/auth/register` allows allowlisted emails to register without an invite code.
**Rejected:**
- **Custom header `X-Internal-Tester-Email` for anonymous flows.** Spoofable. The auth/register-payload checks are sufficient because the user has to OWN the email to register or log in.
- **Separate allowlists per surface (`INTERNAL_PRICING_TESTERS`, `INTERNAL_OAUTH_TESTERS`).** Premature splitting. The Phase O use case is "this small set of people can see the new flow"; one variable handles it. If finer granularity emerges, split then.
- **Database table for the allowlist.** Env var matches the spec from the plan doc and fits the soft-cutover lifecycle — list is small, changes infrequently, lives alongside other deployment-time config.
**Consequences:**
- Stripe internal validation can run end-to-end in prod test mode without flipping the global flag.
- Anonymous callers always see the global flag — the allowlist never leaks via unauthenticated request content. Three regression tests in `test_config_public.py` enforce this.
- `INTERNAL_TESTER_EMAILS` plumbed through `docker-compose.dev.yml` and documented in `backend/.env.example`. Railway prod env will need the same var set during Phase O cutover.
---
## 2026-05-07 — Reconcile plan tier taxonomy (rename `team` → `enterprise`, add `starter`)
**Context:** PR #162 left a real architectural gap. Marketing surface (PricingPage, Stripe products) was wired for `Starter / Pro / Enterprise` while backend was on `free / pro / team`. `plan_billing.plan` FK referenced `plan_limits.plan` so the `BillingPlan` schema's `Literal["pro", "starter", "team", "enterprise"]` could accept values that violated the FK. `plan_billing` was unseeded in dev, so no checkout could complete. `Subscription.plan.in_(["pro", "team"])` paid-plan checks wouldn't recognize `enterprise`. Self-serve cutover was blocked at the data layer.
**Decision:** Reconcile to a single taxonomy — backend slugs become `free / pro / starter / enterprise`, matching the marketing surface and Stripe products. Migration `4ce3e594cb87`:
1. Defensive `UPDATE subscriptions SET plan='enterprise' WHERE plan='team'` (dev had zero such rows; safety for any prod stragglers).
2. Rename the `plan_limits.plan='team'` row to `'enterprise'`.
3. Insert a `starter` row with caps interpolated between free and pro: `max_trees=10`, `max_sessions=75`, `max_users=1`, `max_ai_builds_per_month=15`, no KB Accelerator, no custom branding, no priority support.
Code rename across schemas, `Subscription` paid-plan/`has_pro_entitlement` checks, admin endpoints, frontend `useSubscription.isPaidPlan`. Resource visibility (`Tree.visibility='team'`, `StepLibrary.visibility='team'`) is a separate domain and intentionally untouched — that string means "shared with my account" and has nothing to do with the subscription tier.
New `backend/scripts/sync_stripe_plan_ids.py` — idempotent upsert of `plan_billing` rows from Stripe products by exact name match (`ResolutionFlow Starter / Pro / Enterprise`). Picks the active monthly recurring price for tiers that have one. Annual fields stay NULL by design — annual pricing is intentionally out of scope for the soft cutover ("want to be able to exit if necessary without breaching any terms").
**Rejected:**
- **Map marketing names to existing slugs (Option A from the discussion).** Smallest diff but means PricingPage cards have to translate `enterprise``team` at render time, and "Starter" can't exist as a real backend tier — it'd have to be hidden or dropped. Kicks the can.
- **Add `starter` only, keep `team` slug as cosmetic enterprise (Option C).** Mixed taxonomy across layers — slug-vs-display-name divergence guarantees confusion in 6 months. Compromise that's worse than either pure choice.
- **Annual pricing in this iteration.** User's explicit constraint: skip annual to keep exit-flexibility. Schema columns (`annual_price_cents`, `stripe_annual_price_id`) preserved as nullable for future re-enable.
- **Auto-archive the existing Enterprise `$500/mo` test-mode price.** Done manually via Stripe MCP after un-setting the product's `default_price` first. Spec says Enterprise is sales-led with no catalog price.
**Consequences:**
- `plan_billing` table is now seedable and seeded. Test-mode `plan_billing` populated for all 3 tiers via `sync_stripe_plan_ids.py`. Live mode runs the same script after manual Dashboard setup of products + prices.
- New consumers of `Subscription.plan` literal must use `("free", "pro", "starter", "enterprise")`. Three call sites already updated. Backend-wide grep is the safety net for new ones.
- `Subscription.is_paid` and `has_pro_entitlement` now include `starter` — Starter is a paid tier with a real $19.99/mo price.
- 86/86 passing across the subscription/billing/plan/invite/admin sweep after the rename.
- Test fixtures: `conftest.py` plan_limits seed updated to the new taxonomy. `_seed_plan_limits` helper in `test_plans_public.py` is now a true upsert so tests can override `max_users` even when conftest seeded the canonical value.
---
## 2026-05-07 — Standardize backend Python on 3.12
**Context:** Runtime facts had drifted from docs. The backend Dockerfiles and running dev container were already on Python 3.12, GitHub CI had just been updated to 3.12, but project docs still said Python 3.11 and Gitea CI relied on the runner's ambient Python.

View File

@@ -2,47 +2,56 @@
# HANDOFF.md
**Last updated:** 2026-05-08
**Last updated:** 2026-05-07 (PR #162 CI investigation/fixes)
**Active task:** PR #164 (`feat/billing-plan-taxonomy`) open in Gitea with 5 commits at head `2c9f5e9`. Closes the last code blockers for self-serve cutover. After merge, only manual ops remain (Stripe live-mode Dashboard config, Railway prod env vars, internal validation, flag flip). PR #162 and #163 merged into main this session as squash commits `f1be3ab` and `dad5e1f`.
**Active task:** PR #162 (`feat/self-serve-signup-phase-2`) is open in Gitea. Current session is resolving its failing checks.
## Where this session ended
PR #164 commits (oldest → newest):
PR #162 originally failed quickly in Gitea CI. Public Gitea status metadata was available, but job logs redirected to login and no `GITEA_TOKEN` was present. The branch was pushed over SSH.
1. `ba36c47 feat(billing): reconcile plan taxonomy and add Stripe sync script` — migration `4ce3e594cb87` renames `plan_limits.plan='team'``'enterprise'` (defensive update of any subscriptions on the old slug; dev had zero), adds `starter` row with caps interpolated between free and pro. Code rename across schemas, `Subscription` paid-plan checks, admin endpoints, frontend `useSubscription`. Resource visibility (`Tree.visibility='team'`, `StepLibrary.visibility='team'`) is a separate domain and intentionally untouched. New `backend/scripts/sync_stripe_plan_ids.py` — idempotent upsert of `plan_billing` rows from Stripe products by exact name match, picks active monthly recurring price, leaves annual fields NULL by design.
2. `a628b24 chore(dev): pass STRIPE_* env to backend container` — wires `STRIPE_*` + `SELF_SERVE_ENABLED` + `INTERNAL_TESTER_EMAILS` through `docker-compose.dev.yml`. New repo-root `.env.example`.
3. `8494366 feat(billing): add INTERNAL_TESTER_EMAILS allowlist for self-serve soft cutover``Settings.is_internal_tester` + `is_self_serve_active_for`, new `get_current_user_optional` dep, `/config/public` honors allowlist for authenticated callers, `/auth/register` allows allowlisted emails without invite code. 5 regression tests in `test_config_public.py`.
4. `8649a4a docs: refresh CURRENT-STATE, ROADMAP, README, DECISIONS for self-serve cutover` — CURRENT-STATE bumped with PR #159164 entries; ROADMAP got a "Status as of 2026-05-07" preamble (historical content preserved underneath); README fixed legacy `patherly_postgres` and `UI-DESIGN-SYSTEM.md` references; DECISIONS appended two entries.
5. `2c9f5e9 fix(frontend): page-title — escapes + propagate plan taxonomy through frontend types``LandingPage.tsx` had `—` (six literal characters) inside JSX attribute strings, rendering as literal text in browser tabs. Replaced with literal em dash. PageMeta default tagline updated from "Decision Tree Platform" (stale) to "AI-Powered Troubleshooting for MSPs". Fixed TS errors that surfaced from the previous taxonomy commit not propagating through frontend types — `types/{account,admin,billing}.ts`, `admin/{AccountsPage,InviteCodesPage}.tsx`, `AccountSettingsPage.tsx`, `subscription/CheckoutButton.tsx`. tsc -b clean, lint clean.
Fixed environment drift first:
Stripe state (test mode via MCP, livemode=false): 3 active products (Starter $19.99/mo, Pro $29.99/mo, Enterprise no price); leftover Enterprise `$500/mo` test price archived (had to clear `default_price` on the product first); `plan_billing` populated for all three tiers in dev DB via `sync_stripe_plan_ids.py`.
- Standardized backend native/dev/CI Python on 3.12.13 to match Docker.
- Added `.python-version`.
- Rebuilt `backend/venv` from pyenv Python 3.12.13 and verified native `pytest --version` / `alembic --version` with explicit local env.
- Updated Gitea CI backend/e2e Python setup to 3.12.
Working tree clean (only pre-existing untracked files: `abc-feat-self-serve-signup-phase-2-design-...md`, `core.*`, `docs/architecture/`, `docs/tutorials/` — same set noted in prior handoff as "do not stage").
Fixed Gitea runner assumptions next:
Single alembic head: `4ce3e594cb87` after PR #164 merges (was `c6cbfc534fad`).
- Added `actions/setup-node@v4` with Node 20 to Gitea frontend and e2e jobs.
- Pushed `fix(ci): set up node in gitea workflow`.
Local frontend validation then exposed real lint failures in Phase 2 React code under the current lint stack. The current WIP fixes:
- `react-refresh/only-export-components` for exported pure helpers used by tests/shared invite OAuth code.
- `react-hooks/set-state-in-effect` warnings where local state intentionally mirrors route/config/cache state.
- `react-hooks/purity` warnings from `Date.now()` during render.
- Redundant loading-state write in pricing page.
Validation after those frontend changes:
- `docker exec -w /app resolutionflow_frontend npm run lint` passed.
- `docker exec -w /app resolutionflow_frontend npm run test:coverage` passed (`198` tests).
- `docker exec -w /app -e NODE_OPTIONS=--max-old-space-size=4096 resolutionflow_frontend npm run build` passed.
Known local noise:
- React `act(...)` warnings appeared in existing tests during coverage but did not fail the suite.
- Vite emitted large chunk warnings during build.
- Unrelated dirty/untracked files remain and should not be staged unless explicitly requested: `docker-compose.dev.yml`, `.env.example`, `abc-feat-self-serve-signup-phase-2-design-20260507-112020.md`, `core.*`, `docs/architecture/`, `docs/tutorials/`.
## Resume point
1. Verify PR #164 CI green:
`curl -fsSL https://gitea.resolutionflow.com/api/v1/repos/chihlasm/resolutionflow/commits/2c9f5e9/status | python -m json.tool`
2. Squash-merge PR #164.
3. **Phase O manual ops** (after merge):
- Stripe Dashboard live-mode: 3 Products, monthly Prices for Starter ($19.99) + Pro ($29.99), no Prices on Enterprise (sales-led), Customer Portal with plan-switching disabled, webhook at `https://api.resolutionflow.com/api/v1/webhooks/stripe` with 5 events. Save live signing secret.
- Railway prod env: `STRIPE_SECRET_KEY=sk_live_...`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_PUBLISHABLE_KEY` + `VITE_STRIPE_PUBLISHABLE_KEY` (frontend redeploy required — Vite bake-at-build, Lesson 60), `OAUTH_REDIRECT_BASE=https://resolutionflow.com`, `SELF_SERVE_ENABLED=false` (still false at this point), `INTERNAL_TESTER_EMAILS=<allowlist>`, prod Google + Microsoft OAuth credentials.
- Run sync against prod backend: `railway run python -m scripts.sync_stripe_plan_ids`. Verify `plan_billing` rows have `sk_live_*` price IDs.
4. Internal validation (Phase O Task 46): 9 scenarios with internal testers whose emails match `INTERNAL_TESTER_EMAILS`.
5. Flag flip (Task 47): email pilots, set `SELF_SERVE_ENABLED=true` + `VITE_SELF_SERVE_ENABLED=true` (frontend redeploy). PostHog signup-funnel dashboard + Sentry alert at >1/hour Stripe webhook errors.
## Open issues from this session (non-code, user-side)
- **Apex DNS missing.** `resolutionflow.com` (apex) returns no A/CNAME at the authoritative DNS (Namecheap per SOA `dns1.registrar-servers.com.`). When `www` was reconfigured in Railway, the apex record got dropped from the zone. `www` works (cert provisioned 2026-05-08 01:40 UTC, valid Let's Encrypt SAN). Symptom: apex unreachable from user's machine; Stripe verifier "URL couldn't be reached." User to re-add apex record at Namecheap (ALIAS Record host=`@` value=`c9g7uku8.up.railway.app`) or re-add the apex as a Railway custom domain and follow Railway's DNS instructions. The Railway path is more durable.
- **Edge HSTS sticky state on user's machine.** Browser remembers the earlier broken-cert visit. Fix: `edge://net-internals/#hsts` (delete `resolutionflow.com` and `www.resolutionflow.com`) + `#dns` clear host cache + `#sockets` flush. Cert IS valid on the wire (proven by `curl --resolve` returning 200 OK from the user's box).
1. Commit the frontend lint fixes and `.ai/` handoff updates with the required Codex trailer.
2. Push `feat/self-serve-signup-phase-2`.
3. Poll Gitea PR #162 statuses for the new head SHA:
`curl -fsSL https://gitea.resolutionflow.com/api/v1/repos/chihlasm/resolutionflow/statuses/<sha> | python -m json.tool`
4. If statuses are still pending, report that local frontend CI is green and Gitea runner work is queued/running. If a check fails, public statuses may show only the context/description; logs require authenticated Gitea access.
## Carry-forward
- Annual pricing intentionally NOT implemented — user wants exit flexibility ("want to be able to exit if necessary without breaching any terms"). Schema columns (`annual_price_cents`, `stripe_annual_price_id`) preserved as nullable for future re-enable. `sync_stripe_plan_ids.py` leaves annual fields NULL.
- `INTERNAL_TESTER_EMAILS` parsed comma-separated → normalized lowercase list. Anonymous callers always see the global flag — allowlist never leaks via unauthenticated request content (regression test enforces).
- Office-hours design doc from this session at `~/.gstack/projects/chihlasm-resolutionflow/abc-feat-self-serve-signup-phase-2-design-20260507-112020.md`. Captures the "documentation builder" thesis (cut branching Flows from pilot UI, focus on Day 1 onboarding checklist + 3 deep-capture procedures + Hudu/IT Glue/CW output). Pre-build assignment: 3 cold calls with external Directors of Onboarding before scoping the build. NOT yet adopted as roadmap — gated on the validation calls.
- Frontend lint shows 3 warnings in `coverage/` (auto-generated). Untouched.
- Backend env: `SALES_LEAD_RECIPIENT_EMAIL`. Frontend env additions for cutover: `VITE_SELF_SERVE_ENABLED`, `VITE_GOOGLE_CLIENT_ID`, `VITE_MS_CLIENT_ID`, `VITE_OAUTH_REDIRECT_BASE`, `VITE_CALENDLY_URL`, `VITE_STRIPE_PUBLISHABLE_KEY`.
- Phase O manual ops remain pending after PR review/merge: Stripe live setup, internal validation, feature-flag flip.
- Backend env: `SALES_LEAD_RECIPIENT_EMAIL`.
- Frontend env: `VITE_SELF_SERVE_ENABLED`, `VITE_GOOGLE_CLIENT_ID`, `VITE_MS_CLIENT_ID`, `VITE_OAUTH_REDIRECT_BASE`, `VITE_CALENDLY_URL`.
- Single alembic head remains `c6cbfc534fad`; Phase 2 added no migrations.

View File

@@ -12,32 +12,6 @@
---
## 2026-05-08 03:30 UTC — Claude — PR #164 self-serve cutover code blockers, doc refresh, page-title bug, DNS triage
**Accomplished:**
- Merged PR #162 (self-serve Phase 2 frontend) and PR #163 (seed users email-verified) into main via Gitea API squash merge. Created branch `feat/billing-plan-taxonomy` off the new main; pushed 5 commits closing the last code blockers for Phase O cutover. PR #164 opened at gitea pulls/164.
- Plan taxonomy reconciliation. Discovered the marketing surface (PricingPage, Stripe products) was wired for `Starter / Pro / Enterprise` while backend was on `free / pro / team`; `BillingPlan` schema's `Literal["pro","starter","team","enterprise"]` could accept FK-violating values; `plan_billing` was unseeded. Migration `4ce3e594cb87` renames `plan_limits.plan='team'``'enterprise'` (defensive update of any subscriptions on the old slug; dev had zero), adds `starter` row with caps interpolated between free and pro (`max_trees=10`, `sessions=75`, `users=1`, `ai=15/mo`, no KB Accelerator, no custom branding, no priority support). Code rename across schemas (`invite_code`, `billing`, `admin`, `subscription`), `Subscription` paid-plan/`has_pro_entitlement` checks, `admin_dashboard.py`, `admin.py`, frontend `useSubscription.isPaidPlan`. Resource visibility (`Tree.visibility='team'`, `StepLibrary.visibility='team'`) is a separate domain (means "shared with my account") and intentionally untouched. 86/86 passing across subscription/billing/plan/invite/admin sweep after the rename. Conftest plan_limits seed + `_seed_plan_limits` helper made a true upsert.
- New `backend/scripts/sync_stripe_plan_ids.py` — idempotent upsert from Stripe products by exact name match (`ResolutionFlow Starter / Pro / Enterprise`), picks active monthly recurring price, leaves annual fields NULL by design. Works against test or live keys via `STRIPE_SECRET_KEY`. Run against test mode populated `plan_billing` for all 3 tiers in dev DB. Annual pricing intentionally skipped per user's exit-flexibility constraint.
- Stripe MCP work (test mode, `livemode=false`): archived leftover Enterprise `$500/mo` test price (had to clear the product's `default_price` first — Stripe blocks archive otherwise). Verified test-mode product set: Starter $19.99/mo, Pro $29.99/mo, Enterprise no price (sales-led).
- `INTERNAL_TESTER_EMAILS` allowlist. Phase O Task 46 needed it as a code blocker (flagged in prior SESSION_LOG as "backend support is NOT yet built"). `Settings.is_internal_tester` (case-insensitive membership) + `is_self_serve_active_for(email)` (returns global flag OR allowlist hit) centralize the check. New `get_current_user_optional` dep — best-effort auth that returns `None` instead of 401, used by `/config/public` so the same endpoint serves anonymous and authed. `/config/public` returns `self_serve_enabled=true` for authenticated allowlist members; `/auth/register` allows allowlisted emails without invite code. 5 regression tests including "anonymous callers always see the global flag" (prevents leak via unauthenticated request content).
- Stripe env passthrough: `docker-compose.dev.yml` now wires `STRIPE_*` + `SELF_SERVE_ENABLED` + `INTERNAL_TESTER_EMAILS` into the backend container. New repo-root `.env.example`. `backend/.env.example` updated with the self-serve cutover vars.
- Page-title bug fix on `LandingPage.tsx`. Two JSX attribute strings (`title="..."`, `description="..."`) had `—` (six literal characters) — JSX attribute strings don't process JS escape sequences, so the browser tab and OG description rendered the literal text instead of an em dash. Replaced with the literal em dash character. Verified by grep — every other `\u...` in the codebase is inside a real JS string (`'...'` literal or `{...}` JSX expression) where escapes resolve at compile time. PageMeta default tagline updated from stale "Decision Tree Platform" to "AI-Powered Troubleshooting for MSPs" (matches index.html and brand positioning).
- Frontend taxonomy followups (caught by tsc -b after rebuild). The earlier taxonomy commit didn't propagate through frontend types: `types/account.ts`, `types/admin.ts`, `types/billing.ts`, `admin/AccountsPage.tsx` (state type, select onChange cast, `<option value="team">` rendered UI), `admin/InviteCodesPage.tsx` (PLAN_OPTIONS array, state type, onChange cast), `AccountSettingsPage.tsx` (`plan !== 'team'` check + CheckoutButton prop), `subscription/CheckoutButton.tsx` (prop type + planLabels). All updated to `'free' | 'pro' | 'starter' | 'enterprise'`. tsc clean. Lint clean (3 warnings only in auto-generated `coverage/`).
- Doc refresh commit (`docs: refresh CURRENT-STATE, ROADMAP, README, DECISIONS for self-serve cutover`). CURRENT-STATE bumped to 2026-05-07; added entries for PR #159164; refreshed What's In Progress / What's Next around Phase O. ROADMAP got a "Status as of 2026-05-07" preamble (months-stale historical content kept underneath as record); In Progress and What's Next sections updated. README fixed legacy `patherly_postgres` Docker command, project-tree path, `UI-DESIGN-SYSTEM.md` reference; added `AGENTS.md`, `PROJECT_CONTEXT.md`, `PRODUCT.md` to docs table. DECISIONS appended two entries (taxonomy reconciliation, allowlist).
- Office-hours session ran via `/office-hours` skill earlier in this session. Design doc saved at `~/.gstack/projects/chihlasm-resolutionflow/abc-feat-self-serve-signup-phase-2-design-20260507-112020.md`. Captured the "documentation builder" thesis — cut branching Flows from pilot UI, focus product around FlowPilot + Day 1 onboarding checklist as navigational frame + 3 deep-capture procedures (M365 tenant build, Windows server build, credential vault) + Hudu/IT Glue/ConnectWise output. Founder is a Director-of-Onboarding at his own MSP (Andrea Henry); pre-build assignment is 3 cold calls with external Directors of Onboarding before scoping. NOT yet adopted as roadmap.
- DNS / cert triage: `www.resolutionflow.com` was unreachable (Railway "train hasn't arrived" page) — user added it as a custom domain in Railway, cert provisioned at 2026-05-08 01:40 UTC, `www` now serves 200 with valid Let's Encrypt SAN. Apex `resolutionflow.com` separately discovered to have NO A/CNAME at authoritative DNS (Namecheap per SOA `dns1.registrar-servers.com.`). When user reconfigured `www`, the apex record dropped from the zone. From Railway-edge IP both names work fine when DNS is forced (proven by `curl --resolve` returning 200 OK from user's box) — so the apex cert is also valid; the failure mode is purely DNS-level absence. User asked for HSTS clearance steps in Edge — provided `edge://net-internals/#hsts`, `#dns`, `#sockets` walkthrough plus Linux DNS flush options.
**Left for next session:**
- Verify PR #164 CI green, then squash-merge.
- Phase O manual ops sequence (Stripe Dashboard live-mode setup, Railway prod env vars including `INTERNAL_TESTER_EMAILS`, run `sync_stripe_plan_ids.py` against prod, internal validation Task 46, flag flip Task 47, PostHog dashboards, Sentry alert).
- User-side: re-add apex DNS record at Namecheap (ALIAS `@``c9g7uku8.up.railway.app`, or re-add apex in Railway), clear Edge HSTS state.
**Files touched (all on `feat/billing-plan-taxonomy`, all pushed):** `backend/alembic/versions/4ce3e594cb87_add_starter_rename_team_to_enterprise.py` (new), `backend/scripts/sync_stripe_plan_ids.py` (new), `backend/app/{schemas/{billing,invite_code,admin,subscription}.py, models/subscription.py, api/{deps.py, endpoints/{auth.py, admin.py, admin_dashboard.py, config.py}}, core/config.py}`, `frontend/src/{components/{common/PageMeta.tsx, subscription/CheckoutButton.tsx}, hooks/useSubscription.ts, pages/{LandingPage.tsx, AccountSettingsPage.tsx, admin/{AccountsPage.tsx, InviteCodesPage.tsx}}, types/{account.ts, admin.ts, billing.ts}}`, `backend/tests/{conftest.py, test_admin_plan_limits.py, test_invite_plan.py, test_plans_public.py, test_config_public.py}`, `docker-compose.dev.yml`, `.env.example` (new), `backend/.env.example`, `CURRENT-STATE.md`, `03-DEVELOPMENT-ROADMAP.md`, `README.md`, `.ai/{DECISIONS.md, HANDOFF.md, CURRENT_TASK.md, SESSION_LOG.md}`.
---
## 2026-05-07 11:45 EDT — Codex — Push PR #162 CI runner setup fixes
- Inspected Gitea PR #162 via public API. PR head was `380fcf7` and all CI jobs failed quickly; pushed local commits through `4a37a47`, including Python 3.12 setup for Gitea backend/e2e jobs.

View File

@@ -1,12 +0,0 @@
REPO_ROOT=/opt/docker/code-server/workspace/resolutionflow
POSTGRES_PORT=5433
SECRET_KEY=
ANTHROPIC_API_KEY=
GOOGLE_AI_API_KEY=
STRIPE_SECRET_KEY=sk_test_
STRIPE_PUBLISHABLE_KEY=pk_test_
STRIPE_WEBHOOK_SECRET=whsec_
VITE_STRIPE_PUBLISHABLE_KEY=pk_test_
INTERNAL_TESTER_EMAILS=internaltest@resolutionflow.com

View File

@@ -1,25 +1,11 @@
# Development Roadmap
> **Last Updated:** May 7, 2026
> **Product:** ResolutionFlow (repo path: `resolutionflow/`; `patherly` is the legacy internal name)
> **Last Updated:** March 18, 2026
> **Product:** ResolutionFlow (repo: patherly)
> **Target Market:** MSP companies — IT service providers managing infrastructure and support for multiple clients
---
## Status as of 2026-05-07
The historical phase content below (Phase 1 through Phase 5) is preserved as a factual record. **This section is the live status overlay — read it first.**
**Where we are:** Pre-PMF, Go-to-Market Validation. Backend feature-complete (50+ endpoints, 100+ tests). FlowPilot session UX is the daily-driver surface and recently went through PR #155 (escalation wedge), #156 (`applied_pending` non-terminal status), #158 (impeccable pass + tasklane keyboard flow), #159 (Diátaxis User Guides), #160 (sidebar IA + account redesign).
**Currently in flight:** Self-serve signup cutover. Phase 1 backend (#161) and Phase 2 frontend (#162) merged. PR #164 (open) closes the last code blockers — plan taxonomy reconciliation (`team``enterprise`, add `starter`) and `INTERNAL_TESTER_EMAILS` allowlist for the soft cutover. After merge, remaining work is **manual operations only**: Stripe Dashboard live-mode setup, Railway prod env vars, internal validation pass, public flag flip. See `docs/superpowers/plans/2026-05-06-self-serve-signup-phase-2-frontend-cutover.md` Phase O for the checklist.
**Product thesis being tested:** "We're not a documentation app. We are the documentation builders." Captured in `~/.gstack/projects/chihlasm-resolutionflow/abc-feat-self-serve-signup-phase-2-design-20260507-112020.md` (office-hours design doc). Pre-build assignment: 3 calls with external Directors of Onboarding (cold, no friendly contacts) to validate the framing before adopting it as the public positioning.
**What's not yet decided:** Whether to formally cut branching Flows from the pilot UI surface in favor of a Project (linear procedure) + FlowPilot + Documentation-Builder positioning. Discussed in /office-hours but no implementation work scheduled — gated on the 3 external validation calls.
---
## Completed Work
### Phase 1: MVP
@@ -86,26 +72,13 @@ The historical phase content below (Phase 1 through Phase 5) is preserved as a f
| Task | Status | Notes |
|------|--------|-------|
| Self-serve signup cutover (Phase O) | In Progress | PR #164 merge → Stripe live-mode Dashboard setup → Railway prod env vars → internal validation → public flag flip. Code blockers cleared by #164 (taxonomy + `INTERNAL_TESTER_EMAILS` allowlist). |
| External validation of documentation-builder thesis | Not started | 3 calls with external Directors of Onboarding (cold). Decision gate before scoping a "Day 1 onboarding checklist" build. |
| ConnectWise PSA Integration (Advanced) | Deferred | Core complete — ticket linking, note posting, member mapping, ticket context retrieval. Callback webhooks deferred until pilot signal demands them. |
| ConnectWise PSA Integration (Advanced) | In Progress | Core done — ticket linking, note posting, member mapping. Remaining: callback webhooks, deeper ticket context in sessions |
| PR #114 Merge | In Progress | Empty states, onboarding, PDF exports, branding, supporting data — ready for review |
---
## What's Next
### Phase O Cutover (Weeks 0-1)
| Step | Status |
|---|---|
| Merge PR #164 (taxonomy reconciliation + allowlist) | Open, CI green |
| Stripe Dashboard live-mode setup (Products + Prices for Starter/Pro, no Prices on Enterprise, Customer Portal config, webhook endpoint with 5 events) | Manual op |
| Railway prod env vars (`sk_live_*`, `whsec_*`, `INTERNAL_TESTER_EMAILS`, prod Google + Microsoft OAuth credentials, `OAUTH_REDIRECT_BASE`, `STRIPE_PUBLISHABLE_KEY`, `VITE_STRIPE_PUBLISHABLE_KEY` for frontend redeploy) | Manual op |
| Run `python -m scripts.sync_stripe_plan_ids` against prod backend; verify `plan_billing` has `sk_live_*` price IDs | Manual op |
| Internal validation pass (9 scenarios from Phase O Task 46) | Manual op |
| Email pilots about complimentary status, flip `SELF_SERVE_ENABLED=true` (frontend redeploy required for `VITE_SELF_SERVE_ENABLED`) | Manual op |
| PostHog signup-funnel dashboard + Sentry alert at >1/hour Stripe webhook errors | Manual op |
### Near-Term Priorities (from Stack Priorities Plan)
| Feature | Status | Description |
@@ -113,7 +86,7 @@ The historical phase content below (Phase 1 through Phase 5) is preserved as a f
| Coverage gates in CI | ✅ Complete | Backend enforced at 80%, frontend coverage reporting enabled |
| Security headers | ✅ Complete | HSTS, CSP (report-only), X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy |
| Web Vitals / performance budgets | ✅ Complete | LCP, INP, CLS, FCP, TTFB reported to PostHog via web-vitals |
| Search and recall improvements | ✅ Complete | Structured filters + FTS + Voyage AI semantic search shipped (see CURRENT-STATE.md "Search & Recall" section) |
| Search and recall improvements | ⬜ Not started | Search sessions by flow, tag, client, ticket context |
### 3A: Quick Wins & UX (Priority: Medium)

View File

@@ -2,32 +2,16 @@
> **Purpose:** Quick-reference file showing exactly where the project stands.
> **For Claude Code:** Read this first to understand what's done and what's next.
> **Last Updated:** May 7, 2026
> **Last Updated:** May 1, 2026
---
## Active Phase: Go-to-Market Validation (Pre-PMF) — Self-serve cutover (Phase O) in flight
Self-serve signup backend (Phase 1) and frontend (Phase 2) are merged. Cutover (Phase O) is gated on manual ops: live-mode Stripe Dashboard config, Railway prod env vars, internal validation pass against prod test mode, then the public flag flip. Plan: `docs/superpowers/plans/2026-05-06-self-serve-signup-phase-2-frontend-cutover.md`.
## Active Phase: Go-to-Market Validation (Pre-PMF)
---
## Recently shipped (post-0.1.0.0)
- **2026-05-13 — `feat/session-expiration-policy` (open)** Session expiration policy series — 8 commits, fixes the "logged in forever" bug and adds owner-side controls. Migration `b269a1add160` adds `accounts.session_idle_minutes` + `session_absolute_minutes` (NULL = use system default, defaults Strict 3d/14d via `Settings.SESSION_*_MINUTES_DEFAULT`). Refresh-token JWT carries `auth_time` + `idle_max` + `abs_max` claims (seconds) snapshotted at every login entry point (`/auth/login`, `/auth/login/json`, both OAuth callbacks). `/auth/refresh` enforces absolute cap (`now >= auth_time + abs_max` → 401 `session_expired_absolute`), atomic-revoke-then-check prevents replay. Error-detail taxonomy on the wire distinguishes `session_expired_idle` / `session_expired_absolute` / `invalid_refresh_token`. New owner-only `GET/PATCH /accounts/me/security` returns `{idle_minutes, absolute_minutes, effective_*, *_min/max, active_users}` with audit logging on PATCH. `POST /accounts/me/security/revoke-sessions` bulk-revokes refresh tokens for the account (`scope: "all" | "others"`), audited. Frontend: new `/account/security` page (Strict/Standard/Custom presets, active-users list with name + email + last-login-ago, count-aware revoke buttons + confirmation modal), `useAuthSessionExpiry` hook + top-of-app `SessionExpiryToast` (differentiated by idle vs absolute), cyan info-tone banner on `/login?reason=session_expired`. Plan + design review in `docs/plans/2026-05-13-session-expiration-policy.md` (initial 4/10 → 9/10 via `/plan-design-review`). 28 backend tests; tsc clean. Pending: open PR, merge, document follow-up issues (per-user device list, super-admin global ceiling UI).
- **2026-05-07 — PR #164 (open)** Plan taxonomy reconciliation + `INTERNAL_TESTER_EMAILS` allowlist. Marketing surface (PricingPage, Stripe products) used `Starter / Pro / Enterprise` while backend was on `free / pro / team`, leaving `plan_billing` unseeded and `BillingPlan` schema accepting a literal that violated the FK. Migration `4ce3e594cb87`: rename `team``enterprise` in `plan_limits`, add `starter` row (caps interpolated between free and pro: `max_trees=10`, `sessions=75`, `ai=15/mo`), defensive update of any subscriptions on the `team` slug. Code rename across schemas, `Subscription` paid-plan checks, admin endpoints, and frontend `useSubscription`. Resource visibility (`Tree.visibility='team'`, `StepLibrary.visibility='team'`) is a separate domain and intentionally untouched. New `backend/scripts/sync_stripe_plan_ids.py` — idempotent upsert of `plan_billing` rows from Stripe products by exact name match, picks active monthly recurring price, leaves annual fields NULL by design. Test-mode `plan_billing` populated for all 3 tiers in dev. Phase O Task 46 allowlist: `INTERNAL_TESTER_EMAILS` env var (comma-separated) bypasses `SELF_SERVE_ENABLED=false` for specific authenticated users — `Settings.is_self_serve_active_for(email)` centralizes the check; `/config/public` returns `self_serve_enabled=true` for allowlisted authenticated callers; `/auth/register` allows allowlisted emails to register without invite code. New `get_current_user_optional` dep for endpoints that work both anonymous and authed.
- **2026-05-06 — PR #163** Seed test users marked email-verified. Fixed seeded users showing the email verification banner in dev/test, blocking flows that gate on `email_verified=True`. Squash-merged into main as `dad5e1f`.
- **2026-05-06 — PR #162** Self-serve signup Phase 2 (frontend cutover). 18 commits across Tasks 2744 of the Phase 2 plan: backend remainders + frontend billing foundation + auth surfaces (OAuth + accept-invite + verify-email) + welcome wizard + dashboard redesign (TrialPill, NextStepCard, unified checklist) + public surfaces (`/pricing`, `/contact-sales`) + beta-signup deprecation. Single alembic head `c6cbfc534fad` (no new migrations in Phase 2). Squash-merged as `f1be3ab`.
- **2026-05-?? — PR #161** Self-serve signup backend (Phase 1). `plan_billing` sibling table for Stripe + catalog metadata, `sales_leads` and `stripe_events` tables, `complimentary` status with `has_pro_entitlement`, `BillingService.start_trial` wired into `/auth/register`, `/billing/checkout-session`, Stripe webhook handler with idempotency via `stripe_events`, Google + Microsoft OAuth callbacks with `oauth_identities` linking, `require_verified_email_after_grace` + `require_active_subscription` guards, bulk-create + soft-revoke invite endpoints, account-invite email-match enforcement, pilot complimentary backfill, `accounts.team_size_bucket` + `primary_psa` for wizard. Squash-merged as `f918b76`.
- **2026-05-02 — PR #159** In-product User Guides rewrite to Diátaxis how-tos. Replaced 15 feature-dump guides with 43 problem-oriented how-tos grouped under 10 categories. Dropped Maintenance Flows / AI Assistant / Flow Assist Sparkles guides (UI no longer exists). Renamed Step Library → Solutions Library. Authored 14 net-new how-tos for FlowPilot-era surfaces (tasklane keyboard flow, what-we-know, resolve, escalate, record-fix-outcome, post-docs-to-ticket, share-update, pause-and-leave, build-script-from-scratch, open-suggested-flow, pin-a-flow, invite-teammate, etc.). Schema additions: `category`, optional `relatedSlugs`. Browser-verified against engineer + owner login.
- **2026-05-?? — PR #160** Post-PR-159 UI cleanup — sidebar IA + account redesign. Squash-merged as `a8b22cf`.
- **2026-05-01 — PR #158** Session-screen UX impeccable pass + tasklane keyboard flow. Heuristic score 24/40 → 33/40 across five sub-passes (distill, quieter, layout, typeset, polish). Removed duplicate "Suggested checks" chip strip → TaskLane is the single source of truth; added inline `Next steps · N pending` cue on the latest action-bearing AI bubble; consolidated session header to Resolve + Escalate + ⋯ kebab; centered messages column to match composer; dropped all banned decorations (side stripes, gradient surfaces, backdrop blur, accent borderTop) for a single decoration channel per surface; unified 14 text sizes into a 5-step scale. TaskLane keyboard flow: Enter submits + auto-advances, Shift+Enter newline, Esc cancel, focus jumps to Send after the last task. Banner ↔ script-panel are now linked (collapse hides both, any outcome closes both). WhatWeKnow section is collapsible with `sessionStorage` memory + auto-collapse-at-5-facts. Side fix: ParameterizationPreview no longer over-highlights short parameter values (word-boundary check). Two backlog entries logged in `.ai/TODO.md`: ConcludeSessionModal multi-select and `bg-card-hover` Tailwind drift in CommandPalette.
- **2026-05-01 — PR #156** Suggested-fix "Awaiting verification" outcome. Engineers can now park a fix in `applied_pending` (waiting on client power-cycle, AD replication, license sync, etc.) instead of forcing a synchronous worked/didn't/partial verdict. PendingBanner with worked / didn't / update reason / dismiss; nudge "Still checking" records pending with a reason; page-level Resolve auto-patches pending → success before the resolution flow opens; page-level Escalate intercepts pending. Migration `c0f3a4b7e91d` (`pending_reason` column + status CHECK constraint).
- **2026-04-30 — PR #155** Escalation Mode wedge. Magic-moment handoff-context screen for senior pickup, live SSE escalation arrivals, post-claim time-to-first-action metric (`GET /analytics/flowpilot/escalations`), atomic role-gated claim with conflict resolution, queue self-exclusion, chat ownership extended to claimed sessions. The wedge for the first paying-customer push.
@@ -231,30 +215,17 @@ Self-serve signup backend (Phase 1) and frontend (Phase 2) are merged. Cutover (
## What's In Progress
- **Self-serve cutover (Phase O):** PR #164 (open) closes the last code blockers — taxonomy reconciliation + `INTERNAL_TESTER_EMAILS` allowlist. After merge, remaining work is purely manual ops: live-mode Stripe Dashboard config, Railway prod env vars, internal validation pass with Andrea Henry + 2-3 external Directors of Onboarding, then `SELF_SERVE_ENABLED=true` flip with frontend redeploy.
- **Stripe live-mode setup:** Test-mode is fully wired (3 products, monthly prices for Starter/Pro, Enterprise sales-led, `plan_billing` seeded via `sync_stripe_plan_ids.py`). Live mode requires manual Dashboard config — same script handles seeding live IDs.
- **GTM Validation:** Shadow & Ship — founder uses product for real MSP tickets daily, then hands logins to 5 colleagues.
- **Solutions Library spec:** Written at `docs/plans/2026-03-23-solutions-library-design.md`, implementation deferred to post-pilot.
- **GTM Validation:** Shadow & Ship — founder uses product for 2 weeks, then hands logins to 5 colleagues
- **Solutions Library spec:** Written at `docs/plans/2026-03-23-solutions-library-design.md`, implementation deferred to post-pilot
---
## What's Next (Priority Order)
### Phase O Cutover (Weeks 0-1)
- Merge PR #164
- Stripe Dashboard live-mode setup (Products + Prices for Starter/Pro, no Prices on Enterprise, Customer Portal config, webhook endpoint with 5 events)
- Railway prod env vars (`sk_live_*`, `whsec_*`, `INTERNAL_TESTER_EMAILS`, prod Google + Microsoft OAuth credentials, `OAUTH_REDIRECT_BASE`)
- Run `sync_stripe_plan_ids.py` against prod backend; verify `plan_billing` has `sk_live_*` price IDs
- Internal validation pass (9 scenarios from Phase O Task 46 plan)
- Email pilots about complimentary status, flip `SELF_SERVE_ENABLED=true` (frontend redeploy required for `VITE_SELF_SERVE_ENABLED`)
- PostHog dashboards + Sentry alert at >1/hour Stripe webhook errors
### Pilot Phase (Weeks 1-2)
- Founder dogfooding: use ResolutionFlow for real MSP tickets daily
- 3 calls with external Directors of Onboarding to validate the documentation-builder thesis (cold pitch, no friendly contacts)
- Collect feedback on copilot-first experience and self-serve onboarding flow
- Collect feedback on copilot-first experience
- Fix issues discovered during real usage
### Post-Pilot (Weeks 3-4)

View File

@@ -13,8 +13,8 @@
```bash
# Prerequisites: Docker, Python 3.12, Node.js 20+
# Start PostgreSQL (and the rest of the dev stack)
docker compose -f docker-compose.dev.yml up -d
# Start PostgreSQL
docker start patherly_postgres
# Backend
cd backend
@@ -105,17 +105,16 @@ Every session generates timestamped, detailed notes formatted for your PSA. Engi
## Project Structure
```
resolutionflow/
patherly/
├── backend/
│ ├── app/
│ │ ├── main.py # FastAPI entry point
│ │ ├── api/endpoints/ # Route handlers (50+ endpoints)
│ │ ├── api/endpoints/ # Route handlers (35+ endpoints)
│ │ ├── core/ # Config, database, permissions, security
│ │ ├── models/ # SQLAlchemy models
│ │ ├── schemas/ # Pydantic schemas
│ │ └── services/psa/ # PSA provider abstraction layer
│ ├── alembic/ # Database migrations
│ ├── scripts/ # Seed + sync scripts (incl. sync_stripe_plan_ids.py)
│ └── tests/ # Integration tests (100+)
├── frontend/
│ ├── src/
@@ -123,19 +122,13 @@ resolutionflow/
│ │ ├── pages/ # Page components
│ │ ├── store/ # Zustand stores
│ │ └── types/ # TypeScript interfaces
├── .ai/ # Dual-agent handoff system (PROJECT_CONTEXT, HANDOFF, etc.)
├── docs/ # Design docs, plans, ConnectWise reference
├── brand-assets/ # SVGs, brand guide
├── CLAUDE.md # AI assistant project context (Claude Code)
├── AGENTS.md # AI assistant project context (Codex; shared protocol with CLAUDE.md)
├── CLAUDE.md # AI assistant project context
├── CURRENT-STATE.md # Detailed feature status
├── DESIGN-SYSTEM.md # Visual + interaction design system
├── PRODUCT.md # Design intent and brand personality
└── CHANGELOG.md # Release history
```
> The on-disk repo path is `resolutionflow/`. `patherly` is the legacy internal name — still appears in some Railway service names and the prod DB name. Treat as an alias, not canonical.
---
## Running Tests
@@ -156,13 +149,10 @@ npm run build
| Document | Purpose |
|----------|---------|
| [CLAUDE.md](CLAUDE.md) | Project context for Claude Code |
| [AGENTS.md](AGENTS.md) | Project context for Codex (shared protocol with CLAUDE.md) |
| [.ai/PROJECT_CONTEXT.md](.ai/PROJECT_CONTEXT.md) | Stable architectural truth |
| [CLAUDE.md](CLAUDE.md) | Full project context for AI-assisted development |
| [CURRENT-STATE.md](CURRENT-STATE.md) | Detailed feature status |
| [03-DEVELOPMENT-ROADMAP.md](03-DEVELOPMENT-ROADMAP.md) | Development roadmap |
| [DESIGN-SYSTEM.md](DESIGN-SYSTEM.md) | Visual + interaction design system (charcoal palette + electric blue accent) |
| [PRODUCT.md](PRODUCT.md) | Design intent, users, brand personality |
| [UI-DESIGN-SYSTEM.md](UI-DESIGN-SYSTEM.md) | Design system (Slate & Ice) |
| [DEV-ENV.md](DEV-ENV.md) | Development environment setup |
| [CHANGELOG.md](CHANGELOG.md) | Release history |

View File

@@ -29,14 +29,4 @@ CW_CLIENT_ID=<CONNECTWISE CLIENT ID>
# When unset, app/core/config.py:stripe_enabled returns False and Stripe code paths short-circuit.
STRIPE_SECRET_KEY=sk_test_
STRIPE_PUBLISHABLE_KEY=pk_test_
STRIPE_WEBHOOK_SECRET=whsec_
# Self-serve cutover
# SELF_SERVE_ENABLED is the master switch for the public self-serve signup
# flow (pricing page, invite-code-optional registration). Default is false
# until Phase O cutover.
# INTERNAL_TESTER_EMAILS is a comma-separated allowlist that bypasses the
# global flag for specific users — used for prod test-mode validation
# before the public flip. Empty by default.
SELF_SERVE_ENABLED=false
INTERNAL_TESTER_EMAILS=
STRIPE_WEBHOOK_SECRET=whsec_

View File

@@ -1,84 +0,0 @@
"""add_starter_rename_team_to_enterprise
Revision ID: 4ce3e594cb87
Revises: c6cbfc534fad
Create Date: 2026-05-07 19:36:27.172082
Plan tier taxonomy reconciliation. Marketing surface and Stripe products
named "Starter / Pro / Enterprise"; backend was on "free / pro / team".
This migration:
1. Defensively migrates any existing subscriptions on plan='team' to
plan='enterprise' (dev has zero such rows; prod is expected to have
none, but the UPDATE is safe and idempotent).
2. Renames the plan_limits row 'team' -> 'enterprise'. plan_billing
and plan_feature_defaults are FK-referenced but currently empty;
the rename works because PostgreSQL allows updating PK values when
no FK rows reference them.
3. Inserts a new plan_limits row for 'starter' between free and pro.
Resource visibility (Tree.visibility, StepLibrary.visibility) also uses
the string 'team' for "shared with my account" — that is a separate
domain and is intentionally not touched.
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = '4ce3e594cb87'
down_revision: Union[str, None] = 'c6cbfc534fad'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.execute("UPDATE subscriptions SET plan = 'enterprise' WHERE plan = 'team'")
op.execute("UPDATE plan_limits SET plan = 'enterprise' WHERE plan = 'team'")
op.execute("""
INSERT INTO plan_limits (
plan,
max_trees,
max_sessions_per_month,
max_users,
custom_branding,
priority_support,
export_formats,
max_ai_builds_per_month,
max_ai_builds_per_24h,
kb_accelerator_enabled,
kb_max_lifetime_conversions,
kb_batch_max_size,
kb_allowed_formats,
kb_detailed_analysis,
kb_conversational_refinement,
kb_step_library_matching,
kb_history_limit
) VALUES (
'starter',
10,
75,
1,
FALSE,
FALSE,
'["markdown", "text", "html"]'::jsonb,
15,
5,
FALSE,
NULL,
NULL,
'["txt", "paste", "md"]'::jsonb,
FALSE,
FALSE,
FALSE,
NULL
)
ON CONFLICT (plan) DO NOTHING
""")
def downgrade() -> None:
op.execute("DELETE FROM plan_limits WHERE plan = 'starter'")
op.execute("UPDATE plan_limits SET plan = 'team' WHERE plan = 'enterprise'")
op.execute("UPDATE subscriptions SET plan = 'team' WHERE plan = 'enterprise'")

View File

@@ -1,72 +0,0 @@
"""add_session_policy_columns_to_accounts
Revision ID: b269a1add160
Revises: 4ce3e594cb87
Create Date: 2026-05-13 19:50:51.343777
Adds per-account session-policy overrides. NULL on either column means
"use the system default from Settings.SESSION_*_MINUTES_DEFAULT." The
CHECK constraint is defense-in-depth for the both-set case; the partial-
override case (one NULL, one set) is validated at the app layer because
the DB cannot see Settings.
See docs/plans/2026-05-13-session-expiration-policy.md for full design.
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = 'b269a1add160'
down_revision: Union[str, None] = '4ce3e594cb87'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column(
'accounts',
sa.Column(
'session_idle_minutes',
sa.Integer(),
nullable=True,
comment=(
'Account override for idle session window in minutes. '
'NULL = use Settings.SESSION_IDLE_MINUTES_DEFAULT.'
),
),
)
op.add_column(
'accounts',
sa.Column(
'session_absolute_minutes',
sa.Integer(),
nullable=True,
comment=(
'Account override for absolute session lifetime in minutes. '
'NULL = use Settings.SESSION_ABSOLUTE_MINUTES_DEFAULT.'
),
),
)
op.create_check_constraint(
'session_idle_le_absolute_when_both_set',
'accounts',
'('
'session_idle_minutes IS NULL '
'OR session_absolute_minutes IS NULL '
'OR session_idle_minutes <= session_absolute_minutes'
')',
)
op.execute(
"COMMENT ON CONSTRAINT session_idle_le_absolute_when_both_set ON accounts IS "
"'Defense in depth: catches idle > absolute when both are overridden. "
"Partial-override case (one NULL, one set) is validated at the app layer "
"against current system defaults, since the DB cannot see Settings.'"
)
def downgrade() -> None:
op.drop_constraint('session_idle_le_absolute_when_both_set', 'accounts', type_='check')
op.drop_column('accounts', 'session_absolute_minutes')
op.drop_column('accounts', 'session_idle_minutes')

View File

@@ -7,13 +7,7 @@ from sqlalchemy import select
import sentry_sdk
from app.core.database import get_db
from jose import JWTError
from app.core.security import (
IdleTokenExpired,
decode_refresh_token_strict,
decode_token,
)
from app.core.security import decode_token
from app.models.user import User
from app.models.plan_limits import PlanLimits
from app.core.tenant_context import set_current_account_id, clear_current_account_id
@@ -70,72 +64,15 @@ async def get_current_user(
return user
async def get_current_user_optional(
request: Request,
db: Annotated[AsyncSession, Depends(get_admin_db)],
) -> Optional[User]:
"""Best-effort current user for endpoints that work both anonymous and authed.
Returns None on missing/invalid/expired token instead of raising. Used by
surfaces like /config/public that anonymous clients can hit but where an
authenticated user gets a tailored response (e.g. INTERNAL_TESTER_EMAILS
allowlist override).
"""
auth_header = request.headers.get("Authorization") or request.headers.get("authorization")
if not auth_header or not auth_header.lower().startswith("bearer "):
return None
token = auth_header.split(None, 1)[1].strip()
if not token:
return None
payload = decode_token(token)
if payload is None or payload.get("type") != "access":
return None
user_id = payload.get("sub")
if user_id is None:
return None
try:
user_uuid = UUID(user_id)
except ValueError:
return None
result = await db.execute(select(User).where(User.id == user_uuid))
return result.scalar_one_or_none()
async def get_refresh_token_payload(
token: Annotated[str, Depends(oauth2_scheme)]
) -> dict:
"""Extract and validate a refresh token from the Authorization header.
Returns one of three outcomes via HTTP 401 `detail`:
- `session_expired_idle` — JWT signature valid but `exp` past
- `invalid_refresh_token` — any other decode failure, or `type != "refresh"`
- (200 path) — returns the decoded payload
The frontend uses these to choose between the "your session ended for
security" banner and a plain logout redirect. See
docs/plans/2026-05-13-session-expiration-policy.md §4.10.
"""
try:
payload = decode_refresh_token_strict(token)
except IdleTokenExpired:
"""Extract and validate a refresh token from the Authorization header."""
payload = decode_token(token)
if payload is None or payload.get("type") != "refresh":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="session_expired_idle",
headers={"WWW-Authenticate": "Bearer"},
)
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid_refresh_token",
headers={"WWW-Authenticate": "Bearer"},
)
if payload.get("type") != "refresh":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid_refresh_token",
detail="Invalid refresh token",
headers={"WWW-Authenticate": "Bearer"},
)
return payload

View File

@@ -1,214 +0,0 @@
"""Account session-policy endpoints — owner-only.
GET /accounts/me/security — read the policy + system bounds.
PATCH /accounts/me/security — set or clear the per-account override.
POST /accounts/me/security/revoke-sessions lands in the next commit.
See docs/plans/2026-05-13-session-expiration-policy.md §4.7 / §4.11.
"""
from datetime import datetime, timezone
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select, update as sa_update
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import require_account_owner
from app.core.admin_database import get_admin_db
from app.core.audit import log_audit
from app.core.config import settings
from app.core.security import resolve_session_policy
from app.models.account import Account
from app.models.refresh_token import RefreshToken
from app.models.user import User
from app.schemas.account_security import (
ActiveUser,
RevokeSessionsRequest,
RevokeSessionsResponse,
SessionPolicyResponse,
SessionPolicyUpdateRequest,
)
router = APIRouter(prefix="/accounts/me/security", tags=["account-security"])
def _policy_response(
account: Account, active_users: list[ActiveUser]
) -> SessionPolicyResponse:
eff_idle, eff_abs = resolve_session_policy(account)
return SessionPolicyResponse(
idle_minutes=account.session_idle_minutes,
absolute_minutes=account.session_absolute_minutes,
effective_idle_minutes=eff_idle,
effective_absolute_minutes=eff_abs,
idle_minutes_min=settings.SESSION_IDLE_MINUTES_MIN,
idle_minutes_max=settings.SESSION_IDLE_MINUTES_MAX,
absolute_minutes_min=settings.SESSION_ABSOLUTE_MINUTES_MIN,
absolute_minutes_max=settings.SESSION_ABSOLUTE_MINUTES_MAX,
active_users=active_users,
)
async def _load_account(db: AsyncSession, account_id) -> Account:
return (
await db.execute(select(Account).where(Account.id == account_id))
).scalar_one()
async def _load_active_users(db: AsyncSession, account_id) -> list[ActiveUser]:
"""Return distinct users in this account who currently hold an
un-revoked refresh token. See plan §4.7."""
from app.models.refresh_token import RefreshToken
stmt = (
select(User.id, User.name, User.email, User.last_login)
.join(RefreshToken, RefreshToken.user_id == User.id)
.where(User.account_id == account_id, RefreshToken.revoked_at.is_(None))
.distinct()
.order_by(User.last_login.desc().nulls_last())
)
rows = (await db.execute(stmt)).all()
return [
ActiveUser(user_id=row.id, name=row.name, email=row.email, last_login_at=row.last_login)
for row in rows
]
@router.get("", response_model=SessionPolicyResponse)
async def get_session_policy(
current_user: Annotated[User, Depends(require_account_owner)],
db: Annotated[AsyncSession, Depends(get_admin_db)],
):
account = await _load_account(db, current_user.account_id)
active_users = await _load_active_users(db, current_user.account_id)
return _policy_response(account, active_users)
@router.patch("", response_model=SessionPolicyResponse)
async def update_session_policy(
body: SessionPolicyUpdateRequest,
current_user: Annotated[User, Depends(require_account_owner)],
db: Annotated[AsyncSession, Depends(get_admin_db)],
):
account = await _load_account(db, current_user.account_id)
# Snapshot effective values BEFORE change, for audit.
old_idle = account.session_idle_minutes
old_abs = account.session_absolute_minutes
effective_old_idle, effective_old_abs = resolve_session_policy(account)
new_idle = body.idle_minutes
new_abs = body.absolute_minutes
# Per-field bound checks. NULL clears the override and is always valid.
if new_idle is not None and not (
settings.SESSION_IDLE_MINUTES_MIN <= new_idle <= settings.SESSION_IDLE_MINUTES_MAX
):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=(
f"idle_minutes must be between {settings.SESSION_IDLE_MINUTES_MIN} "
f"and {settings.SESSION_IDLE_MINUTES_MAX}"
),
)
if new_abs is not None and not (
settings.SESSION_ABSOLUTE_MINUTES_MIN <= new_abs <= settings.SESSION_ABSOLUTE_MINUTES_MAX
):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=(
f"absolute_minutes must be between {settings.SESSION_ABSOLUTE_MINUTES_MIN} "
f"and {settings.SESSION_ABSOLUTE_MINUTES_MAX}"
),
)
# Effective-value invariant: idle must not exceed absolute after defaults.
# The DB CHECK only catches the both-set case; this catches the partial-
# override case where (e.g.) idle=43200 with absolute=NULL would yield an
# effective idle larger than the system default absolute.
effective_new_idle = new_idle if new_idle is not None else settings.SESSION_IDLE_MINUTES_DEFAULT
effective_new_abs = new_abs if new_abs is not None else settings.SESSION_ABSOLUTE_MINUTES_DEFAULT
if effective_new_idle > effective_new_abs:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=(
f"Effective idle ({effective_new_idle}min) cannot exceed effective "
f"absolute ({effective_new_abs}min)"
),
)
account.session_idle_minutes = new_idle
account.session_absolute_minutes = new_abs
await log_audit(
db,
user_id=current_user.id,
account_id=account.id,
action="account.session_policy_update",
resource_type="account",
resource_id=account.id,
details={
"old": {"idle_minutes": old_idle, "absolute_minutes": old_abs},
"new": {"idle_minutes": new_idle, "absolute_minutes": new_abs},
"effective_old": {
"idle_minutes": effective_old_idle,
"absolute_minutes": effective_old_abs,
},
"effective_new": {
"idle_minutes": effective_new_idle,
"absolute_minutes": effective_new_abs,
},
},
)
await db.commit()
await db.refresh(account)
active_users = await _load_active_users(db, account.id)
return _policy_response(account, active_users)
@router.post("/revoke-sessions", response_model=RevokeSessionsResponse)
async def revoke_sessions(
body: RevokeSessionsRequest,
current_user: Annotated[User, Depends(require_account_owner)],
db: Annotated[AsyncSession, Depends(get_admin_db)],
):
"""Bulk-revoke refresh tokens for users in the caller's account.
`scope="all"` revokes every active session in the account, including
the caller's own. `scope="others"` preserves the caller's sessions.
The caller's access token is NOT revoked (we don't track access JTIs);
it dies on its 5-minute timer. For `scope="all"`, the frontend is
expected to log the caller out locally after the response.
See docs/plans/2026-05-13-session-expiration-policy.md §4.11.
"""
# Subquery: refresh-token rows belonging to users in this account.
user_ids_subq = select(User.id).where(User.account_id == current_user.account_id)
stmt = (
sa_update(RefreshToken)
.where(
RefreshToken.user_id.in_(user_ids_subq),
RefreshToken.revoked_at.is_(None),
)
.values(revoked_at=datetime.now(timezone.utc))
.returning(RefreshToken.id)
)
if body.scope == "others":
stmt = stmt.where(RefreshToken.user_id != current_user.id)
result = await db.execute(stmt)
revoked_count = len(result.all())
await log_audit(
db,
user_id=current_user.id,
account_id=current_user.account_id,
action="account.sessions_revoked_bulk",
resource_type="account",
resource_id=current_user.account_id,
details={"scope": body.scope, "revoked_count": revoked_count},
)
await db.commit()
return RevokeSessionsResponse(revoked_count=revoked_count)

View File

@@ -972,7 +972,7 @@ async def update_user_plan(
current_user: Annotated[User, Depends(require_admin)],
):
"""Change a user's subscription plan (super admin only)."""
if data.plan not in ("free", "pro", "starter", "enterprise"):
if data.plan not in ("free", "pro", "team"):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid plan")
user, subscription = await _get_user_subscription(user_id, db)
old_plan = subscription.plan
@@ -991,7 +991,7 @@ async def update_account_plan(
current_user: Annotated[User, Depends(require_admin)],
):
"""Change an account subscription plan (super admin only)."""
if data.plan not in ("free", "pro", "starter", "enterprise"):
if data.plan not in ("free", "pro", "team"):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid plan")
account, subscription = await _get_account_subscription(account_id, db)
old_plan = subscription.plan

View File

@@ -28,7 +28,7 @@ async def get_dashboard_metrics(
) or 0
paid_accounts = await db.scalar(
select(func.count()).select_from(Subscription).where(
Subscription.plan.in_(["pro", "starter", "enterprise"])
Subscription.plan.in_(["pro", "team"])
)
) or 0
total_trees = await db.scalar(

View File

@@ -20,7 +20,6 @@ from app.core.security import (
create_email_verification_token,
decode_token,
hash_token,
resolve_session_policy,
)
from app.models.user import User
from app.models.invite_code import InviteCode
@@ -68,108 +67,6 @@ async def store_refresh_token(db: AsyncSession, refresh_token_str: str, user_id)
db.add(token_record)
async def _mint_session_tokens(user: User, db: AsyncSession) -> Token:
"""Mint a fresh refresh+access pair for a new login.
Snapshots the account's current session policy into the refresh JWT
(auth_time/idle_max/abs_max) and registers the JTI in refresh_tokens.
Caller is responsible for committing the session. Use this for every
NEW login (password, OAuth, etc.) — for /auth/refresh use
_refresh_session_tokens instead, which carries claims forward.
See docs/plans/2026-05-13-session-expiration-policy.md §4.6.
"""
account = (
await db.execute(select(Account).where(Account.id == user.account_id))
).scalar_one()
idle_minutes, abs_minutes = resolve_session_policy(account)
idle_max_seconds = idle_minutes * 60
abs_max_seconds = abs_minutes * 60
now = datetime.now(timezone.utc)
auth_time_unix = int(now.timestamp())
refresh_token_str = create_refresh_token(
user_id=str(user.id),
auth_time=auth_time_unix,
idle_max_seconds=idle_max_seconds,
abs_max_seconds=abs_max_seconds,
)
access_token = create_access_token(data={"sub": str(user.id)})
await store_refresh_token(db, refresh_token_str, user.id)
return Token(
access_token=access_token,
refresh_token=refresh_token_str,
token_type="bearer",
must_change_password=user.must_change_password,
idle_expires_at=now + timedelta(seconds=idle_max_seconds),
absolute_expires_at=datetime.fromtimestamp(
auth_time_unix + abs_max_seconds, tz=timezone.utc
),
)
async def _resolve_refresh_claims(
payload: dict, user: User, db: AsyncSession
) -> tuple[int, int, int]:
"""Return (auth_time, idle_max_seconds, abs_max_seconds) for a refresh.
Grandfathers legacy tokens issued before the session-policy PR: tokens
missing any of auth_time/idle_max/abs_max get treated as if just minted
under the account's current policy. One free rotation under the new
rules — see plan §5.1. Callers that have the claims use them as-is.
"""
auth_time = payload.get("auth_time")
idle_max_seconds = payload.get("idle_max")
abs_max_seconds = payload.get("abs_max")
if auth_time is None or idle_max_seconds is None or abs_max_seconds is None:
account = (
await db.execute(select(Account).where(Account.id == user.account_id))
).scalar_one()
idle_minutes, abs_minutes = resolve_session_policy(account)
auth_time = int(datetime.now(timezone.utc).timestamp())
idle_max_seconds = idle_minutes * 60
abs_max_seconds = abs_minutes * 60
return auth_time, idle_max_seconds, abs_max_seconds
async def _mint_with_claims(
user: User,
auth_time: int,
idle_max_seconds: int,
abs_max_seconds: int,
db: AsyncSession,
) -> Token:
"""Mint a refresh+access pair carrying explicit session-policy claims.
Used by /auth/refresh after the grandfather + absolute-cap checks
have already produced the effective claim values. Caller commits.
"""
now = datetime.now(timezone.utc)
refresh_token_str = create_refresh_token(
user_id=str(user.id),
auth_time=auth_time,
idle_max_seconds=idle_max_seconds,
abs_max_seconds=abs_max_seconds,
)
access_token = create_access_token(data={"sub": str(user.id)})
await store_refresh_token(db, refresh_token_str, user.id)
return Token(
access_token=access_token,
refresh_token=refresh_token_str,
token_type="bearer",
must_change_password=user.must_change_password,
idle_expires_at=now + timedelta(seconds=idle_max_seconds),
absolute_expires_at=datetime.fromtimestamp(
auth_time + abs_max_seconds, tz=timezone.utc
),
)
def _generate_display_code() -> str:
"""Generate a random 8-character alphanumeric display code."""
chars = string.ascii_uppercase + string.digits
@@ -253,7 +150,7 @@ async def register(
# and so paid/trial-bearing codes still apply when supplied.
if (
settings.REQUIRE_INVITE_CODE
and not settings.is_self_serve_active_for(user_data.email)
and not settings.SELF_SERVE_ENABLED
and not user_data.invite_code
):
raise HTTPException(
@@ -426,9 +323,20 @@ async def login(
# Update last login
user.last_login = datetime.now(timezone.utc)
token = await _mint_session_tokens(user, db)
# Create tokens
access_token = create_access_token(data={"sub": str(user.id)})
refresh_token_str = create_refresh_token(data={"sub": str(user.id)})
# Store refresh token hash in DB
await store_refresh_token(db, refresh_token_str, user.id)
await db.commit()
return token
return Token(
access_token=access_token,
refresh_token=refresh_token_str,
token_type="bearer",
must_change_password=user.must_change_password,
)
@router.post("/login/json", response_model=Token)
@@ -451,9 +359,19 @@ async def login_json(
user.last_login = datetime.now(timezone.utc)
token = await _mint_session_tokens(user, db)
access_token = create_access_token(data={"sub": str(user.id)})
refresh_token_str = create_refresh_token(data={"sub": str(user.id)})
# Store refresh token hash in DB
await store_refresh_token(db, refresh_token_str, user.id)
await db.commit()
return token
return Token(
access_token=access_token,
refresh_token=refresh_token_str,
token_type="bearer",
must_change_password=user.must_change_password,
)
@router.post("/refresh", response_model=Token)
@@ -463,39 +381,13 @@ async def refresh_token(
payload: Annotated[dict, Depends(get_refresh_token_payload)],
db: Annotated[AsyncSession, Depends(get_admin_db)]
):
"""Refresh access token, enforcing both idle and absolute session windows.
Algorithm (see plan §4.5):
1. Decode refresh JWT (the dep already rejects idle-expired tokens with
session_expired_idle).
2. Load the user. If missing or inactive, 401 invalid_refresh_token.
3. Resolve effective auth_time/idle_max/abs_max (grandfather legacy
tokens that pre-date this PR).
4. Atomically revoke the JTI regardless of outcome — so an absolute-
expired token cannot be replayed; the second attempt finds it
already revoked and gets invalid_refresh_token instead.
5. If the atomic UPDATE matched zero rows, 401 invalid_refresh_token.
6. If now >= auth_time + abs_max, 401 session_expired_absolute.
7. Otherwise mint new tokens carrying the claims forward.
"""
"""Refresh access token using refresh token (rotation: old token is revoked)."""
user_id = payload.get("sub")
jti = payload.get("jti")
user = (await db.execute(select(User).where(User.id == user_id))).scalar_one_or_none()
if not user or not user.is_active:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid_refresh_token",
)
auth_time, idle_max_seconds, abs_max_seconds = await _resolve_refresh_claims(
payload, user, db
)
# Atomically revoke the old refresh token first — this consumes the
# token regardless of whether the absolute check passes, so an absolute-
# expired token cannot be replayed.
# Atomically revoke the old refresh token (token rotation).
# Using a conditional UPDATE prevents the race where two concurrent
# refresh requests both read revoked_at=NULL and both succeed.
if jti:
token_hash = hash_token(jti)
result = await db.execute(
@@ -508,31 +400,35 @@ async def refresh_token(
.returning(RefreshToken.id, RefreshToken.user_id)
)
revoked_row = result.fetchone()
if not revoked_row:
# Either the token doesn't exist or was already revoked/used
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid_refresh_token",
detail="Refresh token has been revoked"
)
# Absolute-window check. Boundary is `>=`, not `>` — a deadline equal to
# now is expired. The token row has already been revoked above, so the
# client cannot retry this token even though we're raising after the
# consume.
now_unix = int(datetime.now(timezone.utc).timestamp())
if now_unix >= auth_time + abs_max_seconds:
# Commit the revoke so the consumed-on-failure invariant survives
# any subsequent rollback in the request lifecycle.
await db.commit()
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="session_expired_absolute",
detail="User not found"
)
token = await _mint_with_claims(
user, auth_time, idle_max_seconds, abs_max_seconds, db
)
access_token = create_access_token(data={"sub": str(user.id)})
new_refresh_token_str = create_refresh_token(data={"sub": str(user.id)})
# Store new refresh token
await store_refresh_token(db, new_refresh_token_str, user.id)
await db.commit()
return token
return Token(
access_token=access_token,
refresh_token=new_refresh_token_str,
token_type="bearer"
)
@router.get("/me", response_model=UserResponse)

View File

@@ -11,31 +11,22 @@ frontend codegen and other call sites if needed.
from __future__ import annotations
from typing import Annotated, Optional
from fastapi import APIRouter
from fastapi import APIRouter, Depends
from app.api.deps import get_current_user_optional
from app.core.config import settings
from app.models.user import User
from app.schemas.config import PublicConfigResponse
router = APIRouter(prefix="/config", tags=["config"])
@router.get("/public", response_model=PublicConfigResponse)
async def get_public_config(
current_user: Annotated[Optional[User], Depends(get_current_user_optional)],
) -> PublicConfigResponse:
async def get_public_config() -> PublicConfigResponse:
"""Return public-safe runtime config.
`oauth_providers` reflects which OAuth client IDs are configured server
side; the frontend uses it to render only buttons that will actually
succeed. `self_serve_enabled` is the master switch for the new public
self-serve signup flow; an authenticated caller whose email is on the
INTERNAL_TESTER_EMAILS allowlist sees `True` even when the global flag
is off, so internal validation in prod test mode can exercise the full
surface before the public flip.
self-serve signup flow.
"""
providers: list[str] = []
if settings.GOOGLE_CLIENT_ID:
@@ -43,8 +34,7 @@ async def get_public_config(
if settings.MS_CLIENT_ID:
providers.append("microsoft")
user_email = current_user.email if current_user else None
return PublicConfigResponse(
self_serve_enabled=settings.is_self_serve_active_for(user_email),
self_serve_enabled=settings.SELF_SERVE_ENABLED,
oauth_providers=providers,
)

View File

@@ -7,9 +7,10 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.endpoints.auth import _mint_session_tokens
from app.api.endpoints.auth import store_refresh_token
from app.core.admin_database import get_admin_db
from app.core.config import settings
from app.core.security import create_access_token, create_refresh_token
from app.models.account import Account
from app.models.account_invite import AccountInvite
from app.models.oauth_identity import OAuthIdentity
@@ -186,14 +187,17 @@ async def google_callback(
account_invite_code=payload.account_invite_code,
invited_email=payload.invited_email,
)
token = await _mint_session_tokens(user, db)
refresh_token_str = create_refresh_token({"sub": str(user.id)})
# Persist the refresh-token JTI so the first /auth/refresh call doesn't
# reject this token as "revoked" (the rotation logic requires a row to
# mark as used). _sign_in_or_register already committed; this needs a
# second commit.
await store_refresh_token(db, refresh_token_str, user.id)
await db.commit()
return OAuthCallbackResponse(
access_token=token.access_token,
refresh_token=token.refresh_token,
access_token=create_access_token({"sub": str(user.id)}),
refresh_token=refresh_token_str,
is_new_user=is_new,
idle_expires_at=token.idle_expires_at,
absolute_expires_at=token.absolute_expires_at,
)
@@ -213,12 +217,15 @@ async def microsoft_callback(
account_invite_code=payload.account_invite_code,
invited_email=payload.invited_email,
)
token = await _mint_session_tokens(user, db)
refresh_token_str = create_refresh_token({"sub": str(user.id)})
# Persist the refresh-token JTI so the first /auth/refresh call doesn't
# reject this token as "revoked" (the rotation logic requires a row to
# mark as used). _sign_in_or_register already committed; this needs a
# second commit.
await store_refresh_token(db, refresh_token_str, user.id)
await db.commit()
return OAuthCallbackResponse(
access_token=token.access_token,
refresh_token=token.refresh_token,
access_token=create_access_token({"sub": str(user.id)}),
refresh_token=refresh_token_str,
is_new_user=is_new,
idle_expires_at=token.idle_expires_at,
absolute_expires_at=token.absolute_expires_at,
)

View File

@@ -72,7 +72,6 @@ from app.api.endpoints import (
webhooks,
accounts,
account_invite_lookup,
account_security,
)
api_router = APIRouter()
@@ -145,7 +144,6 @@ api_router.include_router(folders.router, dependencies=_tenant_deps)
api_router.include_router(step_categories.router, dependencies=_pro_deps)
api_router.include_router(steps.router, dependencies=_pro_deps)
api_router.include_router(accounts.router, dependencies=_tenant_deps)
api_router.include_router(account_security.router, dependencies=_tenant_deps)
api_router.include_router(shares.router, dependencies=_tenant_deps)
api_router.include_router(tree_markdown.router, dependencies=_tenant_deps)
api_router.include_router(ratings.router, dependencies=_tenant_deps)

View File

@@ -69,19 +69,6 @@ class Settings(BaseSettings):
ACCESS_TOKEN_EXPIRE_MINUTES: int = 5
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
# Session policy — see docs/plans/2026-05-13-session-expiration-policy.md
# Refresh tokens enforce two windows: idle (between rotations) and absolute
# (from original login). Defaults can be overridden per-account, bounded by
# the MIN/MAX values below. Values are minutes everywhere except inside the
# refresh JWT, where idle_max/abs_max are stored as seconds for direct
# Unix-time math.
SESSION_IDLE_MINUTES_DEFAULT: int = 4320 # 3 days
SESSION_ABSOLUTE_MINUTES_DEFAULT: int = 20160 # 14 days
SESSION_IDLE_MINUTES_MIN: int = 15
SESSION_IDLE_MINUTES_MAX: int = 43200 # 30 days
SESSION_ABSOLUTE_MINUTES_MIN: int = 60 # 1 hour
SESSION_ABSOLUTE_MINUTES_MAX: int = 129600 # 90 days
# Security
BCRYPT_ROUNDS: int = 12
@@ -110,40 +97,6 @@ class Settings(BaseSettings):
STRIPE_WEBHOOK_SECRET: Optional[str] = None
SELF_SERVE_ENABLED: bool = False
# Internal tester allowlist for soft cutover. Comma-separated emails;
# when SELF_SERVE_ENABLED is False, listed users still see the self-serve
# surfaces (pricing page, invite-code-optional registration, etc.) so the
# full flow can be exercised in prod test mode before public flip.
INTERNAL_TESTER_EMAILS: list[str] = []
@field_validator("INTERNAL_TESTER_EMAILS", mode="before")
@classmethod
def split_internal_tester_emails(cls, v) -> list[str]:
"""Parse a comma-separated string into a normalized lowercase list."""
if v is None or v == "":
return []
if isinstance(v, list):
return [e.strip().lower() for e in v if e and e.strip()]
if isinstance(v, str):
return [e.strip().lower() for e in v.split(",") if e.strip()]
return []
def is_internal_tester(self, email: Optional[str]) -> bool:
"""Case-insensitive allowlist check. None/empty email is never a tester."""
if not email:
return False
return email.lower() in self.INTERNAL_TESTER_EMAILS
def is_self_serve_active_for(self, email: Optional[str]) -> bool:
"""True if self-serve surfaces should render for this user.
Either the global flag is on, or the user is on the internal-tester
allowlist. Anonymous calls (email is None) only see the global flag.
"""
if self.SELF_SERVE_ENABLED:
return True
return self.is_internal_tester(email)
@property
def stripe_enabled(self) -> bool:
"""Check if Stripe is configured."""

View File

@@ -5,18 +5,9 @@ import uuid
from datetime import datetime, timedelta, timezone
from typing import Optional
from jose import JWTError, jwt
from jose.exceptions import ExpiredSignatureError
from passlib.context import CryptContext
from .config import settings
class IdleTokenExpired(Exception):
"""Raised by decode_refresh_token_strict when a refresh JWT is past its `exp`.
Distinct from JWTError so callers can map idle expiry to `session_expired_idle`
on the wire while all other decode failures map to `invalid_refresh_token`.
"""
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
@@ -42,54 +33,14 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
return encoded_jwt
def create_refresh_token(
user_id: str,
*,
auth_time: int,
idle_max_seconds: int,
abs_max_seconds: int,
) -> str:
"""Create a JWT refresh token with session-policy claims embedded.
The JWT carries five claims beyond the standard `sub`/`type`/`jti`:
- `auth_time`: Unix-seconds timestamp of the original login; never reset
on rotation. Used by `/auth/refresh` to enforce the absolute cap.
- `idle_max`: idle window in seconds, snapshotted from the account's
policy at login. Carried forward across rotations unchanged.
- `abs_max`: absolute lifetime in seconds, snapshotted at login.
- `exp`: current idle deadline (`now + idle_max`). Standard JWT expiry.
See docs/plans/2026-05-13-session-expiration-policy.md §4.2 for the unit
convention (everything outside the JWT is minutes; inside the JWT it's
seconds so `auth_time + abs_max` is direct Unix math).
"""
now = datetime.now(timezone.utc)
expire = now + timedelta(seconds=idle_max_seconds)
def create_refresh_token(data: dict) -> str:
"""Create a JWT refresh token with a unique jti for revocation tracking."""
to_encode = data.copy()
expire = datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
jti = str(uuid.uuid4())
to_encode = {
"sub": user_id,
"type": "refresh",
"jti": jti,
"exp": expire,
"auth_time": auth_time,
"idle_max": idle_max_seconds,
"abs_max": abs_max_seconds,
}
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
def resolve_session_policy(account) -> tuple[int, int]:
"""Return (idle_minutes, absolute_minutes) for an account.
NULL overrides fall back to the system defaults from Settings. Partial
overrides (one column NULL, one set) are intentionally allowed at this
layer; the PATCH /accounts/me/security endpoint validates the resolved
effective values to enforce idle <= absolute. See plan §4.3.
"""
idle = account.session_idle_minutes or settings.SESSION_IDLE_MINUTES_DEFAULT
absolute = account.session_absolute_minutes or settings.SESSION_ABSOLUTE_MINUTES_DEFAULT
return idle, absolute
to_encode.update({"exp": expire, "type": "refresh", "jti": jti})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def hash_token(jti: str) -> str:
@@ -98,14 +49,7 @@ def hash_token(jti: str) -> str:
def decode_token(token: str) -> Optional[dict]:
"""Decode and validate a JWT token.
Collapses all jose errors (including expiry) into None — preserved for
access tokens, password-reset tokens, and email-verification tokens where
the caller does not need to distinguish expiry from invalid. Refresh tokens
use decode_refresh_token_strict instead so they can map idle expiry to
`session_expired_idle` distinctly.
"""
"""Decode and validate a JWT token."""
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
return payload
@@ -113,24 +57,6 @@ def decode_token(token: str) -> Optional[dict]:
return None
def decode_refresh_token_strict(token: str) -> dict:
"""Decode a refresh token, distinguishing idle expiry from invalid.
Raises:
IdleTokenExpired: token signature is valid but `exp` is past — i.e. the
idle window has elapsed.
JWTError: any other decode failure (bad signature, malformed, wrong
algorithm).
Type discrimination (`type == "refresh"`) is the caller's responsibility —
this function only inspects the JWT itself.
"""
try:
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
except ExpiredSignatureError as e:
raise IdleTokenExpired() from e
def create_password_reset_token(user_id: str) -> str:
"""Create a JWT password reset token (30-minute expiry, unique JTI)."""
jti = str(uuid.uuid4())

View File

@@ -44,12 +44,6 @@ class Account(Base):
Integer, nullable=True, default=100, server_default="100"
)
# Session policy override (NULL = use Settings.SESSION_*_MINUTES_DEFAULT).
# Validated at the app layer because the DB cannot see Settings; a DB
# CHECK constraint covers the both-set case only.
session_idle_minutes: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
session_absolute_minutes: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# Custom branding (Task 9)
branding_logo_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
branding_primary_color: Mapped[Optional[str]] = mapped_column(String(7), nullable=True) # hex like #06b6d4

View File

@@ -37,12 +37,12 @@ class Subscription(Base):
@property
def is_paid(self) -> bool:
# Excludes complimentary and trialing so MRR/paid-customer metrics aren't inflated.
return self.plan in ("pro", "starter", "enterprise") and self.status not in ("complimentary", "trialing")
return self.plan in ("pro", "team") and self.status not in ("complimentary", "trialing")
@property
def has_pro_entitlement(self) -> bool:
"""True if the account can access Pro features right now."""
if self.plan in ("pro", "starter", "enterprise"):
if self.plan in ("pro", "team"):
if self.status in ("active", "complimentary"):
return True
if self.status == "trialing" and self.current_period_end is not None:

View File

@@ -1,77 +0,0 @@
"""Schemas for /accounts/me/security — session-policy management.
See docs/plans/2026-05-13-session-expiration-policy.md §4.7 and §4.11.
"""
from datetime import datetime
from typing import Literal, Optional
from uuid import UUID
from pydantic import BaseModel, Field
class ActiveUser(BaseModel):
"""One row in the active-users list on GET /accounts/me/security.
Rendered as 'name (email) · logged in 2d ago' on the Account Security
page. `last_login_at` reflects the last successful sign-in, not the last
refresh-token use — that requires the deferred refresh_tokens.last_used_at
follow-up (see plan §9).
"""
user_id: UUID
name: str
email: str
last_login_at: Optional[datetime] = None
class SessionPolicyResponse(BaseModel):
"""GET /accounts/me/security — the policy in effect for this account.
Surfaces both the override (which may be NULL) and the effective value
(after defaults applied) so the frontend can show the current state
without re-implementing the defaults logic.
"""
# Per-account override values, NULL = "use system default."
idle_minutes: Optional[int] = Field(
default=None,
description="Account override; NULL means use the system default.",
)
absolute_minutes: Optional[int] = Field(default=None)
# Effective values after defaults applied (always non-NULL).
effective_idle_minutes: int
effective_absolute_minutes: int
# System-imposed bounds for the Custom-preset form inputs.
idle_minutes_min: int
idle_minutes_max: int
absolute_minutes_min: int
absolute_minutes_max: int
# Active sessions in this account — users with at least one un-revoked
# refresh token. Drives the Active Sessions section in the UI.
active_users: list[ActiveUser] = Field(default_factory=list)
class SessionPolicyUpdateRequest(BaseModel):
"""PATCH /accounts/me/security — set or clear the per-account override.
Pass `null` for either field to clear the override and fall back to the
system default. Both bounds checks and the idle <= absolute invariant
are validated against the *effective* values at the endpoint, since the
DB CHECK constraint only covers the both-set case.
"""
idle_minutes: Optional[int] = None
absolute_minutes: Optional[int] = None
class RevokeSessionsRequest(BaseModel):
"""POST /accounts/me/security/revoke-sessions — bulk-revoke refresh tokens."""
scope: Literal["all", "others"] = "all"
class RevokeSessionsResponse(BaseModel):
revoked_count: int

View File

@@ -125,7 +125,7 @@ class AdminAccountDetailResponse(AdminAccountListItem):
class AdminAccountCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=255)
plan: Literal["free", "pro", "starter", "enterprise"] = "free"
plan: Literal["free", "pro", "team"] = "free"
owner_email: Optional[EmailStr] = Field(None, description="Email of an existing user to set as owner")

View File

@@ -4,7 +4,7 @@ from pydantic import BaseModel
class CheckoutSessionCreate(BaseModel):
plan: Literal["pro", "starter", "enterprise"]
plan: Literal["pro", "starter", "team", "enterprise"]
seats: int
billing_interval: Literal["monthly", "annual"] = "monthly"

View File

@@ -9,7 +9,7 @@ class InviteCodeCreate(BaseModel):
expires_at: Optional[datetime] = Field(None, description="Optional expiration time")
note: Optional[str] = Field(None, max_length=255, description="Note about who this code is for")
email: Optional[EmailStr] = Field(None, description="Recipient email for invite delivery")
assigned_plan: Literal["free", "pro", "starter", "enterprise"] = Field("free", description="Plan to assign on registration")
assigned_plan: Literal["free", "pro", "team"] = Field("free", description="Plan to assign on registration")
trial_duration_days: Optional[int] = Field(None, ge=1, le=90, description="Trial duration in days (1-90)")
@model_validator(mode="after")

View File

@@ -1,5 +1,3 @@
from datetime import datetime
from pydantic import BaseModel
@@ -18,11 +16,6 @@ class OAuthCallbackResponse(BaseModel):
refresh_token: str
token_type: str = "bearer"
is_new_user: bool
# Session-policy expiry windows — mirrors Token in token.py so the
# frontend can drive expiry-soon toasts identically for password and
# OAuth logins.
idle_expires_at: datetime | None = None
absolute_expires_at: datetime | None = None
class InviteLookupResponse(BaseModel):

View File

@@ -41,7 +41,7 @@ class SubscriptionDetails(BaseModel):
class SubscriptionPlanUpdate(BaseModel):
plan: str # free, pro, starter, enterprise
plan: str # free, pro, team
model_config = {"json_schema_extra": {"examples": [{"plan": "pro"}]}}

View File

@@ -1,4 +1,3 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
@@ -8,12 +7,6 @@ class Token(BaseModel):
refresh_token: str
token_type: str = "bearer"
must_change_password: bool = False
# Session-policy expiry windows derived from the refresh JWT. Frontend
# uses these to drive the "your session ends soon" toast and to know
# when /auth/refresh will reject for absolute expiry. See
# docs/plans/2026-05-13-session-expiration-policy.md §4.2.
idle_expires_at: Optional[datetime] = None
absolute_expires_at: Optional[datetime] = None
class TokenPayload(BaseModel):

View File

@@ -1,274 +0,0 @@
#!/usr/bin/env python3
"""
Create or promote a site-wide super-admin user on any environment.
Designed for the prod bootstrap case where no admin exists yet and self-serve
signup is gated, so there is no way to obtain admin access through the UI.
Also safe to use as a recovery tool: if an admin email exists already, the
script just promotes them to `is_super_admin=True` instead of duplicating.
Usage:
# Bootstrap a fresh super-admin and email a password-reset link:
python -m scripts.create_site_admin --email michael@resolutionflow.com --send-reset
# Same but emit the reset URL on stdout instead of sending email (useful
# if email infra is not configured yet or if you want to bypass the inbox):
python -m scripts.create_site_admin --email michael@resolutionflow.com --print-reset
# Promote an existing user (no reset needed if they already have a password):
python -m scripts.create_site_admin --email michael@resolutionflow.com --promote-only
The script is idempotent. Running it twice on the same email is safe.
"""
from __future__ import annotations
import argparse
import asyncio
import random
import string
import sys
import uuid
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
from app.core.config import settings
from app.core.email import EmailService
from app.core.security import (
create_password_reset_token,
decode_token,
hash_token,
)
def _display_code() -> str:
return "".join(random.choices(string.ascii_uppercase + string.digits, k=8))
async def _find_user(conn: AsyncConnection, email: str):
result = await conn.execute(
text(
"SELECT id, account_id, is_super_admin, password_hash "
"FROM users WHERE email = :email"
),
{"email": email},
)
return result.first()
async def _create_user_and_account(
conn: AsyncConnection,
email: str,
name: str,
account_name: str,
now: datetime,
) -> uuid.UUID:
"""Create a new Account and a new super-admin User as its owner.
Mirrors the shape used by seed_test_users.py for the super-admin row,
minus the shared dev password — this bootstrap user gets no password
until the reset flow runs.
"""
account_id = uuid.uuid4()
user_id = uuid.uuid4()
await conn.execute(
text(
"""
INSERT INTO accounts (id, name, display_code, created_at, updated_at)
VALUES (:id, :name, :code, :now, :now)
"""
),
{"id": account_id, "name": account_name, "code": _display_code(), "now": now},
)
await conn.execute(
text(
"""
INSERT INTO users (
id, email, password_hash, name, role, is_super_admin,
is_team_admin, is_active, account_id, account_role,
created_at, email_verified_at
)
VALUES (
:id, :email, NULL, :name, 'engineer', true,
false, true, :account_id, 'owner',
:now, :now
)
"""
),
{
"id": user_id,
"email": email,
"name": name,
"account_id": account_id,
"now": now,
},
)
await conn.execute(
text("UPDATE accounts SET owner_id = :uid WHERE id = :aid"),
{"uid": user_id, "aid": account_id},
)
return user_id
async def _promote_existing(conn: AsyncConnection, user_id: uuid.UUID, now: datetime) -> None:
"""Promote an existing user to super-admin and backfill verification."""
await conn.execute(
text(
"""
UPDATE users
SET is_super_admin = true,
email_verified_at = COALESCE(email_verified_at, :now),
is_active = true
WHERE id = :uid
"""
),
{"uid": user_id, "now": now},
)
async def _issue_reset_link(
conn: AsyncConnection, user_id: uuid.UUID, send_email: bool, email: str
) -> Optional[str]:
"""Generate a password-reset token, persist its hash, and return the URL.
Mirrors /auth/password/forgot. We commit the token row directly because
the script owns its own transaction (not the API request lifecycle).
"""
raw_token = create_password_reset_token(str(user_id))
payload = decode_token(raw_token)
if not payload or not payload.get("jti"):
return None
await conn.execute(
text(
"""
INSERT INTO password_reset_tokens
(id, token_hash, user_id, expires_at, created_at)
VALUES (:id, :token_hash, :user_id, :expires_at, :created_at)
"""
),
{
"id": uuid.uuid4(),
"token_hash": hash_token(payload["jti"]),
"user_id": user_id,
"expires_at": datetime.fromtimestamp(payload["exp"], tz=timezone.utc),
"created_at": datetime.now(timezone.utc),
},
)
reset_url = f"{settings.FRONTEND_URL}/reset-password?token={raw_token}"
if send_email:
# Best-effort. If email infra is misconfigured, the caller still
# has --print-reset as a fallback.
try:
await EmailService.send_password_reset_email(
to_email=email, reset_url=reset_url
)
except Exception as exc: # noqa: BLE001
print(f" [WARN] Email send failed: {exc}")
print(f" [WARN] Use the printed URL below as a fallback.")
return reset_url
async def main(args: argparse.Namespace) -> int:
email = args.email.strip().lower()
name = args.name or email.split("@", 1)[0].title()
account_name = args.account_name or "ResolutionFlow Admin"
admin_url = getattr(settings, "ADMIN_DATABASE_URL", None) or settings.DATABASE_URL
engine = create_async_engine(admin_url, echo=False)
now = datetime.now(timezone.utc)
try:
async with engine.begin() as conn:
existing = await _find_user(conn, email)
if existing is None:
if args.promote_only:
print(f"[ERROR] --promote-only set but no user with email {email!r} exists.")
return 1
user_id = await _create_user_and_account(
conn, email, name, account_name, now
)
print(f" [OK] Created super-admin user {email} (id={user_id})")
else:
user_id = existing.id
if existing.is_super_admin:
print(f" [SKIP] {email} already exists and is super-admin (id={user_id})")
else:
await _promote_existing(conn, user_id, now)
print(f" [OK] Promoted {email} to super-admin (id={user_id})")
# Skip reset issuance for --promote-only when the user already
# has a password (they can just log in with their existing creds).
should_issue_reset = not args.promote_only or (
existing is not None and existing.password_hash is None
)
if should_issue_reset:
reset_url = await _issue_reset_link(
conn, user_id, send_email=args.send_reset, email=email
)
if reset_url is None:
print(" [ERROR] Failed to mint password-reset token.")
return 2
print()
if args.send_reset:
print(f" [OK] Password-reset email sent to {email}")
print(f" [INFO] Reset link (also emailed) — copy if email is delayed:")
if args.print_reset or not args.send_reset:
print(f" {reset_url}")
else:
print(f" {reset_url}")
print()
print(" This link expires per PASSWORD_RESET_TOKEN_EXPIRE in settings.")
finally:
await engine.dispose()
return 0
def _build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="create_site_admin",
description="Create or promote a site-wide super-admin user.",
)
p.add_argument("--email", required=True, help="Email of the admin (will be normalized to lowercase).")
p.add_argument("--name", help="Display name. Defaults to the local part of the email, title-cased.")
p.add_argument(
"--account-name",
help="Account name to create alongside a brand-new user. Ignored if the user already exists. Defaults to 'ResolutionFlow Admin'.",
)
mode = p.add_mutually_exclusive_group()
mode.add_argument(
"--send-reset",
action="store_true",
help="Send a password-reset email to the admin. The reset URL is also printed to stdout as a fallback.",
)
mode.add_argument(
"--print-reset",
action="store_true",
help="Mint a reset token and print the URL to stdout WITHOUT sending email. Use when email infra is not configured.",
)
mode.add_argument(
"--promote-only",
action="store_true",
help="Only promote an existing user to super-admin. Will NOT create a new user, and will NOT issue a reset link unless the existing user has no password.",
)
return p
if __name__ == "__main__":
print("\n[*] ResolutionFlow — Site Admin Bootstrap")
print("=" * 60)
args = _build_parser().parse_args()
sys.exit(asyncio.run(main(args)))

View File

@@ -97,18 +97,7 @@ async def main() -> None:
)
row = result.first()
if row:
# Backfill email_verified_at for existing rows so older test
# users created before this script set the field still bypass
# the 7-day verification grace.
await conn.execute(
text("""
UPDATE users
SET email_verified_at = COALESCE(email_verified_at, :now)
WHERE email = :email
"""),
{"email": cfg["email"], "now": now},
)
print(f" [SKIP] {cfg['email']} already exists (email_verified_at backfilled if null)")
print(f" [SKIP] {cfg['email']} already exists")
if cfg["key"] == "team_admin":
team_account_id = row.account_id
continue
@@ -141,17 +130,12 @@ async def main() -> None:
# ---- Create User ----
user_id = uuid.uuid4()
# email_verified_at is stamped at seed time so test users bypass the
# 7-day verification grace immediately. Without this, fixtures hit
# require_verified_email_after_grace once their created_at ages past
# 7 days and get walled out of protected routes.
await conn.execute(
text("""
INSERT INTO users (id, email, password_hash, name, role, is_super_admin,
is_team_admin, is_active, account_id, account_role,
created_at, email_verified_at)
is_team_admin, is_active, account_id, account_role, created_at)
VALUES (:id, :email, :pw, :name, 'engineer', :is_sa, :is_ta, true,
:account_id, :account_role, :now, :now)
:account_id, :account_role, :now)
"""),
{
"id": user_id,

View File

@@ -1,199 +0,0 @@
#!/usr/bin/env python3
"""Sync plan_billing rows from Stripe products and prices.
Reads the active Stripe environment (test or live, determined by
STRIPE_SECRET_KEY in env), looks up the canonical ResolutionFlow products
by exact name match, picks the active monthly recurring price for tiers
that have one, and upserts plan_billing rows.
Idempotent. Safe to re-run after price changes, after live cutover, or
after rotating Stripe keys.
Tier mapping (name in Stripe -> plan slug in plan_limits):
ResolutionFlow Starter -> starter (monthly price required)
ResolutionFlow Pro -> pro (monthly price required)
ResolutionFlow Enterprise -> enterprise (no price, sales-led)
Annual prices are intentionally not supported in this iteration. The
plan_billing schema allows annual fields (stripe_annual_price_id,
annual_price_cents); this script leaves them NULL.
Usage:
docker exec -w /app resolutionflow_backend python -m scripts.sync_stripe_plan_ids
docker exec -w /app resolutionflow_backend python -m scripts.sync_stripe_plan_ids --dry-run
"""
import argparse
import asyncio
import logging
import sys
from typing import Optional
import stripe
from app.core.config import settings
from app.core.database import async_session_maker
from sqlalchemy import text
logger = logging.getLogger("sync_stripe_plan_ids")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
PLAN_NAME_TO_SLUG = {
"ResolutionFlow Starter": "starter",
"ResolutionFlow Pro": "pro",
"ResolutionFlow Enterprise": "enterprise",
}
PLANS_REQUIRING_PRICE = {"starter", "pro"}
PLAN_DEFAULTS = {
"starter": {"sort_order": 10, "is_public": True},
"pro": {"sort_order": 20, "is_public": True},
"enterprise": {"sort_order": 30, "is_public": True},
}
def find_product_by_name(target: str) -> Optional[stripe.Product]:
"""Page through active products and return the first exact name match."""
for product in stripe.Product.list(active=True, limit=100).auto_paging_iter():
if product.name == target:
return product
return None
def find_active_monthly_price(product_id: str) -> Optional[stripe.Price]:
"""Return the active recurring monthly price for a product, or None."""
candidates = [
p
for p in stripe.Price.list(product=product_id, active=True, limit=100).auto_paging_iter()
if p.type == "recurring"
and p.recurring is not None
and p.recurring.get("interval") == "month"
and p.recurring.get("interval_count", 1) == 1
]
if not candidates:
return None
if len(candidates) > 1:
logger.warning(
"Product %s has %d active monthly recurring prices; picking %s. "
"Archive the others to silence this warning.",
product_id, len(candidates), candidates[0].id,
)
return candidates[0]
async def upsert_plan_billing(
plan: str,
display_name: str,
description: Optional[str],
monthly_price_cents: Optional[int],
stripe_product_id: Optional[str],
stripe_monthly_price_id: Optional[str],
sort_order: int,
is_public: bool,
dry_run: bool,
) -> None:
"""Upsert one plan_billing row. Annual fields stay NULL."""
if dry_run:
logger.info(
"[dry-run] would upsert plan=%s display=%s monthly_cents=%s "
"product=%s monthly_price=%s",
plan, display_name, monthly_price_cents,
stripe_product_id, stripe_monthly_price_id,
)
return
sql = text("""
INSERT INTO plan_billing (
plan, display_name, description,
monthly_price_cents, annual_price_cents,
stripe_product_id, stripe_monthly_price_id, stripe_annual_price_id,
is_public, is_archived, sort_order
) VALUES (
:plan, :display_name, :description,
:monthly_price_cents, NULL,
:stripe_product_id, :stripe_monthly_price_id, NULL,
:is_public, FALSE, :sort_order
)
ON CONFLICT (plan) DO UPDATE SET
display_name = EXCLUDED.display_name,
description = EXCLUDED.description,
monthly_price_cents = EXCLUDED.monthly_price_cents,
stripe_product_id = EXCLUDED.stripe_product_id,
stripe_monthly_price_id = EXCLUDED.stripe_monthly_price_id,
is_public = EXCLUDED.is_public,
sort_order = EXCLUDED.sort_order,
updated_at = NOW()
""")
async with async_session_maker() as session:
await session.execute(sql, {
"plan": plan,
"display_name": display_name,
"description": description,
"monthly_price_cents": monthly_price_cents,
"stripe_product_id": stripe_product_id,
"stripe_monthly_price_id": stripe_monthly_price_id,
"is_public": is_public,
"sort_order": sort_order,
})
await session.commit()
logger.info("upserted plan_billing for plan=%s", plan)
async def main(dry_run: bool) -> int:
if not settings.STRIPE_SECRET_KEY:
logger.error("STRIPE_SECRET_KEY is not set. Refusing to run.")
return 2
stripe.api_key = settings.STRIPE_SECRET_KEY
mode = "live" if settings.STRIPE_SECRET_KEY.startswith("sk_live_") else "test"
logger.info("connected to Stripe in %s mode", mode)
errors: list[str] = []
for product_name, plan in PLAN_NAME_TO_SLUG.items():
defaults = PLAN_DEFAULTS[plan]
product = find_product_by_name(product_name)
if product is None:
errors.append(f"Stripe product not found: {product_name!r}")
continue
price = None
if plan in PLANS_REQUIRING_PRICE:
price = find_active_monthly_price(product.id)
if price is None:
errors.append(
f"No active monthly recurring price for {product_name!r} "
f"(product {product.id})"
)
continue
await upsert_plan_billing(
plan=plan,
display_name=product.name,
description=product.description,
monthly_price_cents=price.unit_amount if price else None,
stripe_product_id=product.id,
stripe_monthly_price_id=price.id if price else None,
sort_order=defaults["sort_order"],
is_public=defaults["is_public"],
dry_run=dry_run,
)
if errors:
for e in errors:
logger.error(e)
return 1
logger.info("done")
return 0
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dry-run", action="store_true", help="Log actions without writing.")
args = parser.parse_args()
sys.exit(asyncio.run(main(dry_run=args.dry_run)))

View File

@@ -172,9 +172,8 @@ async def test_db() -> AsyncGenerator[AsyncSession, None]:
INSERT INTO plan_limits (plan, max_trees, max_sessions_per_month, max_users, custom_branding, priority_support, export_formats)
VALUES
('free', 3, 20, 1, false, false, '["markdown", "text"]'),
('starter', 10, 75, 1, false, false, '["markdown", "text", "html"]'),
('pro', 25, 200, 5, true, false, '["markdown", "text", "html"]'),
('enterprise', NULL, NULL, NULL, true, true, '["markdown", "text", "html"]')
('team', NULL, NULL, NULL, true, true, '["markdown", "text", "html"]')
"""))
# Seed the platform/system account (PLATFORM_ACCOUNT_ID) needed by

View File

@@ -122,9 +122,9 @@ class TestAdminPlanLimits:
):
"""PUT /admin/plan-limits upserts a plan_billing row when billing
fields are included in the body."""
# Ensure no plan_billing row exists for "enterprise" yet.
# Ensure no plan_billing row exists for "team" yet.
existing = (await test_db.execute(
select(PlanBilling).where(PlanBilling.plan == "enterprise")
select(PlanBilling).where(PlanBilling.plan == "team")
)).scalar_one_or_none()
if existing is not None:
await test_db.delete(existing)
@@ -133,7 +133,7 @@ class TestAdminPlanLimits:
response = await client.put(
"/api/v1/admin/plan-limits",
json={
"plan": "enterprise",
"plan": "team",
"max_trees": None,
"max_sessions_per_month": None,
"max_users": None,
@@ -163,7 +163,7 @@ class TestAdminPlanLimits:
# Confirm the row was actually persisted.
await test_db.commit() # ensure session sees other-session writes
pb = (await test_db.execute(
select(PlanBilling).where(PlanBilling.plan == "enterprise")
select(PlanBilling).where(PlanBilling.plan == "team")
)).scalar_one_or_none()
assert pb is not None
assert pb.display_name == "Team"
@@ -179,17 +179,17 @@ class TestAdminPlanLimits:
plan_billing row when the caller passes explicit nulls. The set of
guarded fields is {display_name, is_public, is_archived, sort_order}.
"""
# Seed a plan_billing row for "enterprise" with non-default values for every
# Seed a plan_billing row for "team" with non-default values for every
# NOT NULL field so we can detect any clobbering.
existing = (await test_db.execute(
select(PlanBilling).where(PlanBilling.plan == "enterprise")
select(PlanBilling).where(PlanBilling.plan == "team")
)).scalar_one_or_none()
if existing is not None:
await test_db.delete(existing)
await test_db.commit()
seeded = PlanBilling(
plan="enterprise",
plan="team",
display_name="Team Seeded",
is_public=False,
is_archived=True,
@@ -201,7 +201,7 @@ class TestAdminPlanLimits:
response = await client.put(
"/api/v1/admin/plan-limits",
json={
"plan": "enterprise",
"plan": "team",
"max_trees": None,
"max_sessions_per_month": None,
"max_users": None,
@@ -221,7 +221,7 @@ class TestAdminPlanLimits:
# Confirm the seeded NOT NULL values were preserved.
await test_db.commit() # ensure session sees writes from the request
pb = (await test_db.execute(
select(PlanBilling).where(PlanBilling.plan == "enterprise")
select(PlanBilling).where(PlanBilling.plan == "team")
)).scalar_one_or_none()
assert pb is not None
assert pb.display_name == "Team Seeded"

View File

@@ -49,58 +49,6 @@ class TestConfigPublic:
assert response.status_code == 200
assert response.json()["oauth_providers"] == ["microsoft"]
@pytest.mark.asyncio
async def test_get_config_public_returns_true_for_internal_tester(
self,
client: AsyncClient,
auth_headers: dict,
test_user: dict,
monkeypatch: pytest.MonkeyPatch,
):
"""Authenticated user whose email is on INTERNAL_TESTER_EMAILS sees
self_serve_enabled=True even when the global flag is off."""
monkeypatch.setattr(settings, "SELF_SERVE_ENABLED", False)
monkeypatch.setattr(settings, "GOOGLE_CLIENT_ID", None)
monkeypatch.setattr(settings, "MS_CLIENT_ID", None)
monkeypatch.setattr(settings, "INTERNAL_TESTER_EMAILS", [test_user["email"].lower()])
response = await client.get("/api/v1/config/public", headers=auth_headers)
assert response.status_code == 200
assert response.json()["self_serve_enabled"] is True
@pytest.mark.asyncio
async def test_get_config_public_returns_false_for_non_tester_when_global_off(
self,
client: AsyncClient,
auth_headers: dict,
monkeypatch: pytest.MonkeyPatch,
):
"""Authenticated user NOT on the allowlist sees the global flag —
prevents accidental opt-in via stale credentials or empty allowlist."""
monkeypatch.setattr(settings, "SELF_SERVE_ENABLED", False)
monkeypatch.setattr(settings, "GOOGLE_CLIENT_ID", None)
monkeypatch.setattr(settings, "MS_CLIENT_ID", None)
monkeypatch.setattr(settings, "INTERNAL_TESTER_EMAILS", ["someone-else@example.com"])
response = await client.get("/api/v1/config/public", headers=auth_headers)
assert response.status_code == 200
assert response.json()["self_serve_enabled"] is False
@pytest.mark.asyncio
async def test_get_config_public_anonymous_ignores_allowlist(
self, client: AsyncClient, monkeypatch: pytest.MonkeyPatch
):
"""Anonymous callers always see the global flag — the allowlist is
keyed on authenticated identity, not request content."""
monkeypatch.setattr(settings, "SELF_SERVE_ENABLED", False)
monkeypatch.setattr(settings, "GOOGLE_CLIENT_ID", None)
monkeypatch.setattr(settings, "MS_CLIENT_ID", None)
monkeypatch.setattr(settings, "INTERNAL_TESTER_EMAILS", ["anon-tester@example.com"])
response = await client.get("/api/v1/config/public")
assert response.status_code == 200
assert response.json()["self_serve_enabled"] is False
class TestRegisterInviteCodeGate:
"""Regression + new-behavior tests for /auth/register vs SELF_SERVE_ENABLED."""
@@ -150,55 +98,3 @@ class TestRegisterInviteCodeGate:
assert body["email"] == "self-serve@example.com"
assert body["account_role"] == "owner"
assert "account_id" in body
@pytest.mark.asyncio
async def test_register_invite_code_optional_for_internal_tester(
self, client: AsyncClient, monkeypatch: pytest.MonkeyPatch
):
"""SELF_SERVE_ENABLED is False but the registering email is on
INTERNAL_TESTER_EMAILS — registration should succeed without an
invite code, matching the per-email soft-cutover behavior."""
monkeypatch.setattr(settings, "REQUIRE_INVITE_CODE", True)
monkeypatch.setattr(settings, "SELF_SERVE_ENABLED", False)
monkeypatch.setattr(
settings, "INTERNAL_TESTER_EMAILS", ["tester@example.com"]
)
response = await client.post(
"/api/v1/auth/register",
json={
"email": "tester@example.com",
"password": "SecurePass123!",
"name": "Internal Tester",
},
)
assert response.status_code == 201, response.text
body = response.json()
assert body["email"] == "tester@example.com"
assert body["account_role"] == "owner"
@pytest.mark.asyncio
async def test_register_blocked_for_non_tester_when_self_serve_disabled(
self, client: AsyncClient, monkeypatch: pytest.MonkeyPatch
):
"""Registering with an email NOT on the allowlist still 400s when
self-serve is off and no invite code is provided. Prevents the
allowlist from leaking to public users."""
monkeypatch.setattr(settings, "REQUIRE_INVITE_CODE", True)
monkeypatch.setattr(settings, "SELF_SERVE_ENABLED", False)
monkeypatch.setattr(
settings, "INTERNAL_TESTER_EMAILS", ["other@example.com"]
)
response = await client.post(
"/api/v1/auth/register",
json={
"email": "outsider@example.com",
"password": "SecurePass123!",
"name": "Outsider",
},
)
assert response.status_code == 400
assert "invite code is required" in response.json()["detail"].lower()

View File

@@ -49,7 +49,7 @@ class TestInviteCodeCreation:
):
response = await client.post(
"/api/v1/invites",
json={"assigned_plan": "enterprise", "email": "beta@example.com"},
json={"assigned_plan": "team", "email": "beta@example.com"},
headers=admin_auth_headers,
)
assert response.status_code == 201
@@ -149,7 +149,7 @@ class TestRegistrationWithInvitePlan:
# Create team invite without trial
resp = await client.post(
"/api/v1/invites",
json={"assigned_plan": "enterprise"},
json={"assigned_plan": "team"},
headers=admin_auth_headers,
)
code = resp.json()["code"]
@@ -172,7 +172,7 @@ class TestRegistrationWithInvitePlan:
sub = (await test_db.execute(
select(Subscription).where(Subscription.account_id == user.account_id)
)).scalar_one()
assert sub.plan == "enterprise"
assert sub.plan == "team"
assert sub.status == "active"

View File

@@ -14,12 +14,7 @@ from app.models.plan_limits import PlanLimits
async def _seed_plan_limits(test_db, plan: str, max_users: int | None) -> None:
"""Ensure a plan_limits row exists with the given max_users.
Upserts: conftest seeds the canonical plans (free/starter/pro/enterprise)
so this helper has to overwrite max_users when a test wants different
values for fixture-driven assertions.
"""
"""Ensure a plan_limits row exists for the given plan name."""
existing = await test_db.get(PlanLimits, plan)
if existing is None:
test_db.add(
@@ -33,9 +28,7 @@ async def _seed_plan_limits(test_db, plan: str, max_users: int | None) -> None:
export_formats=["markdown", "text"],
)
)
else:
existing.max_users = max_users
await test_db.commit()
await test_db.commit()
class TestGetPlansPublic:

View File

@@ -1,782 +0,0 @@
"""Tests for the session-expiration-policy series.
See docs/plans/2026-05-13-session-expiration-policy.md.
Test numbers below correspond to the cases listed in §6 of the plan.
This file grows across commits:
- Commit 2: error-detail taxonomy (#11 + wrong-type + bad-signature)
- Commit 3: claims embedded at login + response fields surfaced (#1, #14)
- Commit 4: absolute-cap enforcement + grandfather path (#8, #9, #12)
- Commit 5: GET/PATCH /accounts/me/security (#2, #3, #4, #5, #7, #16)
- Commit 6: POST /accounts/me/security/revoke-sessions (#17-#22)
"""
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from httpx import AsyncClient
from jose import jwt
from app.core.config import settings
def _encode_refresh_token(
*,
sub: str,
exp: datetime,
token_type: str = "refresh",
secret: str | None = None,
) -> str:
"""Build a refresh JWT with arbitrary `exp` for testing.
Bypasses create_refresh_token so tests can produce already-expired
tokens, wrong-type tokens, or wrong-signature tokens.
"""
return jwt.encode(
{
"sub": sub,
"type": token_type,
"jti": str(uuid.uuid4()),
"exp": exp,
},
secret or settings.SECRET_KEY,
algorithm=settings.ALGORITHM,
)
class TestRefreshTokenErrorTaxonomy:
"""§6 test #11 — refresh-token error-detail taxonomy.
`/auth/refresh` distinguishes idle expiry from generic invalid-token
failures via `detail`, so the frontend can choose between the "session
ended for security" banner and a plain logout redirect.
"""
@pytest.mark.asyncio
async def test_idle_expired_refresh_returns_session_expired_idle(
self, client: AsyncClient, test_user: dict
):
token = _encode_refresh_token(
sub=test_user["user_data"]["id"],
exp=datetime.now(timezone.utc) - timedelta(seconds=1),
)
response = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 401
assert response.json()["detail"] == "session_expired_idle"
@pytest.mark.asyncio
async def test_wrong_type_token_returns_invalid_refresh_token(
self, client: AsyncClient, test_user: dict
):
token = _encode_refresh_token(
sub=test_user["user_data"]["id"],
exp=datetime.now(timezone.utc) + timedelta(minutes=5),
token_type="access",
)
response = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 401
assert response.json()["detail"] == "invalid_refresh_token"
@pytest.mark.asyncio
async def test_bad_signature_returns_invalid_refresh_token(
self, client: AsyncClient, test_user: dict
):
token = _encode_refresh_token(
sub=test_user["user_data"]["id"],
exp=datetime.now(timezone.utc) + timedelta(minutes=5),
secret="not-the-real-secret-key",
)
response = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 401
assert response.json()["detail"] == "invalid_refresh_token"
class TestSessionPolicyClaims:
"""§6 tests #1 and #14 — session-policy claims stamped at login.
Every token-issuing endpoint embeds auth_time/idle_max/abs_max in
the refresh JWT and surfaces idle_expires_at/absolute_expires_at on
the response.
"""
@pytest.mark.asyncio
async def test_login_json_embeds_session_claims_with_defaults(
self, client: AsyncClient, test_user: dict
):
before = datetime.now(timezone.utc)
response = await client.post(
"/api/v1/auth/login/json",
json={
"email": test_user["email"],
"password": test_user["password"],
},
)
assert response.status_code == 200, response.json()
body = response.json()
after = datetime.now(timezone.utc)
# Response surfaces both expiry windows as ISO strings.
assert body["idle_expires_at"] is not None
assert body["absolute_expires_at"] is not None
idle_at = datetime.fromisoformat(body["idle_expires_at"])
abs_at = datetime.fromisoformat(body["absolute_expires_at"])
# Strict default: 3 days idle, 14 days absolute.
assert timedelta(days=3) - timedelta(seconds=10) <= idle_at - before <= timedelta(days=3) + timedelta(seconds=10)
assert timedelta(days=14) - timedelta(seconds=10) <= abs_at - before <= timedelta(days=14) + timedelta(seconds=10)
# JWT carries the claims in seconds, plus auth_time as Unix seconds.
decoded = jwt.decode(
body["refresh_token"], settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
assert decoded["idle_max"] == 3 * 24 * 60 * 60 # 259200
assert decoded["abs_max"] == 14 * 24 * 60 * 60 # 1209600
assert int(before.timestamp()) <= decoded["auth_time"] <= int(after.timestamp())
@pytest.mark.asyncio
async def test_refresh_carries_claims_forward_unchanged(
self, client: AsyncClient, test_user: dict
):
# Login produces the original session.
login_resp = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
original_refresh = login_resp.json()["refresh_token"]
original_payload = jwt.decode(
original_refresh, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
# Refresh rotates the token but must carry auth_time/idle_max/abs_max
# forward unchanged so the absolute window doesn't slide.
refresh_resp = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {original_refresh}"},
)
assert refresh_resp.status_code == 200, refresh_resp.json()
new_refresh = refresh_resp.json()["refresh_token"]
new_payload = jwt.decode(
new_refresh, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
assert new_payload["auth_time"] == original_payload["auth_time"]
assert new_payload["idle_max"] == original_payload["idle_max"]
assert new_payload["abs_max"] == original_payload["abs_max"]
# Idle deadline does slide because exp = now + idle_max.
assert new_payload["exp"] >= original_payload["exp"]
# JTI rotates.
assert new_payload["jti"] != original_payload["jti"]
def _backdate_auth_time(refresh_token: str, *, seconds_back: int) -> str:
"""Re-sign a refresh JWT with an earlier auth_time, preserving JTI.
The DB row in refresh_tokens is keyed on hash(jti), so preserving jti
lets the atomic revoke step still find the row. Used to simulate
"this session is past its absolute cap" without waiting two weeks.
"""
payload = jwt.decode(
refresh_token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
payload["auth_time"] = payload["auth_time"] - seconds_back
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
class TestSessionPolicyEndpoint:
"""§6 tests #2, #3, #4, #5, #7, #16 — GET/PATCH /accounts/me/security."""
@pytest.mark.asyncio
async def test_get_returns_defaults_and_bounds(
self, client: AsyncClient, auth_headers: dict, test_user: dict
):
response = await client.get(
"/api/v1/accounts/me/security", headers=auth_headers
)
assert response.status_code == 200, response.json()
body = response.json()
# No override yet -> effective values are the system defaults.
assert body["idle_minutes"] is None
assert body["absolute_minutes"] is None
assert body["effective_idle_minutes"] == 4320 # 3d Strict default
assert body["effective_absolute_minutes"] == 20160 # 14d
assert body["idle_minutes_min"] == 15
assert body["idle_minutes_max"] == 43200
assert body["absolute_minutes_min"] == 60
assert body["absolute_minutes_max"] == 129600
# active_users reflects users with un-revoked refresh tokens.
# auth_headers logged the owner in once, so they should appear.
assert isinstance(body["active_users"], list)
assert len(body["active_users"]) >= 1
emails = [u["email"] for u in body["active_users"]]
assert test_user["email"] in emails
# Schema check on one row.
first = body["active_users"][0]
assert "user_id" in first
assert "name" in first
assert "email" in first
assert "last_login_at" in first
@pytest.mark.asyncio
async def test_patch_persists_override_and_returns_new_state(
self, client: AsyncClient, auth_headers: dict
):
response = await client.patch(
"/api/v1/accounts/me/security",
headers=auth_headers,
json={"idle_minutes": 60, "absolute_minutes": 240},
)
assert response.status_code == 200, response.json()
body = response.json()
assert body["idle_minutes"] == 60
assert body["absolute_minutes"] == 240
assert body["effective_idle_minutes"] == 60
assert body["effective_absolute_minutes"] == 240
# Next login picks up the new policy.
login_resp = await client.post(
"/api/v1/auth/login/json",
json={"email": "test@example.com", "password": "TestPassword123!"},
)
new_payload = jwt.decode(
login_resp.json()["refresh_token"],
settings.SECRET_KEY,
algorithms=[settings.ALGORITHM],
)
assert new_payload["idle_max"] == 60 * 60 # 3600 seconds
assert new_payload["abs_max"] == 240 * 60 # 14400 seconds
@pytest.mark.asyncio
async def test_patch_rejects_idle_below_min(
self, client: AsyncClient, auth_headers: dict
):
response = await client.patch(
"/api/v1/accounts/me/security",
headers=auth_headers,
json={"idle_minutes": 5, "absolute_minutes": 60},
)
assert response.status_code == 422
assert "idle_minutes" in response.json()["detail"]
@pytest.mark.asyncio
async def test_patch_rejects_absolute_above_max(
self, client: AsyncClient, auth_headers: dict
):
response = await client.patch(
"/api/v1/accounts/me/security",
headers=auth_headers,
json={"absolute_minutes": 200000},
)
assert response.status_code == 422
@pytest.mark.asyncio
async def test_patch_rejects_idle_greater_than_absolute_both_set(
self, client: AsyncClient, auth_headers: dict
):
response = await client.patch(
"/api/v1/accounts/me/security",
headers=auth_headers,
json={"idle_minutes": 300, "absolute_minutes": 120},
)
assert response.status_code == 422
assert "exceed" in response.json()["detail"].lower()
@pytest.mark.asyncio
async def test_patch_rejects_partial_override_when_effective_invalid(
self, client: AsyncClient, auth_headers: dict
):
"""§6 test #5 — partial override: idle=43200, absolute=NULL ->
effective idle (43200) > effective absolute (20160 default) -> 422.
"""
response = await client.patch(
"/api/v1/accounts/me/security",
headers=auth_headers,
json={"idle_minutes": 43200, "absolute_minutes": None},
)
assert response.status_code == 422
assert "exceed" in response.json()["detail"].lower()
@pytest.mark.asyncio
async def test_non_owner_cannot_patch(
self, client: AsyncClient, test_user: dict, test_db
):
"""§6 test #7 — engineer role is forbidden."""
from app.models.user import User
from sqlalchemy import select
# Add a second user in the same account with account_role=engineer.
result = await test_db.execute(
select(User).where(User.email == test_user["email"])
)
owner = result.scalar_one()
engineer = User(
email="engineer-policy@example.com",
password_hash=owner.password_hash, # reuse the bcrypt hash
name="Engineer",
role="engineer",
is_super_admin=False,
is_active=True,
account_id=owner.account_id,
account_role="engineer",
email_verified_at=datetime.now(timezone.utc),
)
test_db.add(engineer)
await test_db.commit()
login_resp = await client.post(
"/api/v1/auth/login/json",
json={
"email": "engineer-policy@example.com",
"password": test_user["password"],
},
)
assert login_resp.status_code == 200
engineer_headers = {
"Authorization": f"Bearer {login_resp.json()['access_token']}"
}
response = await client.patch(
"/api/v1/accounts/me/security",
headers=engineer_headers,
json={"idle_minutes": 60, "absolute_minutes": 240},
)
assert response.status_code == 403
@pytest.mark.asyncio
async def test_patch_writes_audit_row(
self, client: AsyncClient, auth_headers: dict, test_db
):
"""§6 test #16 — PATCH emits one account.session_policy_update
audit event with old/new + effective_old/new payload.
"""
from app.models.audit_log import AuditLog
from sqlalchemy import select
response = await client.patch(
"/api/v1/accounts/me/security",
headers=auth_headers,
json={"idle_minutes": 120, "absolute_minutes": 480},
)
assert response.status_code == 200
result = await test_db.execute(
select(AuditLog).where(AuditLog.action == "account.session_policy_update")
)
rows = result.scalars().all()
assert len(rows) == 1
entry = rows[0]
assert entry.resource_type == "account"
assert entry.details["new"] == {"idle_minutes": 120, "absolute_minutes": 480}
assert entry.details["effective_new"] == {
"idle_minutes": 120,
"absolute_minutes": 480,
}
assert entry.details["effective_old"]["idle_minutes"] == 4320 # default
assert entry.details["effective_old"]["absolute_minutes"] == 20160
async def _seed_extra_account_user(
test_db, *, email: str, account_id, password_hash: str, role: str = "engineer"
):
"""Add a second user under an existing account for revoke-scope tests."""
from app.models.user import User
user = User(
email=email,
password_hash=password_hash,
name=email,
role="engineer",
is_super_admin=False,
is_active=True,
account_id=account_id,
account_role=role,
email_verified_at=datetime.now(timezone.utc),
)
test_db.add(user)
await test_db.commit()
return user
class TestBulkRevoke:
"""§6 tests #17-#22 — POST /accounts/me/security/revoke-sessions."""
@pytest.mark.asyncio
async def test_revoke_all_kills_callers_own_session(
self, client: AsyncClient, test_user: dict, test_db
):
"""§6 test #17 — scope=all includes the caller's own token. After
the response, the caller's refresh_token gets invalid_refresh_token
on next /auth/refresh.
"""
from app.models.user import User
from sqlalchemy import select
owner = (
await test_db.execute(
select(User).where(User.email == test_user["email"])
)
).scalar_one()
await _seed_extra_account_user(
test_db,
email="member-revoke-all@example.com",
account_id=owner.account_id,
password_hash=owner.password_hash,
)
# Owner logs in (also seeds owner's refresh-token row).
owner_login = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
owner_refresh = owner_login.json()["refresh_token"]
owner_access = owner_login.json()["access_token"]
# Member also logs in so there's another active refresh-token row.
member_login = await client.post(
"/api/v1/auth/login/json",
json={
"email": "member-revoke-all@example.com",
"password": test_user["password"],
},
)
assert member_login.status_code == 200
response = await client.post(
"/api/v1/accounts/me/security/revoke-sessions",
headers={"Authorization": f"Bearer {owner_access}"},
json={"scope": "all"},
)
assert response.status_code == 200, response.json()
assert response.json()["revoked_count"] == 2
# Owner's own refresh now returns invalid_refresh_token.
retry = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {owner_refresh}"},
)
assert retry.status_code == 401
assert retry.json()["detail"] == "invalid_refresh_token"
@pytest.mark.asyncio
async def test_revoke_others_preserves_callers_session(
self, client: AsyncClient, test_user: dict, test_db
):
"""§6 test #18 — scope=others excludes the caller's user_id from
the bulk update. Caller can still refresh; other users cannot.
"""
from app.models.user import User
from sqlalchemy import select
owner = (
await test_db.execute(
select(User).where(User.email == test_user["email"])
)
).scalar_one()
await _seed_extra_account_user(
test_db,
email="member-revoke-others@example.com",
account_id=owner.account_id,
password_hash=owner.password_hash,
)
owner_login = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
owner_refresh = owner_login.json()["refresh_token"]
owner_access = owner_login.json()["access_token"]
member_login = await client.post(
"/api/v1/auth/login/json",
json={
"email": "member-revoke-others@example.com",
"password": test_user["password"],
},
)
member_refresh = member_login.json()["refresh_token"]
response = await client.post(
"/api/v1/accounts/me/security/revoke-sessions",
headers={"Authorization": f"Bearer {owner_access}"},
json={"scope": "others"},
)
assert response.status_code == 200
assert response.json()["revoked_count"] == 1
# Owner's refresh still works.
owner_retry = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {owner_refresh}"},
)
assert owner_retry.status_code == 200
# Member's refresh is dead.
member_retry = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {member_refresh}"},
)
assert member_retry.status_code == 401
assert member_retry.json()["detail"] == "invalid_refresh_token"
@pytest.mark.asyncio
async def test_revoke_is_account_scoped(
self, client: AsyncClient, test_user: dict, test_admin: dict
):
"""§6 test #19 — owner of account A cannot revoke tokens in account B.
test_admin lives in its own account. After test_user's owner runs
revoke-all, test_admin's session continues to work.
"""
owner_login = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
owner_access = owner_login.json()["access_token"]
admin_login = await client.post(
"/api/v1/auth/login/json",
json={"email": test_admin["email"], "password": test_admin["password"]},
)
admin_refresh = admin_login.json()["refresh_token"]
response = await client.post(
"/api/v1/accounts/me/security/revoke-sessions",
headers={"Authorization": f"Bearer {owner_access}"},
json={"scope": "all"},
)
assert response.status_code == 200
# Only test_user's own session is revoked.
assert response.json()["revoked_count"] == 1
admin_retry = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {admin_refresh}"},
)
assert admin_retry.status_code == 200
@pytest.mark.asyncio
async def test_revoke_engineer_forbidden(
self, client: AsyncClient, test_user: dict, test_db
):
"""§6 test #20 — engineer-role member gets 403."""
from app.models.user import User
from sqlalchemy import select
owner = (
await test_db.execute(
select(User).where(User.email == test_user["email"])
)
).scalar_one()
await _seed_extra_account_user(
test_db,
email="engineer-revoke@example.com",
account_id=owner.account_id,
password_hash=owner.password_hash,
)
engineer_login = await client.post(
"/api/v1/auth/login/json",
json={
"email": "engineer-revoke@example.com",
"password": test_user["password"],
},
)
engineer_access = engineer_login.json()["access_token"]
response = await client.post(
"/api/v1/accounts/me/security/revoke-sessions",
headers={"Authorization": f"Bearer {engineer_access}"},
json={"scope": "all"},
)
assert response.status_code == 403
@pytest.mark.asyncio
async def test_revoke_writes_audit_row(
self, client: AsyncClient, test_user: dict, test_db
):
"""§6 test #21 — emits one account.sessions_revoked_bulk event."""
from app.models.audit_log import AuditLog
from sqlalchemy import select
owner_login = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
owner_access = owner_login.json()["access_token"]
response = await client.post(
"/api/v1/accounts/me/security/revoke-sessions",
headers={"Authorization": f"Bearer {owner_access}"},
json={"scope": "all"},
)
assert response.status_code == 200
result = await test_db.execute(
select(AuditLog).where(AuditLog.action == "account.sessions_revoked_bulk")
)
rows = result.scalars().all()
assert len(rows) == 1
entry = rows[0]
assert entry.details["scope"] == "all"
assert entry.details["revoked_count"] == 1
@pytest.mark.asyncio
async def test_revoke_is_idempotent(
self, client: AsyncClient, test_user: dict
):
"""§6 test #22 — second immediate POST returns revoked_count=0
(no already-revoked rows get double-stamped or counted again).
"""
owner_login = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
owner_access = owner_login.json()["access_token"]
first = await client.post(
"/api/v1/accounts/me/security/revoke-sessions",
headers={"Authorization": f"Bearer {owner_access}"},
json={"scope": "others"}, # owner's own session preserved
)
assert first.status_code == 200
second = await client.post(
"/api/v1/accounts/me/security/revoke-sessions",
headers={"Authorization": f"Bearer {owner_access}"},
json={"scope": "others"},
)
assert second.status_code == 200
assert second.json()["revoked_count"] == 0
class TestAbsoluteCap:
"""§6 tests #8, #9, #12 — absolute-cap enforcement and grandfather path."""
@pytest.mark.asyncio
async def test_refresh_at_absolute_deadline_rejects(
self, client: AsyncClient, test_user: dict
):
"""§6 test #8 — boundary check uses `>=`, not `>`.
A token whose auth_time + abs_max equals now() is expired, not
valid. Backdate the original token's auth_time by exactly abs_max
seconds so now >= deadline.
"""
login_resp = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
original = login_resp.json()["refresh_token"]
abs_max = jwt.decode(
original, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)["abs_max"]
expired = _backdate_auth_time(original, seconds_back=abs_max)
response = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {expired}"},
)
assert response.status_code == 401
assert response.json()["detail"] == "session_expired_absolute"
@pytest.mark.asyncio
async def test_absolute_expired_token_is_consumed(
self, client: AsyncClient, test_user: dict
):
"""§6 test #9 — first attempt returns session_expired_absolute and
revokes the row; second attempt sees the revoked row and returns
invalid_refresh_token. Prevents replay of an absolute-expired token.
"""
login_resp = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
original = login_resp.json()["refresh_token"]
abs_max = jwt.decode(
original, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)["abs_max"]
expired = _backdate_auth_time(original, seconds_back=abs_max + 1)
first = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {expired}"},
)
assert first.status_code == 401
assert first.json()["detail"] == "session_expired_absolute"
second = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {expired}"},
)
assert second.status_code == 401
assert second.json()["detail"] == "invalid_refresh_token"
@pytest.mark.asyncio
async def test_grandfather_path_for_legacy_token(
self, client: AsyncClient, test_user: dict, test_db
):
"""§6 test #12 — refresh token issued before this PR (no auth_time
claim) gets one successful rotation; the new token has fresh
auth_time/idle_max/abs_max claims snapshotted from current policy.
"""
from app.core.security import hash_token
from app.models.refresh_token import RefreshToken
login_resp = await client.post(
"/api/v1/auth/login/json",
json={"email": test_user["email"], "password": test_user["password"]},
)
original = login_resp.json()["refresh_token"]
original_payload = jwt.decode(
original, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
# Strip the new claims to simulate a token issued before this PR.
# JTI preserved so the DB-side revoke still finds the row.
legacy_payload = {
"sub": original_payload["sub"],
"type": "refresh",
"jti": original_payload["jti"],
"exp": original_payload["exp"],
}
legacy_token = jwt.encode(
legacy_payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM
)
response = await client.post(
"/api/v1/auth/refresh",
headers={"Authorization": f"Bearer {legacy_token}"},
)
assert response.status_code == 200, response.json()
new_payload = jwt.decode(
response.json()["refresh_token"],
settings.SECRET_KEY,
algorithms=[settings.ALGORITHM],
)
assert new_payload.get("auth_time") is not None
assert new_payload.get("idle_max") == 3 * 24 * 60 * 60
assert new_payload.get("abs_max") == 14 * 24 * 60 * 60
# auth_time was set to ~now during grandfather, not preserved from
# the legacy token (since the legacy token didn't have one).
now_unix = int(datetime.now(timezone.utc).timestamp())
assert abs(new_payload["auth_time"] - now_unix) < 10

View File

@@ -40,16 +40,11 @@ services:
- ALGORITHM=HS256
- ACCESS_TOKEN_EXPIRE_MINUTES=15
- REFRESH_TOKEN_EXPIRE_DAYS=7
- REQUIRE_INVITE_CODE=false
- REQUIRE_INVITE_CODE=true
- FEEDBACK_EMAIL=feedback@resolutionflow.com
- AI_PROVIDER=anthropic
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
- GOOGLE_AI_API_KEY=${GOOGLE_AI_API_KEY:-}
- STRIPE_SECRET_KEY=${STRIPE_SECRET_KEY:-}
- STRIPE_PUBLISHABLE_KEY=${STRIPE_PUBLISHABLE_KEY:-}
- STRIPE_WEBHOOK_SECRET=${STRIPE_WEBHOOK_SECRET:-}
- SELF_SERVE_ENABLED=${SELF_SERVE_ENABLED:-false}
- INTERNAL_TESTER_EMAILS=${INTERNAL_TESTER_EMAILS:-}
- ENABLE_MCP_MICROSOFT_LEARN=true
- FRONTEND_URL=http://docker-01:5173
- CORS_ORIGINS=["http://localhost:5173","http://127.0.0.1:5173","http://docker-01:5173","http://100.64.78.44:5173"]

View File

@@ -1,493 +0,0 @@
# Session Expiration Policy — Design & Implementation Plan
**Date:** 2026-05-13
**Owner:** Michael Chihlas
**Status:** Draft — pending review
**Related issue:** none yet (file after plan approval)
---
## 1. Problem
Today, once a user logs in to ResolutionFlow, they effectively stay logged in forever:
- Access token: 5 minutes — fine.
- Refresh token: 7 days, with JTI rotation. Every `/auth/refresh` mints a fresh 7-day window and revokes the old JTI.
- Frontend stores both in `localStorage`; Axios interceptor silently refreshes on every 401.
Net effect: a **sliding 7-day session with no absolute cap**. As long as a user opens the app at least once a week, the refresh token rolls forward indefinitely. There is no enforced re-authentication, no idle-timeout cap, no maximum session lifetime — and no per-account control for MSP owners whose customers may demand stricter security.
This was acceptable for pilot but is **not acceptable for self-serve launch**:
- MSP buyers' SOC2 / cyber-insurance auditors routinely require enforced session timeouts.
- A stolen device with an unlocked browser hands an attacker indefinite access.
- Owners of paying accounts expect to be able to set policy for their members.
## 2. Goals
1. **System-level absolute cap** — no session can exceed N days regardless of activity.
2. **Idle cap** — sessions inactive for N days must require re-login.
3. **Per-account owner override** — account owners can tighten or (within sysadmin-imposed ceilings) loosen the policy for their account.
4. **Graceful UX** — users get warned before forced re-login; rotation continues to be silent within the active window.
5. **Backward-compatible rollout** — existing refresh tokens are grandfathered for one rotation, not invalidated at deploy.
## 3. Non-goals
- Multi-device session management (revoke individual devices). Tracked separately; out of scope here.
- "Remember this device" / trusted device list. Out of scope.
- Per-user (vs per-account) overrides. Out of scope.
- Re-auth on sensitive action (step-up auth). Out of scope.
- Annual review of session policy (analytics dashboards). Out of scope.
## 4. Design
### 4.1 Two windows, both enforced
| Window | Default | Meaning |
|---|---|---|
| **Idle** | 3 days | Maximum time between `/auth/refresh` calls. Rotation extends this window. |
| **Absolute** | 14 days | Hard cap from original login (`auth_time`). Rotation does **not** extend this. |
The shorter of the two governs: a token is valid only if `now < min(idle_exp, auth_time + absolute_max)`.
### 4.2 JWT payload changes
Refresh-token JWT today (`backend/app/core/security.py:36`):
```json
{ "sub": "<user_id>", "type": "refresh", "jti": "<uuid>", "exp": <idle_exp> }
```
New refresh-token JWT:
```json
{
"sub": "<user_id>",
"type": "refresh",
"jti": "<uuid>",
"exp": <idle_exp>, // unchanged semantics, now = idle window
"auth_time": <login_unix_ts>, // original login (Unix seconds); NOT reset on rotation
"idle_max": <idle_seconds>, // captured at login (account policy snapshot, seconds)
"abs_max": <abs_seconds> // captured at login (account policy snapshot, seconds)
}
```
**Unit convention (single source of truth):**
| Surface | Unit | Why |
|---|---|---|
| `Settings.SESSION_*_MINUTES`, `accounts.session_*_minutes`, PATCH `/accounts/me/security` request/response, frontend form inputs | **minutes** | Human-readable, matches the column names, what owners actually edit |
| `idle_max`, `abs_max` inside the refresh JWT, `auth_time` | **seconds (Unix)** | Lets `auth_time + abs_max` be direct Unix math against `int(time.time())` with no conversion at check time |
| `idle_expires_at`, `absolute_expires_at` on API responses, `useAuthSessionExpiry` hook | **ISO 8601 UTC strings** | Matches the rest of the API surface (`DateTime(timezone=True)` everywhere) |
`resolve_session_policy(account)` (see §4.4) returns minutes; the `_mint_session_tokens` helper multiplies by 60 once when stamping the JWT. That's the only place the conversion happens.
Why snapshot `idle_max`/`abs_max` into the JWT instead of looking up the account policy on every refresh? Two reasons:
- Refresh path stays DB-cheap (one query, not two).
- If an owner tightens the policy after a user has logged in, the user's existing session continues under the policy in effect at login — fairer UX, matches what Okta and Microsoft do. New logins pick up the tightened policy.
Counter-consideration: if an owner *loosens* policy, existing sessions stay tight until next login. Acceptable; users won't notice. The owner-tightens case (security event) is the one that matters, and a kill-all-sessions admin button covers that scenario (out of scope here — log an issue).
### 4.3 Per-account policy storage
New columns on `accounts`:
| Column | Type | Nullable | Meaning |
|---|---|---|---|
| `session_idle_minutes` | `Integer` | yes | NULL = use system default |
| `session_absolute_minutes` | `Integer` | yes | NULL = use system default |
Minutes (not days) so admins can configure shorter windows for high-security tenants if needed. Stored as Integer to match existing pattern; conversion to `timedelta` happens at use site.
System-imposed bounds (in `Settings`, environment-overridable):
| Setting | Default | Floor | Ceiling |
|---|---|---|---|
| `SESSION_IDLE_MINUTES_DEFAULT` | 4320 (3d) | n/a | n/a |
| `SESSION_ABSOLUTE_MINUTES_DEFAULT` | 20160 (14d) | n/a | n/a |
| `SESSION_IDLE_MINUTES_MIN` | 15 | hard floor | account override cannot go below |
| `SESSION_IDLE_MINUTES_MAX` | 43200 (30d) | account override cannot go above | |
| `SESSION_ABSOLUTE_MINUTES_MIN` | 60 (1h) | hard floor | |
| `SESSION_ABSOLUTE_MINUTES_MAX` | 129600 (90d) | account override cannot go above | |
Plus invariant: an account's *effective* idle window must not exceed its *effective* absolute window. Enforcement is layered:
- **App-level (PATCH endpoint, authoritative):** before writing the row, resolve both effective values (`override ?? system_default`) and reject when effective idle > effective absolute. This is the only place that knows the current system defaults, so it's the only place that can catch a partial-override hole like `session_idle_minutes=43200, session_absolute_minutes=NULL` when the system absolute default is 20160.
- **DB CHECK constraint (defense in depth, narrower):** `session_idle_minutes IS NULL OR session_absolute_minutes IS NULL OR session_idle_minutes <= session_absolute_minutes`. This only catches the both-set case; the partial-override case is intentionally outside the DB's reach because the DB can't see `Settings`. Document this in a comment on the constraint.
Alternative considered: require both columns to be NULL or both set (XOR-with-NULL). Rejected because it forces an owner who only wants to override idle to also re-declare the absolute window, which leaks the system default into account data and makes the system default harder to evolve later.
### 4.4 Resolution function
```python
# backend/app/core/security.py
def resolve_session_policy(account: Account) -> tuple[int, int]:
"""Return (idle_minutes, absolute_minutes) for an account, applying defaults."""
idle = account.session_idle_minutes or settings.SESSION_IDLE_MINUTES_DEFAULT
abs_ = account.session_absolute_minutes or settings.SESSION_ABSOLUTE_MINUTES_DEFAULT
return idle, abs_
```
Called once at each of the four token-issuing entry points listed in §4.6 (`/auth/login`, `/auth/login/json`, `/auth/google/callback`, `/auth/microsoft/callback`) and snapshotted into the JWT via `_mint_session_tokens`. Not called on `/auth/refresh` — that path carries forward the existing snapshot.
### 4.5 Refresh endpoint changes
`POST /auth/refresh` (`backend/app/api/endpoints/auth.py:377`) currently:
1. Decodes refresh JWT (via `get_refresh_token_payload` dep).
2. Atomically revokes old JTI (`UPDATE … SET revoked_at=now() WHERE token_hash=? AND revoked_at IS NULL RETURNING …`).
3. Mints new refresh + access tokens with same `sub`.
New algorithm (precise):
1. Decode refresh JWT (idle expiry already surfaced as `session_expired_idle` by `decode_refresh_token_strict`; see §4.10).
2. **NEW:** load `user` and `user.account` by `sub` from the decoded payload. Needed before any legacy-token handling because the grandfather path needs to read the account's current policy. If the user is missing or inactive, return 401 with `detail="invalid_refresh_token"` (existing behavior, unchanged).
3. **NEW (grandfather path):** if `auth_time` is missing from the payload (legacy token issued before this PR), treat it as `now()` and snapshot the loaded account's current policy via `resolve_session_policy(account)` into `idle_max`/`abs_max`. One free rotation under the new policy.
4. **NEW:** compute `absolute_deadline = auth_time + abs_max` (both in Unix seconds). Compare with `now >= absolute_deadline`, not `>` — a token whose deadline equals `now()` is expired, not valid.
5. **Atomically revoke the JTI regardless of outcome** (single UPDATE, same statement as today). This consumes the token whether or not the absolute check passes — so an absolute-expired token cannot be replayed forever; a second attempt finds the row already `revoked_at IS NOT NULL` and falls through to the existing "invalid or revoked refresh token" 401.
6. If the atomic UPDATE matched zero rows (already revoked): 401 with `detail="invalid_refresh_token"`.
7. If `now >= absolute_deadline`: 401 with `detail="session_expired_absolute"`. (The row is already revoked from step 5.)
8. Otherwise mint new tokens, **carrying forward `auth_time`, `idle_max`, `abs_max` unchanged** from the old token (or freshly snapshotted if grandfathered in step 3).
Helper contract: `_refresh_session_tokens(payload, user, account, db) -> Token`. Takes the validated decoded payload plus the already-loaded user/account so it doesn't re-query. Returns the same `Token` shape as `_mint_session_tokens` (with the two new ISO expiry fields). Distinct from `_mint_session_tokens` because the refresh path carries claims forward instead of resolving policy.
Idle expiry is handled earlier in the chain: `get_refresh_token_payload` calls `decode_token`, which returns `None` for any JWT past `exp` — that's the existing 401 path. See §4.10 for distinguishing idle expiry from generic invalid-token errors in the response.
### 4.6 Login endpoints
Token-issuing endpoints that need the snapshot logic (verified against the codebase):
| Endpoint | File:line | Response model |
|---|---|---|
| `POST /auth/login` (form-encoded, OAuth2PasswordRequestForm) | `backend/app/api/endpoints/auth.py:303` | `Token` |
| `POST /auth/login/json` (JSON body — what the frontend actually calls) | `backend/app/api/endpoints/auth.py:342` | `Token` |
| `POST /auth/google/callback` | `backend/app/api/endpoints/oauth.py:174` | `OAuthCallbackResponse` |
| `POST /auth/microsoft/callback` | `backend/app/api/endpoints/oauth.py:204` | `OAuthCallbackResponse` |
| `POST /auth/refresh` | `backend/app/api/endpoints/auth.py:377` | `Token` |
`POST /auth/register` (`auth.py:92`) returns `UserResponse` and **does not auto-login** — the frontend follows up with a separate call to `/auth/login/json`. No token-minting changes needed in `/register` itself; the subsequent `/login/json` call will pick up the new claims naturally.
Each of the four token-issuing endpoints (login, login/json, both OAuth callbacks) calls `create_refresh_token` with the extra claims. Wrap in a helper `_mint_session_tokens(user, account, db) -> Token` (or `OAuthCallbackResponse` — see §4.10 on shared response fields) to avoid drift across four sites. `/auth/refresh` uses a variant that carries forward existing claims instead of re-snapshotting policy.
### 4.7 Account security endpoint
New endpoint module: `backend/app/api/endpoints/account_security.py`
```
GET /accounts/me/security → returns {
idle_minutes, absolute_minutes,
effective_idle_minutes, effective_absolute_minutes,
system_min/max bounds,
active_users: [{user_id, name, email, last_login_at}, ...]
}
PATCH /accounts/me/security → owner only; validates bounds + invariant; writes account row
```
`require_account_owner` from `app/api/deps.py:189` enforces ownership. Returns the *effective* values (after defaults applied) so the frontend doesn't have to know about NULL semantics.
**`active_users` field** (added during plan-design-review pass on 2026-05-13): the GET response includes a list of users with at least one un-revoked refresh token in this account. Query: `SELECT DISTINCT u.id, u.email, u.name, u.last_login FROM users u JOIN refresh_tokens rt ON rt.user_id = u.id WHERE u.account_id = :acct AND rt.revoked_at IS NULL`. The frontend uses this to render the "Active sessions" section with names + relative last-login timestamps (see §4.8) rather than a faceless count. Caveat: `last_login` updates only at login, not on refresh — so the relative timestamp is honest about "when they signed in," not "last touched the app." Per-refresh activity needs the deferred `refresh_tokens.last_used_at` follow-up (§9).
### 4.8 Frontend changes
**Response-field naming (single scheme, used everywhere):**
Both `Token` (`/auth/login`, `/auth/login/json`, `/auth/refresh`) and `OAuthCallbackResponse` (`/auth/google/callback`, `/auth/microsoft/callback`) gain two new fields:
| Field | Type | Source |
|---|---|---|
| `idle_expires_at` | ISO 8601 UTC string | derived from refresh JWT `exp` |
| `absolute_expires_at` | ISO 8601 UTC string | derived from refresh JWT `auth_time + abs_max` |
ISO strings (not Unix ints) for consistency with the rest of the API surface, which uses `DateTime(timezone=True)` everywhere. Frontend parses with `new Date(...)`.
**New hook:** `frontend/src/hooks/useAuthSessionExpiry.ts`
- Reads `idleExpiresAt` and `absoluteExpiresAt` from `authStore`.
- Returns `{ idleExpiresAt, absoluteExpiresAt, warning, reason }` where `warning ∈ {"none", "soon", "now"}` and `reason ∈ {"idle", "absolute"}` indicating which window is closer.
- "soon" fires at T-5min on whichever window comes first.
- Pairs with a top-of-app `<SessionExpiryToast />` mounted in `AppLayout.tsx`.
**SessionExpiryToast — differentiated by `reason`** (locked during plan-design-review):
- **`reason === "idle"`** (idle window is closer): warning-amber tone. Copy: *"Your session times out in 5 minutes."* Action button: `[Stay signed in]` → triggers a manual `/auth/refresh` call (resets the idle window). On success, toast dismisses + the store updates `idleExpiresAt`. On failure (e.g. absolute cap is also nearby and the refresh hits `session_expired_absolute`), fall through to the standard 401-handling redirect.
- **`reason === "absolute"`** (absolute window is closer): info-cyan tone (matching the `?reason=session_expired` banner). Copy: *"Your session ends at HH:MM for security. You'll need to sign in again."* No action button — nothing the user can do extends an absolute cap. Optional secondary action: `[Sign in now]` link to `/login` for users who want to re-auth proactively.
- Toast does not auto-dismiss (persists until acted on or window expires).
- Re-fires only after a successful `/auth/refresh` extends the idle window past T-5min and we cross back into "soon" later. Does not nag.
**Modified:** `frontend/src/api/client.ts` interceptor
- On 401 with `detail="session_expired_absolute"` **or** `detail="session_expired_idle"`: **skip the refresh attempt**, flush tokens, redirect to `/login?reason=session_expired`. (Both surfaces go through the same banner — users don't need to distinguish the two.)
- On 401 with `detail="invalid_refresh_token"` or any other detail: current behavior (drop to `/login` without the reason banner).
- Existing access-token-expired flow (transparent `/auth/refresh`) unchanged.
**Modified:** `frontend/src/store/authStore.ts`
- `setTokens(token: Token)` (`authStore.ts:140`) is the single token-persistence path used by both `login()` and the OAuth flow. Extend the `Token` type with `idle_expires_at` + `absolute_expires_at`; `setTokens` writes them to store + localStorage alongside the access/refresh tokens. No new action.
- The Axios refresh interceptor (`api/client.ts:139`) destructures `access_token, refresh_token` today — extend to read the two new fields and call `setTokens` so refreshed sessions update their expiry metadata.
- **Legacy-state migration:** on store rehydrate, if tokens exist but `idle_expires_at` / `absolute_expires_at` are missing from localStorage, leave them `null` and let the next `/auth/refresh` populate them via response fields. The hook treats `null` as "unknown — don't warn yet." No forced logout for pre-deploy localStorage.
**Modified:** `frontend/src/pages/OAuthCallbackPage.tsx`
- The `setTokens({...})` call at `OAuthCallbackPage.tsx:102` currently passes `{access_token, refresh_token, token_type}` from the `OAuthCallbackResponse`. Add `idle_expires_at` and `absolute_expires_at` to the spread so OAuth-issued sessions get the same expiry metadata as password logins.
**New page:** `frontend/src/pages/account/AccountSecuritySettingsPage.tsx`
- Lives under existing `/account` routing with `requireRoleOwner` style guard. Card lives in `AccountSettingsPage.tsx` grid alongside Branding / Chat Retention; **hidden entirely for non-owners** (matches existing role-conditional rendering at `AccountSettingsPage.tsx:597-651`).
- Page shell matches `ChatRetentionSettingsPage.tsx`: `max-w-2xl mx-auto py-8 px-6`, header row with Lucide icon + Bricolage 22px page title, `card-flat rounded-2xl p-6 space-y-6` body.
- **Vertical order (top → bottom):**
1. Page header (Lucide `Shield` icon + "Session Security")
2. One-line intro paragraph (`text-muted-foreground`): *"Control how long sessions can last before users must sign in again."*
3. **Session policy** card: three radios (Strict / Standard / Custom) with effective minute values visible per option ("Strict — 3d idle, 14d absolute"), then two numeric inputs (Idle minutes, Absolute minutes). **Inputs are always visible; disabled when a preset is selected.** Below inputs: hint text showing the system min/max from the GET response. Save button (primary) + inline `text-emerald-400 "Settings saved"` success ping for 3s after save (matching `ChatRetentionSettingsPage.tsx:112-114`).
4. Info line directly below Save: *"New policy applies the next time each person signs in. Use **Active sessions** below to force it immediately."* (`text-muted-foreground`, bold on "Active sessions" — anchor link or just visual emphasis).
5. Visual divider (1px `border-default`).
6. **Active sessions** section (see below for details).
- **Initial GET loading state:** centered `Loader2 animate-spin` page-body, matching `ChatRetentionSettingsPage.tsx:46-51`.
- **Inline validation** on Custom inputs: debounced 300ms; red border (`border-danger`) + small error text below field; Save button disabled when any field is invalid. Server-side 422 from PATCH surfaces via the existing axios interceptor toast.
**Active sessions section (within the same page):**
- GET response includes `active_users: [{user_id, name, email, last_login_at}, ...]` — backend addition; see §4.7.
- Section header: "Active sessions"
- Subhead: "N people are signed in to this account." (singular: "Only you are signed in.")
- Active-users list: one row per active user — `name (email) · logged in 2d ago` (relative time from `last_login_at`). Caller's own row marked with a small "(you)" tag.
- Buttons below the list — count-aware:
- **count > 1:** Two ghost buttons side-by-side — `[Sign out everyone except me]` and `[Sign me out and everyone else]` (the latter uses `text-danger` color to telegraph the self-impact).
- **count = 1 (solo owner):** Hide the "except me" button (it would revoke 0 — confusing). Show only `[Sign me out everywhere]` (still useful — signs the owner out from their other devices).
**Bulk-revoke confirmation modal** (via `components/common/Modal.tsx`):
- **scope=others:** title *"Sign out other users?"* · body *"This signs out the N other active users in your account. They'll need to sign in again. You stay signed in."* · buttons `[Cancel]` (ghost) + `[Sign out N users]` (`text-danger`).
- **scope=all:** title *"Sign out everyone?"* · body *"This signs out all N active users including yourself. Everyone will need to sign in again."* · buttons `[Cancel]` (ghost) + `[Sign out everyone]` (`text-danger`).
- After success: modal closes, `toast.success("Signed out N sessions")`. For scope=all: 1.5s delay → `useAuthStore.getState().logout()` + `window.location = '/login'` (no banner — they just did this, they know why they're here).
**Modified:** `AccountSettingsPage.tsx`
- Add a "Session Security" link card to the existing grid (owner-only visibility, alongside Branding / Chat Retention). Lucide `Shield` icon.
**New login page banner:** when `?reason=session_expired` is present, show a small info-tone banner **above the email/password form**:
- Background: `info-dim` (cyan-dim, `rgba(103,232,249,0.10)` dark / `rgba(8,145,178,0.07)` light per DESIGN-SYSTEM.md)
- Text color: `info` text token
- Border: `1px solid info-dim`
- Padding: 12px 16px, `radius-sm` (5px)
- Icon: Lucide `Info` (16px, info color, left-aligned)
- Copy: *"You were signed out for security. Sign back in to continue."*
- Not dismissable — disappears naturally when the user submits the form (the query string clears on navigate).
- Note: this is the first cyan info-tone banner in the app; sets the precedent we'll reuse for future neutral system messages.
**Modified:** `AccountSettingsPage.tsx`
- Add a "Session Security" link card to the existing grid (owner-only visibility).
**New login page banner:** when `?reason=session_expired` is present, show a calm info banner: "Your session ended for security. Please sign in again." (No alarm UI, just clarity. Same banner for both idle and absolute expiry; the user doesn't need to learn the distinction.)
### 4.9 Migration
`alembic revision -m "add session policy columns to accounts"` (manual, per Lesson 77).
```sql
ALTER TABLE accounts
ADD COLUMN session_idle_minutes INTEGER,
ADD COLUMN session_absolute_minutes INTEGER,
ADD CONSTRAINT session_idle_le_absolute_when_both_set
CHECK (session_idle_minutes IS NULL
OR session_absolute_minutes IS NULL
OR session_idle_minutes <= session_absolute_minutes);
COMMENT ON CONSTRAINT session_idle_le_absolute_when_both_set ON accounts IS
'Defense in depth: catches idle > absolute when both are overridden. '
'The partial-override case (one NULL, one set) is validated at the app layer '
'against current system defaults, since the DB cannot see Settings.';
```
No backfill: NULL is the intended state for "use system default."
Confirm: `accounts` is in the global-tables list per PROJECT_CONTEXT.md, so the migration does **not** add RLS predicates. Verified — `accounts` is explicitly named there.
### 4.10 Error-detail taxonomy
`/auth/refresh` returns 401 with one of these `detail` values, so the frontend can distinguish UX paths:
| `detail` | When | Frontend action |
|---|---|---|
| `session_expired_idle` | refresh JWT past `exp` (idle window elapsed) | flush tokens, redirect `/login?reason=session_expired` |
| `session_expired_absolute` | refresh JWT alive, but `now >= auth_time + abs_max` | flush tokens, redirect `/login?reason=session_expired` |
| `invalid_refresh_token` | JTI not in DB, already revoked, signature bad, type mismatch | flush tokens, redirect `/login` (no banner) |
Implementation note: `decode_token` currently swallows `JWTError` and returns `None`, so idle expiry is indistinguishable from a signature failure at the dep level. Fix by switching `get_refresh_token_payload` (or adding a sibling) to call `jwt.decode` directly and catch `ExpiredSignatureError` separately from generic `JWTError`. Idle-expired tokens raise the former; map that to `session_expired_idle`. All other JWT errors map to `invalid_refresh_token`.
### 4.11 Bulk session revocation (kill-all-sessions)
**Endpoint:** `POST /accounts/me/security/revoke-sessions`, owner-only via `require_account_owner`.
**Request body:**
```json
{ "scope": "all" | "others" }
```
Default `"all"` if body omitted. `"others"` excludes the calling user's own refresh tokens (so the owner stays signed in); `"all"` includes them.
**Response:**
```json
{ "revoked_count": <int> }
```
**Behavior:**
- Single SQL UPDATE: `refresh_tokens.revoked_at = now()` for rows where `user_id IN (SELECT id FROM users WHERE account_id = :caller_account_id)` AND `revoked_at IS NULL`. If `scope="others"`, also AND `user_id != caller.id`.
- All affected users' next `/auth/refresh` matches zero rows in the atomic revoke (§4.5 step 5) → 401 `invalid_refresh_token` → redirect to `/login` (no banner — the user was signed out by an admin, not by expiry; the plain `/login` redirect is honest UX).
- Caller's access token is not revoked (we don't track access JTIs by design); it dies naturally on its 5-minute timer. For `scope="all"`, the frontend handles UX by clearing localStorage and redirecting to `/login` after the response — so the stale access token simply isn't used. Accept the 5-minute window where the caller's access token could in theory still hit endpoints; this matches the existing logout flow and is consistent with the threat model (the action is "kick everyone out," not "instantly invalidate every credential").
**Audit:** writes one `account.sessions_revoked_bulk` event with `{actor_user_id, account_id, scope, revoked_count}`.
**Out of scope:** distinguishing `session_revoked_by_admin` from `invalid_refresh_token` on the wire for affected users. Doing so requires tracking the revocation reason per `refresh_tokens` row (new column). Not worth the complexity right now — the affected user just sees they're logged out, same as if they'd been logged out for any other reason. Revisit if pilots ask for it.
**Why not also per-user-device revoke?** Refresh tokens today don't carry device/user-agent metadata; the unit of granularity is "all of user X's active sessions" (which is most of what people want anyway — e.g., I lost my laptop). The endpoint is account-scoped because that's the owner-control story we're shipping. Per-user device list is a follow-up if/when needed (§9).
## 5. Backward compatibility
### 5.1 Existing refresh tokens (no `auth_time` claim)
On first `/auth/refresh` after deploy:
- Backend detects missing `auth_time`, treats current time as `auth_time`, snapshots current account policy.
- User effectively gets one free 14-day absolute window starting at first post-deploy refresh.
Trade-off vs forcing universal re-login on deploy:
- ✅ Zero deploy-day support burden (no pilots flood Slack with "I got logged out").
- ❌ Users with active sessions see no enforcement for up to 14 days.
Given the user base is small (pilot phase) and the bigger goal is *new* signups have a secure default, the friendly path wins.
### 5.2 If we ever need to invalidate everyone
`SECRET_KEY` rotation kills all existing tokens. Documented in `DEV-ENV.md` but not part of this PR.
## 6. Test plan
Backend (`backend/tests/test_session_policy.py` — new file, unless noted):
1. **Default policy applied** — login without account override → JWT has `idle_max=259200`, `abs_max=1209600` (seconds; 3d/14d). Account/settings columns are minutes (4320/20160); the helper multiplies by 60 when stamping.
2. **Account override honored** — owner PATCHes `session_idle_minutes=60`, `session_absolute_minutes=240` → next login JWT has `idle_max=3600`, `abs_max=14400` (seconds).
3. **Override bounds enforced** — PATCH idle below `SESSION_IDLE_MINUTES_MIN` → 422; PATCH absolute above `SESSION_ABSOLUTE_MINUTES_MAX` → 422.
4. **Invariant enforced (both-set)** — PATCH idle=300, absolute=120 → 422.
5. **Invariant enforced (partial override)** — system default absolute=20160; PATCH idle=43200 with absolute=NULL → 422 (effective idle > effective absolute, app-layer check).
6. **DB constraint catches both-set inversion** — direct SQL `UPDATE accounts SET session_idle_minutes=300, session_absolute_minutes=120` rolls back with `CheckViolation`.
7. **Non-owner cannot PATCH** — engineer/viewer get 403.
8. **Refresh respects absolute cap (boundary)** — set `auth_time = now - abs_max` exactly → refresh 401 with `session_expired_absolute` (deadline check is `>=`, not `>`).
9. **Absolute-expired token is consumed** — attempt #1 returns `session_expired_absolute`; attempt #2 with the same token returns `invalid_refresh_token` (row was revoked atomically in #1, cannot be replayed).
10. **Refresh extends idle but not absolute** — rotate twice within `abs_max`; both succeed; `auth_time` unchanged across rotations.
11. **Idle expiry (boundary)** — set refresh `exp = now` → 401 with `session_expired_idle` (not generic `invalid_refresh_token`).
12. **Grandfather path** — legacy refresh token without `auth_time`/`idle_max`/`abs_max` → one successful rotation; new JWT has all three claims, `auth_time≈now()`.
13. **Tightening after login doesn't affect existing sessions** — login under policy A, owner tightens to policy B, refresh succeeds under A's snapshot.
14. **`/auth/login/json` carries new claims and response fields** — JWT decode shows `auth_time`/`idle_max`/`abs_max`; response body has `idle_expires_at` + `absolute_expires_at` as ISO strings.
15. **OAuth callback responses include expiry fields**`/auth/google/callback` and `/auth/microsoft/callback` `OAuthCallbackResponse` bodies have both `idle_expires_at` and `absolute_expires_at`. Mock the Google/Microsoft token-exchange step; assert on the final response shape.
16. **Policy update writes audit row** — PATCH `/accounts/me/security` emits one `account.session_policy_update` audit event with `actor_user_id`, `account_id`, and a payload of `{old: {...}, new: {...}, effective_old: {...}, effective_new: {...}}`. Verify via the existing audit-log query in `core/audit.py`.
17. **Bulk revoke scope=all** — seed three active refresh tokens for two users in the account (caller + one other). POST `/accounts/me/security/revoke-sessions` with `{"scope": "all"}``revoked_count=3`; caller's own refresh token is now revoked too. Their next `/auth/refresh` → 401 `invalid_refresh_token`.
18. **Bulk revoke scope=others** — same seed. POST with `{"scope": "others"}``revoked_count=2` (caller's token survives). Caller's `/auth/refresh` still succeeds; the other user's `/auth/refresh` → 401 `invalid_refresh_token`.
19. **Bulk revoke is account-scoped** — seed tokens for users in account A and account B. Owner of A POSTs revoke → `revoked_count` reflects only A's tokens; B's tokens remain active.
20. **Bulk revoke is owner-only** — engineer/viewer POST → 403; super_admin POST against `/me` works only if they own an account (the endpoint is `/me`, not `/{account_id}`).
21. **Bulk revoke writes audit row**`account.sessions_revoked_bulk` with `{actor_user_id, account_id, scope, revoked_count}`.
22. **Bulk revoke is idempotent** — second immediate POST returns `revoked_count=0` (no already-revoked rows are double-stamped).
Frontend (`frontend/src/__tests__/` or colocated `*.test.tsx`):
- `useAuthSessionExpiry` returns `"soon"` within 5min of whichever of `idleExpiresAt`/`absoluteExpiresAt` comes first; `reason` field indicates which.
- Axios interceptor on 401 with `session_expired_absolute` redirects to `/login?reason=session_expired` instead of attempting refresh.
- Axios interceptor on 401 with `session_expired_idle` does the same.
- Axios interceptor on 401 with `invalid_refresh_token` redirects to `/login` *without* the reason banner.
- `authStore` rehydrate handles legacy localStorage shape (no `idleExpiresAt`/`absoluteExpiresAt`) without throwing or forced logout; hook treats `null` as "no warning."
Manual:
- Log in as `owner@`, set **Custom (idle=60 min, absolute=240 min)** under Account → Session Security, log out, log in as `engineer@` (same account), decode the refresh JWT in localStorage, confirm `idle_max=3600` and `abs_max=14400` (seconds — the configured minutes × 60).
- Confirm the existing `useSessionTimer` (troubleshooting-flow timer) is unaffected by the new hook.
- Pre-deploy localStorage path: install build, log in to capture token, deploy session-policy build, refresh page — confirm no forced logout and that the next `/auth/refresh` populates the new fields.
## 7. Rollout
1. Land migration + backend changes behind no flag (the absolute cap is the whole point — flagging it defeats the purpose).
2. Default policy is Strict (3d/14d) for new accounts. Existing pilot accounts get NULL → defaults; user can manually loosen any pilot account via the new endpoint or direct SQL if friction emerges.
3. After deploy, watch Sentry for spikes in `session_expired_absolute` 401s (expected: tiny — only legacy tokens approaching 14-day mark hit this) and unexpected refresh failures.
4. Announce in pilot Slack: "We added session expiration. You'll be asked to log in again every 2 weeks max. Account owners can adjust under Account → Session Security."
## 8. Files touched
### Backend
- `backend/app/core/config.py` — new `SESSION_*` settings (defaults + min/max bounds).
- `backend/app/core/security.py``create_refresh_token` signature change (accepts `auth_time`/`idle_max`/`abs_max`), `resolve_session_policy(account)` helper, `decode_refresh_token_strict()` that distinguishes `ExpiredSignatureError` from generic `JWTError`.
- `backend/app/api/deps.py` — update `get_refresh_token_payload` to surface idle-expiry as `session_expired_idle` instead of collapsing into a generic 401.
- `backend/app/api/endpoints/auth.py` — refresh-endpoint logic (atomic-revoke-then-check-absolute), `_mint_session_tokens(user, account, db) -> Token` helper, login + login/json call sites.
- `backend/app/api/endpoints/oauth.py` — both callbacks call `_mint_session_tokens`; `OAuthCallbackResponse` gains the two new fields.
- `backend/app/schemas/token.py``Token` (`token.py:5`) adds `idle_expires_at` + `absolute_expires_at` (ISO strings).
- `backend/app/schemas/oauth.py``OAuthCallbackResponse` adds the same two fields.
- `backend/app/api/endpoints/account_security.py` — NEW (~130 lines: GET/PATCH for policy + POST `/revoke-sessions`, audit logging for both mutations).
- `backend/app/api/router.py` — register new router.
- `backend/app/models/account.py` — two new columns + DB CHECK constraint.
- `backend/app/schemas/account_security.py` — NEW (request/response: policy GET/PATCH with effective + bounds; `RevokeSessionsRequest` + `RevokeSessionsResponse`).
- `backend/app/core/audit.py` — add `account.session_policy_update` event type (or use the existing generic emitter if it accepts free-form types — verify during impl).
- `backend/alembic/versions/<hash>_session_policy_columns.py` — NEW (manual; per Lesson 77, never `--rev-id`).
- `backend/tests/test_session_policy.py` — NEW.
### Frontend
- `frontend/src/api/client.ts` — interceptor branches on both `session_expired_idle` and `session_expired_absolute` (same redirect target `/login?reason=session_expired`); also propagates new expiry fields from successful `/auth/refresh` responses into `setTokens`.
- `frontend/src/api/auth.ts``Token` type adds the two new ISO fields.
- `frontend/src/store/authStore.ts``setTokens` persists the new expiry fields (no new action).
- `frontend/src/pages/OAuthCallbackPage.tsx` — pass `idle_expires_at` + `absolute_expires_at` through `setTokens({...})` at line 102.
- `frontend/src/hooks/useAuthSessionExpiry.ts` — NEW.
- `frontend/src/components/common/SessionExpiryToast.tsx` — NEW.
- `frontend/src/components/layout/AppLayout.tsx` — mount toast.
- `frontend/src/pages/account/AccountSecuritySettingsPage.tsx` — NEW (policy form + Active Sessions section with two revoke buttons + confirmation modal).
- `frontend/src/pages/AccountSettingsPage.tsx` — add link card.
- `frontend/src/router.tsx` — register route.
- `frontend/src/pages/LoginPage.tsx``?reason=session_expired` banner.
### Docs
- `.ai/DECISIONS.md` — entry for the 3d/14d default + per-account-override architecture.
- `CURRENT-STATE.md` — add session policy to "auth surface" summary.
Approx ~600 LoC across backend + frontend, plus tests.
## 9. Resolved decisions & follow-ups
Decisions baked into this plan (not open questions):
- **Audit logging is required.** PATCH `/accounts/me/security` writes one `account.session_policy_update` audit event; POST `/revoke-sessions` writes `account.sessions_revoked_bulk`. Security-relevant by definition. Covered in §6 tests #16 and #21 and §8 backend file list.
- **Presets are Strict and Standard only**, plus Custom. No "Loose" preset; owners who want a loose policy can use Custom and own the choice explicitly.
- **Tightening policy mid-session does NOT force-logout existing sessions** — but owners *can* force it via the bulk-revoke endpoint in §4.11. Existing sessions continue under the policy snapshot they were issued under unless explicitly revoked. The Account Security page surfaces this in copy (§4.8).
- **Bulk revoke is account-scoped, two-mode (`all` / `others`).** Per-user device lists are out of scope (§4.11).
Follow-up issues to file after this plan is approved (not blocking this PR):
1. **Super-admin global lock with UI** — today, env-var ceilings cover this. File an issue to expose `SESSION_*_MAX` as a sysadmin-editable setting if/when a customer asks.
2. **Per-user device list + per-device revoke** — refresh tokens would gain `user_agent` + `ip` + `last_used_at` columns; a new "Active devices" page would let users self-revoke individual sessions. File only if a real ask arrives. The account-wide bulk revoke covers the breach-response use case in the meantime.
3. **Per-user (not per-account) policy** — out of scope. File only if a real ask arrives.
## 10. Sequence of commits
1. `feat(auth): add session policy settings + account columns + migration` (settings + model + migration + DB CHECK; no behavior change yet).
2. `feat(auth): distinguish idle expiry from invalid refresh tokens` (`decode_refresh_token_strict`, `session_expired_idle` detail, test #11). Lands the error-detail taxonomy from §4.10 before anything depends on it.
3. `feat(auth): embed auth_time/idle_max/abs_max in refresh tokens` (`security.py` + `_mint_session_tokens` helper called from `/auth/login`, `/auth/login/json`, both OAuth callbacks; `Token` and `OAuthCallbackResponse` gain `idle_expires_at` + `absolute_expires_at`). Refresh still doesn't enforce absolute cap yet.
4. `feat(auth): enforce absolute session cap in /auth/refresh` (atomic-revoke-then-check, `session_expired_absolute` detail, grandfather logic, tests #8#13).
5. `feat(api): add GET/PATCH /accounts/me/security endpoint` (router, schemas, owner gate, bounds + partial-override invariant validation, audit logging on PATCH).
6. `feat(api): add POST /accounts/me/security/revoke-sessions` (bulk-revoke endpoint with `scope=all|others`, single-UPDATE implementation, audit logging, tests #17#22).
7. `feat(ui): handle session_expired_{idle,absolute} in axios interceptor + authStore` (new fields persisted, legacy-state migration, redirect to `/login?reason=session_expired`).
8. `feat: AccountSecuritySettingsPage + active-users list + toasts + login banner` (Strict/Standard/Custom presets with always-visible-disabled Custom inputs, count-aware Active Sessions section with name/email/last-login rows, differentiated SessionExpiryToast for idle-vs-absolute, cyan info-tone login banner, scope=all auto-redirect-after-toast UX. Includes a small backend addition: `active_users` field on `GET /accounts/me/security` — see §4.7).
9. `docs: add decision entry + update CURRENT-STATE auth surface` (`.ai/DECISIONS.md`, `CURRENT-STATE.md`).
Each commit independently passes `pytest --override-ini="addopts="` and `npm run build`. The two backend behavior gates (#2 and #4) ship behind no flag — they're the point of the work — but they're sequenced so any rollback is a single commit.
---
**Review checklist before implementation:**
- [x] Defaults confirmed: 3d idle / 14d absolute.
- [x] Per-account override approved.
- [x] Grandfather strategy (one free rotation) approved vs hard cutover.
- [x] Error-detail taxonomy approved (idle vs absolute distinct on the wire; same UX in the frontend).
- [x] Audit logging is a requirement, not optional.
- [x] Loose preset dropped; Strict / Standard / Custom only.
- [x] ISO timestamps (not Unix ints) for `idle_expires_at` / `absolute_expires_at` everywhere.
- [x] DB CHECK constraint scope documented; partial-override case validated app-side.
- [ ] System bounds in §4.3 acceptable as specified (15min floor, 30d idle ceiling, 90d absolute ceiling).
- [ ] Final approval on commit sequence in §10.
- [ ] No conflict with Phase O cutover sequencing (this can ship before OR after EIN/Stripe lands; independent path).
- [ ] File the kill-all-sessions follow-up issue per §9 before implementation begins, so the Account Security page can link to it (or leave the support-contact copy in place).
---
## GSTACK REVIEW REPORT
| Review | Trigger | Why | Runs | Status | Findings |
|--------|---------|-----|------|--------|----------|
| CEO Review | `/plan-ceo-review` | Scope & strategy | 0 | — | not run |
| Codex Review | `/codex review` | Independent 2nd opinion | 0 | — | not run |
| Eng Review | `/plan-eng-review` | Architecture & tests (required) | 0 | — | not run (the plan itself was eng-reviewed inline across 7 commits — backend complete & green) |
| Design Review | `/plan-design-review` | UI/UX gaps | 1 | CLEAR (PLAN) | score: 4/10 → 9/10, 7 decisions added |
| DX Review | `/plan-devex-review` | Developer experience gaps | 0 | — | not run |
**UNRESOLVED:** 0 design decisions; 3 plan-level checklist items remain (system bounds, commit sequence, Phase O sequencing — none block design).
**VERDICT:** DESIGN CLEARED — page layout, state coverage, post-revoke flow, toast logic, login banner tone, and form copy all locked. Commit 8 has a complete spec.

View File

@@ -1,49 +0,0 @@
import apiClient from './client'
export interface ActiveUser {
user_id: string
name: string
email: string
last_login_at: string | null
}
export interface SessionPolicyResponse {
idle_minutes: number | null
absolute_minutes: number | null
effective_idle_minutes: number
effective_absolute_minutes: number
idle_minutes_min: number
idle_minutes_max: number
absolute_minutes_min: number
absolute_minutes_max: number
active_users: ActiveUser[]
}
export interface SessionPolicyUpdateRequest {
idle_minutes: number | null
absolute_minutes: number | null
}
export interface RevokeSessionsResponse {
revoked_count: number
}
export const accountSecurityApi = {
async get(): Promise<SessionPolicyResponse> {
const response = await apiClient.get<SessionPolicyResponse>('/accounts/me/security')
return response.data
},
async update(body: SessionPolicyUpdateRequest): Promise<SessionPolicyResponse> {
const response = await apiClient.patch<SessionPolicyResponse>('/accounts/me/security', body)
return response.data
},
async revokeSessions(scope: 'all' | 'others'): Promise<RevokeSessionsResponse> {
const response = await apiClient.post<RevokeSessionsResponse>(
'/accounts/me/security/revoke-sessions',
{ scope },
)
return response.data
},
}

View File

@@ -6,8 +6,6 @@ export interface OAuthCallbackResponse {
refresh_token: string
token_type: string
is_new_user: boolean
idle_expires_at?: string | null
absolute_expires_at?: string | null
}
export const authApi = {

View File

@@ -136,18 +136,15 @@ apiClient.interceptors.response.use(
},
})
const { access_token, refresh_token, idle_expires_at, absolute_expires_at } = response.data
const { access_token, refresh_token } = response.data
localStorage.setItem('access_token', access_token)
localStorage.setItem('refresh_token', refresh_token)
// Sync Zustand auth store — include the new expiry fields so
// useAuthSessionExpiry stays accurate after each refresh.
// Sync Zustand auth store
useAuthStore.getState().setTokens({
access_token,
refresh_token,
token_type: 'bearer',
idle_expires_at,
absolute_expires_at,
})
isRefreshing = false
@@ -162,28 +159,11 @@ apiClient.interceptors.response.use(
isRefreshing = false
onRefreshFailed(refreshError)
// Refresh failed — clear tokens and redirect to login. The redirect
// target depends on WHY the refresh failed (plan §4.10):
// - session_expired_idle / session_expired_absolute: the user hit a
// policy boundary. Show the calm "session ended for security"
// banner via ?reason=session_expired.
// - invalid_refresh_token (or anything else): plain logout, no
// banner — the user wasn't kicked by policy, the token just
// wasn't recognized.
const refreshAxiosErr = refreshError as AxiosError
const refreshDetail = (refreshAxiosErr.response?.data as { detail?: string })?.detail
const isPolicyExpiry =
refreshDetail === 'session_expired_idle' ||
refreshDetail === 'session_expired_absolute'
// Refresh failed — clear tokens and redirect to login
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
useAuthStore.getState().logout()
if (!window.location.pathname.startsWith('/login')) {
window.location.href = isPolicyExpiry
? '/login?reason=session_expired'
: '/login'
}
window.location.href = '/login'
return Promise.reject(refreshError)
}
}

View File

@@ -1,89 +0,0 @@
import { useState } from 'react'
import { Modal } from '@/components/common/Modal'
import { cn } from '@/lib/utils'
interface RevokeSessionsModalProps {
isOpen: boolean
onClose: () => void
onConfirm: () => Promise<void>
scope: 'all' | 'others'
activeUserCount: number
}
/**
* Confirmation modal for bulk session revocation. Two scopes:
*
* - "others" — revokes other users' sessions, caller stays signed in.
* - "all" — revokes everyone including the caller; the parent handles
* the post-revoke auto-redirect to /login (see plan §4.8 D4).
*/
export function RevokeSessionsModal({
isOpen,
onClose,
onConfirm,
scope,
activeUserCount,
}: RevokeSessionsModalProps) {
const [busy, setBusy] = useState(false)
const isAll = scope === 'all'
const otherCount = isAll ? activeUserCount : Math.max(activeUserCount - 1, 0)
const title = isAll ? 'Sign out everyone?' : 'Sign out other users?'
const body = isAll
? `This signs out all ${activeUserCount} active users including yourself. Everyone will need to sign in again.`
: `This signs out the ${otherCount} other active users in your account. They'll need to sign in again. You stay signed in.`
const confirmLabel = isAll
? 'Sign out everyone'
: otherCount === 1
? 'Sign out 1 user'
: `Sign out ${otherCount} users`
const handleConfirm = async () => {
setBusy(true)
try {
await onConfirm()
} finally {
setBusy(false)
}
}
return (
<Modal
isOpen={isOpen}
onClose={busy ? () => undefined : onClose}
title={title}
size="sm"
footer={
<div className="flex justify-end gap-2">
<button
type="button"
onClick={onClose}
disabled={busy}
className={cn(
'rounded-md border px-4 py-2 text-sm font-medium',
'border-border text-foreground hover:bg-card-hover',
'disabled:opacity-50',
)}
>
Cancel
</button>
<button
type="button"
onClick={handleConfirm}
disabled={busy}
className={cn(
'rounded-md border px-4 py-2 text-sm font-medium',
'border-danger/40 bg-danger/10 text-danger hover:bg-danger/15',
'disabled:opacity-50',
)}
>
{busy ? 'Working…' : confirmLabel}
</button>
</div>
}
>
<p className="text-sm text-foreground">{body}</p>
</Modal>
)
}

View File

@@ -1,35 +0,0 @@
import { Link } from 'react-router-dom'
// Styles live in src/styles/landing.css under `.landing-footer*`. The component
// must be rendered inside a `.landing-page` wrapper so the `--lp-*` CSS
// variables resolve. All current marketing surfaces (LandingPage,
// PricingPage, ContactSalesPage) already provide that wrapper.
export function MarketingFooter() {
return (
<footer className="landing-footer">
<div className="landing-footer-inner">
<div className="landing-footer-left">
<div className="landing-nav-logo-icon" style={{ width: 24, height: 24, borderRadius: 6 }}>
<svg viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: 14, height: 14 }}>
<circle cx="12" cy="5" r="2" />
<line x1="12" y1="7" x2="12" y2="11" />
<circle cx="6" cy="15" r="2" />
<circle cx="18" cy="15" r="2" />
<line x1="12" y1="11" x2="6" y2="13" />
<line x1="12" y1="11" x2="18" y2="13" />
</svg>
</div>
<span className="landing-footer-copy">&copy; 2026 ResolutionFlow</span>
</div>
<ul className="landing-footer-links">
<li><Link to="/privacy">Privacy</Link></li>
<li><Link to="/terms">Terms</Link></li>
<li><Link to="/policies">Policies</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</div>
</footer>
)
}
export default MarketingFooter

View File

@@ -8,7 +8,6 @@ interface PageMetaProps {
}
const SITE_NAME = 'ResolutionFlow'
const DEFAULT_TAGLINE = 'AI-Powered Troubleshooting for MSPs'
const DEFAULT_DESCRIPTION = 'Transform troubleshooting into guided workflows with automatic documentation'
/**
@@ -21,7 +20,7 @@ export function PageMeta({
ogImage,
ogType = 'website',
}: PageMetaProps) {
const fullTitle = title ? `${title} | ${SITE_NAME}` : `${SITE_NAME} ${DEFAULT_TAGLINE}`
const fullTitle = title ? `${title} | ${SITE_NAME}` : `${SITE_NAME} - Decision Tree Platform`
return (
<Helmet>

View File

@@ -1,125 +0,0 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { AlertCircle, Info, X } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useAuthSessionExpiry } from '@/hooks/useAuthSessionExpiry'
import { authApi } from '@/api/auth'
import { useAuthStore } from '@/store/authStore'
/**
* Top-of-app notice that fires when the session is within 5 minutes of
* idle OR absolute expiry. Behavior differs by which window is closer
* (per docs/plans/2026-05-13-session-expiration-policy.md §4.8):
*
* - Idle: warning-amber tone, "Stay signed in" button hits /auth/refresh.
* - Absolute: info-cyan tone, no action — re-auth is required.
*
* Persists until the user dismisses, refreshes, or the window expires.
*/
export function SessionExpiryToast() {
const { warning, reason, idleExpiresAt, absoluteExpiresAt } = useAuthSessionExpiry()
const setTokens = useAuthStore((s) => s.setTokens)
const navigate = useNavigate()
const [busy, setBusy] = useState(false)
const [dismissed, setDismissed] = useState(false)
if (warning !== 'soon' || dismissed) return null
const handleStay = async () => {
setBusy(true)
try {
const refreshed = await authApi.refresh()
localStorage.setItem('access_token', refreshed.access_token)
localStorage.setItem('refresh_token', refreshed.refresh_token)
setTokens(refreshed)
setDismissed(true)
} catch {
// The axios interceptor handles the redirect on session_expired_*;
// if we land here, something else went wrong — just close the toast.
setDismissed(true)
} finally {
setBusy(false)
}
}
const handleSignInNow = () => navigate('/login')
// ── Format the deadline for the absolute case ──
const deadline = reason === 'idle' ? idleExpiresAt : absoluteExpiresAt
const deadlineLabel = deadline
? deadline.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })
: ''
const isIdle = reason === 'idle'
const Icon = isIdle ? AlertCircle : Info
return (
<div
role="status"
aria-live="polite"
className={cn(
'fixed top-4 right-4 z-50 max-w-md rounded-lg border p-4 shadow-lg',
'flex items-start gap-3',
isIdle
? 'bg-warning-dim border-warning/30 text-warning'
: 'bg-info-dim border-info/30 text-info',
)}
>
<Icon size={18} className="mt-0.5 shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium">
{isIdle
? 'Your session times out in 5 minutes.'
: `Your session ends at ${deadlineLabel} for security.`}
</p>
<p className="mt-0.5 text-xs opacity-90">
{isIdle
? 'Click to stay signed in.'
: "You'll need to sign in again."}
</p>
<div className="mt-2 flex items-center gap-2">
{isIdle ? (
<button
type="button"
onClick={handleStay}
disabled={busy}
className={cn(
'rounded-md px-3 py-1.5 text-xs font-medium',
'bg-warning/20 text-warning border border-warning/40 hover:bg-warning/30',
'disabled:opacity-50',
)}
>
{busy ? 'Refreshing…' : 'Stay signed in'}
</button>
) : (
<button
type="button"
onClick={handleSignInNow}
className={cn(
'rounded-md px-3 py-1.5 text-xs font-medium',
'bg-info/20 text-info border border-info/40 hover:bg-info/30',
)}
>
Sign in now
</button>
)}
<button
type="button"
onClick={() => setDismissed(true)}
className="text-xs opacity-70 hover:opacity-100"
>
Dismiss
</button>
</div>
</div>
<button
type="button"
onClick={() => setDismissed(true)}
aria-label="Dismiss"
className="shrink-0 opacity-70 hover:opacity-100"
>
<X size={14} />
</button>
</div>
)
}

View File

@@ -6,7 +6,6 @@ import type { OnboardingStatus } from '@/api/onboarding'
import { useTrialBanner } from '@/hooks/useTrialBanner'
import type { TrialBannerStage } from '@/hooks/useTrialBanner'
import { useOnboardingStatus } from '@/hooks/useOnboardingStatus'
import { FOCUS_START_SESSION_EVENT } from '@/components/dashboard/StartSessionInput'
/**
* Next-step card — surfaces the single highest-priority incomplete onboarding
@@ -115,10 +114,9 @@ export function pickNextStep(
export function NextStepCard() {
const status = useOnboardingStatus()
const [locallyDismissed, setLocallyDismissed] = useState(false)
const [locallyHidden, setLocallyHidden] = useState(false)
const { stage } = useTrialBanner()
if (!status || status.dismissed || locallyDismissed || locallyHidden) return null
if (!status || status.dismissed || locallyDismissed) return null
const next = pickNextStep(status, stage)
if (!next) return null
@@ -156,29 +154,14 @@ export function NextStepCard() {
</button>
</div>
<div className="mt-3">
{next.key === 'ran_session' ? (
<button
type="button"
onClick={() => {
window.dispatchEvent(new Event(FOCUS_START_SESSION_EVENT))
setLocallyHidden(true)
}}
data-testid="next-step-cta"
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1"
>
{next.ctaLabel}
<ArrowRight size={14} />
</button>
) : (
<Link
to={next.ctaPath}
data-testid="next-step-cta"
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1"
>
{next.ctaLabel}
<ArrowRight size={14} />
</Link>
)}
<Link
to={next.ctaPath}
data-testid="next-step-cta"
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1"
>
{next.ctaLabel}
<ArrowRight size={14} />
</Link>
</div>
</div>
)

View File

@@ -5,7 +5,6 @@ import type { OnboardingStatus } from '@/api/onboarding'
import { useTrialBanner } from '@/hooks/useTrialBanner'
import type { TrialBannerStage } from '@/hooks/useTrialBanner'
import { useOnboardingStatus } from '@/hooks/useOnboardingStatus'
import { FOCUS_START_SESSION_EVENT } from '@/components/dashboard/StartSessionInput'
/**
* Unified setup checklist — single list (no SOLO/TEAM bifurcation).
@@ -113,21 +112,6 @@ export function SetupChecklist() {
{item.label}
</span>
</div>
) : item.key === 'ran_session' ? (
<button
type="button"
onClick={() => window.dispatchEvent(new Event(FOCUS_START_SESSION_EVENT))}
className={cn(
'w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors text-left',
'hover:bg-[rgba(255,255,255,0.04)]',
)}
data-testid={`checklist-item-${item.key}`}
data-done="false"
>
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-border" />
<span className="flex-1 text-foreground">{item.label}</span>
<ChevronRight size={14} className="text-muted-foreground shrink-0" />
</button>
) : (
<Link
to={item.path}

View File

@@ -18,38 +18,19 @@ const SUGGESTIONS: { icon: LucideIcon; label: string }[] = [
const ACCEPTED_FILE_TYPES = 'image/png,image/jpeg,image/gif,image/webp,.txt,.log,.csv,.pdf,.docx'
export const FOCUS_START_SESSION_EVENT = 'rf:focus-start-session'
export function StartSessionInput() {
const [value, setValue] = useState('')
const [showLogs, setShowLogs] = useState(false)
const [logContent, setLogContent] = useState('')
const [pendingUploads, setPendingUploads] = useState<PendingUpload[]>([])
const [isDragOver, setIsDragOver] = useState(false)
const [nudge, setNudge] = useState(false)
const navigate = useNavigate()
const wrapperRef = useRef<HTMLDivElement>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const dragCounterRef = useRef(0)
useEffect(() => { textareaRef.current?.focus() }, [])
// External "focus me" trigger (e.g. NextStepCard "Start a session" CTA on
// the same page). Scrolls into view, focuses the textarea, and pulses a
// ring so the click feels intentional even when the input was already
// partially visible.
useEffect(() => {
const handler = () => {
wrapperRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })
textareaRef.current?.focus({ preventScroll: true })
setNudge(true)
window.setTimeout(() => setNudge(false), 900)
}
window.addEventListener(FOCUS_START_SESSION_EVENT, handler)
return () => window.removeEventListener(FOCUS_START_SESSION_EVENT, handler)
}, [])
// Auto-grow textarea
useEffect(() => {
const el = textareaRef.current
@@ -209,8 +190,7 @@ export function StartSessionInput() {
return (
<div
ref={wrapperRef}
className="w-full scroll-mt-6"
className="w-full"
onDragOver={handleDragOver}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
@@ -218,11 +198,9 @@ export function StartSessionInput() {
>
{/* Main input area */}
<div className={cn(
'relative rounded-2xl border bg-card transition-all duration-300',
'relative rounded-2xl border bg-card transition-all',
isDragOver ? 'border-primary/50 bg-primary/5' : 'border-border',
nudge
? 'border-[rgba(96,165,250,0.6)] ring-2 ring-[rgba(96,165,250,0.35)] shadow-[0_0_0_6px_rgba(96,165,250,0.12)]'
: 'focus-within:border-[rgba(96,165,250,0.25)] focus-within:ring-1 focus-within:ring-[rgba(96,165,250,0.1)]'
'focus-within:border-[rgba(96,165,250,0.25)] focus-within:ring-1 focus-within:ring-[rgba(96,165,250,0.1)]'
)}>
{/* Drag overlay */}
{isDragOver && (

View File

@@ -12,7 +12,6 @@ import { EmailVerificationBanner } from './EmailVerificationBanner'
import { EmailVerificationGate } from '@/components/common/EmailVerificationGate'
import { ViewTransitionOutlet } from './ViewTransitionOutlet'
import { FeedbackWidget } from '@/components/common/FeedbackWidget'
import { SessionExpiryToast } from '@/components/common/SessionExpiryToast'
import { cn } from '@/lib/utils'
export function AppLayout() {
@@ -70,7 +69,6 @@ export function AppLayout() {
return (
<>
<SessionExpiryToast />
<div
className={cn('app-shell relative z-1', sidebarPinned && 'app-shell--pinned')}
data-testid="app-shell"

View File

@@ -1,12 +1,12 @@
import { cn } from '@/lib/utils'
interface CheckoutButtonProps {
plan: 'starter' | 'pro' | 'enterprise'
plan: 'pro' | 'team'
className?: string
}
export function CheckoutButton({ plan, className }: CheckoutButtonProps) {
const planLabels = { starter: 'Starter', pro: 'Pro', enterprise: 'Enterprise' }
const planLabels = { pro: 'Pro', team: 'Team' }
return (
<button

View File

@@ -1,69 +0,0 @@
import { useEffect, useReducer } from 'react'
import { useAuthStore } from '@/store/authStore'
const SOON_MS = 5 * 60 * 1000 // 5 minutes
export type ExpiryWarning = 'none' | 'soon' | 'now'
export type ExpiryReason = 'idle' | 'absolute'
interface ExpiryState {
idleExpiresAt: Date | null
absoluteExpiresAt: Date | null
warning: ExpiryWarning
/**
* Which window is the closer (and therefore the active) deadline. Used by
* SessionExpiryToast to pick the right copy + action button: idle gets
* "Stay signed in" (calls /auth/refresh); absolute is informational only.
*/
reason: ExpiryReason | null
}
function computeState(token: ReturnType<typeof useAuthStore.getState>['token']): ExpiryState {
const idleStr = token?.idle_expires_at
const absStr = token?.absolute_expires_at
if (!idleStr || !absStr) {
return { idleExpiresAt: null, absoluteExpiresAt: null, warning: 'none', reason: null }
}
const idle = new Date(idleStr)
const abs = new Date(absStr)
const now = Date.now()
const idleMs = idle.getTime() - now
const absMs = abs.getTime() - now
// Closer window wins.
const reason: ExpiryReason = idleMs <= absMs ? 'idle' : 'absolute'
const closestMs = Math.min(idleMs, absMs)
let warning: ExpiryWarning = 'none'
if (closestMs <= 0) warning = 'now'
else if (closestMs <= SOON_MS) warning = 'soon'
return { idleExpiresAt: idle, absoluteExpiresAt: abs, warning, reason }
}
/**
* Track how close the active session is to its idle/absolute deadline.
*
* Returns `warning: "soon"` within 5 min of whichever window comes first,
* and `reason: "idle" | "absolute"` so callers can choose the right UX
* (idle is recoverable via /auth/refresh; absolute is not). Re-evaluates
* every 30 seconds while authenticated; cheap (single Date subtraction).
*
* See docs/plans/2026-05-13-session-expiration-policy.md §4.8.
*/
export function useAuthSessionExpiry(): ExpiryState {
const token = useAuthStore((s) => s.token)
// Derived state — computed during render, not synced via setState in an
// effect. The reducer here is only a tick counter that forces re-render on
// the 30s cadence so the relative timestamps stay current. See React 19
// guidance: https://react.dev/learn/you-might-not-need-an-effect
const [, tick] = useReducer((n: number) => n + 1, 0)
useEffect(() => {
if (!token?.idle_expires_at || !token?.absolute_expires_at) return
const interval = window.setInterval(tick, 30_000)
return () => window.clearInterval(interval)
}, [token])
return computeState(token)
}

View File

@@ -8,7 +8,7 @@ export function useSubscription() {
const usage = subscription?.usage ?? null
const isActive = subscription?.subscription.status === 'active' || subscription?.subscription.status === 'trialing'
const isPaidPlan = plan === 'pro' || plan === 'starter' || plan === 'enterprise'
const isPaidPlan = plan === 'pro' || plan === 'team'
const canUseFeature = (feature: 'custom_branding' | 'priority_support'): boolean => {
if (!limits) return false

View File

@@ -17,7 +17,6 @@ import {
Plug,
RefreshCw,
Server,
Shield,
UserCog,
X,
} from 'lucide-react'
@@ -419,10 +418,10 @@ export function AccountSettingsPage() {
<p className="text-sm text-muted-foreground">Plan limits unavailable.</p>
)}
{plan !== 'enterprise' && (
{plan !== 'team' && (
<div className="flex flex-wrap justify-end gap-2 pt-2">
{plan === 'free' && <CheckoutButton plan="pro" />}
<CheckoutButton plan="enterprise" />
<CheckoutButton plan="team" />
</div>
)}
</section>
@@ -633,12 +632,6 @@ export function AccountSettingsPage() {
title="Chat retention"
description="Conversation retention and assistant data lifecycle"
/>
<SettingsRow
to="/account/security"
icon={<Shield className="h-4 w-4" />}
title="Session security"
description="Session-expiration policy and active sessions"
/>
<SettingsRow
to="/account/categories"
icon={<FolderTree className="h-4 w-4" />}

View File

@@ -1,88 +0,0 @@
import { Link } from 'react-router-dom'
import { PageMeta } from '@/components/common/PageMeta'
export default function ContactPage() {
return (
<>
<PageMeta title="Contact" description="Contact ResolutionFlow customer service, sales, billing, or security." />
<div className="min-h-screen bg-background text-foreground">
<div className="mx-auto max-w-3xl px-6 py-16">
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">&larr; Back to home</Link>
<h1 className="text-3xl font-bold font-heading mb-4">Contact ResolutionFlow</h1>
<p className="text-muted-foreground mb-10">
We respond to customer inquiries Monday through Friday during U.S. business hours, excluding federal holidays. Email is the fastest path to a response.
</p>
<div className="space-y-8 text-muted-foreground leading-relaxed">
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Phone</h2>
<p>
<a href="tel:+14709494131" className="text-primary hover:underline">(470) 949-4131</a>
</p>
<p className="text-sm mt-1">Monday&ndash;Friday, 9:00 AM&ndash;5:00 PM ET, excluding U.S. federal holidays.</p>
</section>
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Email</h2>
<ul className="space-y-2">
<li>
<strong className="text-foreground">General support:</strong>{' '}
<a href="mailto:support@resolutionflow.com" className="text-primary hover:underline">support@resolutionflow.com</a>
</li>
<li>
<strong className="text-foreground">Sales and Enterprise:</strong>{' '}
<a href="mailto:sales@resolutionflow.com" className="text-primary hover:underline">sales@resolutionflow.com</a>
</li>
<li>
<strong className="text-foreground">Billing and account:</strong>{' '}
<a href="mailto:billing@resolutionflow.com" className="text-primary hover:underline">billing@resolutionflow.com</a>
</li>
<li>
<strong className="text-foreground">Security and privacy:</strong>{' '}
<a href="mailto:security@resolutionflow.com" className="text-primary hover:underline">security@resolutionflow.com</a>
</li>
</ul>
</section>
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Response times</h2>
<ul className="list-disc list-inside space-y-1">
<li>General support: within one (1) business day</li>
<li>Billing or account access: within one (1) business day</li>
<li>Security disclosures: within twenty-four (24) hours, including weekends</li>
</ul>
</section>
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Mailing address</h2>
{/* TODO: replace with full mailing address once P.O. Box is set up. */}
<p>
Available on request. Email{' '}
<a href="mailto:support@resolutionflow.com" className="text-primary hover:underline">support@resolutionflow.com</a>{' '}
and we will provide our current mailing address.
</p>
</section>
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Sales and demos</h2>
<p>
Interested in a guided demo or Enterprise pricing? Use our{' '}
<Link to="/contact-sales" className="text-primary hover:underline">sales contact form</Link>{' '}
to book a time directly.
</p>
</section>
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Related</h2>
<ul className="list-disc list-inside space-y-1">
<li><Link to="/policies" className="text-primary hover:underline">Customer Policies</Link> &mdash; billing, refunds, cancellation, and promotions</li>
<li><Link to="/terms" className="text-primary hover:underline">Terms of Service</Link></li>
<li><Link to="/privacy" className="text-primary hover:underline">Privacy Policy</Link></li>
</ul>
</section>
</div>
</div>
</div>
</>
)
}

View File

@@ -3,7 +3,6 @@ import { Link } from 'react-router-dom'
import { salesApi, type SalesLeadSource } from '@/api/sales'
import { PageMeta } from '@/components/common/PageMeta'
import { MarketingFooter } from '@/components/common/MarketingFooter'
import { useAppConfig } from '@/hooks/useAppConfig'
import '@/styles/landing.css'
@@ -343,8 +342,6 @@ export function ContactSalesPage() {
</form>
)}
</section>
<MarketingFooter />
</main>
</div>
)

View File

@@ -2,7 +2,6 @@ import { useState, useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import { PageMeta } from '@/components/common/PageMeta'
import { useAppConfig } from '@/hooks/useAppConfig'
import { MarketingFooter } from '@/components/common/MarketingFooter'
import '@/styles/landing.css'
const FAQ_ITEMS = [
@@ -16,7 +15,7 @@ const FAQ_ITEMS = [
},
{
q: 'What PSA tools do you integrate with?',
a: 'Launching with ConnectWise PSA session documentation exports directly as internal ticket notes. Atera and Syncro integrations are next. During beta, you can copy formatted notes into any PSA.',
a: 'Launching with ConnectWise PSA \u2014 session documentation exports directly as internal ticket notes. Atera and Syncro integrations are next. During beta, you can copy formatted notes into any PSA.',
},
{
q: 'What counts as a \u201csession\u201d?',
@@ -24,7 +23,7 @@ const FAQ_ITEMS = [
},
{
q: 'What if FlowPilot gets it wrong?',
a: 'FlowPilot is a copilot, not autopilot. Every suggestion is a recommendation you decide what to act on. And because every step is documented, you always have a full audit trail of what was tried and why.',
a: 'FlowPilot is a copilot, not autopilot. Every suggestion is a recommendation \u2014 you decide what to act on. And because every step is documented, you always have a full audit trail of what was tried and why.',
},
]
@@ -76,8 +75,8 @@ export default function LandingPage() {
return (
<>
<PageMeta
title="ResolutionFlow From Issue to Resolution, Documented"
description="Your AI troubleshooting copilot. Describe the issue, get help fixing it, and get clean ticket notes automatically."
title="ResolutionFlow \u2014 From Issue to Resolution, Documented"
description="Your AI troubleshooting copilot. Describe the issue, get help fixing it, and get clean ticket notes \u2014 automatically."
/>
<div className="landing-page">
@@ -411,7 +410,29 @@ export default function LandingPage() {
</div>
</section>
<MarketingFooter />
{/* Footer */}
<footer className="landing-footer">
<div className="landing-footer-inner">
<div className="landing-footer-left">
<div className="landing-nav-logo-icon" style={{ width: 24, height: 24, borderRadius: 6 }}>
<svg viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: 14, height: 14 }}>
<circle cx="12" cy="5" r="2" />
<line x1="12" y1="7" x2="12" y2="11" />
<circle cx="6" cy="15" r="2" />
<circle cx="18" cy="15" r="2" />
<line x1="12" y1="11" x2="6" y2="13" />
<line x1="12" y1="11" x2="18" y2="13" />
</svg>
</div>
<span className="landing-footer-copy">&copy; 2026 ResolutionFlow</span>
</div>
<ul className="landing-footer-links">
<li><Link to="/privacy">Privacy</Link></li>
<li><Link to="/terms">Terms</Link></li>
<li><a href="mailto:hello@resolutionflow.com">Contact</a></li>
</ul>
</div>
</footer>
</main>
</div>
</>

View File

@@ -1,6 +1,5 @@
import { useState } from 'react'
import { Link, useNavigate, useLocation } from 'react-router-dom'
import { Info } from 'lucide-react'
import { useAuthStore } from '@/store/authStore'
import { BrandLogo } from '@/components/common/BrandLogo'
import { PasswordInput } from '@/components/common/PasswordInput'
@@ -18,11 +17,6 @@ export function LoginPage() {
const from = (location.state as { from?: { pathname: string } })?.from?.pathname || '/'
// When the user lands here after the session-policy axios interceptor
// forcibly logged them out, show a calm info-tone banner above the form.
// See docs/plans/2026-05-13-session-expiration-policy.md §4.8.
const showSessionExpiredBanner = new URLSearchParams(location.search).get('reason') === 'session_expired'
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLocalError('')
@@ -66,15 +60,6 @@ export function LoginPage() {
</p>
</div>
{showSessionExpiredBanner && (
<div className="rounded-md border border-info/30 bg-info-dim px-4 py-3 flex items-start gap-2">
<Info size={16} className="text-info mt-0.5 shrink-0" />
<p className="text-sm text-info">
You were signed out for security. Sign back in to continue.
</p>
</div>
)}
<form onSubmit={handleSubmit} className="mt-8 space-y-6" data-testid="login-form">
<div className="card-flat p-6 space-y-4">
{(error || localError) && (

View File

@@ -103,8 +103,6 @@ export function OAuthCallbackPage() {
access_token: result.access_token,
refresh_token: result.refresh_token,
token_type: result.token_type || 'bearer',
idle_expires_at: result.idle_expires_at,
absolute_expires_at: result.absolute_expires_at,
})
// Hydrate user / account / subscription.
await fetchUser()

View File

@@ -1,194 +0,0 @@
import { Link } from 'react-router-dom'
import { PageMeta } from '@/components/common/PageMeta'
export default function PoliciesPage() {
return (
<>
<PageMeta title="Customer Policies" description="ResolutionFlow customer service, billing, refunds, cancellation, legal restrictions, and promotional terms." />
<div className="min-h-screen bg-background text-foreground">
<div className="mx-auto max-w-3xl px-6 py-16">
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">&larr; Back to home</Link>
<h1 className="text-3xl font-bold font-heading mb-4">Customer Policies</h1>
<p className="text-muted-foreground mb-2">Last updated: May 7, 2026</p>
<p className="text-muted-foreground mb-2"><strong className="text-foreground">Operator:</strong> ResolutionFlow, LLC (the &ldquo;Company&rdquo;), operator of ResolutionFlow (&ldquo;Service&rdquo;).</p>
<p className="text-muted-foreground mb-8"><strong className="text-foreground">Product:</strong> ResolutionFlow &mdash; a software-as-a-service troubleshooting platform for Managed Service Providers (MSPs).</p>
<p className="text-muted-foreground mb-6 leading-relaxed">
This document consolidates the policies that govern your use of ResolutionFlow, including how to contact us, how billing works, how to cancel, how refunds and disputes are handled, the legal restrictions that apply, and the terms of any promotional offers. It is intended to satisfy the disclosure requirements of our payment processors (including Stripe) and to give customers clear, accessible answers to common billing and account questions.
</p>
<p className="text-muted-foreground mb-10 leading-relaxed">
ResolutionFlow is a digital subscription service. We do not sell or ship physical goods, so a return policy does not apply; the section on refunds below covers all circumstances in which money may be returned.
</p>
<hr className="border-border mb-10" />
<div className="space-y-10 text-muted-foreground leading-relaxed">
{/* Section 1 */}
<section id="contact">
<h2 className="text-xl font-semibold text-foreground mb-3">1. Customer Service Contact</h2>
<p>We respond to customer inquiries during standard business hours, Monday through Friday, excluding U.S. federal holidays. The fastest path to a response is email.</p>
<ul className="mt-3 space-y-1">
<li><strong className="text-foreground">Phone:</strong> <a href="tel:+14709494131" className="text-primary hover:underline">(470) 949-4131</a></li>
<li><strong className="text-foreground">Email (primary channel):</strong> <a href="mailto:support@resolutionflow.com" className="text-primary hover:underline">support@resolutionflow.com</a></li>
<li><strong className="text-foreground">Sales and Enterprise inquiries:</strong> <a href="mailto:sales@resolutionflow.com" className="text-primary hover:underline">sales@resolutionflow.com</a></li>
<li><strong className="text-foreground">Billing and account inquiries:</strong> <a href="mailto:billing@resolutionflow.com" className="text-primary hover:underline">billing@resolutionflow.com</a></li>
<li><strong className="text-foreground">Security and privacy inquiries:</strong> <a href="mailto:security@resolutionflow.com" className="text-primary hover:underline">security@resolutionflow.com</a></li>
</ul>
{/* TODO: replace with full mailing address once P.O. Box is set up. */}
<p className="mt-4"><strong className="text-foreground">Mailing address:</strong> available on request &mdash; email <a href="mailto:support@resolutionflow.com" className="text-primary hover:underline">support@resolutionflow.com</a>.</p>
<p className="mt-2"><strong className="text-foreground">Web contact form:</strong> <Link to="/contact" className="text-primary hover:underline">resolutionflow.com/contact</Link></p>
<p className="mt-4"><strong className="text-foreground">Target response times:</strong></p>
<ul className="list-disc list-inside space-y-1 mt-1">
<li>General support: within one (1) business day</li>
<li>Billing or account access issues: within one (1) business day</li>
<li>Security disclosures: within twenty-four (24) hours, including weekends</li>
</ul>
<p className="mt-3">Customers on the Enterprise plan have additional contact channels and service levels defined in their order form.</p>
</section>
{/* Section 2 */}
<section id="returns">
<h2 className="text-xl font-semibold text-foreground mb-3">2. Return Policy</h2>
<p>ResolutionFlow is a software-as-a-service product delivered electronically. Because no physical goods are sold or shipped, no return policy applies. All refund-related questions are governed by Section 3 (Refund and Dispute Policy) below.</p>
</section>
{/* Section 3 */}
<section id="refunds">
<h2 className="text-xl font-semibold text-foreground mb-3">3. Refund and Dispute Policy</h2>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">3.1 Subscription model</h3>
<p>ResolutionFlow is sold as a recurring monthly subscription. The Service is billed in advance: the first charge occurs at the end of any free trial period (or immediately if no trial applies), and subsequent charges occur on the same day each month until the subscription is cancelled. There are currently no annual subscription terms; if and when annual terms become available, refund handling for those terms will be specified at the point of sale.</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">3.2 Free trial</h3>
<p>New customers receive a 14-day free trial of the Pro plan. No charge is made during the trial. If the customer does not cancel before the trial ends, the subscription converts automatically to a paid plan at the price disclosed at signup. Cancelling before the trial ends prevents any charge. The trial is intended to be the customer&rsquo;s primary opportunity to evaluate the Service before paying.</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">3.3 Refund policy</h3>
<p><strong className="text-foreground">Monthly subscriptions are non-refundable.</strong> Because the customer can cancel at any time and is never billed for a future period after cancellation, we do not issue refunds for partial months, unused features, or change-of-mind cancellations made after the billing date. This is the standard model for B2B SaaS and is consistent with how the Service is priced and delivered.</p>
<p className="mt-3">We will issue a refund or credit at our discretion in the following circumstances:</p>
<ul className="list-disc list-inside space-y-2 mt-2">
<li><strong className="text-foreground">Duplicate or accidental charge.</strong> If a customer is charged twice for the same billing period, or charged after a verifiable cancellation that we failed to process, we refund the erroneous charge in full.</li>
<li><strong className="text-foreground">Fraudulent charge.</strong> If a customer demonstrates that their payment method was used without authorization, we cooperate with the cardholder and the issuing bank to resolve the dispute and refund or reverse the charge as appropriate.</li>
<li><strong className="text-foreground">Material Service failure.</strong> If the Service is materially unavailable for an extended period due to our fault, we may issue a service credit applied to the next billing cycle. Credits are not paid as cash refunds.</li>
<li><strong className="text-foreground">Annual prepayments (when offered).</strong> If annual prepayment becomes available in the future, the refund terms for those subscriptions will be disclosed at the point of sale.</li>
</ul>
<p className="mt-3">Refunds, where issued, are returned to the original payment method used for the charge. Refund processing typically completes within five (5) to ten (10) business days, depending on the customer&rsquo;s bank or card issuer.</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">3.4 Disputes and chargebacks</h3>
<p>If you believe a charge is incorrect, please contact <a href="mailto:billing@resolutionflow.com" className="text-primary hover:underline">billing@resolutionflow.com</a> <strong className="text-foreground">before</strong> initiating a chargeback with your bank or card issuer. We can almost always resolve billing questions faster than the dispute process and without affecting your account standing.</p>
<p className="mt-3">If a chargeback is filed against an active subscription, the associated account may be suspended pending resolution to prevent further charges. We respond to chargeback inquiries from card networks with the records we maintain, including signup records, billing history, login activity, and product usage. We do not retaliate against customers for filing legitimate disputes; suspensions during a dispute are operational, not punitive.</p>
<p className="mt-3">Customers who repeatedly file chargebacks for charges that they previously authorized and used may be permanently banned from the Service.</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">3.5 Enterprise refunds</h3>
<p>Customers on the Enterprise plan are governed by the refund and dispute terms in their executed order form or master services agreement. Where those terms conflict with this section, the order form or MSA controls.</p>
</section>
{/* Section 4 */}
<section id="cancellation">
<h2 className="text-xl font-semibold text-foreground mb-3">4. Cancellation Policy</h2>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">4.1 How to cancel</h3>
<p>Customers can cancel their subscription at any time, without contacting support, through one of the following routes:</p>
<ol className="list-decimal list-inside space-y-2 mt-2">
<li><strong className="text-foreground">Account settings &rarr; Billing &rarr; Manage subscription</strong>, which opens the Stripe Customer Portal and allows the customer to cancel directly.</li>
<li><strong className="text-foreground">Email <a href="mailto:billing@resolutionflow.com" className="text-primary hover:underline">billing@resolutionflow.com</a></strong> from the email address on file. We will process the cancellation within one (1) business day and confirm by reply.</li>
</ol>
<p className="mt-3">Customers on the Enterprise plan should follow the cancellation procedure specified in their order form or MSA.</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">4.2 What happens when you cancel</h3>
<ul className="list-disc list-inside space-y-2">
<li><strong className="text-foreground">No future charges.</strong> Your subscription will not renew. The card on file will not be charged again.</li>
<li><strong className="text-foreground">Access continues until the end of the current billing period.</strong> If you cancel mid-month, you retain full access to the Service until the end of the period you have already paid for. We do not lock you out early.</li>
<li><strong className="text-foreground">Trial cancellations.</strong> Cancelling during a free trial ends the trial immediately. No charge is made.</li>
<li><strong className="text-foreground">No partial refunds.</strong> Per Section 3.3, the unused portion of the current billing period is not refunded.</li>
</ul>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">4.3 What happens to your data</h3>
<p>For a period of thirty (30) days after the end of the current billing period, your account is retained in a read-only state. During this window you can:</p>
<ul className="list-disc list-inside space-y-2 mt-2">
<li>Reactivate the subscription and resume work without any data loss.</li>
<li>Export your sessions, flows, and documentation in any of the supported export formats (Markdown, plain text, HTML, PDF, or PSA-formatted notes).</li>
<li>Request a copy of your data by emailing <a href="mailto:security@resolutionflow.com" className="text-primary hover:underline">security@resolutionflow.com</a>.</li>
</ul>
<p className="mt-3">After thirty (30) days, all customer-generated content is permanently deleted from production systems. Backups are purged within ninety (90) days. Some metadata may be retained as required for tax, legal, or fraud-prevention obligations.</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">4.4 Reactivation</h3>
<p>A cancelled account can be reactivated within the thirty (30) day retention window by signing in and re-subscribing. Beyond that window, the customer can sign up again, but prior data will not be available.</p>
</section>
{/* Section 5 */}
<section id="legal">
<h2 className="text-xl font-semibold text-foreground mb-3">5. Legal and Export Restrictions</h2>
<p>ResolutionFlow is operated from the United States and is subject to U.S. law, including export control and economic sanctions regulations administered by the U.S. Department of the Treasury Office of Foreign Assets Control (&ldquo;OFAC&rdquo;) and the U.S. Department of Commerce Bureau of Industry and Security (&ldquo;BIS&rdquo;).</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">5.1 Eligibility</h3>
<p>By subscribing to or using the Service, you represent and warrant that:</p>
<ul className="list-disc list-inside space-y-2 mt-2">
<li>You are not located in, ordinarily resident in, or organized under the laws of a country or region subject to comprehensive U.S. sanctions (including, as of this date, Cuba, Iran, North Korea, Syria, and the so-called Crimea, Donetsk, and Luhansk regions of Ukraine).</li>
<li>You are not identified on the U.S. Treasury Department&rsquo;s List of Specially Designated Nationals and Blocked Persons (SDN List), the U.S. Commerce Department&rsquo;s Denied Persons List or Entity List, or any other restricted-party list maintained by the U.S. government, the United Nations Security Council, the European Union, or the United Kingdom.</li>
<li>You will not use the Service in violation of any applicable U.S. or foreign export control or sanctions law.</li>
</ul>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">5.2 Use restrictions</h3>
<p>The Service is intended for general business use by Managed Service Providers and similar IT services organizations. The Service may not be used in connection with:</p>
<ul className="list-disc list-inside space-y-2 mt-2">
<li>The design, development, production, or use of nuclear, chemical, or biological weapons, or missile systems capable of delivering such weapons.</li>
<li>Any application where failure of the Service could reasonably be expected to cause death, personal injury, or severe physical or environmental damage (including life-support systems, primary medical diagnostic systems, nuclear facilities, or air traffic control).</li>
</ul>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">5.3 Right to refuse service</h3>
<p>We reserve the right to refuse, suspend, or terminate service to any customer where we have a reasonable belief, based on the information available to us, that providing the Service would violate applicable law, sanctions, or our policies. Where service is terminated for compliance reasons, any prepaid amounts are refunded to the extent permitted by law.</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">5.4 Governing law and venue</h3>
<p>These policies are governed by the laws of the State of Georgia, without regard to its conflict-of-laws principles. Any dispute arising out of these policies or your use of the Service will be brought in the state or federal courts located in Cherokee County, Georgia, and you consent to the personal jurisdiction of those courts. This venue clause does not apply where prohibited by mandatory consumer protection law in your jurisdiction.</p>
</section>
{/* Section 6 */}
<section id="promotions">
<h2 className="text-xl font-semibold text-foreground mb-3">6. Promotions: Terms and Conditions</h2>
<p>From time to time we may offer promotional pricing, extended trials, referral credits, free upgrades, or other promotional benefits (&ldquo;Promotions&rdquo;). The following general terms apply to all Promotions, in addition to any specific terms disclosed at the time the Promotion is offered:</p>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">6.1 General terms</h3>
<ul className="list-disc list-inside space-y-2">
<li>Promotions apply only to the specific accounts, plans, and billing periods identified at the time of the offer.</li>
<li>Promotions cannot be combined with other Promotions unless we expressly state otherwise.</li>
<li>Promotional pricing applies for the period stated in the offer. After that period, the subscription renews at the then-current standard price for the applicable plan unless cancelled.</li>
<li>Promotional credits and discounts have no cash value and are not transferable, refundable, or redeemable for currency.</li>
<li>Customers must be in good standing (no overdue balances, no active chargebacks, no policy violations) to receive or continue receiving a Promotion.</li>
<li>We may modify or discontinue a Promotion at any time, except where doing so would be inconsistent with the terms disclosed at the time the customer accepted the Promotion.</li>
<li>We reserve the right to revoke a Promotion and recover its value if we determine, in good faith, that the customer obtained the Promotion through fraud, duplicate accounts, abuse, or violation of these terms.</li>
</ul>
<h3 className="text-base font-semibold text-foreground mt-4 mb-2">6.2 Active promotions</h3>
<p>A current list of active Promotions, along with their specific terms, is published at <Link to="/promotions" className="text-primary hover:underline">resolutionflow.com/promotions</Link>. Where there is any inconsistency between the general terms above and the specific terms of an individual Promotion, the specific terms control for that Promotion only.</p>
<p className="mt-3">If no Promotions are active, that page will state so.</p>
</section>
{/* Section 7 */}
<section id="changes">
<h2 className="text-xl font-semibold text-foreground mb-3">7. Changes to These Policies</h2>
<p>We may update these policies from time to time. Material changes will be announced by email to the address on file for the account at least fifteen (15) days before they take effect, and the &ldquo;Last updated&rdquo; date at the top of this document will be revised. Continued use of the Service after the effective date of a change constitutes acceptance of the updated policies. Customers who do not accept a material change may cancel under Section 4 before the effective date.</p>
</section>
{/* Section 8 */}
<section id="agreements">
<h2 className="text-xl font-semibold text-foreground mb-3">8. Relationship to Other Agreements</h2>
<p>These policies are part of, and incorporated into, the ResolutionFlow <Link to="/terms" className="text-primary hover:underline">Terms of Service</Link> and the <Link to="/privacy" className="text-primary hover:underline">Privacy Policy</Link>. Where these policies conflict with the Terms of Service or Privacy Policy, the Terms of Service control for matters of contract formation, liability, warranties, and dispute resolution; the Privacy Policy controls for matters of personal data handling; and these policies control for matters of billing, refunds, cancellation, customer service contact, legal restrictions, and Promotions.</p>
<p className="mt-3">For Enterprise customers operating under an executed order form or master services agreement, that agreement controls in the event of any conflict with these policies.</p>
</section>
<hr className="border-border" />
<p className="text-sm italic">
Questions about these policies? Email{' '}
<a href="mailto:billing@resolutionflow.com" className="text-primary hover:underline">billing@resolutionflow.com</a>{' '}
or use the contact form at{' '}
<Link to="/contact" className="text-primary hover:underline">resolutionflow.com/contact</Link>.
</p>
</div>
</div>
</div>
</>
)
}

View File

@@ -3,7 +3,6 @@ import { Link } from 'react-router-dom'
import { plansApi, type PublicPlanResponse } from '@/api/plans'
import { PageMeta } from '@/components/common/PageMeta'
import { MarketingFooter } from '@/components/common/MarketingFooter'
import { useAppConfig } from '@/hooks/useAppConfig'
import '@/styles/landing.css'
@@ -432,8 +431,6 @@ export function PricingPage() {
>
Built on Stripe + AWS · Encrypted in transit and at rest
</section>
<MarketingFooter />
</main>
</div>
)

View File

@@ -34,7 +34,7 @@ export default function PrivacyPage() {
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">5. Contact</h2>
<p>Questions about this policy? Email <a href="mailto:security@resolutionflow.com" className="text-primary hover:underline">security@resolutionflow.com</a> or visit our <Link to="/contact" className="text-primary hover:underline">contact page</Link>. Billing, cancellation, refund, and promotional terms are governed by our <Link to="/policies" className="text-primary hover:underline">Customer Policies</Link>.</p>
<p>Questions about this policy? Email us at <a href="mailto:hello@resolutionflow.com" className="text-primary hover:underline">hello@resolutionflow.com</a>.</p>
</section>
</div>
</div>

View File

@@ -1,37 +0,0 @@
import { Link } from 'react-router-dom'
import { PageMeta } from '@/components/common/PageMeta'
export default function PromotionsPage() {
return (
<>
<PageMeta title="Promotions" description="Active ResolutionFlow promotional offers and their terms." />
<div className="min-h-screen bg-background text-foreground">
<div className="mx-auto max-w-3xl px-6 py-16">
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">&larr; Back to home</Link>
<h1 className="text-3xl font-bold font-heading mb-4">Promotions</h1>
<p className="text-muted-foreground mb-10">Last updated: May 7, 2026</p>
<div className="space-y-6 text-muted-foreground leading-relaxed">
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Current promotions</h2>
<p>No promotions are currently active.</p>
<p className="mt-3">
Promotional offers, when running, will be listed on this page with their specific terms (eligible plans, duration, redemption rules, expiration). The general terms that apply to all promotions are described in{' '}
<Link to="/policies" className="text-primary hover:underline">Section 6 of our Customer Policies</Link>.
</p>
</section>
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">Questions</h2>
<p>
Email{' '}
<a href="mailto:billing@resolutionflow.com" className="text-primary hover:underline">billing@resolutionflow.com</a>{' '}
for questions about a promotion you received by email, or to ask about upcoming offers.
</p>
</section>
</div>
</div>
</div>
</>
)
}

View File

@@ -39,7 +39,7 @@ export default function TermsPage() {
<section>
<h2 className="text-xl font-semibold text-foreground mb-3">6. Contact</h2>
<p>Questions about these terms? Email <a href="mailto:support@resolutionflow.com" className="text-primary hover:underline">support@resolutionflow.com</a> or visit our <Link to="/contact" className="text-primary hover:underline">contact page</Link>. Billing, cancellation, refund, and promotional terms are governed by our <Link to="/policies" className="text-primary hover:underline">Customer Policies</Link>.</p>
<p>Questions about these terms? Email us at <a href="mailto:hello@resolutionflow.com" className="text-primary hover:underline">hello@resolutionflow.com</a>.</p>
</section>
</div>
</div>

View File

@@ -1,353 +0,0 @@
import { useEffect, useMemo, useState } from 'react'
import { Loader2, Save, Shield } from 'lucide-react'
import { cn } from '@/lib/utils'
import { toast } from '@/lib/toast'
import { useAuthStore } from '@/store/authStore'
import { accountSecurityApi, type SessionPolicyResponse } from '@/api/accountSecurity'
import { RevokeSessionsModal } from '@/components/account/RevokeSessionsModal'
type Preset = 'strict' | 'standard' | 'custom'
const PRESETS: Record<Exclude<Preset, 'custom'>, { idle: number; absolute: number; label: string; sub: string }> = {
strict: { idle: 4320, absolute: 20160, label: 'Strict', sub: '3 days idle · 14 days absolute' },
standard: { idle: 10080, absolute: 43200, label: 'Standard', sub: '7 days idle · 30 days absolute' },
}
function detectPreset(idle: number, absolute: number): Preset {
if (idle === PRESETS.strict.idle && absolute === PRESETS.strict.absolute) return 'strict'
if (idle === PRESETS.standard.idle && absolute === PRESETS.standard.absolute) return 'standard'
return 'custom'
}
function relativeFromNow(iso: string | null): string {
if (!iso) return 'unknown'
const diffMs = Date.now() - new Date(iso).getTime()
const m = Math.round(diffMs / 60_000)
if (m < 1) return 'just now'
if (m < 60) return `${m}m ago`
const h = Math.round(m / 60)
if (h < 24) return `${h}h ago`
const d = Math.round(h / 24)
if (d < 30) return `${d}d ago`
return new Date(iso).toLocaleDateString()
}
export default function AccountSecuritySettingsPage() {
const currentUserId = useAuthStore((s) => s.user?.id) ?? null
const [data, setData] = useState<SessionPolicyResponse | null>(null)
const [loading, setLoading] = useState(true)
const [preset, setPreset] = useState<Preset>('strict')
const [idleMin, setIdleMin] = useState<string>('')
const [absMin, setAbsMin] = useState<string>('')
const [saving, setSaving] = useState(false)
const [success, setSuccess] = useState(false)
const [modalScope, setModalScope] = useState<'all' | 'others' | null>(null)
useEffect(() => {
void load()
}, [])
const load = async () => {
setLoading(true)
try {
const res = await accountSecurityApi.get()
setData(res)
const eff = res
const detected = detectPreset(eff.effective_idle_minutes, eff.effective_absolute_minutes)
setPreset(detected)
setIdleMin(String(eff.effective_idle_minutes))
setAbsMin(String(eff.effective_absolute_minutes))
} catch {
toast.error('Could not load security settings')
} finally {
setLoading(false)
}
}
const customDisabled = preset !== 'custom'
// Sync the inputs to the chosen preset so the visible values track the radio.
const handlePresetChange = (next: Preset) => {
setPreset(next)
if (next === 'strict') {
setIdleMin(String(PRESETS.strict.idle))
setAbsMin(String(PRESETS.strict.absolute))
} else if (next === 'standard') {
setIdleMin(String(PRESETS.standard.idle))
setAbsMin(String(PRESETS.standard.absolute))
}
}
const validation = useMemo(() => {
if (!data) return { idleErr: null, absErr: null, ok: false }
const idle = parseInt(idleMin, 10)
const abs = parseInt(absMin, 10)
let idleErr: string | null = null
let absErr: string | null = null
if (!Number.isFinite(idle)) idleErr = 'Required'
else if (idle < data.idle_minutes_min || idle > data.idle_minutes_max) {
idleErr = `Between ${data.idle_minutes_min} and ${data.idle_minutes_max}`
}
if (!Number.isFinite(abs)) absErr = 'Required'
else if (abs < data.absolute_minutes_min || abs > data.absolute_minutes_max) {
absErr = `Between ${data.absolute_minutes_min} and ${data.absolute_minutes_max}`
}
if (!idleErr && !absErr && idle > abs) {
idleErr = 'Idle cannot exceed absolute'
}
return { idleErr, absErr, ok: !idleErr && !absErr }
}, [data, idleMin, absMin])
const handleSave = async () => {
if (!validation.ok || !data) return
setSaving(true)
setSuccess(false)
try {
const body =
preset === 'custom'
? { idle_minutes: parseInt(idleMin, 10), absolute_minutes: parseInt(absMin, 10) }
: preset === 'strict'
? { idle_minutes: PRESETS.strict.idle, absolute_minutes: PRESETS.strict.absolute }
: { idle_minutes: PRESETS.standard.idle, absolute_minutes: PRESETS.standard.absolute }
const updated = await accountSecurityApi.update(body)
setData(updated)
setSuccess(true)
setTimeout(() => setSuccess(false), 3000)
} catch {
// Global axios interceptor surfaces 422 via toast.
} finally {
setSaving(false)
}
}
const handleRevokeConfirm = async () => {
if (!modalScope) return
const scope = modalScope
try {
const res = await accountSecurityApi.revokeSessions(scope)
toast.success(`Signed out ${res.revoked_count} sessions`)
setModalScope(null)
if (scope === 'all') {
// Per plan §4.8 D4: small delay so the user sees the toast,
// then clear local state and redirect to /login.
setTimeout(() => {
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
useAuthStore.getState().logout()
window.location.href = '/login'
}, 1500)
} else {
// scope=others: reload to reflect the new (shorter) active-users list.
await load()
}
} catch {
// global handler
}
}
if (loading || !data) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="animate-spin text-primary" size={24} />
</div>
)
}
const activeUserCount = data.active_users.length
const solo = activeUserCount <= 1
return (
<div className="max-w-2xl mx-auto py-8 px-6 space-y-6">
<div className="flex items-center gap-3">
<Shield size={20} className="text-primary" />
<h1 className="text-xl font-heading font-bold text-foreground">Session Security</h1>
</div>
<p className="text-sm text-muted-foreground">
Control how long sessions can last before users must sign in again.
</p>
{/* ── Policy card ────────────────────────────────────────────────── */}
<div className="card-flat rounded-2xl p-6 space-y-5">
<fieldset className="space-y-3">
<legend className="text-sm font-medium text-foreground mb-1">Policy</legend>
{(['strict', 'standard', 'custom'] as const).map((p) => {
const isSelected = preset === p
const labels = p === 'custom'
? { label: 'Custom', sub: 'Set your own idle and absolute windows below' }
: PRESETS[p]
return (
<label
key={p}
className={cn(
'flex items-start gap-3 rounded-lg border p-3 cursor-pointer transition-colors',
isSelected
? 'border-primary/40 bg-primary/[0.06]'
: 'border-border hover:bg-card-hover',
)}
>
<input
type="radio"
name="preset"
value={p}
checked={isSelected}
onChange={() => handlePresetChange(p)}
className="mt-0.5"
/>
<div className="flex-1">
<div className="text-sm font-medium text-foreground">{labels.label}</div>
<div className="text-xs text-muted-foreground mt-0.5">{labels.sub}</div>
</div>
</label>
)
})}
</fieldset>
{/* Custom inputs — always visible, disabled outside Custom */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="font-sans text-xs uppercase tracking-widest text-muted-foreground block mb-1.5">
Idle minutes
</label>
<input
type="number"
value={idleMin}
onChange={(e) => setIdleMin(e.target.value)}
disabled={customDisabled}
min={data.idle_minutes_min}
max={data.idle_minutes_max}
className={cn(
'w-full rounded-xl border bg-card text-foreground text-sm px-4 py-2.5',
'focus:outline-hidden focus:border-primary/30',
'disabled:opacity-50 disabled:cursor-not-allowed',
validation.idleErr && !customDisabled && 'border-danger/50',
)}
style={{
borderColor:
validation.idleErr && !customDisabled ? undefined : 'var(--color-border-default)',
}}
/>
<p className="text-[11px] text-muted-foreground mt-1">
{validation.idleErr && !customDisabled
? validation.idleErr
: `Between ${data.idle_minutes_min} and ${data.idle_minutes_max} min`}
</p>
</div>
<div>
<label className="font-sans text-xs uppercase tracking-widest text-muted-foreground block mb-1.5">
Absolute minutes
</label>
<input
type="number"
value={absMin}
onChange={(e) => setAbsMin(e.target.value)}
disabled={customDisabled}
min={data.absolute_minutes_min}
max={data.absolute_minutes_max}
className={cn(
'w-full rounded-xl border bg-card text-foreground text-sm px-4 py-2.5',
'focus:outline-hidden focus:border-primary/30',
'disabled:opacity-50 disabled:cursor-not-allowed',
validation.absErr && !customDisabled && 'border-danger/50',
)}
style={{
borderColor:
validation.absErr && !customDisabled ? undefined : 'var(--color-border-default)',
}}
/>
<p className="text-[11px] text-muted-foreground mt-1">
{validation.absErr && !customDisabled
? validation.absErr
: `Between ${data.absolute_minutes_min} and ${data.absolute_minutes_max} min`}
</p>
</div>
</div>
<div className="flex items-center gap-3 pt-2">
<button
type="button"
onClick={handleSave}
disabled={saving || !validation.ok}
className="bg-primary text-white font-semibold text-sm rounded-lg px-5 py-2.5 hover:brightness-110 active:scale-[0.98] transition-all disabled:opacity-40 flex items-center gap-2"
>
{saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
Save Policy
</button>
{success && <span className="text-sm text-emerald-400">Settings saved</span>}
</div>
<p className="text-xs text-muted-foreground border-t border-border pt-3">
New policy applies the next time each person signs in. Use{' '}
<span className="font-medium text-foreground">Active sessions</span> below to force it
immediately.
</p>
</div>
{/* ── Active sessions card ───────────────────────────────────────── */}
<div className="card-flat rounded-2xl p-6 space-y-4">
<div>
<h2 className="text-sm font-medium text-foreground">Active sessions</h2>
<p className="text-xs text-muted-foreground mt-1">
{solo
? 'Only you are signed in to this account.'
: `${activeUserCount} people are signed in to this account.`}
</p>
</div>
<ul className="space-y-2">
{data.active_users.map((u) => {
const isMe = u.user_id === currentUserId
return (
<li
key={u.user_id}
className="flex items-center gap-3 rounded-lg border border-border bg-card px-3 py-2"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 text-sm font-medium text-foreground">
<span className="truncate">{u.name}</span>
{isMe && (
<span className="text-[10px] uppercase tracking-wider text-muted-foreground">
(you)
</span>
)}
</div>
<div className="text-xs text-muted-foreground truncate">
{u.email} · last signed in {relativeFromNow(u.last_login_at)}
</div>
</div>
</li>
)
})}
</ul>
<div className="flex flex-wrap gap-2 pt-2">
{!solo && (
<button
type="button"
onClick={() => setModalScope('others')}
className="rounded-md border border-border bg-transparent px-3 py-1.5 text-sm font-medium text-foreground hover:bg-card-hover"
>
Sign out everyone except me
</button>
)}
<button
type="button"
onClick={() => setModalScope('all')}
className="rounded-md border border-danger/40 bg-danger/10 px-3 py-1.5 text-sm font-medium text-danger hover:bg-danger/15"
>
{solo ? 'Sign me out everywhere' : 'Sign me out and everyone else'}
</button>
</div>
</div>
<RevokeSessionsModal
isOpen={modalScope !== null}
scope={modalScope ?? 'others'}
activeUserCount={activeUserCount}
onClose={() => setModalScope(null)}
onConfirm={handleRevokeConfirm}
/>
</div>
)
}

Some files were not shown because too many files have changed in this diff Show More