diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c115c38 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +node_modules +.next +.env +.env.* +!.env.example +docker/.env +docker/data +design +*.log diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..bd53cbe --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +# broke as one container. Built from this checkout, so it runs exactly the commit you have here. +# Use docker/docker-compose.yml to run it with its own database and sign-in (see docker/README.md). +# +# NEXT_PUBLIC_* values are built into the browser code, so they are build args. Change them and you rebuild. + +FROM node:22-alpine AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY . . +ARG NEXT_PUBLIC_SUPABASE_URL +ARG NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY +ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL \ + NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=$NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY \ + NEXT_TELEMETRY_DISABLED=1 +RUN npm run build + +FROM node:22-alpine +WORKDIR /app +ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 +COPY --from=build --chown=node:node /app /app +USER node +EXPOSE 3000 +# next start directly, not scripts/start.mjs: that one git-pulls on every start and listens on 127.0.0.1 only. +# Database changes in supabase/migrations still apply on start (src/instrumentation.ts) through SUPABASE_DB_URL. +CMD ["node_modules/.bin/next", "start", "-H", "0.0.0.0", "-p", "3000"] diff --git a/docker/.gitignore b/docker/.gitignore new file mode 100644 index 0000000..24f9f8d --- /dev/null +++ b/docker/.gitignore @@ -0,0 +1,2 @@ +.env +data/ diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 0000000..ae75c2e --- /dev/null +++ b/docker/README.md @@ -0,0 +1,70 @@ +# Run broke fully on your own server + +Everything runs here: broke, its Postgres database, sign-in and the REST API (the parts of Supabase it uses), a mail catcher for sign-in links, and optionally Ollama for AI. No Supabase cloud, no Vercel, no auto-update. + +| Container | What it does | Port | +| --- | --- | --- | +| gateway | nginx: broke plus `/auth/v1` and `/rest/v1` on one address | `HTTP_PORT` (3000) | +| broke | the app, built from this checkout | inside only | +| db | Supabase's Postgres image | inside only | +| auth | Supabase Auth (GoTrue): email sign-in links | inside only | +| rest | PostgREST: the database API, row-level security applies | inside only | +| mailpit | catches sign-in emails, behind a password | `MAIL_UI_PORT` (8025) | +| ollama | local AI, only with `--profile ai` | inside only | + +## First start + +1. Pick the address you will open broke on, for example `http://192.168.1.10:3000` (your Unraid IP). Then make the secrets: + + ```bash + node docker/setup.mjs --url http://192.168.1.10:3000 + ``` + + No Node on the server: + + ```bash + docker run --rm -v "$PWD":/w -w /w node:22-alpine node docker/setup.mjs --url http://192.168.1.10:3000 + ``` + + On Unraid, edit `docker/.env` and set `DATA_DIR=/mnt/user/appdata/broke`. + +2. Start it: + + ```bash + docker compose -f docker/docker-compose.yml up -d --build + ``` + + With local AI as well: add `--profile ai`, then pull a model, for example `docker exec broke-ollama-1 ollama pull qwen3:8b`. + +3. Open your address, type your email, then open Mailpit on port 8025 (user `broke`, password `MAIL_PASSWORD` in `docker/.env`) and click the link. + +4. Lock it to you: set `DISABLE_SIGNUP=true` in `docker/.env`, then run `up -d` again. + +5. Add your bank: Accounts, Add accounts, import a statement. For ING, download your transactions from Mijn ING as CSV (comma or semicolon both work). + +## Unraid + +Install the Compose Manager plugin, add a stack, and point it at this folder's `docker-compose.yml`, or run the commands above over SSH from the repo folder. Keep the port on your LAN or behind Tailscale. Don't forward it on your router. + +## Good to know + +- `PUBLIC_URL` is built into the app. If your server's address changes, update `.env` and run `up -d --build`. +- broke's server reaches Supabase through `PUBLIC_URL` as well, so the server must be able to reach its own address (it can on Unraid). +- Back up `DATA_DIR/db` and `docker/.env` together. The database is useless without the secrets in `.env`. +- Database changes in `supabase/migrations` apply each time broke starts. + +## Updating from upstream + +This copy never pulls by itself. To see and pick what's new: + +```bash +git fetch upstream +``` + +```bash +git log --oneline main..upstream/main +``` + +Review, then `git merge upstream/main` (or `git cherry-pick ` for single ones), and rebuild with `up -d --build`. + +`docker/db/*.sql` come from Supabase's self-hosting setup (Apache-2.0). diff --git a/docker/db/jwt.sql b/docker/db/jwt.sql new file mode 100644 index 0000000..09a7283 --- /dev/null +++ b/docker/db/jwt.sql @@ -0,0 +1,3 @@ +\set jwt_exp `echo "$JWT_EXP"` + +ALTER DATABASE postgres SET "app.settings.jwt_exp" TO :'jwt_exp'; diff --git a/docker/db/roles.sql b/docker/db/roles.sql new file mode 100644 index 0000000..8f7161a --- /dev/null +++ b/docker/db/roles.sql @@ -0,0 +1,8 @@ +-- NOTE: change to your own passwords for production environments +\set pgpass `echo "$POSTGRES_PASSWORD"` + +ALTER USER authenticator WITH PASSWORD :'pgpass'; +ALTER USER pgbouncer WITH PASSWORD :'pgpass'; +ALTER USER supabase_auth_admin WITH PASSWORD :'pgpass'; +ALTER USER supabase_functions_admin WITH PASSWORD :'pgpass'; +ALTER USER supabase_storage_admin WITH PASSWORD :'pgpass'; diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000..25183b3 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,167 @@ +# broke with everything it needs, all on your own server. See README.md in this folder. +# node docker/setup.mjs --url http://192.168.1.10:3000 (once: writes docker/.env with fresh secrets) +# docker compose -f docker/docker-compose.yml up -d --build +# ... --profile ai up -d (also runs Ollama for local AI) +# +# Supabase parts (db, auth, rest) follow Supabase's own self-hosting setup, cut down to what broke uses. + +name: broke + +x-hardening: &hardening + restart: unless-stopped + security_opt: + - no-new-privileges:true + +services: + # The only port you open: broke and its Supabase API on one address. + gateway: + <<: *hardening + image: nginx:1.28-alpine + ports: + - "${HTTP_PORT:-3000}:80" + volumes: + - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro + depends_on: + - broke + - auth + - rest + + broke: + <<: *hardening + build: + context: .. + args: + NEXT_PUBLIC_SUPABASE_URL: ${PUBLIC_URL} + NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: ${ANON_KEY} + image: broke:local + cap_drop: [ALL] + environment: + NEXT_PUBLIC_SUPABASE_URL: ${PUBLIC_URL} + NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: ${ANON_KEY} + SUPABASE_SERVICE_ROLE_KEY: ${SERVICE_ROLE_KEY} + SUPABASE_DB_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/postgres + LOCAL_LLM_BASE_URL: ${LOCAL_LLM_BASE_URL:-http://ollama:11434/v1} + LOCAL_LLM_MODEL: ${LOCAL_LLM_MODEL:-} + PLAID_CLIENT_ID: ${PLAID_CLIENT_ID:-} + PLAID_SECRET: ${PLAID_SECRET:-} + PLAID_ENV: ${PLAID_ENV:-sandbox} + PLAID_PRODUCTS: transactions + PLAID_COUNTRY_CODES: ${PLAID_COUNTRY_CODES:-US} + # broke's server calls Supabase at PUBLIC_URL too, so the server must be able to reach its own address. + depends_on: + db: + condition: service_healthy + auth: + condition: service_healthy + + db: + <<: *hardening + image: supabase/postgres:17.6.1.136 + volumes: + - ./db/roles.sql:/docker-entrypoint-initdb.d/init-scripts/99-roles.sql:ro + - ./db/jwt.sql:/docker-entrypoint-initdb.d/init-scripts/99-jwt.sql:ro + - ${DATA_DIR:-./data}/db:/var/lib/postgresql/data + - db-config:/etc/postgresql-custom + healthcheck: + test: ["CMD", "pg_isready", "-U", "postgres", "-h", "localhost"] + interval: 5s + timeout: 5s + retries: 20 + environment: + POSTGRES_HOST: /var/run/postgresql + PGPORT: 5432 + POSTGRES_PORT: 5432 + PGPASSWORD: ${POSTGRES_PASSWORD} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + PGDATABASE: postgres + POSTGRES_DB: postgres + JWT_EXP: 3600 + command: ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf", "-c", "log_min_messages=fatal"] + + auth: + <<: *hardening + image: supabase/gotrue:v2.197.0 + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9999/health"] + interval: 5s + timeout: 5s + retries: 20 + depends_on: + db: + condition: service_healthy + environment: + GOTRUE_API_HOST: 0.0.0.0 + GOTRUE_API_PORT: 9999 + API_EXTERNAL_URL: ${PUBLIC_URL}/auth/v1 + GOTRUE_DB_DRIVER: postgres + GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:${POSTGRES_PASSWORD}@db:5432/postgres + GOTRUE_SITE_URL: ${PUBLIC_URL} + GOTRUE_URI_ALLOW_LIST: ${PUBLIC_URL}/** + # Set DISABLE_SIGNUP=true in .env after your first sign-in, so nobody else can make an account. + GOTRUE_DISABLE_SIGNUP: ${DISABLE_SIGNUP:-false} + GOTRUE_JWT_ADMIN_ROLES: service_role + GOTRUE_JWT_AUD: authenticated + GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated + GOTRUE_JWT_EXP: 3600 + GOTRUE_JWT_SECRET: ${JWT_SECRET} + GOTRUE_JWT_ISSUER: ${PUBLIC_URL}/auth/v1 + GOTRUE_EXTERNAL_EMAIL_ENABLED: "true" + GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: "false" + GOTRUE_EXTERNAL_PHONE_ENABLED: "false" + GOTRUE_MAILER_AUTOCONFIRM: "false" + GOTRUE_MAILER_URLPATHS_INVITE: /auth/v1/verify + GOTRUE_MAILER_URLPATHS_CONFIRMATION: /auth/v1/verify + GOTRUE_MAILER_URLPATHS_RECOVERY: /auth/v1/verify + GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: /auth/v1/verify + # Sign-in links go to Mailpit below by default. Point these at a real mail server to get them in your inbox. + GOTRUE_SMTP_HOST: ${SMTP_HOST:-mailpit} + GOTRUE_SMTP_PORT: ${SMTP_PORT:-1025} + GOTRUE_SMTP_USER: ${SMTP_USER:-broke} + GOTRUE_SMTP_PASS: ${SMTP_PASS:-broke} + GOTRUE_SMTP_ADMIN_EMAIL: ${SMTP_FROM:-broke@broke.local} + GOTRUE_SMTP_SENDER_NAME: broke + + rest: + <<: *hardening + image: postgrest/postgrest:v14.18 + depends_on: + db: + condition: service_healthy + environment: + PGRST_DB_URI: postgres://authenticator:${POSTGRES_PASSWORD}@db:5432/postgres + PGRST_DB_SCHEMAS: public + PGRST_DB_MAX_ROWS: 1000 + PGRST_DB_EXTRA_SEARCH_PATH: public + PGRST_DB_ANON_ROLE: anon + PGRST_JWT_SECRET: ${JWT_SECRET} + PGRST_DB_USE_LEGACY_GUCS: "false" + PGRST_APP_SETTINGS_JWT_EXP: 3600 + command: ["postgrest"] + + # Catches sign-in emails. Open http://:8025 (user "broke", MAIL_PASSWORD from .env) to click your link. + mailpit: + <<: *hardening + image: axllent/mailpit:v1.27 + ports: + - "${MAIL_UI_PORT:-8025}:8025" + environment: + MP_UI_AUTH: broke:${MAIL_PASSWORD} + MP_SMTP_AUTH_ACCEPT_ANY: 1 + MP_SMTP_AUTH_ALLOW_INSECURE: 1 + MP_MAX_MESSAGES: 200 + + # Local AI, full detail stays here. Start with --profile ai, then: docker exec broke-ollama-1 ollama pull + ollama: + <<: *hardening + image: ollama/ollama:latest + profiles: [ai] + volumes: + - ${DATA_DIR:-./data}/ollama:/root/.ollama + # For an Nvidia GPU on Unraid (Nvidia Driver plugin), uncomment: + # deploy: + # resources: + # reservations: + # devices: [{ driver: nvidia, count: all, capabilities: [gpu] }] + +volumes: + db-config: diff --git a/docker/nginx.conf b/docker/nginx.conf new file mode 100644 index 0000000..51c7913 --- /dev/null +++ b/docker/nginx.conf @@ -0,0 +1,29 @@ +# One address for everything: broke, plus the two Supabase services it needs, on the same origin. +# The browser and broke's server both reach Supabase at PUBLIC_URL/auth/v1 and PUBLIC_URL/rest/v1. +server { + listen 80; + client_max_body_size 25m; # statement uploads + + proxy_http_version 1.1; + proxy_set_header Host $http_host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $http_host; + + # Supabase Auth (GoTrue). Admin routes still need the service role key. + location /auth/v1/ { + proxy_pass http://auth:9999/; + } + + # Supabase REST (PostgREST). Row-level security decides what each user sees. + location /rest/v1/ { + proxy_pass http://rest:3000/; + } + + location / { + proxy_pass http://broke:3000; + proxy_buffering off; # AI answers stream + proxy_read_timeout 300s; + } +} diff --git a/docker/setup.mjs b/docker/setup.mjs new file mode 100644 index 0000000..d952466 --- /dev/null +++ b/docker/setup.mjs @@ -0,0 +1,67 @@ +#!/usr/bin/env node +// Writes docker/.env with fresh secrets for docker-compose.yml. Run once: +// node docker/setup.mjs --url http://192.168.1.10:3000 +// No Node on the server? docker run --rm -v "$PWD":/w -w /w node:22-alpine node docker/setup.mjs --url http://... +import { createHmac, randomBytes } from "node:crypto"; +import { existsSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const file = join(dirname(fileURLToPath(import.meta.url)), ".env"); +const arg = (name) => { const i = process.argv.indexOf(name); return i > 0 ? process.argv[i + 1] : undefined; }; +const url = (arg("--url") ?? "").replace(/\/$/, ""); +if (!/^https?:\/\/[^/]+$/.test(url)) { + console.error("Give the address you will open broke on, with the port: node docker/setup.mjs --url http://192.168.1.10:3000"); + process.exit(1); +} +if (existsSync(file) && !process.argv.includes("--force")) { + console.error(`${file} already exists. Its secrets protect your data, so it is left alone. Pass --force to replace it (only before first start).`); + process.exit(1); +} + +const hex = (n) => randomBytes(n).toString("hex"); +const b64url = (s) => Buffer.from(s).toString("base64url"); +const jwtSecret = randomBytes(32).toString("base64url"); +const jwt = (role) => { + const now = Math.floor(Date.now() / 1000); + const body = `${b64url(JSON.stringify({ alg: "HS256", typ: "JWT" }))}.${b64url(JSON.stringify({ role, iss: "supabase", iat: now, exp: now + 10 * 365 * 24 * 3600 }))}`; + return `${body}.${createHmac("sha256", jwtSecret).update(body).digest("base64url")}`; +}; +const port = new URL(url).port || (url.startsWith("https") ? "443" : "80"); + +writeFileSync(file, `# Made by docker/setup.mjs. Keep it private and backed up: losing it means losing access to the database. + +# The address you open broke on. Built into the app: change it and rebuild (up -d --build). +PUBLIC_URL=${url} +HTTP_PORT=${port} +# Where the database (and Ollama models) live. On Unraid, for example /mnt/user/appdata/broke +DATA_DIR=./data + +POSTGRES_PASSWORD=${hex(24)} +JWT_SECRET=${jwtSecret} +ANON_KEY=${jwt("anon")} +SERVICE_ROLE_KEY=${jwt("service_role")} + +# Sign-in emails. Mailpit's page is on MAIL_UI_PORT, user "broke". +MAIL_UI_PORT=8025 +MAIL_PASSWORD=${hex(12)} +# Or a real mail server: +# SMTP_HOST= +# SMTP_PORT=587 +# SMTP_USER= +# SMTP_PASS= +# SMTP_FROM= + +# After your first sign-in, set this to true and run up -d again. +DISABLE_SIGNUP=false + +# Local AI (docker compose --profile ai). Empty model = the first one installed. +LOCAL_LLM_BASE_URL=http://ollama:11434/v1 +LOCAL_LLM_MODEL= + +# Optional, US/Canada banks only. CSV import needs none of this. +# PLAID_CLIENT_ID= +# PLAID_SECRET= +# PLAID_ENV=sandbox +`, { mode: 0o600 }); +console.log(`Wrote ${file}\nNext: docker compose -f docker/docker-compose.yml up -d --build\nThen open ${url}`);