Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@
# METRICS_PUSHGATEWAY_URL=http://pushgateway:9091
# METRICS_JOB=joboffer_scanner

# Marketing site / waitlist — CORS allow-origin for the public POST /waitlist
# endpoint (the landing page's origin). Defaults to '*' (dev).
# LANDING_ORIGIN=https://yourdomain.com

# Telegram bot channel (alternative to the Streamlit UI)
# TELEGRAM_BOT_TOKEN=... # from @BotFather

Expand All @@ -130,6 +134,20 @@
# re-encrypting existing rows will break 2FA verification for those users.
# SECRETS_ENCRYPTION_KEY=change-me-to-a-long-random-string

# Billing (optional — [billing] extra: stripe). When STRIPE_SECRET_KEY is
# UNSET, billing is disabled and every user is on the "unlimited" tier —
# self-hosted deployments are never constrained. When set, users without a
# subscription are on the FREE tier (5 analyses / 2 tailored docs per rolling
# 30 days, fast model only); paid tiers come from Stripe via the webhook
# (POST /v1/billing/webhook).
# STRIPE_SECRET_KEY=sk_live_...
# STRIPE_WEBHOOK_SECRET=whsec_... # from the Stripe webhook endpoint config
# STRIPE_PRICE_PRO=price_... # recurring price id for the Pro plan
# STRIPE_PRICE_POWER=price_... # recurring price id for the Power plan
# TIER_WINDOW_DAYS=30 # rolling window for tier counters
# Override tier limits wholesale (partial per-tier overrides merge over defaults):
# TIER_LIMITS_JSON={"free": {"analyses_per_window": 10}}

