feat(api): accounts, organizations and auth schema; CI with Postgres (1/10)
ci / rust (push) Failing after 53s
ci / typescript (push) Failing after 1m44s

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
sparkandClaude Opus 5.5 committed 2026-10-11 14:39:11 +01:00
1 parent aa368a9bdb
commit 02eb41060e
14 files changed
+452 -29

No files matched your search

+21 -2
View File
@@ -7,18 +7,33 @@ on:
jobs:
typescript:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: photoreport
POSTGRES_PASSWORD: photoreport
POSTGRES_DB: photoreport_test
options: >-
--health-cmd "pg_isready -U photoreport"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
DATABASE_URL_TEST: postgresql://photoreport:photoreport@postgres:5432/photoreport_test
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
# pnpm-lock.yaml is committed from the first dev checkout; switch back to --frozen-lockfile then.
# TODO: commit pnpm-lock.yaml, then restore `cache: pnpm` above and `--frozen-lockfile` here.
- run: pnpm install
- run: pnpm -r build
- run: pnpm -r typecheck
- run: pnpm -r test
- name: Deploy scripts parse
run: bash -n infra/deploy/deploy.sh
rust:
runs-on: ubuntu-latest
@@ -30,3 +45,7 @@ jobs:
- run: cargo fmt --all --check
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo test --workspace
- name: Generated controls are up to date
run: |
cargo run -q -p photoreport-engine --example export_controls > packages/contracts/src/controls.generated.json
git diff --exit-code packages/contracts/src/controls.generated.json
+43
View File
@@ -0,0 +1,43 @@
name: desktop-release
# Tag `desktop-vX.Y.Z` builds the desktop installers and attaches them to a Gitea release.
# Linux builds on the standard runner. macOS (.dmg) and Windows (.msi) need runners with those labels:
# register one on a Mac and one on a Windows machine, then uncomment the matrix entries.
on:
push:
tags: ["desktop-v*"]
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
bundles: deb,appimage
# - runner: macos
# bundles: dmg
# - runner: windows
# bundles: msi
runs-on: ${{ matrix.runner }}
env:
VITE_API_URL: https://api.next.photoreport.pt
steps:
- uses: actions/checkout@v4
- name: System libraries (Linux)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libsecret-1-dev
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- uses: dtolnay/rust-toolchain@stable
- run: pnpm install
- run: pnpm --filter @photoreport/contracts --filter @photoreport/sdk build
- run: pnpm --filter @photoreport/desktop icons
- run: pnpm --filter @photoreport/desktop exec tauri build --bundles ${{ matrix.bundles }}
- uses: actions/upload-artifact@v3
with:
name: desktop-${{ matrix.runner }}
path: apps/desktop/src-tauri/target/release/bundle/**
+1
View File
@@ -7,3 +7,4 @@ coverage/
!.env.example
.DS_Store
*.log
apps/api/src/generated/
+3 -1
View File
@@ -18,7 +18,9 @@ Read `docs/ARCHITECTURE.md` before any task. One task id per branch/PR (`task/BI
8. **Language:** code, comments, identifiers and commit messages in English. User-facing copy via i18n (pt-PT first).
9. **Never commit** secrets, `.env`, generated status/summary markdown files, or build output. Deploys never
overwrite a server `.env` (norm BIT-25005, `docs/DEPLOY.md`).
10. **Green CI before merge:** `pnpm -r build && pnpm -r typecheck && pnpm -r test` and `cargo fmt --check`,
10. **Tests touch real infrastructure safely:** API tests run against PostgreSQL and only on a database whose name
ends in `_test`. Never run `prisma migrate reset` or other destructive commands against shared databases.
11. **Green CI before merge:** `pnpm -r build && pnpm -r typecheck && pnpm -r test` and `cargo fmt --check`,
`cargo clippy -D warnings`, `cargo test`.
## Porting from the old projects
+2 -1
View File
@@ -1,10 +1,11 @@
[workspace]
resolver = "2"
members = ["engine/core"]
# The desktop shell needs WebKitGTK/WebView2 system libraries, so it builds on its own (desktop release workflow).
exclude = ["apps/desktop/src-tauri"]
[workspace.package]
edition = "2024"
license = "UNLICENSED"
publish = false
[workspace.dependencies]
+19 -3
View File
@@ -16,6 +16,7 @@ Final domain: `app.photoreport.pt` (built on the `next` environment until cutove
| `apps/site` | Next.js public sites, multi-domain |
| `apps/desktop` | Tauri shell: native engine, local FTP, disk, offline queue |
| `apps/print-agent` | Print Station agent |
| `infra/deploy-receiver` | Gitea webhook receiver that redeploys each container |
| `workers/media` | Node workers: previews, IPTC, ZIPs, emails, Nextcloud delivery |
| `workers/render` | Rust worker: final exports and faces (`lightcraft-faces`) |
| `workers/ml` | Python worker: jersey OCR |
@@ -25,11 +26,26 @@ Final domain: `app.photoreport.pt` (built on the `next` environment until cutove
## Develop
Needs Node 22, pnpm, Rust stable and a local PostgreSQL 16+.
```sh
pnpm install
pnpm -r build && pnpm -r test # TypeScript
cargo test --workspace # Rust
pnpm dev:api # API on :3000 (GET /health)
cp apps/api/.env.example apps/api/.env # set DATABASE_URL, JWT_SECRET (32+ chars), NODE_ENV=development
pnpm --filter @photoreport/api exec prisma migrate deploy
PHOTOREPORT_OWNER_PASSWORD='...' pnpm --filter @photoreport/api create-owner -- \
--org-slug photoreport --org-name PhotoReport --email [email protected] --name "Your Name"
pnpm dev:api # API on :3000
pnpm --filter @photoreport/app dev # web app on :5173
pnpm --filter @photoreport/desktop dev # desktop app (same UI, native window)
```
Checks (same as CI):
```sh
DATABASE_URL_TEST=postgresql://.../photoreport_test pnpm -r build && pnpm -r typecheck && pnpm -r test
cargo fmt --all --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace
```
API tests truncate tables, so they only run against a database whose name ends in `_test`.
Architecture and decisions: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md). Rules for agents: [`AGENTS.md`](AGENTS.md).
+9 -2
View File
@@ -1,5 +1,12 @@
NODE_ENV=production
PORT=3000
LOG_LEVEL=info
APP_VERSION=dev
# DATABASE_URL=postgresql://photoreport:***@pr-db:5432/photoreport
# VALKEY_URL=redis://pr-queue:6379
DATABASE_URL=postgresql://photoreport:CHANGE_ME@pr-db:5432/photoreport
# At least 32 random characters, e.g. `openssl rand -base64 48`
JWT_SECRET=
ACCESS_TOKEN_TTL_SEC=900
REFRESH_TOKEN_TTL_DAYS=30
CORS_ORIGINS=https://app.next.photoreport.pt,tauri://localhost,http://tauri.localhost
APP_PUBLIC_URL=https://app.next.photoreport.pt
ALLOW_SIGNUP=false
+20 -4
View File
@@ -4,14 +4,30 @@
"private": true,
"type": "module",
"scripts": {
"generate": "prisma generate",
"dev": "tsx watch src/server.ts",
"build": "tsc -p tsconfig.json",
"build": "prisma generate && tsc -p tsconfig.json",
"start": "node dist/server.js",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run"
"typecheck": "prisma generate && tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"migrate:deploy": "prisma migrate deploy",
"create-owner": "tsx scripts/create-owner.ts"
},
"dependencies": {
"@fastify/cookie": "^11.1.3",
"@fastify/cors": "^11.3.1",
"@fastify/rate-limit": "^11.2.1",
"@node-rs/argon2": "^2.2.2",
"@photoreport/contracts": "workspace:*",
"fastify": "^5.4.0"
"@prisma/adapter-pg": "^7.10.0",
"@prisma/client": "^7.10.0",
"fastify": "^5.12.5",
"jose": "^6.2.12",
"pg": "^8.23.1",
"zod": "^4.6.5"
},
"devDependencies": {
"@types/pg": "^8.23.1",
"prisma": "^7.10.0"
}
}
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from "prisma/config";
// `prisma generate` runs in CI and builds without a database, so the URL is optional here;
// migrate commands fail clearly if it is missing.
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: { path: "prisma/migrations" },
datasource: { url: process.env.DATABASE_URL ?? "" },
});
@@ -0,0 +1,133 @@
-- CreateEnum
CREATE TYPE "OrganizationMode" AS ENUM ('AGENCY', 'INDEPENDENT');
-- CreateEnum
CREATE TYPE "Role" AS ENUM ('OWNER', 'ADMIN', 'EDITOR', 'INGESTER', 'PHOTOGRAPHER', 'CLIENT');
-- CreateEnum
CREATE TYPE "ClientKind" AS ENUM ('WEB', 'DESKTOP');
-- CreateTable
CREATE TABLE "users" (
"id" UUID NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
"password_hash" TEXT NOT NULL,
"locale" TEXT NOT NULL DEFAULT 'pt-PT',
"email_verified_at" TIMESTAMP(3),
"disabled_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "organizations" (
"id" UUID NOT NULL,
"slug" TEXT NOT NULL,
"name" TEXT NOT NULL,
"mode" "OrganizationMode" NOT NULL DEFAULT 'AGENCY',
"biometrics_enabled" BOOLEAN NOT NULL DEFAULT false,
"biometrics_legal_basis" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "organizations_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "memberships" (
"id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"role" "Role" NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "memberships_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "sessions" (
"id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"family_id" UUID NOT NULL,
"token_hash" TEXT NOT NULL,
"client_kind" "ClientKind" NOT NULL,
"device_label" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expires_at" TIMESTAMP(3) NOT NULL,
"rotated_at" TIMESTAMP(3),
"revoked_at" TIMESTAMP(3),
CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "device_authorizations" (
"id" UUID NOT NULL,
"device_code_hash" TEXT NOT NULL,
"user_code" TEXT NOT NULL,
"client_label" TEXT,
"interval_sec" INTEGER NOT NULL DEFAULT 5,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expires_at" TIMESTAMP(3) NOT NULL,
"last_polled_at" TIMESTAMP(3),
"approved_user_id" UUID,
"approved_at" TIMESTAMP(3),
"denied_at" TIMESTAMP(3),
"consumed_at" TIMESTAMP(3),
CONSTRAINT "device_authorizations_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "user_preferences" (
"user_id" UUID NOT NULL,
"editor_modules" TEXT[] DEFAULT ARRAY['crop', 'basic']::TEXT[],
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "user_preferences_pkey" PRIMARY KEY ("user_id")
);
-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
CREATE UNIQUE INDEX "organizations_slug_key" ON "organizations"("slug");
-- CreateIndex
CREATE INDEX "memberships_organization_id_idx" ON "memberships"("organization_id");
-- CreateIndex
CREATE UNIQUE INDEX "memberships_user_id_organization_id_key" ON "memberships"("user_id", "organization_id");
-- CreateIndex
CREATE UNIQUE INDEX "sessions_token_hash_key" ON "sessions"("token_hash");
-- CreateIndex
CREATE INDEX "sessions_family_id_idx" ON "sessions"("family_id");
-- CreateIndex
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");
-- CreateIndex
CREATE UNIQUE INDEX "device_authorizations_device_code_hash_key" ON "device_authorizations"("device_code_hash");
-- CreateIndex
CREATE UNIQUE INDEX "device_authorizations_user_code_key" ON "device_authorizations"("user_code");
-- AddForeignKey
ALTER TABLE "memberships" ADD CONSTRAINT "memberships_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "memberships" ADD CONSTRAINT "memberships_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "device_authorizations" ADD CONSTRAINT "device_authorizations_approved_user_id_fkey" FOREIGN KEY ("approved_user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "user_preferences" ADD CONSTRAINT "user_preferences_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+131
View File
@@ -0,0 +1,131 @@
// PhotoReport database schema. Every row owned by someone carries organization_id (AGENTS.md rule 4).
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
enum OrganizationMode {
AGENCY // photos belong to the organization; only admins grant access
INDEPENDENT // a photographer working on their own account
}
enum Role {
OWNER
ADMIN
EDITOR
INGESTER
PHOTOGRAPHER
CLIENT
}
enum ClientKind {
WEB
DESKTOP
}
model User {
id String @id @default(uuid()) @db.Uuid
email String @unique // stored lower-cased
name String
passwordHash String @map("password_hash")
locale String @default("pt-PT")
emailVerifiedAt DateTime? @map("email_verified_at")
disabledAt DateTime? @map("disabled_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
memberships Membership[]
sessions Session[]
preferences UserPreferences?
deviceGrants DeviceAuthorization[]
@@map("users")
}
model Organization {
id String @id @default(uuid()) @db.Uuid
slug String @unique
name String
mode OrganizationMode @default(AGENCY)
/// Face recognition is biometric data: off unless enabled with a recorded legal basis.
biometricsEnabled Boolean @default(false) @map("biometrics_enabled")
biometricsLegalBasis String? @map("biometrics_legal_basis")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
memberships Membership[]
@@map("organizations")
}
model Membership {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
role Role
createdAt DateTime @default(now()) @map("created_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
@@unique([userId, organizationId])
@@index([organizationId])
@@map("memberships")
}
/// One refresh-token chain per login. Tokens rotate on every refresh; presenting a rotated token again
/// revokes the whole family (stolen-token detection).
model Session {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
familyId String @map("family_id") @db.Uuid
tokenHash String @unique @map("token_hash")
clientKind ClientKind @map("client_kind")
deviceLabel String? @map("device_label")
createdAt DateTime @default(now()) @map("created_at")
expiresAt DateTime @map("expires_at")
rotatedAt DateTime? @map("rotated_at")
revokedAt DateTime? @map("revoked_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([familyId])
@@index([userId])
@@map("sessions")
}
/// OAuth-style device authorization (RFC 8628) used by the desktop app to sign in through the browser.
model DeviceAuthorization {
id String @id @default(uuid()) @db.Uuid
deviceCodeHash String @unique @map("device_code_hash")
userCode String @unique @map("user_code")
clientLabel String? @map("client_label")
intervalSec Int @default(5) @map("interval_sec")
createdAt DateTime @default(now()) @map("created_at")
expiresAt DateTime @map("expires_at")
lastPolledAt DateTime? @map("last_polled_at")
approvedUserId String? @map("approved_user_id") @db.Uuid
approvedAt DateTime? @map("approved_at")
deniedAt DateTime? @map("denied_at")
consumedAt DateTime? @map("consumed_at")
approvedUser User? @relation(fields: [approvedUserId], references: [id], onDelete: Cascade)
@@map("device_authorizations")
}
/// Per-user settings that follow the user across web and desktop.
model UserPreferences {
userId String @id @map("user_id") @db.Uuid
editorModules String[] @default(["crop", "basic"]) @map("editor_modules")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("user_preferences")
}
+58
View File
@@ -0,0 +1,58 @@
/**
* Bootstraps an organization and its first owner. Run once per environment:
* pnpm --filter @photoreport/api create-owner -- --org-slug photoreport --org-name "PhotoReport" \
* --email [email protected] --name "Your Name"
* The password is read from the PHOTOREPORT_OWNER_PASSWORD environment variable, never from argv.
*/
import { parseArgs } from "node:util";
import { hashPassword, MIN_PASSWORD_LENGTH } from "../src/auth/passwords.js";
import { loadConfig } from "../src/config.js";
import { createDb } from "../src/db.js";
const { values } = parseArgs({
options: {
"org-slug": { type: "string" },
"org-name": { type: "string" },
"org-mode": { type: "string", default: "AGENCY" },
email: { type: "string" },
name: { type: "string" },
},
});
const password = process.env.PHOTOREPORT_OWNER_PASSWORD ?? "";
const slug = values["org-slug"];
const orgName = values["org-name"];
const email = values.email?.trim().toLowerCase();
const name = values.name;
const mode = values["org-mode"] === "INDEPENDENT" ? "INDEPENDENT" : "AGENCY";
if (!slug || !orgName || !email || !name) {
console.error("Missing --org-slug, --org-name, --email or --name");
process.exit(1);
}
if (password.length < MIN_PASSWORD_LENGTH) {
console.error(`Set PHOTOREPORT_OWNER_PASSWORD (at least ${MIN_PASSWORD_LENGTH} characters)`);
process.exit(1);
}
const db = createDb(loadConfig().DATABASE_URL);
try {
const passwordHash = await hashPassword(password);
const result = await db.$transaction(async (tx) => {
const user =
(await tx.user.findUnique({ where: { email } })) ??
(await tx.user.create({ data: { email, name, passwordHash, preferences: { create: {} } } }));
const org =
(await tx.organization.findUnique({ where: { slug } })) ??
(await tx.organization.create({ data: { slug, name: orgName, mode } }));
await tx.membership.upsert({
where: { userId_organizationId: { userId: user.id, organizationId: org.id } },
create: { userId: user.id, organizationId: org.id, role: "OWNER" },
update: { role: "OWNER" },
});
return { userId: user.id, organizationId: org.id };
});
console.log(JSON.stringify(result));
} finally {
await db.$disconnect();
}
-16
View File
@@ -1,16 +0,0 @@
import { describe, expect, it } from "vitest";
import { buildApp } from "./app.js";
describe("api", () => {
it("reports health", async () => {
const app = buildApp({ version: "test" });
const res = await app.inject({ method: "GET", url: "/health" });
expect(res.json()).toEqual({ status: "ok", version: "test" });
});
it("rejects malformed edits", async () => {
const app = buildApp({ version: "test" });
const res = await app.inject({ method: "POST", url: "/v1/edits/validate", payload: { edit: {} } });
expect(res.statusCode).toBe(400);
});
});