Spaces:
Paused

github-actions[bot] commited on
Commit
1fe7075
·
1 Parent(s): b3aa1b4

Automated Deploy: 23110475c742a5d4f03930b55bca09042215c1dd

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. Dockerfile +65 -0
  3. README.md +7 -5
  4. apps/prevision-api/.env.example +12 -0
  5. apps/prevision-api/.gitignore +4 -0
  6. apps/prevision-api/.oxlintrc.json +10 -0
  7. apps/prevision-api/README.md +82 -0
  8. apps/prevision-api/nest-cli.json +8 -0
  9. apps/prevision-api/package.json +66 -0
  10. apps/prevision-api/prisma.config.ts +9 -0
  11. apps/prevision-api/prisma/catalog.json +699 -0
  12. apps/prevision-api/prisma/migrations/20261003131649_init/migration.sql +74 -0
  13. apps/prevision-api/prisma/migrations/20261003143919_subscriptions/migration.sql +41 -0
  14. apps/prevision-api/prisma/migrations/migration_lock.toml +3 -0
  15. apps/prevision-api/prisma/schema.prisma +108 -0
  16. apps/prevision-api/src/app.module.ts +27 -0
  17. apps/prevision-api/src/app.setup.ts +28 -0
  18. apps/prevision-api/src/catalog/catalog.module.ts +11 -0
  19. apps/prevision-api/src/catalog/catalog.service.ts +38 -0
  20. apps/prevision-api/src/catalog/interfaces/catalog-entry.interface.ts +13 -0
  21. apps/prevision-api/src/clerk/clerk.module.ts +8 -0
  22. apps/prevision-api/src/clerk/clerk.service.spec.ts +41 -0
  23. apps/prevision-api/src/clerk/clerk.service.ts +62 -0
  24. apps/prevision-api/src/clerk/interfaces/clerk.interface.ts +9 -0
  25. apps/prevision-api/src/common/dto/paginated.dto.ts +15 -0
  26. apps/prevision-api/src/common/dto/pagination-query.dto.ts +22 -0
  27. apps/prevision-api/src/common/exceptions/app.exception.ts +14 -0
  28. apps/prevision-api/src/common/filters/http-exception.filter.spec.ts +37 -0
  29. apps/prevision-api/src/common/filters/http-exception.filter.ts +42 -0
  30. apps/prevision-api/src/common/interceptors/response.interceptor.spec.ts +26 -0
  31. apps/prevision-api/src/common/interceptors/response.interceptor.ts +18 -0
  32. apps/prevision-api/src/common/interfaces/api-response.interface.ts +17 -0
  33. apps/prevision-api/src/common/utils/bearer-token.ts +6 -0
  34. apps/prevision-api/src/config/app-config.interface.ts +39 -0
  35. apps/prevision-api/src/config/app-config.spec.ts +50 -0
  36. apps/prevision-api/src/config/app-config.ts +88 -0
  37. apps/prevision-api/src/config/config.module.ts +9 -0
  38. apps/prevision-api/src/generations/allowance.spec.ts +28 -0
  39. apps/prevision-api/src/generations/allowance.ts +17 -0
  40. apps/prevision-api/src/generations/dto/create-generation.dto.ts +11 -0
  41. apps/prevision-api/src/generations/dto/generation-created.dto.ts +6 -0
  42. apps/prevision-api/src/generations/dto/usage.dto.ts +10 -0
  43. apps/prevision-api/src/generations/generations.controller.ts +23 -0
  44. apps/prevision-api/src/generations/generations.module.ts +11 -0
  45. apps/prevision-api/src/generations/generations.service.spec.ts +87 -0
  46. apps/prevision-api/src/generations/generations.service.ts +71 -0
  47. apps/prevision-api/src/generations/guards/internal-token.guard.spec.ts +30 -0
  48. apps/prevision-api/src/generations/guards/internal-token.guard.ts +32 -0
  49. apps/prevision-api/src/generations/interfaces/allowance.interface.ts +11 -0
  50. apps/prevision-api/src/health/health.controller.ts +22 -0
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.jpg filter=lfs diff=lfs merge=lfs -text
37
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
38
+ *.png filter=lfs diff=lfs merge=lfs -text
39
+ *.webp filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:22-slim AS prevision-api
2
+ WORKDIR /repo
3
+ RUN corepack enable
4
+ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
5
+ COPY apps/prevision-api/package.json apps/prevision-api/
6
+ RUN pnpm install --frozen-lockfile --filter @prevision/api
7
+ COPY apps/prevision-api/ apps/prevision-api/
8
+ RUN pnpm --filter @prevision/api generate && \
9
+ pnpm --filter @prevision/api build && \
10
+ pnpm --filter @prevision/api deploy --prod --legacy /out
11
+
12
+ FROM python:3.12-slim
13
+
14
+ # A Space exposes one port (7860), so nginx owns it and the renderer moves to 7861.
15
+ ENV PYTHONUNBUFFERED=1 \
16
+ PYTHONDONTWRITEBYTECODE=1 \
17
+ HF_HOME=/home/user/.cache/huggingface \
18
+ VISUALIZER_CONFIG=visualizer.gpu.toml \
19
+ VISUALIZER_PORT=7861 \
20
+ PREVISION_API_PORT=8001 \
21
+ PREVISION_API_INTERNAL_URL=http://127.0.0.1:8001 \
22
+ AUTH_ENFORCEMENT=on \
23
+ PROCESSING_TOKEN_AUDIENCE=prevision-processing \
24
+ HOME=/home/user
25
+
26
+ RUN apt-get update && \
27
+ apt-get install -y --no-install-recommends \
28
+ bash \
29
+ curl \
30
+ git \
31
+ git-lfs \
32
+ procps \
33
+ wget \
34
+ ffmpeg \
35
+ libglib2.0-0 \
36
+ libgomp1 \
37
+ build-essential \
38
+ ca-certificates \
39
+ nginx && \
40
+ rm -rf /var/lib/apt/lists/*
41
+
42
+ RUN useradd -m -u 1000 user
43
+
44
+ WORKDIR /app
45
+
46
+ COPY apps/renderer/requirements-base.txt apps/renderer/requirements-gpu-cu126.txt ./
47
+ RUN pip install --no-cache-dir --upgrade pip && \
48
+ pip install --no-cache-dir -r requirements-gpu-cu126.txt
49
+
50
+ COPY --chown=user:1000 apps/renderer/ /app/
51
+
52
+ COPY --from=prevision-api /usr/local/bin/node /usr/local/bin/node
53
+ COPY --chown=user:1000 --from=prevision-api /out /srv/prevision
54
+ COPY infra/runpod/start.sh /usr/local/bin/start-services
55
+ COPY infra/huggingface/start.sh /usr/local/bin/start-space
56
+ COPY infra/huggingface/nginx.conf /etc/prevision/nginx.conf
57
+ RUN chmod 0755 /usr/local/bin/start-services /usr/local/bin/start-space && \
58
+ mkdir -p data/uploads data/jobs data/qa-runs && \
59
+ chown -R user:1000 /app /srv/prevision
60
+
61
+ USER user
62
+
63
+ EXPOSE 7860
64
+
65
+ CMD ["/usr/local/bin/start-space"]
README.md CHANGED
@@ -1,11 +1,13 @@
1
  ---
2
  title: Prevision
3
- emoji: 🐨
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: docker
 
7
  pinned: false
8
- license: mit
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
  ---
2
  title: Prevision
3
+ emoji: 🏠
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
+ short_description: Prevision account API and GPU room renderer
10
  ---
11
 
12
+ Deployed from the PREVISION repository by the `Deploy Hugging Face Space` GitHub workflow.
13
+ `/api/*` is the account API; every other path is the renderer.
apps/prevision-api/.env.example ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ENVIRONMENT=development
2
+ PREVISION_DATABASE_URL=postgresql://postgres:postgres@localhost:55432/prevision_dev
3
+ PREVISION_API_PORT=8001
4
+ PREVISION_ALLOWED_ORIGINS=http://localhost:5173
5
+ PREVISION_APP_URL=http://localhost:5173
6
+ CLERK_SECRET_KEY=replace-with-development-clerk-secret
7
+ PROCESSING_TOKEN_SECRET=local-development-processing-secret-change-me
8
+ PROCESSING_TOKEN_AUDIENCE=prevision-processing
9
+ STRIPE_SECRET_KEY=replace-with-stripe-test-secret
10
+ STRIPE_WEBHOOK_SECRET=replace-with-webhook-signing-secret
11
+ STRIPE_PRICE_STARTER=replace-with-starter-price-id
12
+ STRIPE_PRICE_GROWTH=replace-with-growth-price-id
apps/prevision-api/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ src/generated/
2
+ dist/
3
+ .env
4
+ *.tsbuildinfo
apps/prevision-api/.oxlintrc.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
3
+ "rules": {
4
+ "typescript/no-explicit-any": "off",
5
+ "typescript/no-floating-promises": "error"
6
+ },
7
+ "env": {
8
+ "node": true
9
+ }
10
+ }
apps/prevision-api/README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prevision API
2
+
3
+ NestJS 12 + Prisma 7 (PostgreSQL). Serves the Prevision web app at `/api/*`:
4
+
5
+ | Route | |
6
+ |---|---|
7
+ | `GET /api/me` | the signed-in account and its free tries `{limit, used, remaining}` |
8
+ | `GET /api/tiles`, `/api/tiles/facets`, `/api/tiles/:slug` | the studio's tile library (paginated list, facet counts, one tile) |
9
+ | `POST /api/processing-token` | a 10-minute token for the renderer (issuer `prevision-api`) |
10
+ | `POST /internal/generations`, `/internal/generations/:id/refund` | the renderer charging and refunding a free try (internal token) |
11
+ | `GET /api/subscriptions/current` | the active plan, or null |
12
+ | `POST /api/subscriptions/checkout` `{plan}` | a Stripe Checkout URL for Starter or Growth |
13
+ | `POST /api/subscriptions/portal` | a Stripe billing portal URL |
14
+ | `POST /api/webhooks/stripe` | Stripe events (signature checked), keeps `subscriptions` in sync |
15
+ | `GET /health`, `/ready` | liveness, database readiness |
16
+
17
+ ## Responses
18
+
19
+ Success: `{ "success": true, "data": ..., "meta"?: { "page", "pageSize", "total", "totalPages" } }` (`meta` on paginated lists). Error: `{ "success": false, "error": { "code", "message" } }`. `ResponseInterceptor` and `HttpExceptionFilter` in `src/common` produce both.
20
+
21
+ ## Layout
22
+
23
+ ```
24
+ src/
25
+ common/ interceptors, filters, exceptions, pagination DTOs, shared interfaces
26
+ config/ env loading (APP_CONFIG) and its interface
27
+ prisma/ PrismaService, soft-delete extension
28
+ clerk/ Clerk token verification and profile lookup
29
+ users/ account from a Clerk sign-in, ClerkAuthGuard, GET /me
30
+ generations/ free tries (renderer charges/refunds via /internal)
31
+ catalog/ seeds the tiles table from prisma/catalog.json
32
+ tiles/ tile library reads
33
+ scripts/ seed-catalog, set-user-role (run from dist/)
34
+ rendering/ renderer processing tokens
35
+ stripe/ the shared Stripe client
36
+ subscriptions/ checkout, billing portal, current plan; the only writer of subscriptions
37
+ webhooks/ Stripe webhook: signature guard, event → subscription sync
38
+ health/ /health, /ready
39
+ test/ e2e specs per feature (real Postgres)
40
+ ```
41
+
42
+ ## Auth
43
+
44
+ Clerk owns sign-in. Every `/api` route needs `Authorization: Bearer <Clerk session token>`; `ClerkAuthGuard` verifies it (signature, expiry, `azp` in `PREVISION_ALLOWED_ORIGINS`) and loads the account, creating it on the first request. No waitlist, approval or onboarding.
45
+
46
+ `CLERK_SECRET_KEY` is a comma-separated list, one key per Clerk instance (staging: `sk_live_…,sk_test_…`). `ClerkService` accepts a token signed by any of them and looks a new user up in whichever instance owns it, so the custom domain (production instance) and `vercel.app` previews (development instance) share one API. Accounts are matched by Clerk id, then by verified email, so the same person signing in through both instances gets one account.
47
+
48
+ ## Free tries
49
+
50
+ Each account gets `FREE_GENERATIONS` (10) room-photo visualizations; admins are unlimited. The renderer calls `POST /internal/generations` before accepting a job from a Prevision token; `GenerationsService.create` locks the user row, counts `generations` without `refunded_at` and answers 402 `NO_FREE_TRIES` at the limit. A failed job is refunded once (`refunded_at`). Sample rooms are never charged.
51
+
52
+ ## Billing (Stripe)
53
+
54
+ Plans: Starter $70/month (`STARTER_MONTHLY_GENERATIONS`, 150) and Growth $140/month (`GROWTH_MONTHLY_GENERATIONS`, 600). `subscriptions/` creates Checkout sessions (Prevision branding, USD only) and billing-portal sessions; `webhooks/` verifies the signature on the raw body and re-syncs the subscription from Stripe for `checkout.session.completed` and `customer.subscription.created|updated|deleted`. The allowance (`generations/allowance.ts`) is: admin unlimited, active subscription = monthly plan limit since `current_period_start`, otherwise the lifetime free tries.
55
+
56
+ Local testing: `stripe listen --forward-to localhost:<port>/api/webhooks/stripe` and put the printed `whsec_…` in `STRIPE_WEBHOOK_SECRET`; pay with card `4242 4242 4242 4242`. Staging's endpoint is `we_1UMUCpFuPzalTB3Q6226EaDs` (pod :8001); its secrets come from `STRIPE_SECRET_KEY_STAGING` / `STRIPE_WEBHOOK_SECRET_STAGING`.
57
+
58
+ ## Database
59
+
60
+ Prevision has its own database (`PREVISION_DATABASE_URL`, Supabase project `mceapsmuhgupvksxmtis` on staging, session pooler URL), fully owned by Prisma: `users` (with `role`: `user` or `admin`, `stripe_customer_id`), `subscriptions`, `generations` and `tiles`. Migrations live in `prisma/migrations`; RLS is enabled on every table. The tiles are the 19 shared demo tiles in `prisma/catalog.json`, upserted on every start. Users and tiles are soft-deleted (`deleted_at`), never removed; `PrismaService.db` hides them automatically.
61
+
62
+ ## Admins
63
+
64
+ No admin panel: an admin is a user with `role = admin`, which removes the free-try limit. After the person has signed in once: `pnpm build && pnpm user:role <email> admin` (or `user` to revert), with `PREVISION_DATABASE_URL` set.
65
+
66
+ ## Commands
67
+
68
+ ```bash
69
+ pnpm dev # nest start --watch, port PREVISION_API_PORT (8001)
70
+ pnpm generate # prisma generate (turbo runs it before build, lint and test)
71
+ pnpm build # nest build
72
+ pnpm lint # oxlint + tsc
73
+ pnpm test # unit + e2e (real Postgres; TEST_DATABASE_URL, default localhost:55432/prevision_api_test)
74
+ pnpm db:migrate # prisma migrate dev (review the SQL; enable RLS on new tables)
75
+ pnpm db:deploy # prisma migrate deploy (the pod runs this on start)
76
+ ```
77
+
78
+ Local `.env` (git-ignored): `PREVISION_DATABASE_URL`, `CLERK_SECRET_KEY` (comma-separated to accept several Clerk instances, e.g. `sk_live_…,sk_test_…`), `PROCESSING_TOKEN_SECRET`, `PREVISION_ALLOWED_ORIGINS`, `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_PRICE_STARTER`, `STRIPE_PRICE_GROWTH`, optionally `PREVISION_API_PORT`, `PREVISION_APP_URL`, `STRIPE_LOGO_URL`, `STRIPE_PORTAL_CONFIGURATION_ID`, `CLERK_JWT_KEY`. Full list: `src/config/app-config.ts`.
79
+
80
+ ## Deployment
81
+
82
+ See [the deployment runbook](../../docs/DEPLOYMENT.md). Backend builds and deployments are manual.
apps/prevision-api/nest-cli.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json.schemastore.org/nest-cli",
3
+ "collection": "@nestjs/schematics",
4
+ "sourceRoot": "src",
5
+ "compilerOptions": {
6
+ "deleteOutDir": true
7
+ }
8
+ }
apps/prevision-api/package.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@prevision/api",
3
+ "version": "0.0.0",
4
+ "description": "Prevision API: Clerk sign-in, free visualizer tries, the tile catalog and renderer tokens.",
5
+ "private": true,
6
+ "type": "module",
7
+ "files": [
8
+ "dist",
9
+ "prisma",
10
+ "prisma.config.ts"
11
+ ],
12
+ "scripts": {
13
+ "build": "nest build",
14
+ "start": "nest start",
15
+ "start:dev": "nest start --watch",
16
+ "start:debug": "nest start --debug --watch",
17
+ "start:prod": "node dist/main",
18
+ "lint": "oxlint --type-aware src/ test/ && tsc --noEmit -p tsconfig.json",
19
+ "test": "vitest run && vitest run --config ./vitest.config.e2e.ts",
20
+ "test:watch": "vitest",
21
+ "test:cov": "vitest run --coverage",
22
+ "test:debug": "vitest --inspect-brk --no-file-parallelism",
23
+ "test:e2e": "vitest run --config ./vitest.config.e2e.ts",
24
+ "dev": "nest start --watch",
25
+ "test:unit": "vitest run",
26
+ "db:migrate": "prisma migrate dev",
27
+ "db:deploy": "prisma migrate deploy",
28
+ "generate": "prisma generate",
29
+ "db:seed": "node dist/scripts/seed-catalog.js",
30
+ "user:role": "node dist/scripts/set-user-role.js"
31
+ },
32
+ "dependencies": {
33
+ "@clerk/backend": "^3.22.0",
34
+ "@nestjs/common": "^12.0.1",
35
+ "@nestjs/core": "^12.0.1",
36
+ "@nestjs/platform-express": "^12.0.1",
37
+ "@prisma/adapter-pg": "^7.10.0",
38
+ "@prisma/client": "^7.10.0",
39
+ "class-transformer": "^0.5.1",
40
+ "class-validator": "^0.15.1",
41
+ "dotenv": "^18.0.5",
42
+ "jose": "^6.2.12",
43
+ "pg": "^8.23.1",
44
+ "prisma": "^7.10.0",
45
+ "reflect-metadata": "^0.2.2",
46
+ "rxjs": "^7.8.1",
47
+ "stripe": "^23.0.0"
48
+ },
49
+ "devDependencies": {
50
+ "@nestjs/cli": "^12.0.0",
51
+ "@nestjs/schematics": "^12.0.0",
52
+ "@nestjs/testing": "^12.0.1",
53
+ "@types/express": "^5.0.0",
54
+ "@types/node": "^24.0.0",
55
+ "@types/pg": "^8.23.1",
56
+ "@types/supertest": "^7.0.0",
57
+ "@vitest/coverage-v8": "^4.1.2",
58
+ "oxlint": "^1.58.0",
59
+ "oxlint-tsgolint": "^7.0.2001",
60
+ "prettier": "^3.4.2",
61
+ "supertest": "^7.0.0",
62
+ "typescript": "^6.0.2",
63
+ "vite": "^8.3.2",
64
+ "vitest": "^4.1.2"
65
+ }
66
+ }
apps/prevision-api/prisma.config.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import 'dotenv/config';
2
+ import { defineConfig } from 'prisma/config';
3
+
4
+ export default defineConfig({
5
+ schema: 'prisma/schema.prisma',
6
+ migrations: { path: 'prisma/migrations' },
7
+ // `prisma generate` needs no database; migrate commands fail clearly without one.
8
+ datasource: { url: process.env.PREVISION_DATABASE_URL ?? '' },
9
+ });
apps/prevision-api/prisma/catalog.json ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tiles": [
3
+ {
4
+ "slug": "black-marble-herringbone",
5
+ "name": "Black Marble Herringbone",
6
+ "collection": null,
7
+ "surfaces": [
8
+ "floor"
9
+ ],
10
+ "widthMm": 75,
11
+ "heightMm": 300,
12
+ "position": 11,
13
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-marble-herringbone/image-57508b5a7b735517.jpg",
14
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-marble-herringbone/thumbnail-57508b5a7b735517.jpg",
15
+ "assets": {},
16
+ "render": {
17
+ "scale": 1,
18
+ "keywords": [
19
+ "floor"
20
+ ],
21
+ "tileWidthInches": 3,
22
+ "tileHeightInches": 12,
23
+ "patternWidthInches": 48,
24
+ "patternHeightInches": 48,
25
+ "tileWidthMeters": 0.075,
26
+ "tileHeightMeters": 0.3,
27
+ "patternWidthMeters": 1.2,
28
+ "patternHeightMeters": 1.2,
29
+ "patternUnit": "multi-tile",
30
+ "groutWidthMeters": 0,
31
+ "layout": "grid",
32
+ "roughness": 0.3,
33
+ "reflectivity": 0.28,
34
+ "normalStrength": 0.1,
35
+ "roughnessMapStrength": 0.2,
36
+ "specularStrength": 0.38,
37
+ "tileVariationStrength": 0.04
38
+ }
39
+ },
40
+ {
41
+ "slug": "black-white-encaustic",
42
+ "name": "Black White Encaustic",
43
+ "collection": null,
44
+ "surfaces": [
45
+ "floor"
46
+ ],
47
+ "widthMm": 200,
48
+ "heightMm": 200,
49
+ "position": 8,
50
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-encaustic/image-016f0dba398638a3.jpg",
51
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-encaustic/thumbnail-016f0dba398638a3.jpg",
52
+ "assets": {},
53
+ "render": {
54
+ "scale": 1,
55
+ "keywords": [
56
+ "floor"
57
+ ],
58
+ "tileWidthInches": 8,
59
+ "tileHeightInches": 8,
60
+ "patternWidthInches": 16,
61
+ "patternHeightInches": 16,
62
+ "tileWidthMeters": 0.2,
63
+ "tileHeightMeters": 0.2,
64
+ "patternWidthMeters": 0.4,
65
+ "patternHeightMeters": 0.4,
66
+ "patternUnit": "multi-tile",
67
+ "groutWidthMeters": 0,
68
+ "layout": "grid",
69
+ "roughness": 0.64,
70
+ "reflectivity": 0.04,
71
+ "tileVariationStrength": 0.1
72
+ }
73
+ },
74
+ {
75
+ "slug": "black-white-marble-checker",
76
+ "name": "Black White Marble Checkered",
77
+ "collection": null,
78
+ "surfaces": [
79
+ "floor"
80
+ ],
81
+ "widthMm": 300,
82
+ "heightMm": 300,
83
+ "position": 2,
84
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-marble-checker/image-d3bef9925d890c2d.jpg",
85
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-marble-checker/thumbnail-d3bef9925d890c2d.jpg",
86
+ "assets": {},
87
+ "render": {
88
+ "scale": 1,
89
+ "keywords": [
90
+ "floor"
91
+ ],
92
+ "tileWidthInches": 12,
93
+ "tileHeightInches": 12,
94
+ "patternWidthInches": 72,
95
+ "patternHeightInches": 72,
96
+ "tileWidthMeters": 0.3,
97
+ "tileHeightMeters": 0.3,
98
+ "patternWidthMeters": 1.8,
99
+ "patternHeightMeters": 1.8,
100
+ "patternUnit": "multi-tile",
101
+ "groutWidthMeters": 0,
102
+ "layout": "diamond",
103
+ "roughness": 0.34,
104
+ "reflectivity": 0.24,
105
+ "normalStrength": 0.08,
106
+ "roughnessMapStrength": 0.2,
107
+ "specularStrength": 0.36,
108
+ "tileVariationStrength": 0.06
109
+ }
110
+ },
111
+ {
112
+ "slug": "circular-geometric-marble",
113
+ "name": "Circular Geometric Marble",
114
+ "collection": null,
115
+ "surfaces": [
116
+ "floor"
117
+ ],
118
+ "widthMm": 300,
119
+ "heightMm": 300,
120
+ "position": 1,
121
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/circular-geometric-marble/image-7b161b5b7f104f51.jpg",
122
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/circular-geometric-marble/thumbnail-7b161b5b7f104f51.jpg",
123
+ "assets": {},
124
+ "render": {
125
+ "scale": 1,
126
+ "keywords": [
127
+ "floor"
128
+ ],
129
+ "tileWidthInches": 12,
130
+ "tileHeightInches": 12,
131
+ "patternWidthInches": 72,
132
+ "patternHeightInches": 72,
133
+ "tileWidthMeters": 0.3,
134
+ "tileHeightMeters": 0.3,
135
+ "patternWidthMeters": 1.8,
136
+ "patternHeightMeters": 1.8,
137
+ "patternUnit": "multi-tile",
138
+ "groutWidthMeters": 0,
139
+ "layout": "grid",
140
+ "roughness": 0.3,
141
+ "reflectivity": 0.25,
142
+ "normalStrength": 0.08,
143
+ "roughnessMapStrength": 0.18,
144
+ "specularStrength": 0.38,
145
+ "tileVariationStrength": 0.03
146
+ }
147
+ },
148
+ {
149
+ "slug": "extra-grey-checkerboard",
150
+ "name": "Grey Checkerboard",
151
+ "collection": null,
152
+ "surfaces": [
153
+ "floor"
154
+ ],
155
+ "widthMm": 300,
156
+ "heightMm": 300,
157
+ "position": 4,
158
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-grey-checkerboard/image-f6126641a925b7af.jpg",
159
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-grey-checkerboard/thumbnail-cf85253dd52c5391.webp",
160
+ "assets": {},
161
+ "render": {
162
+ "scale": 1,
163
+ "keywords": [
164
+ "floor"
165
+ ],
166
+ "tileWidthInches": 12,
167
+ "tileHeightInches": 12,
168
+ "patternWidthInches": 96,
169
+ "patternHeightInches": 96,
170
+ "tileWidthMeters": 0.3,
171
+ "tileHeightMeters": 0.3,
172
+ "patternWidthMeters": 2.4,
173
+ "patternHeightMeters": 2.4,
174
+ "patternUnit": "multi-tile",
175
+ "groutWidthMeters": 0,
176
+ "layout": "grid",
177
+ "roughness": 0.74,
178
+ "reflectivity": 0.07,
179
+ "tileVariationStrength": 0.14
180
+ }
181
+ },
182
+ {
183
+ "slug": "extra-light-marble",
184
+ "name": "Light Marble",
185
+ "collection": null,
186
+ "surfaces": [
187
+ "floor"
188
+ ],
189
+ "widthMm": 610,
190
+ "heightMm": 610,
191
+ "position": 6,
192
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-light-marble/image-2a845e5b7f1830cc.jpg",
193
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-light-marble/thumbnail-95b32fe1601db21c.webp",
194
+ "assets": {},
195
+ "render": {
196
+ "scale": 1,
197
+ "keywords": [
198
+ "floor"
199
+ ],
200
+ "tileWidthInches": 24,
201
+ "tileHeightInches": 24,
202
+ "patternWidthInches": 48,
203
+ "patternHeightInches": 48
204
+ }
205
+ },
206
+ {
207
+ "slug": "extra-ornate-cement",
208
+ "name": "Ornate Cement",
209
+ "collection": null,
210
+ "surfaces": [
211
+ "floor"
212
+ ],
213
+ "widthMm": 200,
214
+ "heightMm": 200,
215
+ "position": 5,
216
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-ornate-cement/image-85cfc6cd1e75ac1c.jpg",
217
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-ornate-cement/thumbnail-be398c51ce9f9b08.webp",
218
+ "assets": {},
219
+ "render": {
220
+ "scale": 1,
221
+ "keywords": [
222
+ "floor"
223
+ ],
224
+ "tileWidthInches": 8,
225
+ "tileHeightInches": 8,
226
+ "patternWidthInches": 72,
227
+ "patternHeightInches": 72,
228
+ "tileWidthMeters": 0.2,
229
+ "tileHeightMeters": 0.2,
230
+ "patternWidthMeters": 1.8,
231
+ "patternHeightMeters": 1.8,
232
+ "patternUnit": "multi-tile",
233
+ "groutWidthMeters": 0,
234
+ "layout": "grid",
235
+ "roughness": 0.78,
236
+ "reflectivity": 0.06,
237
+ "tileVariationStrength": 0.14
238
+ }
239
+ },
240
+ {
241
+ "slug": "green-white-marble-inlay",
242
+ "name": "Green White Marble Inlay",
243
+ "collection": null,
244
+ "surfaces": [
245
+ "floor"
246
+ ],
247
+ "widthMm": 300,
248
+ "heightMm": 300,
249
+ "position": 9,
250
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/green-white-marble-inlay/image-62d3b131e38bd305.jpg",
251
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/green-white-marble-inlay/thumbnail-62d3b131e38bd305.jpg",
252
+ "assets": {},
253
+ "render": {
254
+ "scale": 1,
255
+ "keywords": [
256
+ "floor"
257
+ ],
258
+ "tileWidthInches": 12,
259
+ "tileHeightInches": 12,
260
+ "patternWidthInches": 96,
261
+ "patternHeightInches": 96,
262
+ "tileWidthMeters": 0.3,
263
+ "tileHeightMeters": 0.3,
264
+ "patternWidthMeters": 2.4,
265
+ "patternHeightMeters": 2.4,
266
+ "patternUnit": "multi-tile",
267
+ "groutWidthMeters": 0,
268
+ "layout": "grid",
269
+ "roughness": 0.28,
270
+ "reflectivity": 0.3,
271
+ "normalStrength": 0.08,
272
+ "roughnessMapStrength": 0.18,
273
+ "specularStrength": 0.4,
274
+ "tileVariationStrength": 0.02
275
+ }
276
+ },
277
+ {
278
+ "slug": "ivory-gold-marble-slab",
279
+ "name": "Ivory Gold Marble Slab",
280
+ "collection": null,
281
+ "surfaces": [
282
+ "floor"
283
+ ],
284
+ "widthMm": 1800,
285
+ "heightMm": 1200,
286
+ "position": 7,
287
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/image-9aeb915f6518f5ae.webp",
288
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/thumbnail-6a027fa9a7c66aea.webp",
289
+ "assets": {
290
+ "variantImages": [
291
+ "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/variant-1-0939d306001635bd.webp",
292
+ "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/variant-2-fb437c7012479a74.webp",
293
+ "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/variant-3-9aeb915f6518f5ae.webp"
294
+ ]
295
+ },
296
+ "render": {
297
+ "scale": 1,
298
+ "keywords": [
299
+ "floor"
300
+ ],
301
+ "tileWidthInches": 70.87,
302
+ "tileHeightInches": 47.24,
303
+ "patternWidthInches": 425.2,
304
+ "patternHeightInches": 188.98,
305
+ "tileWidthMeters": 1.8,
306
+ "tileHeightMeters": 1.2,
307
+ "patternWidthMeters": 10.8,
308
+ "patternHeightMeters": 4.8,
309
+ "patternUnit": "multi-tile",
310
+ "groutWidthMeters": 0,
311
+ "layout": "grid",
312
+ "roughness": 0.24,
313
+ "reflectivity": 0.34,
314
+ "normalStrength": 0.08,
315
+ "roughnessMapStrength": 0.2,
316
+ "specularStrength": 0.4,
317
+ "tileVariationStrength": 0.02
318
+ }
319
+ },
320
+ {
321
+ "slug": "marble-diamond-tile-floor-pbr0001",
322
+ "name": "Marble Diamond Tile Floor",
323
+ "collection": null,
324
+ "surfaces": [
325
+ "floor"
326
+ ],
327
+ "widthMm": 300,
328
+ "heightMm": 300,
329
+ "position": 12,
330
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/marble-diamond-tile-floor-pbr0001/image-cabfe7d334f03cae.jpg",
331
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/marble-diamond-tile-floor-pbr0001/thumbnail-cabfe7d334f03cae.jpg",
332
+ "assets": {},
333
+ "render": {
334
+ "scale": 1,
335
+ "keywords": [
336
+ "floor"
337
+ ],
338
+ "tileWidthInches": 12,
339
+ "tileHeightInches": 12,
340
+ "patternWidthInches": 60,
341
+ "patternHeightInches": 60,
342
+ "tileWidthMeters": 0.3,
343
+ "tileHeightMeters": 0.3,
344
+ "patternWidthMeters": 1.5,
345
+ "patternHeightMeters": 1.5,
346
+ "patternUnit": "multi-tile",
347
+ "groutWidthMeters": 0,
348
+ "layout": "grid",
349
+ "roughness": 0.34,
350
+ "reflectivity": 0.24,
351
+ "normalStrength": 0.1,
352
+ "heightStrength": 0.04,
353
+ "roughnessMapStrength": 0.2,
354
+ "specularStrength": 0.34,
355
+ "tileVariationStrength": 0.04
356
+ }
357
+ },
358
+ {
359
+ "slug": "old-french-fan-mosaic",
360
+ "name": "Old French Fan Mosaic",
361
+ "collection": null,
362
+ "surfaces": [
363
+ "floor"
364
+ ],
365
+ "widthMm": 38,
366
+ "heightMm": 38,
367
+ "position": 0,
368
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-french-fan-mosaic/image-175f1522576e9cd6.jpg",
369
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-french-fan-mosaic/thumbnail-175f1522576e9cd6.jpg",
370
+ "assets": {},
371
+ "render": {
372
+ "scale": 1,
373
+ "keywords": [
374
+ "floor"
375
+ ],
376
+ "tileWidthInches": 1.5,
377
+ "tileHeightInches": 1.5,
378
+ "patternWidthInches": 70.87,
379
+ "patternHeightInches": 94.49,
380
+ "tileWidthMeters": 0.038,
381
+ "tileHeightMeters": 0.038,
382
+ "patternWidthMeters": 1.8,
383
+ "patternHeightMeters": 2.4,
384
+ "patternUnit": "multi-tile",
385
+ "groutWidthMeters": 0,
386
+ "layout": "grid",
387
+ "roughness": 0.68,
388
+ "reflectivity": 0.05,
389
+ "normalStrength": 0.18,
390
+ "heightStrength": 0.06,
391
+ "roughnessMapStrength": 0.28,
392
+ "specularStrength": 0.12,
393
+ "tileVariationStrength": 0.04
394
+ }
395
+ },
396
+ {
397
+ "slug": "old-stone-star-medallion",
398
+ "name": "Old Stone Star Medallion",
399
+ "collection": null,
400
+ "surfaces": [
401
+ "floor"
402
+ ],
403
+ "widthMm": 600,
404
+ "heightMm": 600,
405
+ "position": 10,
406
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-stone-star-medallion/image-acfb1e7bee783454.jpg",
407
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-stone-star-medallion/thumbnail-acfb1e7bee783454.jpg",
408
+ "assets": {},
409
+ "render": {
410
+ "scale": 1,
411
+ "keywords": [
412
+ "floor"
413
+ ],
414
+ "tileWidthInches": 24,
415
+ "tileHeightInches": 24,
416
+ "patternWidthInches": 96,
417
+ "patternHeightInches": 96,
418
+ "tileWidthMeters": 0.6,
419
+ "tileHeightMeters": 0.6,
420
+ "patternWidthMeters": 2.4,
421
+ "patternHeightMeters": 2.4,
422
+ "patternUnit": "multi-tile",
423
+ "groutWidthMeters": 0,
424
+ "layout": "grid",
425
+ "roughness": 0.5,
426
+ "reflectivity": 0.12,
427
+ "normalStrength": 0.16,
428
+ "heightStrength": 0.05,
429
+ "roughnessMapStrength": 0.25,
430
+ "specularStrength": 0.18
431
+ }
432
+ },
433
+ {
434
+ "slug": "old-wooden-square-flooring-pbr0668",
435
+ "name": "Old Wooden Square Flooring",
436
+ "collection": null,
437
+ "surfaces": [
438
+ "floor"
439
+ ],
440
+ "widthMm": 300,
441
+ "heightMm": 300,
442
+ "position": 14,
443
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-wooden-square-flooring-pbr0668/image-50f823c4ada0839f.jpg",
444
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-wooden-square-flooring-pbr0668/thumbnail-50f823c4ada0839f.jpg",
445
+ "assets": {},
446
+ "render": {
447
+ "scale": 1,
448
+ "keywords": [
449
+ "floor"
450
+ ],
451
+ "tileWidthInches": 12,
452
+ "tileHeightInches": 12,
453
+ "patternWidthInches": 48,
454
+ "patternHeightInches": 48,
455
+ "tileWidthMeters": 0.3,
456
+ "tileHeightMeters": 0.3,
457
+ "patternWidthMeters": 1.2,
458
+ "patternHeightMeters": 1.2,
459
+ "patternUnit": "multi-tile",
460
+ "groutWidthMeters": 0,
461
+ "layout": "grid",
462
+ "roughness": 0.58,
463
+ "reflectivity": 0.08,
464
+ "normalStrength": 0.2,
465
+ "heightStrength": 0.08,
466
+ "roughnessMapStrength": 0.32,
467
+ "specularStrength": 0.12,
468
+ "tileVariationStrength": 0.08
469
+ }
470
+ },
471
+ {
472
+ "slug": "portuguese-tiles-pbr0674",
473
+ "name": "Portuguese Tiles",
474
+ "collection": null,
475
+ "surfaces": [
476
+ "floor"
477
+ ],
478
+ "widthMm": 200,
479
+ "heightMm": 200,
480
+ "position": 13,
481
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/portuguese-tiles-pbr0674/image-45e483c3b6506825.jpg",
482
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/portuguese-tiles-pbr0674/thumbnail-45e483c3b6506825.jpg",
483
+ "assets": {},
484
+ "render": {
485
+ "scale": 1,
486
+ "keywords": [
487
+ "floor"
488
+ ],
489
+ "tileWidthInches": 8,
490
+ "tileHeightInches": 8,
491
+ "patternWidthInches": 24,
492
+ "patternHeightInches": 24,
493
+ "tileWidthMeters": 0.2,
494
+ "tileHeightMeters": 0.2,
495
+ "patternWidthMeters": 0.6,
496
+ "patternHeightMeters": 0.6,
497
+ "patternUnit": "multi-tile",
498
+ "groutWidthMeters": 0,
499
+ "layout": "grid",
500
+ "roughness": 0.58,
501
+ "reflectivity": 0.1,
502
+ "normalStrength": 0.14,
503
+ "heightStrength": 0.05,
504
+ "roughnessMapStrength": 0.24,
505
+ "specularStrength": 0.14,
506
+ "tileVariationStrength": 0.03
507
+ }
508
+ },
509
+ {
510
+ "slug": "terracotta-ivory-marble-checker",
511
+ "name": "Terracotta Ivory Marble Checker",
512
+ "collection": null,
513
+ "surfaces": [
514
+ "floor"
515
+ ],
516
+ "widthMm": 300,
517
+ "heightMm": 300,
518
+ "position": 3,
519
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/terracotta-ivory-marble-checker/image-163cb191dc8ba5f4.jpg",
520
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/terracotta-ivory-marble-checker/thumbnail-163cb191dc8ba5f4.jpg",
521
+ "assets": {},
522
+ "render": {
523
+ "scale": 1,
524
+ "keywords": [
525
+ "floor"
526
+ ],
527
+ "tileWidthInches": 12,
528
+ "tileHeightInches": 12,
529
+ "patternWidthInches": 72,
530
+ "patternHeightInches": 72,
531
+ "tileWidthMeters": 0.3,
532
+ "tileHeightMeters": 0.3,
533
+ "patternWidthMeters": 1.8,
534
+ "patternHeightMeters": 1.8,
535
+ "patternUnit": "multi-tile",
536
+ "groutWidthMeters": 0,
537
+ "layout": "grid",
538
+ "roughness": 0.4,
539
+ "reflectivity": 0.18,
540
+ "normalStrength": 0.12,
541
+ "roughnessMapStrength": 0.24,
542
+ "specularStrength": 0.28,
543
+ "tileVariationStrength": 0.04
544
+ }
545
+ },
546
+ {
547
+ "slug": "versailles-parquet-floor-10-pbr0790",
548
+ "name": "Versailles Parquet Floor 10",
549
+ "collection": null,
550
+ "surfaces": [
551
+ "floor"
552
+ ],
553
+ "widthMm": 1000,
554
+ "heightMm": 1000,
555
+ "position": 15,
556
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/versailles-parquet-floor-10-pbr0790/image-a7260a9aeee7225e.jpg",
557
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/versailles-parquet-floor-10-pbr0790/thumbnail-a7260a9aeee7225e.jpg",
558
+ "assets": {},
559
+ "render": {
560
+ "scale": 0.5,
561
+ "keywords": [
562
+ "floor"
563
+ ],
564
+ "tileWidthInches": 39.37,
565
+ "tileHeightInches": 39.37,
566
+ "patternWidthInches": 157.48,
567
+ "patternHeightInches": 157.48,
568
+ "tileWidthMeters": 1,
569
+ "tileHeightMeters": 1,
570
+ "patternWidthMeters": 4,
571
+ "patternHeightMeters": 4,
572
+ "patternUnit": "multi-tile",
573
+ "groutWidthMeters": 0,
574
+ "layout": "grid",
575
+ "roughness": 0.36,
576
+ "reflectivity": 0.18,
577
+ "normalStrength": 0.16,
578
+ "heightStrength": 0.06,
579
+ "roughnessMapStrength": 0.24,
580
+ "specularStrength": 0.28,
581
+ "tileVariationStrength": 0.04
582
+ }
583
+ },
584
+ {
585
+ "slug": "wallpaper-olive-floral-damask",
586
+ "name": "Olive Floral Damask",
587
+ "collection": null,
588
+ "surfaces": [
589
+ "walls"
590
+ ],
591
+ "widthMm": 530,
592
+ "heightMm": 530,
593
+ "position": 196,
594
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-olive-floral-damask/image-3df71399fb8818a3.jpg",
595
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-olive-floral-damask/thumbnail-05467054368b5e42.jpg",
596
+ "assets": {},
597
+ "render": {
598
+ "scale": 1,
599
+ "keywords": [
600
+ "walls"
601
+ ],
602
+ "tileWidthInches": 20.866141732283467,
603
+ "tileHeightInches": 20.866141732283467,
604
+ "patternWidthInches": 20.866141732283467,
605
+ "patternHeightInches": 20.866141732283467,
606
+ "tileWidthMeters": 0.53,
607
+ "tileHeightMeters": 0.53,
608
+ "patternWidthMeters": 0.53,
609
+ "patternHeightMeters": 0.53,
610
+ "patternUnit": "material",
611
+ "groutWidthMeters": 0,
612
+ "layout": "grid",
613
+ "roughness": 0.86,
614
+ "reflectivity": 0.03,
615
+ "normalStrength": 0.02,
616
+ "heightStrength": 0,
617
+ "roughnessMapStrength": 0.05,
618
+ "specularStrength": 0.03,
619
+ "tileVariationStrength": 0
620
+ }
621
+ },
622
+ {
623
+ "slug": "wallpaper-sage-diamond-medallion",
624
+ "name": "Sage Diamond Medallion",
625
+ "collection": null,
626
+ "surfaces": [
627
+ "walls"
628
+ ],
629
+ "widthMm": 530,
630
+ "heightMm": 530,
631
+ "position": 195,
632
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-diamond-medallion/image-0138ff65535a726e.jpg",
633
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-diamond-medallion/thumbnail-4bf8d54ea97a2ab9.jpg",
634
+ "assets": {},
635
+ "render": {
636
+ "scale": 1,
637
+ "keywords": [
638
+ "walls"
639
+ ],
640
+ "tileWidthInches": 20.866141732283467,
641
+ "tileHeightInches": 20.866141732283467,
642
+ "patternWidthInches": 20.866141732283467,
643
+ "patternHeightInches": 20.866141732283467,
644
+ "tileWidthMeters": 0.53,
645
+ "tileHeightMeters": 0.53,
646
+ "patternWidthMeters": 0.53,
647
+ "patternHeightMeters": 0.53,
648
+ "patternUnit": "material",
649
+ "groutWidthMeters": 0,
650
+ "layout": "grid",
651
+ "roughness": 0.86,
652
+ "reflectivity": 0.03,
653
+ "normalStrength": 0.02,
654
+ "heightStrength": 0,
655
+ "roughnessMapStrength": 0.05,
656
+ "specularStrength": 0.03,
657
+ "tileVariationStrength": 0
658
+ }
659
+ },
660
+ {
661
+ "slug": "wallpaper-sage-ticking-stripe",
662
+ "name": "Sage Ticking Stripe",
663
+ "collection": null,
664
+ "surfaces": [
665
+ "walls"
666
+ ],
667
+ "widthMm": 530,
668
+ "heightMm": 530,
669
+ "position": 194,
670
+ "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-ticking-stripe/image-f841f9653591e1eb.jpg",
671
+ "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-ticking-stripe/thumbnail-d5d3ee999cab10ad.jpg",
672
+ "assets": {},
673
+ "render": {
674
+ "scale": 1,
675
+ "keywords": [
676
+ "walls"
677
+ ],
678
+ "tileWidthInches": 20.866141732283467,
679
+ "tileHeightInches": 20.866141732283467,
680
+ "patternWidthInches": 20.866141732283467,
681
+ "patternHeightInches": 20.866141732283467,
682
+ "tileWidthMeters": 0.53,
683
+ "tileHeightMeters": 0.53,
684
+ "patternWidthMeters": 0.53,
685
+ "patternHeightMeters": 0.53,
686
+ "patternUnit": "material",
687
+ "groutWidthMeters": 0,
688
+ "layout": "grid",
689
+ "roughness": 0.86,
690
+ "reflectivity": 0.03,
691
+ "normalStrength": 0.02,
692
+ "heightStrength": 0,
693
+ "roughnessMapStrength": 0.05,
694
+ "specularStrength": 0.03,
695
+ "tileVariationStrength": 0
696
+ }
697
+ }
698
+ ]
699
+ }
apps/prevision-api/prisma/migrations/20261003131649_init/migration.sql ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- CreateEnum
2
+ CREATE TYPE "user_role" AS ENUM ('user', 'admin');
3
+
4
+ -- CreateTable
5
+ CREATE TABLE "users" (
6
+ "id" UUID NOT NULL,
7
+ "clerk_user_id" VARCHAR(64) NOT NULL,
8
+ "email" VARCHAR(255) NOT NULL,
9
+ "name" VARCHAR(255),
10
+ "role" "user_role" NOT NULL DEFAULT 'user',
11
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
12
+ "updated_at" TIMESTAMPTZ NOT NULL,
13
+ "deleted_at" TIMESTAMPTZ,
14
+
15
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
16
+ );
17
+
18
+ -- CreateTable
19
+ CREATE TABLE "generations" (
20
+ "id" UUID NOT NULL,
21
+ "user_id" UUID NOT NULL,
22
+ "job_id" VARCHAR(64) NOT NULL,
23
+ "refunded_at" TIMESTAMPTZ,
24
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
25
+
26
+ CONSTRAINT "generations_pkey" PRIMARY KEY ("id")
27
+ );
28
+
29
+ -- CreateTable
30
+ CREATE TABLE "tiles" (
31
+ "id" UUID NOT NULL,
32
+ "slug" VARCHAR(120) NOT NULL,
33
+ "name" VARCHAR(255) NOT NULL,
34
+ "collection" VARCHAR(120),
35
+ "surfaces" VARCHAR(20)[],
36
+ "width_mm" INTEGER,
37
+ "height_mm" INTEGER,
38
+ "image_url" VARCHAR(1024) NOT NULL,
39
+ "thumbnail_url" VARCHAR(1024),
40
+ "assets" JSONB NOT NULL DEFAULT '{}',
41
+ "render" JSONB NOT NULL DEFAULT '{}',
42
+ "position" INTEGER,
43
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
44
+ "updated_at" TIMESTAMPTZ NOT NULL,
45
+ "deleted_at" TIMESTAMPTZ,
46
+
47
+ CONSTRAINT "tiles_pkey" PRIMARY KEY ("id")
48
+ );
49
+
50
+ -- CreateIndex
51
+ CREATE UNIQUE INDEX "users_clerk_user_id_key" ON "users"("clerk_user_id");
52
+
53
+ -- CreateIndex
54
+ CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
55
+
56
+ -- CreateIndex
57
+ CREATE UNIQUE INDEX "generations_job_id_key" ON "generations"("job_id");
58
+
59
+ -- CreateIndex
60
+ CREATE INDEX "generations_user_id_idx" ON "generations"("user_id");
61
+
62
+ -- CreateIndex
63
+ CREATE UNIQUE INDEX "tiles_slug_key" ON "tiles"("slug");
64
+
65
+ -- CreateIndex
66
+ CREATE INDEX "tiles_name_idx" ON "tiles"("name");
67
+
68
+ -- AddForeignKey
69
+ ALTER TABLE "generations" ADD CONSTRAINT "generations_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
70
+
71
+ -- No Supabase Data API access to these tables.
72
+ ALTER TABLE "users" ENABLE ROW LEVEL SECURITY;
73
+ ALTER TABLE "generations" ENABLE ROW LEVEL SECURITY;
74
+ ALTER TABLE "tiles" ENABLE ROW LEVEL SECURITY;
apps/prevision-api/prisma/migrations/20261003143919_subscriptions/migration.sql ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- CreateEnum
2
+ CREATE TYPE "subscription_plan" AS ENUM ('starter', 'growth');
3
+
4
+ -- CreateEnum
5
+ CREATE TYPE "subscription_status" AS ENUM ('incomplete', 'incomplete_expired', 'trialing', 'active', 'past_due', 'canceled', 'unpaid', 'paused');
6
+
7
+ -- AlterTable
8
+ ALTER TABLE "users" ADD COLUMN "stripe_customer_id" VARCHAR(64);
9
+
10
+ -- CreateTable
11
+ CREATE TABLE "subscriptions" (
12
+ "id" UUID NOT NULL,
13
+ "user_id" UUID NOT NULL,
14
+ "stripe_subscription_id" VARCHAR(64) NOT NULL,
15
+ "stripe_price_id" VARCHAR(64) NOT NULL,
16
+ "plan" "subscription_plan" NOT NULL,
17
+ "status" "subscription_status" NOT NULL,
18
+ "current_period_start" TIMESTAMPTZ NOT NULL,
19
+ "current_period_end" TIMESTAMPTZ NOT NULL,
20
+ "cancel_at_period_end" BOOLEAN NOT NULL DEFAULT false,
21
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
22
+ "updated_at" TIMESTAMPTZ NOT NULL,
23
+
24
+ CONSTRAINT "subscriptions_pkey" PRIMARY KEY ("id")
25
+ );
26
+
27
+ -- CreateIndex
28
+ CREATE UNIQUE INDEX "subscriptions_stripe_subscription_id_key" ON "subscriptions"("stripe_subscription_id");
29
+
30
+ -- CreateIndex
31
+ CREATE INDEX "subscriptions_user_id_status_idx" ON "subscriptions"("user_id", "status");
32
+
33
+ -- CreateIndex
34
+ CREATE UNIQUE INDEX "users_stripe_customer_id_key" ON "users"("stripe_customer_id");
35
+
36
+ -- AddForeignKey
37
+ ALTER TABLE "subscriptions" ADD CONSTRAINT "subscriptions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
38
+
39
+
40
+ -- No Supabase Data API access.
41
+ ALTER TABLE "subscriptions" ENABLE ROW LEVEL SECURITY;
apps/prevision-api/prisma/migrations/migration_lock.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Please do not edit this file manually
2
+ # It should be added in your version-control system (e.g., Git)
3
+ provider = "postgresql"
apps/prevision-api/prisma/schema.prisma ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ generator client {
2
+ provider = "prisma-client"
3
+ output = "../src/generated/prisma"
4
+ moduleFormat = "esm"
5
+ }
6
+
7
+ datasource db {
8
+ provider = "postgresql"
9
+ }
10
+
11
+ enum UserRole {
12
+ user
13
+ admin
14
+
15
+ @@map("user_role")
16
+ }
17
+
18
+ model User {
19
+ id String @id @default(uuid()) @db.Uuid
20
+ clerkUserId String @unique @map("clerk_user_id") @db.VarChar(64)
21
+ email String @unique @db.VarChar(255)
22
+ name String? @db.VarChar(255)
23
+ /// Admins have unlimited generations. Set with `pnpm user:role <email> admin`.
24
+ role UserRole @default(user)
25
+ stripeCustomerId String? @unique @map("stripe_customer_id") @db.VarChar(64)
26
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
27
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
28
+ deletedAt DateTime? @map("deleted_at") @db.Timestamptz
29
+ generations Generation[]
30
+ subscriptions Subscription[]
31
+
32
+ @@map("users")
33
+ }
34
+
35
+ enum SubscriptionPlan {
36
+ starter
37
+ growth
38
+
39
+ @@map("subscription_plan")
40
+ }
41
+
42
+ /// Mirrors Stripe's subscription statuses.
43
+ enum SubscriptionStatus {
44
+ incomplete
45
+ incomplete_expired
46
+ trialing
47
+ active
48
+ past_due
49
+ canceled
50
+ unpaid
51
+ paused
52
+
53
+ @@map("subscription_status")
54
+ }
55
+
56
+ /// A Stripe subscription, kept in sync by the Stripe webhook. Rows are never deleted.
57
+ model Subscription {
58
+ id String @id @default(uuid()) @db.Uuid
59
+ userId String @map("user_id") @db.Uuid
60
+ user User @relation(fields: [userId], references: [id], onDelete: Restrict)
61
+ stripeSubscriptionId String @unique @map("stripe_subscription_id") @db.VarChar(64)
62
+ stripePriceId String @map("stripe_price_id") @db.VarChar(64)
63
+ plan SubscriptionPlan
64
+ status SubscriptionStatus
65
+ currentPeriodStart DateTime @map("current_period_start") @db.Timestamptz
66
+ currentPeriodEnd DateTime @map("current_period_end") @db.Timestamptz
67
+ cancelAtPeriodEnd Boolean @default(false) @map("cancel_at_period_end")
68
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
69
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
70
+
71
+ @@index([userId, status])
72
+ @@map("subscriptions")
73
+ }
74
+
75
+ /// One room visualization the renderer accepted. Tries used = rows without refundedAt.
76
+ model Generation {
77
+ id String @id @default(uuid()) @db.Uuid
78
+ userId String @map("user_id") @db.Uuid
79
+ user User @relation(fields: [userId], references: [id], onDelete: Restrict)
80
+ jobId String @unique @map("job_id") @db.VarChar(64)
81
+ refundedAt DateTime? @map("refunded_at") @db.Timestamptz
82
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
83
+
84
+ @@index([userId])
85
+ @@map("generations")
86
+ }
87
+
88
+ /// The studio's material library: the shared demo tiles, seeded from prisma/catalog.json.
89
+ model Tile {
90
+ id String @id @default(uuid()) @db.Uuid
91
+ slug String @unique @db.VarChar(120)
92
+ name String @db.VarChar(255)
93
+ collection String? @db.VarChar(120)
94
+ surfaces String[] @db.VarChar(20)
95
+ widthMm Int? @map("width_mm")
96
+ heightMm Int? @map("height_mm")
97
+ imageUrl String @map("image_url") @db.VarChar(1024)
98
+ thumbnailUrl String? @map("thumbnail_url") @db.VarChar(1024)
99
+ assets Json @default("{}")
100
+ render Json @default("{}")
101
+ position Int?
102
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
103
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
104
+ deletedAt DateTime? @map("deleted_at") @db.Timestamptz
105
+
106
+ @@index([name])
107
+ @@map("tiles")
108
+ }
apps/prevision-api/src/app.module.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Module } from '@nestjs/common';
2
+ import { ConfigModule } from './config/config.module.js';
3
+ import { GenerationsModule } from './generations/generations.module.js';
4
+ import { HealthModule } from './health/health.module.js';
5
+ import { PrismaModule } from './prisma/prisma.module.js';
6
+ import { RenderingModule } from './rendering/rendering.module.js';
7
+ import { StripeModule } from './stripe/stripe.module.js';
8
+ import { SubscriptionsModule } from './subscriptions/subscriptions.module.js';
9
+ import { TilesModule } from './tiles/tiles.module.js';
10
+ import { UsersModule } from './users/users.module.js';
11
+ import { WebhooksModule } from './webhooks/webhooks.module.js';
12
+
13
+ @Module({
14
+ imports: [
15
+ ConfigModule,
16
+ PrismaModule,
17
+ StripeModule,
18
+ UsersModule,
19
+ GenerationsModule,
20
+ SubscriptionsModule,
21
+ WebhooksModule,
22
+ TilesModule,
23
+ RenderingModule,
24
+ HealthModule,
25
+ ],
26
+ })
27
+ export class AppModule {}
apps/prevision-api/src/app.setup.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { type INestApplication, RequestMethod, ValidationPipe } from '@nestjs/common';
2
+ import { HttpExceptionFilter } from './common/filters/http-exception.filter.js';
3
+ import { ResponseInterceptor } from './common/interceptors/response.interceptor.js';
4
+ import { APP_CONFIG, isOriginAllowed } from './config/app-config.js';
5
+ import type { AppConfig } from './config/app-config.interface.js';
6
+
7
+ /** Shared by main.ts and the e2e tests. */
8
+ export function setupApp(app: INestApplication): INestApplication {
9
+ const config = app.get<AppConfig>(APP_CONFIG);
10
+ app.setGlobalPrefix('api', {
11
+ exclude: [
12
+ { path: 'health', method: RequestMethod.GET },
13
+ { path: 'ready', method: RequestMethod.GET },
14
+ { path: 'internal/{*path}', method: RequestMethod.ALL },
15
+ ],
16
+ });
17
+ app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }));
18
+ app.useGlobalInterceptors(new ResponseInterceptor());
19
+ app.useGlobalFilters(new HttpExceptionFilter());
20
+ app.enableCors({
21
+ origin: (origin: string | undefined, done: (error: Error | null, allow?: boolean) => void) =>
22
+ done(null, !origin || isOriginAllowed(config, origin)),
23
+ methods: ['GET', 'POST'],
24
+ allowedHeaders: ['Authorization', 'Content-Type'],
25
+ maxAge: 600,
26
+ });
27
+ return app;
28
+ }
apps/prevision-api/src/catalog/catalog.module.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Module } from '@nestjs/common';
2
+ import { ConfigModule } from '../config/config.module.js';
3
+ import { PrismaModule } from '../prisma/prisma.module.js';
4
+ import { CatalogService } from './catalog.service.js';
5
+
6
+ @Module({
7
+ imports: [ConfigModule, PrismaModule],
8
+ providers: [CatalogService],
9
+ exports: [CatalogService],
10
+ })
11
+ export class CatalogModule {}
apps/prevision-api/src/catalog/catalog.service.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Injectable } from '@nestjs/common';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { PrismaService } from '../prisma/prisma.service.js';
4
+ import type { CatalogEntry } from './interfaces/catalog-entry.interface.js';
5
+
6
+ export const CATALOG_PATH = new URL('../../prisma/catalog.json', import.meta.url);
7
+
8
+ @Injectable()
9
+ export class CatalogService {
10
+ constructor(private readonly prisma: PrismaService) {}
11
+
12
+ async load(path: URL | string = CATALOG_PATH): Promise<CatalogEntry[]> {
13
+ return (JSON.parse(await readFile(path, 'utf8')) as { tiles: CatalogEntry[] }).tiles;
14
+ }
15
+
16
+ /**
17
+ * Inserts new tiles and refreshes existing ones in one statement. Entries without an
18
+ * image are skipped, and a soft-deleted tile is never brought back.
19
+ */
20
+ async seed(entries: CatalogEntry[]): Promise<number> {
21
+ const rows = entries.filter((entry) => entry.imageUrl);
22
+ if (!rows.length) return 0;
23
+ return this.prisma.db.$executeRaw`
24
+ INSERT INTO tiles (id, slug, name, collection, surfaces, width_mm, height_mm,
25
+ image_url, thumbnail_url, assets, render, position, updated_at)
26
+ SELECT gen_random_uuid(), slug, name, collection, surfaces, "widthMm", "heightMm",
27
+ "imageUrl", "thumbnailUrl", coalesce(assets, '{}'), coalesce(render, '{}'), position, now()
28
+ FROM jsonb_to_recordset(${JSON.stringify(rows)}::jsonb) AS entry(
29
+ slug text, name text, collection text, surfaces varchar(20)[], "widthMm" int, "heightMm" int,
30
+ "imageUrl" text, "thumbnailUrl" text, assets jsonb, render jsonb, position int)
31
+ ON CONFLICT (slug) DO UPDATE SET
32
+ name = excluded.name, collection = excluded.collection,
33
+ surfaces = excluded.surfaces, width_mm = excluded.width_mm, height_mm = excluded.height_mm,
34
+ image_url = excluded.image_url, thumbnail_url = excluded.thumbnail_url,
35
+ assets = excluded.assets, render = excluded.render, position = excluded.position, updated_at = now()
36
+ WHERE tiles.deleted_at IS NULL`;
37
+ }
38
+ }
apps/prevision-api/src/catalog/interfaces/catalog-entry.interface.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface CatalogEntry {
2
+ slug: string;
3
+ name: string;
4
+ collection: string | null;
5
+ surfaces: string[];
6
+ widthMm: number | null;
7
+ heightMm: number | null;
8
+ position: number | null;
9
+ imageUrl: string | null;
10
+ thumbnailUrl: string | null;
11
+ assets: Record<string, unknown>;
12
+ render: Record<string, unknown>;
13
+ }
apps/prevision-api/src/clerk/clerk.module.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import { Module } from '@nestjs/common';
2
+ import { ClerkService } from './clerk.service.js';
3
+
4
+ @Module({
5
+ providers: [ClerkService],
6
+ exports: [ClerkService],
7
+ })
8
+ export class ClerkModule {}
apps/prevision-api/src/clerk/clerk.service.spec.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createClerkClient, verifyToken } from '@clerk/backend';
2
+ import { testConfig } from '../../test/support/test-config.js';
3
+ import { ClerkService } from './clerk.service.js';
4
+
5
+ vi.mock('@clerk/backend', () => ({ verifyToken: vi.fn(), createClerkClient: vi.fn() }));
6
+
7
+ const config = testConfig({ clerk: { secretKeys: ['sk_live_prod', 'sk_test_dev'] } });
8
+ const getUser = { sk_live_prod: vi.fn(), sk_test_dev: vi.fn() };
9
+
10
+ describe('ClerkService', () => {
11
+ beforeEach(() => {
12
+ vi.mocked(createClerkClient).mockImplementation(
13
+ ({ secretKey }) => ({ users: { getUser: getUser[secretKey as keyof typeof getUser] } }) as never,
14
+ );
15
+ });
16
+
17
+ it('accepts a token from any configured instance', async () => {
18
+ vi.mocked(verifyToken)
19
+ .mockRejectedValueOnce(new Error('kid not found'))
20
+ .mockResolvedValueOnce({ sub: 'user_1', sid: 'sess_1', azp: 'http://app.test' } as never);
21
+ await expect(new ClerkService(config).verifySessionToken('token')).resolves.toEqual({ userId: 'user_1', sessionId: 'sess_1' });
22
+ expect(vi.mocked(verifyToken).mock.calls.map(([, options]) => options.secretKey)).toEqual(['sk_live_prod', 'sk_test_dev']);
23
+ });
24
+
25
+ it('refuses a token no instance signed, or from another origin', async () => {
26
+ vi.mocked(verifyToken).mockRejectedValue(new Error('invalid'));
27
+ await expect(new ClerkService(config).verifySessionToken('token')).rejects.toMatchObject({ status: 401 });
28
+ vi.mocked(verifyToken).mockResolvedValue({ sub: 'user_1', sid: 'sess_1', azp: 'https://evil.test' } as never);
29
+ await expect(new ClerkService(config).verifySessionToken('token')).rejects.toMatchObject({ status: 401 });
30
+ });
31
+
32
+ it('finds the user in whichever instance owns it', async () => {
33
+ getUser.sk_live_prod.mockRejectedValue(new Error('not found'));
34
+ getUser.sk_test_dev.mockResolvedValue({
35
+ firstName: 'Ann',
36
+ lastName: null,
37
+ primaryEmailAddress: { emailAddress: 'Ann@Example.com ', verification: { status: 'verified' } },
38
+ });
39
+ await expect(new ClerkService(config).getVerifiedProfile('user_1')).resolves.toEqual({ email: 'ann@example.com', name: 'Ann' });
40
+ });
41
+ });
apps/prevision-api/src/clerk/clerk.service.ts ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Inject, Injectable, Logger } from '@nestjs/common';
2
+ import { createClerkClient, verifyToken, type ClerkClient } from '@clerk/backend';
3
+ import { AppException, unauthenticated } from '../common/exceptions/app.exception.js';
4
+ import { APP_CONFIG, isOriginAllowed } from '../config/app-config.js';
5
+ import type { AppConfig } from '../config/app-config.interface.js';
6
+ import type { ClerkProfile, ClerkSession } from './interfaces/clerk.interface.js';
7
+
8
+ interface ClerkInstance {
9
+ secretKey: string;
10
+ client: ClerkClient;
11
+ }
12
+
13
+ @Injectable()
14
+ export class ClerkService {
15
+ private readonly logger = new Logger(ClerkService.name);
16
+ private readonly instances: ClerkInstance[];
17
+
18
+ constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) {
19
+ this.instances = config.clerk.secretKeys.map((secretKey) => ({ secretKey, client: createClerkClient({ secretKey }) }));
20
+ }
21
+
22
+ /** Signature, expiry and `azp` (the frontend origin that requested the token). */
23
+ async verifySessionToken(token: string): Promise<ClerkSession> {
24
+ const claims = await this.verifyWithAnyInstance(token);
25
+ if (!claims?.sub || !claims.sid || !isOriginAllowed(this.config, claims.azp)) throw unauthenticated();
26
+ return { userId: claims.sub, sessionId: claims.sid };
27
+ }
28
+
29
+ async getVerifiedProfile(clerkUserId: string): Promise<ClerkProfile> {
30
+ const user = await this.findUser(clerkUserId);
31
+ const email = user.primaryEmailAddress;
32
+ if (!email || email.verification?.status !== 'verified') {
33
+ throw new AppException(403, 'EMAIL_NOT_VERIFIED', 'Please verify your email address to continue.');
34
+ }
35
+ const name = [user.firstName, user.lastName].filter(Boolean).join(' ').trim();
36
+ return { email: email.emailAddress.trim().toLowerCase(), name: name || null };
37
+ }
38
+
39
+ private async verifyWithAnyInstance(token: string) {
40
+ for (const { secretKey } of this.instances) {
41
+ try {
42
+ return await verifyToken(token, { secretKey, jwtKey: this.config.clerk.jwtKey });
43
+ } catch {
44
+ // Signed by another instance (or invalid); try the next one.
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+
50
+ private async findUser(clerkUserId: string) {
51
+ let failure: unknown;
52
+ for (const { client } of this.instances) {
53
+ try {
54
+ return await client.users.getUser(clerkUserId);
55
+ } catch (error) {
56
+ failure = error;
57
+ }
58
+ }
59
+ this.logger.error(`Clerk user lookup failed: ${failure instanceof Error ? failure.message : String(failure)}`);
60
+ throw new AppException(503, 'AUTH_UNAVAILABLE', 'Sign-in is temporarily unavailable. Please try again.');
61
+ }
62
+ }
apps/prevision-api/src/clerk/interfaces/clerk.interface.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ export interface ClerkSession {
2
+ userId: string;
3
+ sessionId: string;
4
+ }
5
+
6
+ export interface ClerkProfile {
7
+ email: string;
8
+ name: string | null;
9
+ }
apps/prevision-api/src/common/dto/paginated.dto.ts ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { PaginationMeta } from '../interfaces/api-response.interface.js';
2
+ import type { PaginationQueryDto } from './pagination-query.dto.js';
3
+
4
+ /** Returned by list endpoints; ResponseInterceptor turns it into `{ data, meta }`. */
5
+ export class Paginated<T> {
6
+ readonly meta: PaginationMeta;
7
+
8
+ constructor(
9
+ readonly items: T[],
10
+ total: number,
11
+ { page, pageSize }: Pick<PaginationQueryDto, 'page' | 'pageSize'>,
12
+ ) {
13
+ this.meta = { page, pageSize, total, totalPages: Math.ceil(total / pageSize) };
14
+ }
15
+ }
apps/prevision-api/src/common/dto/pagination-query.dto.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Type } from 'class-transformer';
2
+ import { IsInt, IsOptional, Max, Min } from 'class-validator';
3
+
4
+ export class PaginationQueryDto {
5
+ @IsOptional()
6
+ @Type(() => Number)
7
+ @IsInt()
8
+ @Min(1)
9
+ @Max(100_000)
10
+ page = 1;
11
+
12
+ @IsOptional()
13
+ @Type(() => Number)
14
+ @IsInt()
15
+ @Min(1)
16
+ @Max(96)
17
+ pageSize = 24;
18
+
19
+ get offset(): number {
20
+ return (this.page - 1) * this.pageSize;
21
+ }
22
+ }
apps/prevision-api/src/common/exceptions/app.exception.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { HttpException } from '@nestjs/common';
2
+
3
+ /** An error with a stable code the frontend can act on. */
4
+ export class AppException extends HttpException {
5
+ constructor(
6
+ status: number,
7
+ readonly code: string,
8
+ message: string,
9
+ ) {
10
+ super(message, status);
11
+ }
12
+ }
13
+
14
+ export const unauthenticated = () => new AppException(401, 'UNAUTHENTICATED', 'Please sign in to continue.');
apps/prevision-api/src/common/filters/http-exception.filter.spec.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BadRequestException, Logger, NotFoundException, type ArgumentsHost } from '@nestjs/common';
2
+ import { AppException } from '../exceptions/app.exception.js';
3
+ import { HttpExceptionFilter } from './http-exception.filter.js';
4
+
5
+ function respond(exception: unknown) {
6
+ const response = { status: vi.fn().mockReturnThis(), json: vi.fn() };
7
+ const host = { switchToHttp: () => ({ getResponse: () => response }) } as unknown as ArgumentsHost;
8
+ new HttpExceptionFilter().catch(exception, host);
9
+ return { status: response.status.mock.calls[0][0], body: response.json.mock.calls[0][0] };
10
+ }
11
+
12
+ describe('HttpExceptionFilter', () => {
13
+ beforeAll(() => Logger.overrideLogger(false));
14
+
15
+ it('keeps the code of an AppException', () => {
16
+ expect(respond(new AppException(402, 'NO_FREE_TRIES', 'None left.'))).toEqual({
17
+ status: 402,
18
+ body: { success: false, error: { code: 'NO_FREE_TRIES', message: 'None left.' } },
19
+ });
20
+ });
21
+
22
+ it('joins validation messages', () => {
23
+ const { status, body } = respond(new BadRequestException(['page must be an integer', 'q is too long']));
24
+ expect(status).toBe(400);
25
+ expect(body.error).toEqual({ code: 'BAD_REQUEST', message: 'page must be an integer; q is too long' });
26
+ });
27
+
28
+ it('maps other HTTP errors by status', () => {
29
+ expect(respond(new NotFoundException()).body.error.code).toBe('NOT_FOUND');
30
+ });
31
+
32
+ it('hides unexpected errors', () => {
33
+ const { status, body } = respond(new Error('database password is wrong'));
34
+ expect(status).toBe(500);
35
+ expect(body.error).toEqual({ code: 'INTERNAL_ERROR', message: 'Something went wrong. Please try again.' });
36
+ });
37
+ });
apps/prevision-api/src/common/filters/http-exception.filter.ts ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Logger } from '@nestjs/common';
2
+ import type { Response } from 'express';
3
+ import { AppException } from '../exceptions/app.exception.js';
4
+ import type { ApiFailure } from '../interfaces/api-response.interface.js';
5
+
6
+ const CODES: Record<number, string> = {
7
+ 400: 'BAD_REQUEST',
8
+ 401: 'UNAUTHENTICATED',
9
+ 403: 'FORBIDDEN',
10
+ 404: 'NOT_FOUND',
11
+ 409: 'CONFLICT',
12
+ 429: 'RATE_LIMITED',
13
+ 503: 'SERVICE_UNAVAILABLE',
14
+ };
15
+
16
+ /** Every error becomes `{ success: false, error: { code, message } }`; unexpected ones are logged, never echoed. */
17
+ @Catch()
18
+ export class HttpExceptionFilter implements ExceptionFilter {
19
+ private readonly logger = new Logger(HttpExceptionFilter.name);
20
+
21
+ catch(exception: unknown, host: ArgumentsHost) {
22
+ const response = host.switchToHttp().getResponse<Response>();
23
+ const [status, body] = this.toBody(exception);
24
+ response.status(status).json(body);
25
+ }
26
+
27
+ private toBody(exception: unknown): [number, ApiFailure] {
28
+ if (exception instanceof AppException) {
29
+ return [exception.getStatus(), failure(exception.code, exception.message)];
30
+ }
31
+ if (exception instanceof HttpException) {
32
+ const status = exception.getStatus();
33
+ const detail = exception.getResponse();
34
+ const message = typeof detail === 'object' && detail && 'message' in detail ? (detail as { message: unknown }).message : exception.message;
35
+ return [status, failure(CODES[status] ?? 'ERROR', Array.isArray(message) ? message.join('; ') : String(message))];
36
+ }
37
+ this.logger.error(exception instanceof Error ? exception.stack : String(exception));
38
+ return [500, failure('INTERNAL_ERROR', 'Something went wrong. Please try again.')];
39
+ }
40
+ }
41
+
42
+ const failure = (code: string, message: string): ApiFailure => ({ success: false, error: { code, message } });
apps/prevision-api/src/common/interceptors/response.interceptor.spec.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { lastValueFrom, of } from 'rxjs';
2
+ import type { CallHandler, ExecutionContext } from '@nestjs/common';
3
+ import { Paginated } from '../dto/paginated.dto.js';
4
+ import { ResponseInterceptor } from './response.interceptor.js';
5
+
6
+ const run = (body: unknown) =>
7
+ lastValueFrom(new ResponseInterceptor().intercept({} as ExecutionContext, { handle: () => of(body) } as CallHandler));
8
+
9
+ describe('ResponseInterceptor', () => {
10
+ it('wraps a body in { success, data }', async () => {
11
+ expect(await run({ id: 1 })).toEqual({ success: true, data: { id: 1 } });
12
+ });
13
+
14
+ it('turns a page into data plus pagination meta', async () => {
15
+ const page = new Paginated(['a', 'b'], 5, { page: 2, pageSize: 2 });
16
+ expect(await run(page)).toEqual({
17
+ success: true,
18
+ data: ['a', 'b'],
19
+ meta: { page: 2, pageSize: 2, total: 5, totalPages: 3 },
20
+ });
21
+ });
22
+
23
+ it('leaves empty responses empty', async () => {
24
+ expect(await run(undefined)).toBeUndefined();
25
+ });
26
+ });
apps/prevision-api/src/common/interceptors/response.interceptor.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
2
+ import { map, type Observable } from 'rxjs';
3
+ import { Paginated } from '../dto/paginated.dto.js';
4
+ import type { ApiSuccess } from '../interfaces/api-response.interface.js';
5
+
6
+ /** Every successful response becomes `{ success: true, data, meta? }`; empty (204) responses stay empty. */
7
+ @Injectable()
8
+ export class ResponseInterceptor<T> implements NestInterceptor<T, ApiSuccess<unknown> | undefined> {
9
+ intercept(_: ExecutionContext, next: CallHandler<T>): Observable<ApiSuccess<unknown> | undefined> {
10
+ return next.handle().pipe(
11
+ map((body) => {
12
+ if (body === undefined) return undefined;
13
+ if (body instanceof Paginated) return { success: true, data: body.items, meta: body.meta };
14
+ return { success: true, data: body };
15
+ }),
16
+ );
17
+ }
18
+ }
apps/prevision-api/src/common/interfaces/api-response.interface.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface PaginationMeta {
2
+ page: number;
3
+ pageSize: number;
4
+ total: number;
5
+ totalPages: number;
6
+ }
7
+
8
+ export interface ApiSuccess<T> {
9
+ success: true;
10
+ data: T;
11
+ meta?: PaginationMeta;
12
+ }
13
+
14
+ export interface ApiFailure {
15
+ success: false;
16
+ error: { code: string; message: string };
17
+ }
apps/prevision-api/src/common/utils/bearer-token.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import type { Request } from 'express';
2
+
3
+ export function bearerToken(request: Request): string | null {
4
+ const [scheme, token] = (request.headers.authorization ?? '').split(' ');
5
+ return scheme?.toLowerCase() === 'bearer' && token?.trim() ? token.trim() : null;
6
+ }
apps/prevision-api/src/config/app-config.interface.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type Environment = 'development' | 'test' | 'staging' | 'production';
2
+
3
+ export interface AppConfig {
4
+ environment: Environment;
5
+ port: number;
6
+ databaseUrl: string;
7
+ allowedOrigins: string[];
8
+ allowedOriginRegex: RegExp | null;
9
+ clerk: {
10
+ /** One per Clerk instance the API accepts, e.g. production and development. */
11
+ secretKeys: string[];
12
+ jwtKey?: string;
13
+ };
14
+ processingToken: {
15
+ secret: string;
16
+ ttlSeconds: number;
17
+ audience: string;
18
+ issuer: string;
19
+ };
20
+ internalTokenAudience: string;
21
+ /** Lifetime free generations for accounts without a subscription. */
22
+ freeGenerations: number;
23
+ /** The Prevision site, for Stripe's success, cancel and portal return links. */
24
+ appUrl: string;
25
+ stripe: StripeConfig;
26
+ }
27
+
28
+ export type PlanId = 'starter' | 'growth';
29
+
30
+ export interface StripeConfig {
31
+ secretKey: string;
32
+ webhookSecret: string;
33
+ /** Stripe Price id and monthly generation allowance of each plan. */
34
+ plans: Record<PlanId, { priceId: string; monthlyGenerations: number }>;
35
+ /** Public URL of the logo shown on Stripe Checkout. Optional. */
36
+ logoUrl?: string;
37
+ /** The branded billing portal configuration (bpc_...). Optional: Stripe's default otherwise. */
38
+ portalConfigurationId?: string;
39
+ }
apps/prevision-api/src/config/app-config.spec.ts ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { isOriginAllowed, loadConfig } from './app-config.js';
2
+
3
+ const base = {
4
+ PREVISION_DATABASE_URL: 'postgresql://u:p@db.test:5432/app',
5
+ CLERK_SECRET_KEY: 'sk_test_x',
6
+ PROCESSING_TOKEN_SECRET: 'x'.repeat(40),
7
+ STRIPE_SECRET_KEY: 'sk_test_x',
8
+ STRIPE_WEBHOOK_SECRET: 'whsec_x',
9
+ STRIPE_PRICE_STARTER: 'price_s',
10
+ STRIPE_PRICE_GROWTH: 'price_g',
11
+ };
12
+
13
+ describe('loadConfig', () => {
14
+ it('applies defaults', () => {
15
+ const config = loadConfig(base);
16
+ expect(config.port).toBe(8001);
17
+ expect(config.freeGenerations).toBe(10);
18
+ expect(config.processingToken).toMatchObject({ issuer: 'prevision-api', audience: 'prevision-processing', ttlSeconds: 600 });
19
+ expect(config.stripe.plans).toEqual({
20
+ starter: { priceId: 'price_s', monthlyGenerations: 150 },
21
+ growth: { priceId: 'price_g', monthlyGenerations: 600 },
22
+ });
23
+ expect(config.appUrl).toBe('http://localhost:5173');
24
+ });
25
+
26
+ it('accepts a comma-separated list of Clerk secret keys', () => {
27
+ expect(loadConfig({ ...base, CLERK_SECRET_KEY: 'sk_live_a, sk_test_b' }).clerk.secretKeys).toEqual(['sk_live_a', 'sk_test_b']);
28
+ expect(() => loadConfig({ ...base, ENVIRONMENT: 'staging', CLERK_SECRET_KEY: 'sk_live_a,pk_live_b' })).toThrow(/Clerk secret keys/);
29
+ });
30
+
31
+ it('matches exact origins and the preview regex', () => {
32
+ const config = loadConfig({
33
+ ...base,
34
+ PREVISION_ALLOWED_ORIGINS: 'https://a.test/, https://b.test',
35
+ PREVISION_ALLOWED_ORIGIN_REGEX: '^https://prevision-[a-z0-9]+-team\\.vercel\\.app$',
36
+ });
37
+ expect(isOriginAllowed(config, 'https://a.test')).toBe(true);
38
+ expect(isOriginAllowed(config, 'https://prevision-abc-team.vercel.app')).toBe(true);
39
+ expect(isOriginAllowed(config, 'https://prevision-abc-team.vercel.app.evil.test')).toBe(false);
40
+ expect(isOriginAllowed(config, undefined)).toBe(false);
41
+ });
42
+
43
+ it('refuses missing or weak settings', () => {
44
+ expect(() => loadConfig({})).toThrow(/PREVISION_DATABASE_URL is required.*CLERK_SECRET_KEY is required/);
45
+ expect(() => loadConfig({ ...base, ENVIRONMENT: 'staging', PROCESSING_TOKEN_SECRET: 'short' })).toThrow(/at least 32/);
46
+ expect(() => loadConfig({ ...base, FREE_GENERATIONS: 'many' })).toThrow(/whole number/);
47
+ expect(() => loadConfig({ ...base, STRIPE_PRICE_GROWTH: '' })).toThrow(/STRIPE_PRICE_GROWTH is required/);
48
+ expect(() => loadConfig({ ...base, ENVIRONMENT: 'staging', STRIPE_WEBHOOK_SECRET: 'nope' })).toThrow(/webhook signing secret/);
49
+ });
50
+ });
apps/prevision-api/src/config/app-config.ts ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AppConfig, Environment } from './app-config.interface.js';
2
+
3
+ export const APP_CONFIG = Symbol('APP_CONFIG');
4
+
5
+ const ENVIRONMENTS: Environment[] = ['development', 'test', 'staging', 'production'];
6
+
7
+ export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
8
+ const problems: string[] = [];
9
+ const required = (name: string) => {
10
+ const value = env[name]?.trim();
11
+ if (!value) problems.push(`${name} is required`);
12
+ return value ?? '';
13
+ };
14
+ const integer = (name: string, fallback: number) => {
15
+ const raw = env[name]?.trim();
16
+ if (!raw) return fallback;
17
+ const value = Number(raw);
18
+ if (!Number.isInteger(value) || value < 0) problems.push(`${name} must be a whole number`);
19
+ return value;
20
+ };
21
+
22
+ const environment = (env.ENVIRONMENT ?? 'development') as Environment;
23
+ if (!ENVIRONMENTS.includes(environment)) problems.push(`ENVIRONMENT must be one of ${ENVIRONMENTS.join(', ')}`);
24
+
25
+ let allowedOriginRegex: RegExp | null = null;
26
+ const regex = env.PREVISION_ALLOWED_ORIGIN_REGEX?.trim();
27
+ if (regex) {
28
+ try {
29
+ allowedOriginRegex = new RegExp(`^(?:${regex.replace(/^\^|\$$/g, '')})$`);
30
+ } catch {
31
+ problems.push('PREVISION_ALLOWED_ORIGIN_REGEX is not a valid regular expression');
32
+ }
33
+ }
34
+
35
+ const config: AppConfig = {
36
+ environment,
37
+ port: integer('PREVISION_API_PORT', 8001),
38
+ databaseUrl: required('PREVISION_DATABASE_URL'),
39
+ allowedOrigins: (env.PREVISION_ALLOWED_ORIGINS ?? 'http://localhost:5173')
40
+ .split(',')
41
+ .map((origin) => origin.trim().replace(/\/$/, ''))
42
+ .filter(Boolean),
43
+ allowedOriginRegex,
44
+ clerk: {
45
+ secretKeys: required('CLERK_SECRET_KEY')
46
+ .split(',')
47
+ .map((key) => key.trim())
48
+ .filter(Boolean),
49
+ jwtKey: env.CLERK_JWT_KEY?.trim() || undefined,
50
+ },
51
+ processingToken: {
52
+ secret: required('PROCESSING_TOKEN_SECRET'),
53
+ ttlSeconds: integer('PROCESSING_TOKEN_TTL_SECONDS', 600),
54
+ audience: env.PROCESSING_TOKEN_AUDIENCE?.trim() || 'prevision-processing',
55
+ issuer: 'prevision-api',
56
+ },
57
+ internalTokenAudience: 'prevision-internal',
58
+ freeGenerations: integer('FREE_GENERATIONS', 10),
59
+ appUrl: (env.PREVISION_APP_URL?.trim() || 'http://localhost:5173').replace(/\/$/, ''),
60
+ stripe: {
61
+ secretKey: required('STRIPE_SECRET_KEY'),
62
+ webhookSecret: required('STRIPE_WEBHOOK_SECRET'),
63
+ plans: {
64
+ starter: { priceId: required('STRIPE_PRICE_STARTER'), monthlyGenerations: integer('STARTER_MONTHLY_GENERATIONS', 150) },
65
+ growth: { priceId: required('STRIPE_PRICE_GROWTH'), monthlyGenerations: integer('GROWTH_MONTHLY_GENERATIONS', 600) },
66
+ },
67
+ logoUrl: env.STRIPE_LOGO_URL?.trim() || undefined,
68
+ portalConfigurationId: env.STRIPE_PORTAL_CONFIGURATION_ID?.trim() || undefined,
69
+ },
70
+ };
71
+
72
+ if (environment === 'staging' || environment === 'production') {
73
+ if (config.processingToken.secret.length < 32) problems.push('PROCESSING_TOKEN_SECRET must be at least 32 characters');
74
+ if (config.allowedOrigins.some((origin) => origin.includes('*'))) problems.push('PREVISION_ALLOWED_ORIGINS must list exact origins');
75
+ if (!config.clerk.secretKeys.every((key) => key.startsWith('sk_'))) problems.push('CLERK_SECRET_KEY must list Clerk secret keys');
76
+ if (!/^(sk|rk)_/.test(config.stripe.secretKey)) problems.push('STRIPE_SECRET_KEY must be a Stripe secret key');
77
+ if (!config.stripe.webhookSecret.startsWith('whsec_')) problems.push('STRIPE_WEBHOOK_SECRET must be a webhook signing secret');
78
+ if (!config.appUrl.startsWith('https://')) problems.push('PREVISION_APP_URL must be an https URL');
79
+ }
80
+ if (problems.length) throw new Error(`Invalid configuration: ${problems.join('; ')}`);
81
+ return config;
82
+ }
83
+
84
+ export function isOriginAllowed(config: AppConfig, origin: string | null | undefined): boolean {
85
+ if (!origin) return false;
86
+ const normalized = origin.replace(/\/$/, '');
87
+ return config.allowedOrigins.includes(normalized) || Boolean(config.allowedOriginRegex?.test(normalized));
88
+ }
apps/prevision-api/src/config/config.module.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import { Global, Module } from '@nestjs/common';
2
+ import { APP_CONFIG, loadConfig } from './app-config.js';
3
+
4
+ @Global()
5
+ @Module({
6
+ providers: [{ provide: APP_CONFIG, useFactory: () => loadConfig() }],
7
+ exports: [APP_CONFIG],
8
+ })
9
+ export class ConfigModule {}
apps/prevision-api/src/generations/allowance.spec.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { testConfig } from '../../test/support/test-config.js';
2
+ import type { Subscription } from '../generated/prisma/client.js';
3
+ import { allowanceFor } from './allowance.js';
4
+
5
+ const subscription = (plan: Subscription['plan']) =>
6
+ ({ plan, currentPeriodStart: new Date('2026-10-01'), currentPeriodEnd: new Date('2026-11-01') }) as Subscription;
7
+
8
+ describe('allowanceFor', () => {
9
+ const config = testConfig();
10
+
11
+ it('gives free accounts their lifetime tries', () => {
12
+ expect(allowanceFor('user', null, config)).toEqual({ plan: 'free', limit: 5, countFrom: null, renewsAt: null });
13
+ });
14
+
15
+ it('gives subscribers their plan for the current billing period', () => {
16
+ expect(allowanceFor('user', subscription('starter'), config)).toEqual({
17
+ plan: 'starter',
18
+ limit: 150,
19
+ countFrom: new Date('2026-10-01'),
20
+ renewsAt: new Date('2026-11-01'),
21
+ });
22
+ expect(allowanceFor('user', subscription('growth'), config).limit).toBe(600);
23
+ });
24
+
25
+ it('never limits admins', () => {
26
+ expect(allowanceFor('admin', subscription('starter'), config)).toMatchObject({ plan: 'unlimited', limit: null });
27
+ });
28
+ });
apps/prevision-api/src/generations/allowance.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AppConfig } from '../config/app-config.interface.js';
2
+ import { UserRole, type Subscription } from '../generated/prisma/client.js';
3
+ import type { Allowance } from './interfaces/allowance.interface.js';
4
+
5
+ /** Admins: unlimited. Subscribers: the plan's monthly allowance. Everyone else: the lifetime free tries. */
6
+ export function allowanceFor(role: UserRole, subscription: Subscription | null, config: AppConfig): Allowance {
7
+ if (role === UserRole.admin) return { plan: 'unlimited', limit: null, countFrom: null, renewsAt: null };
8
+ if (subscription) {
9
+ return {
10
+ plan: subscription.plan,
11
+ limit: config.stripe.plans[subscription.plan].monthlyGenerations,
12
+ countFrom: subscription.currentPeriodStart,
13
+ renewsAt: subscription.currentPeriodEnd,
14
+ };
15
+ }
16
+ return { plan: 'free', limit: config.freeGenerations, countFrom: null, renewsAt: null };
17
+ }
apps/prevision-api/src/generations/dto/create-generation.dto.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { IsString, IsUUID, Matches, MaxLength } from 'class-validator';
2
+
3
+ export class CreateGenerationDto {
4
+ @IsUUID()
5
+ userId: string;
6
+
7
+ @IsString()
8
+ @MaxLength(64)
9
+ @Matches(/^[A-Za-z0-9_-]+$/)
10
+ jobId: string;
11
+ }
apps/prevision-api/src/generations/dto/generation-created.dto.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import { UsageDto } from './usage.dto.js';
2
+
3
+ export class GenerationCreatedDto {
4
+ generationId: string;
5
+ usage: UsageDto;
6
+ }
apps/prevision-api/src/generations/dto/usage.dto.ts ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AllowancePlan } from '../interfaces/allowance.interface.js';
2
+
3
+ /** Generations used against the current allowance. `limit` and `remaining` are null when unlimited. */
4
+ export class UsageDto {
5
+ plan: AllowancePlan;
6
+ limit: number | null;
7
+ used: number;
8
+ remaining: number | null;
9
+ renewsAt: Date | null;
10
+ }
apps/prevision-api/src/generations/generations.controller.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Body, Controller, HttpCode, Param, ParseUUIDPipe, Post, UseGuards } from '@nestjs/common';
2
+ import { CreateGenerationDto } from './dto/create-generation.dto.js';
3
+ import type { GenerationCreatedDto } from './dto/generation-created.dto.js';
4
+ import { GenerationsService } from './generations.service.js';
5
+ import { InternalTokenGuard } from './guards/internal-token.guard.js';
6
+
7
+ /** Called by the renderer; outside /api, so the frontend proxy never reaches it. */
8
+ @Controller('internal/generations')
9
+ @UseGuards(InternalTokenGuard)
10
+ export class GenerationsController {
11
+ constructor(private readonly generations: GenerationsService) {}
12
+
13
+ @Post()
14
+ create(@Body() { userId, jobId }: CreateGenerationDto): Promise<GenerationCreatedDto> {
15
+ return this.generations.create(userId, jobId);
16
+ }
17
+
18
+ @Post(':id/refund')
19
+ @HttpCode(204)
20
+ refund(@Param('id', ParseUUIDPipe) id: string): Promise<void> {
21
+ return this.generations.refund(id);
22
+ }
23
+ }
apps/prevision-api/src/generations/generations.module.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Module } from '@nestjs/common';
2
+ import { GenerationsController } from './generations.controller.js';
3
+ import { GenerationsService } from './generations.service.js';
4
+ import { InternalTokenGuard } from './guards/internal-token.guard.js';
5
+
6
+ @Module({
7
+ controllers: [GenerationsController],
8
+ providers: [GenerationsService, InternalTokenGuard],
9
+ exports: [GenerationsService],
10
+ })
11
+ export class GenerationsModule {}
apps/prevision-api/src/generations/generations.service.spec.ts ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Test } from '@nestjs/testing';
2
+ import { testConfig } from '../../test/support/test-config.js';
3
+ import { APP_CONFIG } from '../config/app-config.js';
4
+ import { PrismaService } from '../prisma/prisma.service.js';
5
+ import { GenerationsService } from './generations.service.js';
6
+
7
+ describe('GenerationsService', () => {
8
+ const period = { plan: 'starter', currentPeriodStart: new Date('2026-10-01'), currentPeriodEnd: new Date('2026-11-01') };
9
+ const tx = { $queryRaw: vi.fn(), subscription: { findFirst: vi.fn() }, generation: { count: vi.fn(), create: vi.fn() } };
10
+ const db = {
11
+ $transaction: vi.fn((work: (client: typeof tx) => unknown) => work(tx)),
12
+ subscription: { findFirst: vi.fn() },
13
+ generation: { count: vi.fn(), updateMany: vi.fn() },
14
+ };
15
+ let service: GenerationsService;
16
+
17
+ beforeEach(async () => {
18
+ vi.clearAllMocks();
19
+ db.subscription.findFirst.mockResolvedValue(null);
20
+ tx.subscription.findFirst.mockResolvedValue(null);
21
+ const moduleRef = await Test.createTestingModule({
22
+ providers: [GenerationsService, { provide: PrismaService, useValue: { db } }, { provide: APP_CONFIG, useValue: testConfig() }],
23
+ }).compile();
24
+ service = moduleRef.get(GenerationsService);
25
+ });
26
+
27
+ it('counts all-time generations for free accounts', async () => {
28
+ db.generation.count.mockResolvedValue(2);
29
+ expect(await service.usage({ id: 'u1', role: 'user' })).toEqual({ plan: 'free', limit: 5, used: 2, remaining: 3, renewsAt: null });
30
+ expect(db.generation.count).toHaveBeenCalledWith({ where: { userId: 'u1', refundedAt: null } });
31
+ });
32
+
33
+ it('counts only this billing period for subscribers', async () => {
34
+ db.subscription.findFirst.mockResolvedValue(period);
35
+ db.generation.count.mockResolvedValue(10);
36
+ expect(await service.usage({ id: 'u1', role: 'user' })).toEqual({
37
+ plan: 'starter',
38
+ limit: 150,
39
+ used: 10,
40
+ remaining: 140,
41
+ renewsAt: period.currentPeriodEnd,
42
+ });
43
+ expect(db.generation.count).toHaveBeenCalledWith({ where: { userId: 'u1', refundedAt: null, createdAt: { gte: period.currentPeriodStart } } });
44
+ });
45
+
46
+ it('records a generation while tries remain', async () => {
47
+ tx.$queryRaw.mockResolvedValue([{ role: 'user' }]);
48
+ tx.generation.count.mockResolvedValue(4);
49
+ tx.generation.create.mockResolvedValue({ id: 'g1' });
50
+ expect(await service.create('u1', 'job-1')).toEqual({
51
+ generationId: 'g1',
52
+ usage: { plan: 'free', limit: 5, used: 5, remaining: 0, renewsAt: null },
53
+ });
54
+ expect(tx.generation.create).toHaveBeenCalledWith({ data: { userId: 'u1', jobId: 'job-1' } });
55
+ });
56
+
57
+ it('answers 402 NO_FREE_TRIES once the free tries are used', async () => {
58
+ tx.$queryRaw.mockResolvedValue([{ role: 'user' }]);
59
+ tx.generation.count.mockResolvedValue(5);
60
+ await expect(service.create('u1', 'job-6')).rejects.toMatchObject({ code: 'NO_FREE_TRIES', status: 402 });
61
+ expect(tx.generation.create).not.toHaveBeenCalled();
62
+ });
63
+
64
+ it('answers 402 PLAN_LIMIT_REACHED at a plan limit', async () => {
65
+ tx.$queryRaw.mockResolvedValue([{ role: 'user' }]);
66
+ tx.subscription.findFirst.mockResolvedValue(period);
67
+ tx.generation.count.mockResolvedValue(150);
68
+ await expect(service.create('u1', 'job-151')).rejects.toMatchObject({ code: 'PLAN_LIMIT_REACHED', status: 402 });
69
+ });
70
+
71
+ it('never limits admins', async () => {
72
+ tx.$queryRaw.mockResolvedValue([{ role: 'admin' }]);
73
+ tx.generation.count.mockResolvedValue(40);
74
+ tx.generation.create.mockResolvedValue({ id: 'g41' });
75
+ expect((await service.create('admin', 'job-41')).usage).toEqual({ plan: 'unlimited', limit: null, used: 41, remaining: null, renewsAt: null });
76
+ });
77
+
78
+ it('refuses unknown or deleted users', async () => {
79
+ tx.$queryRaw.mockResolvedValue([]);
80
+ await expect(service.create('gone', 'job-1')).rejects.toMatchObject({ status: 403 });
81
+ });
82
+
83
+ it('refunds only generations that are not refunded yet', async () => {
84
+ await service.refund('g1');
85
+ expect(db.generation.updateMany).toHaveBeenCalledWith({ where: { id: 'g1', refundedAt: null }, data: { refundedAt: expect.any(Date) } });
86
+ });
87
+ });
apps/prevision-api/src/generations/generations.service.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Inject, Injectable } from '@nestjs/common';
2
+ import { AppException } from '../common/exceptions/app.exception.js';
3
+ import { APP_CONFIG } from '../config/app-config.js';
4
+ import type { AppConfig } from '../config/app-config.interface.js';
5
+ import type { Prisma, User, UserRole } from '../generated/prisma/client.js';
6
+ import { PrismaService } from '../prisma/prisma.service.js';
7
+ import { activeSubscriptionWhere } from '../subscriptions/active-subscription.js';
8
+ import { allowanceFor } from './allowance.js';
9
+ import type { GenerationCreatedDto } from './dto/generation-created.dto.js';
10
+ import type { UsageDto } from './dto/usage.dto.js';
11
+ import type { Allowance } from './interfaces/allowance.interface.js';
12
+
13
+ type Db = Pick<PrismaService['db'], 'subscription' | 'generation'>;
14
+
15
+ @Injectable()
16
+ export class GenerationsService {
17
+ constructor(
18
+ private readonly prisma: PrismaService,
19
+ @Inject(APP_CONFIG) private readonly config: AppConfig,
20
+ ) {}
21
+
22
+ async usage(user: Pick<User, 'id' | 'role'>): Promise<UsageDto> {
23
+ const allowance = await this.allowance(this.prisma.db, user.id, user.role);
24
+ return this.toUsage(allowance, await this.used(this.prisma.db, user.id, allowance));
25
+ }
26
+
27
+ /**
28
+ * Records a job the renderer is about to accept, against the user's allowance.
29
+ * The user row lock serializes concurrent jobs, so the limit can't be passed.
30
+ */
31
+ async create(userId: string, jobId: string): Promise<GenerationCreatedDto> {
32
+ return this.prisma.db.$transaction(async (tx) => {
33
+ const [user] = await tx.$queryRaw<{ role: UserRole }[]>`
34
+ SELECT role FROM users WHERE id = ${userId}::uuid AND deleted_at IS NULL FOR UPDATE`;
35
+ if (!user) throw new AppException(403, 'FORBIDDEN', 'This account cannot create visualizations.');
36
+ const allowance = await this.allowance(tx, userId, user.role);
37
+ const used = await this.used(tx, userId, allowance);
38
+ if (allowance.limit !== null && used >= allowance.limit) throw limitReached(allowance);
39
+ const generation = await tx.generation.create({ data: { userId, jobId } });
40
+ return { generationId: generation.id, usage: this.toUsage(allowance, used + 1) };
41
+ });
42
+ }
43
+
44
+ /** Gives the try back after a failed job. Repeating it changes nothing. */
45
+ async refund(generationId: string): Promise<void> {
46
+ await this.prisma.db.generation.updateMany({
47
+ where: { id: generationId, refundedAt: null },
48
+ data: { refundedAt: new Date() },
49
+ });
50
+ }
51
+
52
+ private async allowance(db: Db, userId: string, role: UserRole): Promise<Allowance> {
53
+ const subscription = await db.subscription.findFirst({ where: activeSubscriptionWhere(userId), orderBy: { currentPeriodEnd: 'desc' } });
54
+ return allowanceFor(role, subscription, this.config);
55
+ }
56
+
57
+ private used(db: Db, userId: string, allowance: Allowance): Promise<number> {
58
+ const where: Prisma.GenerationWhereInput = { userId, refundedAt: null };
59
+ if (allowance.countFrom) where.createdAt = { gte: allowance.countFrom };
60
+ return db.generation.count({ where });
61
+ }
62
+
63
+ private toUsage({ plan, limit, renewsAt }: Allowance, used: number): UsageDto {
64
+ return { plan, limit, used, remaining: limit === null ? null : Math.max(0, limit - used), renewsAt };
65
+ }
66
+ }
67
+
68
+ const limitReached = (allowance: Allowance) =>
69
+ allowance.plan === 'free'
70
+ ? new AppException(402, 'NO_FREE_TRIES', "You've used all your free visualizations.")
71
+ : new AppException(402, 'PLAN_LIMIT_REACHED', "You've used this month's visualizations. They renew with your plan.");
apps/prevision-api/src/generations/guards/internal-token.guard.spec.ts ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ExecutionContext } from '@nestjs/common';
2
+ import { SignJWT } from 'jose';
3
+ import type { AppConfig } from '../../config/app-config.interface.js';
4
+ import { InternalTokenGuard } from './internal-token.guard.js';
5
+
6
+ const SECRET = 'test-processing-secret-0123456789abcdef012';
7
+ const guard = new InternalTokenGuard({ processingToken: { secret: SECRET }, internalTokenAudience: 'prevision-internal' } as AppConfig);
8
+
9
+ const sign = (audience: string, expiresIn = 60) => {
10
+ const now = Math.floor(Date.now() / 1000);
11
+ return new SignJWT({}).setProtectedHeader({ alg: 'HS256' }).setAudience(audience).setIssuedAt(now).setExpirationTime(now + expiresIn).sign(new TextEncoder().encode(SECRET));
12
+ };
13
+ const check = (token?: string) =>
14
+ guard.canActivate({
15
+ switchToHttp: () => ({ getRequest: () => ({ headers: token ? { authorization: `Bearer ${token}` } : {} }) }),
16
+ } as ExecutionContext);
17
+
18
+ describe('InternalTokenGuard', () => {
19
+ it('accepts the renderer token', async () => {
20
+ expect(await check(await sign('prevision-internal'))).toBe(true);
21
+ });
22
+
23
+ it.each([
24
+ ['missing', async () => undefined],
25
+ ['browser processing token', () => sign('prevision-processing')],
26
+ ['expired', () => sign('prevision-internal', -120)],
27
+ ])('refuses a %s token', async (_, token) => {
28
+ await expect(check(await token())).rejects.toMatchObject({ status: 401 });
29
+ });
30
+ });
apps/prevision-api/src/generations/guards/internal-token.guard.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
2
+ import type { Request } from 'express';
3
+ import { jwtVerify } from 'jose';
4
+ import { unauthenticated } from '../../common/exceptions/app.exception.js';
5
+ import { bearerToken } from '../../common/utils/bearer-token.js';
6
+ import { APP_CONFIG } from '../../config/app-config.js';
7
+ import type { AppConfig } from '../../config/app-config.interface.js';
8
+
9
+ /** The renderer in the same pod: a short HS256 token for the internal audience (never a browser token). */
10
+ @Injectable()
11
+ export class InternalTokenGuard implements CanActivate {
12
+ private readonly key: Uint8Array;
13
+
14
+ constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) {
15
+ this.key = new TextEncoder().encode(config.processingToken.secret);
16
+ }
17
+
18
+ async canActivate(context: ExecutionContext): Promise<boolean> {
19
+ const token = bearerToken(context.switchToHttp().getRequest<Request>());
20
+ if (!token) throw unauthenticated();
21
+ try {
22
+ await jwtVerify(token, this.key, {
23
+ algorithms: ['HS256'],
24
+ audience: this.config.internalTokenAudience,
25
+ requiredClaims: ['exp', 'iat'],
26
+ });
27
+ } catch {
28
+ throw unauthenticated();
29
+ }
30
+ return true;
31
+ }
32
+ }
apps/prevision-api/src/generations/interfaces/allowance.interface.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type AllowancePlan = 'free' | 'starter' | 'growth' | 'unlimited';
2
+
3
+ export interface Allowance {
4
+ plan: AllowancePlan;
5
+ /** null = unlimited. */
6
+ limit: number | null;
7
+ /** Generations since this date count against the limit (null = all time). */
8
+ countFrom: Date | null;
9
+ /** When a subscription's allowance renews. */
10
+ renewsAt: Date | null;
11
+ }
apps/prevision-api/src/health/health.controller.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Controller, Get, ServiceUnavailableException } from '@nestjs/common';
2
+ import { PrismaService } from '../prisma/prisma.service.js';
3
+
4
+ @Controller()
5
+ export class HealthController {
6
+ constructor(private readonly prisma: PrismaService) {}
7
+
8
+ @Get('health')
9
+ health() {
10
+ return { status: 'ok' };
11
+ }
12
+
13
+ @Get('ready')
14
+ async ready() {
15
+ try {
16
+ await this.prisma.db.$queryRaw`SELECT 1`;
17
+ } catch {
18
+ throw new ServiceUnavailableException('Database is unavailable.');
19
+ }
20
+ return { status: 'ready' };
21
+ }
22
+ }