# Password reset — self-hosted convenience flag.
# Set to 1 ONLY in single-user/self-hosted deployments to display reset
# tokens directly in the UI. Leave UNSET in multi-tenant production.
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ jobs:
"user_two_factor", "application_shares", "api_tokens",
"webhooks", "webhook_deliveries", "oauth_identities",
"email_verification_tokens", "llm_usage",
"subscriptions", "usage_events", "waitlist_entries",
}
missing = required - tables
assert not missing, f"missing tables after migrate: {missing}"
Expand Down
21 changes: 16 additions & 5 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,28 @@ tools/ LLM-facing tools + ingestion
job_tools, company_tools, salary_tools, resume_tools, data_sources,
url_ingest, browser_scraper (Playwright, optional), html_extract (shared),
company_research (agentic keyless DuckDuckGo + Browserbase fallback)
services/ Business logic (31 modules) — the bulk of the app
services/ Business logic (34 modules) — the bulk of the app
auth, totp, oauth, api_tokens, rate_limit, audit (identity/security)
applications, stages, analytics, timeline, background_analysis (tracking)
master_cv, projects, tailoring, constraint_check, suggestions, pdf_export (CV/artifacts)
sharing, webhooks, telegram_link, notifications, email, reminders (integrations)
checkpoint, bulk_import, system_test, analysis_runner, usage (LLM cost),
account_export, email_verify, _ownership (require_owned helper)
billing (tiers/Stripe), funnel (operator metrics), waitlist,
account_export, email_verify, _ownership (require_owned)
db/ SQLAlchemy 2.0 models + session (StaticPool-aware)
api/ FastAPI app: routes, bearer auth, security headers
bot/ Telegram bot: handlers (pure) + main (runtime)
worker/ Celery app + tasks + CLI runners (reminders, metrics_dump)
utils/ LEAF layer: llm, config, env, crypto, security, diff,
verdict, text, logging_setup, metrics, timing, cache
migrations/ Alembic (17 revisions, 20 tables)
migrations/ Alembic (19 revisions, 23 tables)
chrome-extension/ MV3 extension calling the REST API (JS, Node-tested)
deploy/ Caddy/nginx reverse-proxy examples (CSP/HSTS) +
README (edge topology) + RUNBOOK (backups/incidents)
scripts/ backup_db.sh / restore_db.sh (Postgres ops)
tests/ 43 files, 647 Python tests (7 live e2e, skipped
landing/ static marketing site + waitlist form (deploy at edge)
docs/ STRIPE_SETUP, HARDENING, GTM (founder/ops guides)
tests/ 46 files, 697 Python tests (7 live e2e, skipped
unless RUN_E2E=1) + 9 JS (extract.test.mjs)
```

Expand Down Expand Up @@ -122,7 +125,7 @@ celery -A worker.celery_app:app worker
python -m worker.reminders

# Tests
python -m unittest discover -s tests # ~6 min, 647 tests (7 e2e skipped)
python -m unittest discover -s tests # ~6 min, 697 tests (7 e2e skipped)
node chrome-extension/extract.test.mjs # 9 JS tests

# Migrations
Expand Down Expand Up @@ -161,6 +164,14 @@ mode** (sample data, clearly labelled). `DATABASE_URL` unset ⇒ SQLite at
only links an external identity to a pre-existing local account when the
provider asserts the email is verified (Google OIDC claim / GitHub verified
primary) — otherwise it refuses (anti-account-takeover).
- **Billing never constrains self-hosters.** `services/billing`: with no
`STRIPE_SECRET_KEY`, every user is on the `unlimited` tier and all quota
checks are no-ops. With a key, no-subscription = `free` tier; quotas
(analyses/window, artifacts/window, tier LLM budget, detailed-model,
API access) are enforced inside `check_user_quota`, `tailoring`, and
`api/auth` — entry points only catch `TierLimitExceeded`. Tier limits
live in code (`TIER_LIMITS_JSON` to override), the user's tier in the
`subscriptions` table (mirrored from Stripe via `POST /v1/billing/webhook`).
- **Migrations:** add a model field ⇒ add an Alembic migration. CI runs the
full `up → down → up` on real Postgres. `db.session.reset_engine_for_testing`
uses **StaticPool** so thread-hopping tests (bot handlers, Streamlit
Expand Down
10 changes: 10 additions & 0 deletions api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,14 @@ def require_user(
detail="Invalid or revoked API token.",
headers={"WWW-Authenticate": "Bearer"},
)
# Tier gate: REST API access is a paid-plan feature when billing is
# enabled; a no-op for self-hosted deployments (no Stripe key => unlimited
# tier). 402 (not 403) so clients can distinguish "upgrade" from "denied".
from services.billing import api_access_allowed

if not api_access_allowed(user_id):
raise HTTPException(
status_code=status.HTTP_402_PAYMENT_REQUIRED,
detail="API access requires the Power plan. Upgrade to use the REST API.",
)
return user_id
48 changes: 48 additions & 0 deletions api/billing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Billing endpoints: the Stripe webhook + plan introspection.

The webhook is UNAUTHENTICATED by design — Stripe can't send a bearer token —
and is instead verified by the ``stripe-signature`` header against
``STRIPE_WEBHOOK_SECRET``. It returns 503 when billing isn't configured so a
misrouted deployment fails loudly rather than silently dropping events.
"""

from __future__ import annotations

import logging

from fastapi import APIRouter, Depends, Header, HTTPException, Request

from api.auth import require_user
from services.billing import (
BillingError,
billing_enabled,
handle_webhook_event,
plan_summary,
verify_webhook,
)

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/v1/billing")


@router.post("/webhook")
async def stripe_webhook(
request: Request,
stripe_signature: str = Header(default="", alias="stripe-signature"),
) -> dict:
if not billing_enabled():
raise HTTPException(status_code=503, detail="Billing is not configured.")
payload = await request.body()
try:
event = verify_webhook(payload, stripe_signature)
except BillingError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
handled = handle_webhook_event(event)
return {"received": True, "handled": handled}


@router.get("/plan")
def get_plan(user_id: int = Depends(require_user)) -> dict:
"""Current tier + usage for the authenticated user."""
return plan_summary(user_id)
15 changes: 15 additions & 0 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@

from fastapi import FastAPI, Header, HTTPException, Response, status

from api.billing import router as billing_router
from api.routes import router
from api.security import add_security_headers
from api.waitlist import landing_origin
from api.waitlist import router as waitlist_router
from db.session import init_db
from utils.env import env_bool, env_int
from utils.logging_setup import configure as configure_logging
Expand All @@ -42,6 +45,18 @@ def create_app() -> FastAPI:
version="1.0.0",
)
app.include_router(router)
app.include_router(billing_router)
app.include_router(waitlist_router)
# CORS only for the public waitlist endpoint, scoped to the marketing-site
# origin (LANDING_ORIGIN). The authenticated API is same-origin / token-based
# and needs no CORS.
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=[landing_origin()],
allow_methods=["POST"],
allow_headers=["Content-Type"],
)
add_security_headers(app)

@app.get("/healthz")
Expand Down
12 changes: 7 additions & 5 deletions api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
save_analysis,
)
from services.auth import get_user
from services.billing import TierLimitExceeded, clamp_model
from services.master_cv import MasterCVError, get_master_cv, save_master_cv
from services.rate_limit import RateLimitExceeded
from services.usage import BudgetExceeded
Expand Down Expand Up @@ -129,22 +130,23 @@ def post_analyze(
}

# Enforce the same cost controls as the web/worker paths BEFORE any tokens
# are spent: request-count rate limit + rolling spend budget. Map to the
# conventional HTTP statuses (429 too-many, 402 payment-required).
# are spent: request-count rate limit + spend budget + tier quota. Map to
# the conventional HTTP statuses (429 too-many, 402 payment-required).
try:
check_user_quota(user_id)
except RateLimitExceeded as exc:
raise HTTPException(status_code=429, detail=str(exc)) from exc
except BudgetExceeded as exc:
except (BudgetExceeded, TierLimitExceeded) as exc:
raise HTTPException(status_code=402, detail=str(exc)) from exc

# run_analysis_sync opens the usage-accounting scope so this run's LLM
# tokens/cost are attributed to the caller (the direct run_analysis call
# would ledger them with a NULL owner and skip the budget).
# would ledger them with a NULL owner and skip the budget). clamp_model
# downgrades "detailed" for tiers without detailed-model access.
result = run_analysis_sync(
body.job_posting,
manual_inputs=manual,
model=body.model,
model=clamp_model(user_id, body.model),
resume_text=body.resume_text,
user_id=user_id,
)
Expand Down
39 changes: 39 additions & 0 deletions api/waitlist.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Public waitlist endpoint for the marketing site.

Unauthenticated by design — the landing page (a different origin) POSTs an
email here. CORS is opened narrowly to the configured site origin
(``LANDING_ORIGIN``, default ``*`` for dev). Errors are mapped to clean codes;
duplicates are a 200 (idempotent), bad emails 400, rate-limit 429.
"""

from __future__ import annotations

import os

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

from services.rate_limit import RateLimitExceeded
from services.waitlist import WaitlistError, join_waitlist

router = APIRouter()


class WaitlistRequest(BaseModel):
email: str = Field(min_length=3, max_length=255)
source: str = Field(default="", max_length=64)


def landing_origin() -> str:
return os.getenv("LANDING_ORIGIN", "*")


@router.post("/waitlist")
def post_waitlist(body: WaitlistRequest) -> dict:
try:
result = join_waitlist(body.email, source=body.source)
except WaitlistError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except RateLimitExceeded as exc:
raise HTTPException(status_code=429, detail=str(exc)) from exc
return {"ok": result.ok, "already": result.already}
Loading
Loading