Refactor all references to computer to Superbrain
release gate / check (push) Failing after 6m55s

This commit is contained in:
Andrew S Erwin
2026-10-22 00:33:44 -05:00
parent 45aa3c80aa
commit d870eece1e
84 changed files with 438 additions and 381 deletions
+4 -4
View File
@@ -1,6 +1,6 @@
# docker compose reads this file for every command (even db-up/migrate), # docker compose reads this file for every command (even db-up/migrate),
# because AUTH_SECRET and POSTGRES_PASSWORD use fail-fast `:?` interpolation. # because AUTH_SECRET and POSTGRES_PASSWORD use fail-fast `:?` interpolation.
POSTGRES_PASSWORD=computer POSTGRES_PASSWORD=superbrain
# See RUNNING.md to generate this with Docker. Keep stable for IMAP passwords. # See RUNNING.md to generate this with Docker. Keep stable for IMAP passwords.
AUTH_SECRET=replace-with-a-random-secret AUTH_SECRET=replace-with-a-random-secret
NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_URL=http://localhost:3000
@@ -26,7 +26,7 @@ ADMIN_EMAILS=
# directly — clients could then choose their own rate-limit bucket. # directly — clients could then choose their own rate-limit bucket.
#TRUSTED_PROXY=1 #TRUSTED_PROXY=1
# Keep these defaults on a new install; change only to reuse an existing volume. # Keep these defaults on a new install; change only to reuse an existing volume.
POSTGRES_VOLUME=computer_pgdata POSTGRES_VOLUME=superbrain_pgdata
POSTGRES_VOLUME_EXTERNAL=false POSTGRES_VOLUME_EXTERNAL=false
# Host-side ports for the 127.0.0.1 bindings of app/web. Change on servers # Host-side ports for the 127.0.0.1 bindings of app/web. Change on servers
# where 8080/3000 are already used (scripts/server-deploy.sh pins 18080/13000). # where 8080/3000 are already used (scripts/server-deploy.sh pins 18080/13000).
@@ -45,9 +45,9 @@ OIDC_CLIENT_SECRET=REPLACE_ME
# Go API listen port (default 8080). # Go API listen port (default 8080).
#PORT=8080 #PORT=8080
# Database URL fallback used by the Makefile when DATABASE_URL is unset. # Database URL fallback used by the Makefile when DATABASE_URL is unset.
#DB_URL=postgres://computer:computer@localhost:5432/computer?sslmode=disable #DB_URL=postgres://superbrain:superbrain@localhost:5432/superbrain?sslmode=disable
# Host-level integration tests (normally run via `make integration` instead): # Host-level integration tests (normally run via `make integration` instead):
#TEST_DATABASE_URL=postgres://computer:computer@localhost:5432/computer?sslmode=disable #TEST_DATABASE_URL=postgres://superbrain:superbrain@localhost:5432/superbrain?sslmode=disable
# Browser tests (scripts/e2e.mjs): # Browser tests (scripts/e2e.mjs):
#BASE_URL=http://localhost:3000 #BASE_URL=http://localhost:3000
#CHROMIUM_PATH=/usr/bin/chromium #CHROMIUM_PATH=/usr/bin/chromium
+1 -1
View File
@@ -38,7 +38,7 @@ jobs:
{ {
echo "POSTGRES_PASSWORD=ci-only-$(openssl rand -hex 8)" echo "POSTGRES_PASSWORD=ci-only-$(openssl rand -hex 8)"
echo "AUTH_SECRET=$(openssl rand -hex 32)" echo "AUTH_SECRET=$(openssl rand -hex 32)"
echo "POSTGRES_VOLUME=computer_pgdata" echo "POSTGRES_VOLUME=superbrain_pgdata"
} > .env } > .env
- name: Install web dependencies - name: Install web dependencies
+1 -1
View File
@@ -1,4 +1,4 @@
# Computer — Where We Stand and What's Next # Superbrain — Where We Stand and What's Next
A plain-language look at the app: what it does today, what it doesn't do A plain-language look at the app: what it does today, what it doesn't do
yet, and what we can build over the next 3–6 months. yet, and what we can build over the next 3–6 months.
+15 -15
View File
@@ -6,15 +6,15 @@ saved views, pages, previews, sharing, contacts and email signals.
## Run the whole app ## Run the whole app
**Client setup guide:** [Running computer](RUNNING.md) covers cloning, setup, **Client setup guide:** [Running superbrain](RUNNING.md) covers cloning, setup,
first login, everyday commands, updates, and troubleshooting on Windows, first login, everyday commands, updates, and troubleshooting on Windows,
macOS, and Linux. macOS, and Linux.
Requires Docker with Compose v2 or newer. On a new installation: Requires Docker with Compose v2 or newer. On a new installation:
```bash ```bash
git clone https://github.com/andrewthecodertx/computer.git git clone https://github.com/andrewthecodertx/superbrain.git
cd computer cd superbrain
cp .env.example .env cp .env.example .env
docker run --rm node:22-alpine node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" docker run --rm node:22-alpine node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
``` ```
@@ -45,8 +45,8 @@ On Windows PowerShell, use `Copy-Item .env.example .env` instead of `cp`.
### Existing Docker database ### Existing Docker database
Set `POSTGRES_VOLUME` to its existing Docker volume name and Set `POSTGRES_VOLUME` to its existing Docker volume name and
`POSTGRES_VOLUME_EXTERNAL=true`. The volume must contain the `computer` `POSTGRES_VOLUME_EXTERNAL=true`. The volume must contain the `superbrain`
database and `computer` role. Stop the previous PostgreSQL container before database and `superbrain` role. Stop the previous PostgreSQL container before
mounting that volume in this stack. mounting that volume in this stack.
`db/schema.sql` initializes a **new, empty** database once. `db/migrations/` `db/schema.sql` initializes a **new, empty** database once. `db/migrations/`
@@ -78,7 +78,7 @@ install it); the index-backed page search depends on it.
everywhere"): it bumps the user's token version, so prior assertions and everywhere"): it bumps the user's token version, so prior assertions and
Go cookie sessions stop working. Go cookie sessions stop working.
- The frontend has no runtime Prisma client or direct database connection. - The frontend has no runtime Prisma client or direct database connection.
- Go also supports its own HttpOnly `computer_session` cookie for direct API - Go also supports its own HttpOnly `superbrain_session` cookie for direct API
consumers. Administration uses the real user; data uses the effective user. consumers. Administration uses the real user; data uses the effective user.
- Containers share the Compose backend network. The app runs as non-root - Containers share the Compose backend network. The app runs as non-root
with a read-only filesystem; the web container has temporary `/tmp` storage. with a read-only filesystem; the web container has temporary `/tmp` storage.
@@ -160,28 +160,28 @@ the client registration example and the implementation handoff.
#### 1. Register the app in Authelia #### 1. Register the app in Authelia
Use an Authelia installation with OIDC enabled and a valid HTTPS issuer URL. Use an Authelia installation with OIDC enabled and a valid HTTPS issuer URL.
Register `computer` as a confidential client with: Register `superbrain` as a confidential client with:
- Scopes: `openid`, `profile`, `email`. - Scopes: `openid`, `profile`, `email`.
- Grant type: `authorization_code`; response type: `code`. - Grant type: `authorization_code`; response type: `code`.
- Token endpoint authentication: `client_secret_basic`. - Token endpoint authentication: `client_secret_basic`.
- Redirect URI: `<PUBLIC_APP_URL>/api/auth/callback/authelia`, for example - Redirect URI: `<PUBLIC_APP_URL>/api/auth/callback/authelia`, for example
`https://computer.company.tld/api/auth/callback/authelia`. `https://superbrain.company.tld/api/auth/callback/authelia`.
Generate a client secret as described in the connection guide. Put its Generate a client secret as described in the connection guide. Put its
**hashed digest** in Authelia and its **plain value** in the app's **hashed digest** in Authelia and its **plain value** in the app's
`OIDC_CLIENT_SECRET`. The redirect URI must exactly match the public web URL `OIDC_CLIENT_SECRET`. The redirect URI must exactly match the public web URL
and callback path. It points to the Next.js server, not the Go API on port 8080. and callback path. It points to the Next.js server, not the Go API on port 8080.
#### 2. Configure computer #### 2. Configure superbrain
Edit the root `.env`, replacing the sample values with your deployment values: Edit the root `.env`, replacing the sample values with your deployment values:
```dotenv ```dotenv
NEXTAUTH_URL=https://computer.company.tld NEXTAUTH_URL=https://superbrain.company.tld
COOKIE_SECURE=1 COOKIE_SECURE=1
OIDC_ISSUER=https://auth.company.tld OIDC_ISSUER=https://auth.company.tld
OIDC_CLIENT_ID=computer OIDC_CLIENT_ID=superbrain
OIDC_CLIENT_SECRET=<plain-client-secret> OIDC_CLIENT_SECRET=<plain-client-secret>
``` ```
@@ -269,7 +269,7 @@ Optional operator-provisioned account: set its address in `ADMIN_EMAILS` in
the root `.env`, run `docker compose up -d`, then: the root `.env`, run `docker compose up -d`, then:
```bash ```bash
docker compose exec -e SEED_EMAIL=admin@company.tld -e SEED_PASSWORD='<chosen-password>' app /computer --seed docker compose exec -e SEED_EMAIL=admin@company.tld -e SEED_PASSWORD='<chosen-password>' app /superbrain --seed
``` ```
This trusted command creates an admin for an allowlisted address. It never This trusted command creates an admin for an allowlisted address. It never
@@ -283,16 +283,16 @@ defaults. Point DNS for your domain at the server, have an ssh alias (or
host) ready, then run from the repository root: host) ready, then run from the repository root:
```bash ```bash
HOST=app-server DOMAIN=computer.example.tld CERTBOT_EMAIL=ops@example.tld ./scripts/deploy.sh HOST=app-server DOMAIN=superbrain.example.tld CERTBOT_EMAIL=ops@example.tld ./scripts/deploy.sh
``` ```
(`make deploy` runs the same script with the same variables.) It records the (`make deploy` runs the same script with the same variables.) It records the
exact git revision, refuses dirty trees unless `ALLOW_DIRTY=1`, rsyncs the exact git revision, refuses dirty trees unless `ALLOW_DIRTY=1`, rsyncs the
source, and on the server: provisions Docker/nginx/certbot, writes `.env` on source, and on the server: provisions Docker/nginx/certbot, writes `.env` on
first deploy, takes a pre-deploy database dump plus `.env` snapshot into first deploy, takes a pre-deploy database dump plus `.env` snapshot into
`/var/backups/computer` (15 retained), builds revision-tagged images, and `/var/backups/superbrain` (15 retained), builds revision-tagged images, and
installs the nginx + Let's Encrypt reverse proxy from installs the nginx + Let's Encrypt reverse proxy from
`deploy/nginx/computer.conf.template`. Rollback means re-deploying an older `deploy/nginx/superbrain.conf.template`. Rollback means re-deploying an older
revision or restoring a pre-deploy dump; migrations are additive. See revision or restoring a pre-deploy dump; migrations are additive. See
RUNNING.md → "Running on a remote server" for the operator checklist. RUNNING.md → "Running on a remote server" for the operator checklist.
+9 -5
View File
@@ -13,16 +13,20 @@
set -eu set -eu
DB_HOST="${DB_HOST:-db}" DB_HOST="${DB_HOST:-db}"
DB_USER="${DB_USER:-computer}" DB_USER="${DB_USER:-superbrain}"
[ -n "${PGPASSWORD:-}" ] || { echo "error: PGPASSWORD is required" >&2; exit 1; } [ -n "${PGPASSWORD:-}" ] || {
echo "error: PGPASSWORD is required" >&2
exit 1
}
BASE_DB=computer_conv_schema BASE_DB=superbrain_conv_schema
CHAIN_DB=computer_conv_chain CHAIN_DB=superbrain_conv_chain
psql() { command psql -h "$DB_HOST" -U "$DB_USER" -v ON_ERROR_STOP=1 "$@"; } psql() { command psql -h "$DB_HOST" -U "$DB_USER" -v ON_ERROR_STOP=1 "$@"; }
drop() { psql -q -d postgres -c "DROP DATABASE IF EXISTS $1 WITH (FORCE)" >/dev/null 2>&1 || true; } drop() { psql -q -d postgres -c "DROP DATABASE IF EXISTS $1 WITH (FORCE)" >/dev/null 2>&1 || true; }
drop "$BASE_DB"; drop "$CHAIN_DB" drop "$BASE_DB"
drop "$CHAIN_DB"
trap 'drop "$BASE_DB"; drop "$CHAIN_DB"' EXIT INT TERM trap 'drop "$BASE_DB"; drop "$CHAIN_DB"' EXIT INT TERM
psql -q -d postgres -c "CREATE DATABASE $BASE_DB" psql -q -d postgres -c "CREATE DATABASE $BASE_DB"
+52 -19
View File
@@ -4,63 +4,96 @@
# scratch databases it creates and drops; app data is never touched. Invoked # scratch databases it creates and drops; app data is never touched. Invoked
# by 'make db-converge' alongside the schema convergence check. # by 'make db-converge' alongside the schema convergence check.
set -u set -u
FAIL_DB=computer_conv_atomicity FAIL_DB=superbrain_conv_atomicity
PSQL="psql -h db -U computer -v ON_ERROR_STOP=1" PSQL="psql -h db -U superbrain -v ON_ERROR_STOP=1"
$PSQL -d postgres -qc "DROP DATABASE IF EXISTS $FAIL_DB WITH (FORCE)" $PSQL -d postgres -qc "DROP DATABASE IF EXISTS $FAIL_DB WITH (FORCE)"
$PSQL -d postgres -qc "CREATE DATABASE $FAIL_DB" $PSQL -d postgres -qc "CREATE DATABASE $FAIL_DB"
mkdir -p /tmp/migs mkdir -p /tmp/migs
echo "--- case 1: failing migration leaves no ledger row and no partial DDL" echo "--- case 1: failing migration leaves no ledger row and no partial DDL"
printf 'CREATE TABLE conv_probe(id text);\nSELECT 1/0;\n' >/tmp/migs/999_probe.sql printf 'CREATE TABLE conv_probe(id text);\nSELECT 1/0;\n' >/tmp/migs/999_probe.sql
MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=computer DB_NAME=$FAIL_DB sh /db/migrate.sh MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$FAIL_DB sh /db/migrate.sh
rc=$? rc=$?
echo "migrate exit=$rc" echo "migrate exit=$rc"
[ "$rc" -ne 0 ] || { echo "FAIL: broken migration exited 0"; exit 1; } [ "$rc" -ne 0 ] || {
echo "FAIL: broken migration exited 0"
exit 1
}
rows=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM _migration") rows=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM _migration")
probe=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_probe'") probe=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_probe'")
[ "$rows" = "0" ] || { echo "FAIL: ledger recorded a rolled-back migration ($rows)"; exit 1; } [ "$rows" = "0" ] || {
[ "$probe" = "0" ] || { echo "FAIL: partial DDL survived the rollback"; exit 1; } echo "FAIL: ledger recorded a rolled-back migration ($rows)"
exit 1
}
[ "$probe" = "0" ] || {
echo "FAIL: partial DDL survived the rollback"
exit 1
}
echo "case 1 OK" echo "case 1 OK"
echo "--- case 2: successful migration applies and records atomically" echo "--- case 2: successful migration applies and records atomically"
printf 'CREATE TABLE conv_probe(id text);\n' >/tmp/migs/999_probe.sql printf 'CREATE TABLE conv_probe(id text);\n' >/tmp/migs/999_probe.sql
MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=computer DB_NAME=$FAIL_DB sh /db/migrate.sh MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$FAIL_DB sh /db/migrate.sh
rc=$? rc=$?
[ "$rc" -eq 0 ] || { echo "FAIL: valid migration exited $rc"; exit 1; } [ "$rc" -eq 0 ] || {
echo "FAIL: valid migration exited $rc"
exit 1
}
rows=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM _migration") rows=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM _migration")
probe=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_probe'") probe=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_probe'")
{ [ "$rows" = "1" ] && [ "$probe" = "1" ]; } || { echo "FAIL: apply/record mismatch rows=$rows probe=$probe"; exit 1; } { [ "$rows" = "1" ] && [ "$probe" = "1" ]; } || {
echo "FAIL: apply/record mismatch rows=$rows probe=$probe"
exit 1
}
echo "case 2 OK" echo "case 2 OK"
echo "--- case 3: re-run is a no-op; tampered checksum aborts before applying" echo "--- case 3: re-run is a no-op; tampered checksum aborts before applying"
MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=computer DB_NAME=$FAIL_DB sh /db/migrate.sh || { echo "FAIL: idempotent re-run failed"; exit 1; } MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$FAIL_DB sh /db/migrate.sh || {
echo "FAIL: idempotent re-run failed"
exit 1
}
printf 'CREATE TABLE conv_probe2(id text);\n' >/tmp/migs/999_probe.sql printf 'CREATE TABLE conv_probe2(id text);\n' >/tmp/migs/999_probe.sql
MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=computer DB_NAME=$FAIL_DB sh /db/migrate.sh MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$FAIL_DB sh /db/migrate.sh
rc=$? rc=$?
[ "$rc" -ne 0 ] || { echo "FAIL: tampered migration did not abort"; exit 1; } [ "$rc" -ne 0 ] || {
echo "FAIL: tampered migration did not abort"
exit 1
}
probe2=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_probe2'") probe2=$($PSQL -At -d $FAIL_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_probe2'")
[ "$probe2" = "0" ] || { echo "FAIL: tampered migration applied anyway"; exit 1; } [ "$probe2" = "0" ] || {
echo "FAIL: tampered migration applied anyway"
exit 1
}
echo "case 3 OK" echo "case 3 OK"
echo "--- case 4: concurrent runners — exactly one applies, the loser aborts" echo "--- case 4: concurrent runners — exactly one applies, the loser aborts"
printf 'CREATE TABLE conv_race(id text);\n' >/tmp/migs/999_probe.sql printf 'CREATE TABLE conv_race(id text);\n' >/tmp/migs/999_probe.sql
RACE_DB=computer_conv_race RACE_DB=superbrain_conv_race
$PSQL -d postgres -qc "DROP DATABASE IF EXISTS $RACE_DB WITH (FORCE)" $PSQL -d postgres -qc "DROP DATABASE IF EXISTS $RACE_DB WITH (FORCE)"
$PSQL -d postgres -qc "CREATE DATABASE $RACE_DB" $PSQL -d postgres -qc "CREATE DATABASE $RACE_DB"
MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=computer DB_NAME=$RACE_DB sh /db/migrate.sh >/tmp/race1.log 2>&1 & MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$RACE_DB sh /db/migrate.sh >/tmp/race1.log 2>&1 &
p1=$! p1=$!
MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=computer DB_NAME=$RACE_DB sh /db/migrate.sh >/tmp/race2.log 2>&1 & MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$RACE_DB sh /db/migrate.sh >/tmp/race2.log 2>&1 &
p2=$! p2=$!
rc1=0; rc2=0 rc1=0
rc2=0
wait $p1 || rc1=$? wait $p1 || rc1=$?
wait $p2 || rc2=$? wait $p2 || rc2=$?
# The loser may abort loudly (primary-key violation after the lock handoff) # The loser may abort loudly (primary-key violation after the lock handoff)
# or no-op via the ledger check; what must hold: at least one succeeds, the # or no-op via the ledger check; what must hold: at least one succeeds, the
# ledger has exactly one row, and the file applied exactly once. # ledger has exactly one row, and the file applied exactly once.
{ [ $rc1 -eq 0 ] || [ $rc2 -eq 0 ]; } || { echo "FAIL: both runners failed"; cat /tmp/race1.log /tmp/race2.log; exit 1; } { [ $rc1 -eq 0 ] || [ $rc2 -eq 0 ]; } || {
echo "FAIL: both runners failed"
cat /tmp/race1.log /tmp/race2.log
exit 1
}
rows=$($PSQL -At -d $RACE_DB -c "SELECT count(*) FROM _migration") rows=$($PSQL -At -d $RACE_DB -c "SELECT count(*) FROM _migration")
race=$($PSQL -At -d $RACE_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_race'") race=$($PSQL -At -d $RACE_DB -c "SELECT count(*) FROM pg_tables WHERE tablename='conv_race'")
{ [ "$rows" = "1" ] && [ "$race" = "1" ]; } || { echo "FAIL: race left rows=$rows table=$race"; cat /tmp/race1.log /tmp/race2.log; exit 1; } { [ "$rows" = "1" ] && [ "$race" = "1" ]; } || {
echo "FAIL: race left rows=$rows table=$race"
cat /tmp/race1.log /tmp/race2.log
exit 1
}
echo "case 4 OK" echo "case 4 OK"
$PSQL -d postgres -qc "DROP DATABASE IF EXISTS $RACE_DB WITH (FORCE)" $PSQL -d postgres -qc "DROP DATABASE IF EXISTS $RACE_DB WITH (FORCE)"
+10 -4
View File
@@ -21,10 +21,13 @@
set -eu set -eu
DB_HOST="${DB_HOST:-db}" DB_HOST="${DB_HOST:-db}"
DB_USER="${DB_USER:-computer}" DB_USER="${DB_USER:-superbrain}"
DB_NAME="${DB_NAME:-computer}" DB_NAME="${DB_NAME:-superbrain}"
MIGRATIONS="${MIGRATIONS:-/db/migrations}" MIGRATIONS="${MIGRATIONS:-/db/migrations}"
[ -n "${PGPASSWORD:-}" ] || { echo "error: PGPASSWORD is required" >&2; exit 1; } [ -n "${PGPASSWORD:-}" ] || {
echo "error: PGPASSWORD is required" >&2
exit 1
}
psql() { psql() {
command psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -v ON_ERROR_STOP=1 "$@" command psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -v ON_ERROR_STOP=1 "$@"
@@ -67,7 +70,10 @@ for entry in $(psql -Atc "SELECT name || ':' || checksum FROM _migration"); do
done done
for f in "$MIGRATIONS"/*.sql; do for f in "$MIGRATIONS"/*.sql; do
[ -e "$f" ] || { echo "error: no migrations found in $MIGRATIONS" >&2; exit 1; } [ -e "$f" ] || {
echo "error: no migrations found in $MIGRATIONS" >&2
exit 1
}
name="$(basename "$f")" name="$(basename "$f")"
sum="$(sha256sum "$f" | cut -d' ' -f1)" sum="$(sha256sum "$f" | cut -d' ' -f1)"
recorded="$(psql -Atc "SELECT checksum FROM _migration WHERE name='$name'")" recorded="$(psql -Atc "SELECT checksum FROM _migration WHERE name='$name'")"
+2 -2
View File
@@ -1,5 +1,5 @@
-- computer database schema -- superbrain database schema
-- Derived from computer_porting_guide.md section 2 and prisma/schema.prisma. -- Derived from superbrain_porting_guide.md section 2 and prisma/schema.prisma.
-- IDs are text (CUID/UUID). CASCADE / SetNull per the guide. -- IDs are text (CUID/UUID). CASCADE / SetNull per the guide.
-- Run against an EMPTY database. Never drops or recreates a database. -- Run against an EMPTY database. Never drops or recreates a database.
@@ -1,4 +1,4 @@
# nginx reverse proxy template for the computer stack. # nginx reverse proxy template for the superbrain stack.
# scripts/server-deploy.sh renders __DOMAIN__ and __WEB_PORT__ (the server's # scripts/server-deploy.sh renders __DOMAIN__ and __WEB_PORT__ (the server's
# WEB_HOST_PORT binding) into the installed site config. The Go API is reached # WEB_HOST_PORT binding) into the installed site config. The Go API is reached
# only through web, as in local dev. TLS certificates come from certbot # only through web, as in local dev. TLS certificates come from certbot
+2 -2
View File
@@ -3,8 +3,8 @@ package auth
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"log" "log"
"net/http" "net/http"
+4 -4
View File
@@ -3,15 +3,15 @@ package auth
import ( import (
"context" "context"
"errors" "errors"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/models" "github.com/andrew/superbrain/internal/models"
"log" "log"
"net/http" "net/http"
"sync" "sync"
) )
const ViewAsCookie = "computer_view_as" const ViewAsCookie = "superbrain_view_as"
type SessionUser struct { type SessionUser struct {
ID, Role, RealID, RealRole string ID, Role, RealID, RealRole string
+4 -4
View File
@@ -25,7 +25,7 @@ import (
"crypto/hmac" "crypto/hmac"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"net" "net"
"net/http" "net/http"
"sort" "sort"
@@ -184,9 +184,9 @@ func clientIP(r *http.Request) string {
// SEC-2). Next only forwards an IP when TRUSTED_PROXY=1 pins the boundary // SEC-2). Next only forwards an IP when TRUSTED_PROXY=1 pins the boundary
// that overwrites X-Real-IP (the shipped nginx template does). // that overwrites X-Real-IP (the shipped nginx template does).
const ( const (
headerClientIP = "X-Computer-Client-Ip" headerClientIP = "X-superbrain-Client-Ip"
headerClientTs = "X-Computer-Client-Ts" headerClientTs = "X-superbrain-Client-Ts"
headerClientSig = "X-Computer-Client-Sig" headerClientSig = "X-superbrain-Client-Sig"
// forwardSkew bounds clock skew and replay of the signed identity. // forwardSkew bounds clock skew and replay of the signed identity.
forwardSkew = 60 * time.Second forwardSkew = 60 * time.Second
) )
+4 -4
View File
@@ -7,7 +7,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
@@ -15,7 +15,7 @@ import (
// cookie. The jwt callback stores token.id = user.id and token.provider; the // cookie. The jwt callback stores token.id = user.id and token.provider; the
// session callback copies token.id to session.user.id (porting guide 3.1). // session callback copies token.id to session.user.id (porting guide 3.1).
const ( const (
sessionCookieName = "computer_session" sessionCookieName = "superbrain_session"
// time.Duration is nanoseconds, so multiply by time.Second explicitly. // time.Duration is nanoseconds, so multiply by time.Second explicitly.
sessionMaxAge = 30 * 24 * 60 * 60 * time.Second // 30 days sessionMaxAge = 30 * 24 * 60 * 60 * time.Second // 30 days
@@ -58,7 +58,7 @@ func SignSession(u SessionUser, secret string) (string, error) {
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(now), IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(sessionMaxAge)), ExpiresAt: jwt.NewNumericDate(now.Add(sessionMaxAge)),
Issuer: "computer", Issuer: "superbrain",
}, },
}) })
return tok.SignedString([]byte(secret)) return tok.SignedString([]byte(secret))
@@ -81,7 +81,7 @@ func verifyClaims(token, secret string) (*SessionClaims, error) {
} }
tok, err := jwt.ParseWithClaims(token, &SessionClaims{}, func(t *jwt.Token) (interface{}, error) { tok, err := jwt.ParseWithClaims(token, &SessionClaims{}, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil return []byte(secret), nil
}, jwt.WithValidMethods([]string{"HS256"}), jwt.WithIssuer("computer"), jwt.WithExpirationRequired()) }, jwt.WithValidMethods([]string{"HS256"}), jwt.WithIssuer("superbrain"), jwt.WithExpirationRequired())
if err != nil { if err != nil {
return nil, err return nil, err
} }
+3 -3
View File
@@ -28,12 +28,12 @@ func TestSessionLifetimeAndVerification(t *testing.T) {
if _, e = VerifySession(token, "wrong-secret"); e == nil { if _, e = VerifySession(token, "wrong-secret"); e == nil {
t.Fatal("accepted wrong secret") t.Fatal("accepted wrong secret")
} }
expired := jwt.NewWithClaims(jwt.SigningMethodHS256, SessionClaims{UserID: "alice", RegisteredClaims: jwt.RegisteredClaims{Issuer: "computer", ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour))}}) expired := jwt.NewWithClaims(jwt.SigningMethodHS256, SessionClaims{UserID: "alice", RegisteredClaims: jwt.RegisteredClaims{Issuer: "superbrain", ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour))}})
v, _ := expired.SignedString([]byte("test-secret")) v, _ := expired.SignedString([]byte("test-secret"))
if _, e = VerifySession(v, "test-secret"); e == nil { if _, e = VerifySession(v, "test-secret"); e == nil {
t.Fatal("accepted expired token") t.Fatal("accepted expired token")
} }
token256 := jwt.NewWithClaims(jwt.SigningMethodHS384, SessionClaims{UserID: "alice", RegisteredClaims: jwt.RegisteredClaims{Issuer: "computer", ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}}) token256 := jwt.NewWithClaims(jwt.SigningMethodHS384, SessionClaims{UserID: "alice", RegisteredClaims: jwt.RegisteredClaims{Issuer: "superbrain", ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}})
v, _ = token256.SignedString([]byte("test-secret")) v, _ = token256.SignedString([]byte("test-secret"))
if _, e = VerifySession(v, "test-secret"); e == nil { if _, e = VerifySession(v, "test-secret"); e == nil {
t.Fatal("accepted unexpected algorithm") t.Fatal("accepted unexpected algorithm")
@@ -46,7 +46,7 @@ func signTestToken(t *testing.T, typ string, ttl time.Duration, ver int) string
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, SessionClaims{ tok := jwt.NewWithClaims(jwt.SigningMethodHS256, SessionClaims{
UserID: "alice", Type: typ, Ver: ver, UserID: "alice", Type: typ, Ver: ver,
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{
Issuer: "computer", Issuer: "superbrain",
IssuedAt: jwt.NewNumericDate(now), IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)), ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
}, },
+5 -5
View File
@@ -16,12 +16,12 @@ func TestSignupValidation(t *testing.T) {
body map[string]any body map[string]any
}{ }{
{"empty", map[string]any{}}, {"empty", map[string]any{}},
{"missing password", map[string]any{"email": "ok@computer.test"}}, {"missing password", map[string]any{"email": "ok@superbrain.test"}},
{"invalid email", map[string]any{"email": "not-an-email", "password": "long-enough-password"}}, {"invalid email", map[string]any{"email": "not-an-email", "password": "long-enough-password"}},
{"email with display name", map[string]any{"email": "Name <ok@computer.test>", "password": "long-enough-password"}}, {"email with display name", map[string]any{"email": "Name <ok@superbrain.test>", "password": "long-enough-password"}},
{"short password", map[string]any{"email": "ok@computer.test", "password": "short"}}, {"short password", map[string]any{"email": "ok@superbrain.test", "password": "short"}},
{"7 boundary password", map[string]any{"email": "ok@computer.test", "password": "1234567"}}, {"7 boundary password", map[string]any{"email": "ok@superbrain.test", "password": "1234567"}},
{"overlong password", map[string]any{"email": "ok@computer.test", "password": strings.Repeat("a", 73)}}, {"overlong password", map[string]any{"email": "ok@superbrain.test", "password": strings.Repeat("a", 73)}},
} }
for _, tc := range cases { for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
+4 -4
View File
@@ -4,10 +4,10 @@ import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/andrew/go-computer/internal/auth" "github.com/andrew/superbrain/internal/auth"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/handlers" "github.com/andrew/superbrain/internal/handlers"
"log" "log"
"net/http" "net/http"
"time" "time"
+1 -1
View File
@@ -35,7 +35,7 @@ const (
tagLength = 16 tagLength = 16
versionByte = 1 versionByte = 1
legacyVersion = 0 legacyVersion = 0
hkdfContext = "computer/imap-password/v1" hkdfContext = "superbrain/imap-password/v1"
) )
// Key derives the 32-byte AES key from the secret using HKDF-SHA256. // Key derives the 32-byte AES key from the secret using HKDF-SHA256.
+1 -1
View File
@@ -12,7 +12,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
_ "github.com/jackc/pgx/v5/stdlib" _ "github.com/jackc/pgx/v5/stdlib"
) )
+2 -2
View File
@@ -4,8 +4,8 @@ import (
"context" "context"
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"github.com/andrew/go-computer/internal/models" "github.com/andrew/superbrain/internal/models"
) )
type UserRepo struct{ db *DB } type UserRepo struct{ db *DB }
+3 -3
View File
@@ -6,9 +6,9 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/markdown" "github.com/andrew/superbrain/internal/markdown"
"github.com/andrew/go-computer/internal/preview" "github.com/andrew/superbrain/internal/preview"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"math" "math"
"net/http" "net/http"
"regexp" "regexp"
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/andrew/go-computer/internal/auth" "github.com/andrew/superbrain/internal/auth"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"io" "io"
"log" "log"
+3 -3
View File
@@ -4,7 +4,7 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
) )
// Structured export (trust phase): a single owner-scoped JSON archive that is // Structured export (trust phase): a single owner-scoped JSON archive that is
@@ -68,9 +68,9 @@ func HandleExport(w http.ResponseWriter, r *http.Request) {
detail["items"], detail["sharedWith"] = items, shares detail["items"], detail["sharedWith"] = items, shares
exported = append(exported, detail) exported = append(exported, detail)
} }
w.Header().Set("Content-Disposition", `attachment; filename="computer-export.json"`) w.Header().Set("Content-Disposition", `attachment; filename="superbrain-export.json"`)
respond(w, 200, object{ respond(w, 200, object{
"format": "computer-export", "format": "superbrain-export",
"version": 1, "version": 1,
"exportedAt": time.Now().UTC(), "exportedAt": time.Now().UTC(),
"user": me, "user": me,
+2 -2
View File
@@ -2,8 +2,8 @@ package handlers
import ( import (
"database/sql" "database/sql"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/kanban" "github.com/andrew/superbrain/internal/kanban"
"net/http" "net/http"
"strings" "strings"
) )
+6 -6
View File
@@ -5,12 +5,12 @@ import (
"database/sql" "database/sql"
"encoding/xml" "encoding/xml"
"errors" "errors"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
crypt "github.com/andrew/go-computer/internal/crypto" crypt "github.com/andrew/superbrain/internal/crypto"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/netguard" "github.com/andrew/superbrain/internal/netguard"
"github.com/andrew/go-computer/internal/outbound" "github.com/andrew/superbrain/internal/outbound"
"github.com/andrew/go-computer/internal/signals" "github.com/andrew/superbrain/internal/signals"
"io" "io"
"net" "net"
"net/http" "net/http"
+4 -4
View File
@@ -65,9 +65,9 @@ func TestParseVCardSubset(t *testing.T) {
"UID:uid-1\r\n" + "UID:uid-1\r\n" +
"item1.FN:Preferred Name\r\n" + "item1.FN:Preferred Name\r\n" +
"item1.X-ABLabel:Main\r\n" + "item1.X-ABLabel:Main\r\n" +
"EMAIL;TYPE=WORK:work@computer.test\r\n" + "EMAIL;TYPE=WORK:work@superbrain.test\r\n" +
"EMAIL;TYPE=PREF:pref@computer.test\r\n" + "EMAIL;TYPE=PREF:pref@superbrain.test\r\n" +
"EMAIL:plain@computer.test\r\n" + "EMAIL:plain@superbrain.test\r\n" +
"TEL;TYPE=HOME,VOICE:+1 555 0100\r\n" + "TEL;TYPE=HOME,VOICE:+1 555 0100\r\n" +
"NOTE:folded line\r\n" + "NOTE:folded line\r\n" +
" continuation\r\n" + " continuation\r\n" +
@@ -87,7 +87,7 @@ func TestParseVCardSubset(t *testing.T) {
if len(v["EMAIL"]) != 3 { if len(v["EMAIL"]) != 3 {
t.Fatalf("repeated EMAILs not preserved: %d", len(v["EMAIL"])) t.Fatalf("repeated EMAILs not preserved: %d", len(v["EMAIL"]))
} }
if got := vCardPick(v["EMAIL"]); got != "pref@computer.test" { if got := vCardPick(v["EMAIL"]); got != "pref@superbrain.test" {
t.Fatalf("PREF selection = %q", got) t.Fatalf("PREF selection = %q", got)
} }
// vCard 4.0 numeric PREF ranks below any TYPE=PREF-free occurrence. // vCard 4.0 numeric PREF ranks below any TYPE=PREF-free occurrence.
+8 -8
View File
@@ -7,7 +7,7 @@ import (
"regexp" "regexp"
"strings" "strings"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
) )
// Connected pages (Notion-like upgrades phase 3). // Connected pages (Notion-like upgrades phase 3).
@@ -15,7 +15,7 @@ import (
// Page hierarchy, internal links and embedded collection views are all // Page hierarchy, internal links and embedded collection views are all
// expressed in the page's Markdown, which stays the single source of truth: // expressed in the page's Markdown, which stays the single source of truth:
// //
// - [Any label](computer:page/<id>) links to another page. /pages?id=<id> // - [Any label](superbrain:page/<id>) links to another page. /pages?id=<id>
// and page/<id> are accepted as aliases so hand-written links work too. // and page/<id> are accepted as aliases so hand-written links work too.
// - {{collection:<id>}} embeds a live collection view; an optional // - {{collection:<id>}} embeds a live collection view; an optional
// {{collection:<id>|view=<viewId>}} pins a saved view's filters/sorts. // {{collection:<id>|view=<viewId>}} pins a saved view's filters/sorts.
@@ -38,10 +38,10 @@ func internalPageID(href string) (string, bool) {
href = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(href, "<"), ">")) href = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(href, "<"), ">"))
raw := "" raw := ""
switch { switch {
case strings.HasPrefix(href, "computer://page/"): case strings.HasPrefix(href, "superbrain://page/"):
raw = strings.TrimPrefix(href, "computer://page/") raw = strings.TrimPrefix(href, "superbrain://page/")
case strings.HasPrefix(href, "computer:page/"): case strings.HasPrefix(href, "superbrain:page/"):
raw = strings.TrimPrefix(href, "computer:page/") raw = strings.TrimPrefix(href, "superbrain:page/")
case strings.HasPrefix(href, "page/"): case strings.HasPrefix(href, "page/"):
raw = strings.TrimPrefix(href, "page/") raw = strings.TrimPrefix(href, "page/")
case strings.HasPrefix(href, "/pages/"): case strings.HasPrefix(href, "/pages/"):
@@ -50,11 +50,11 @@ func internalPageID(href string) (string, bool) {
if u, err := url.Parse(href); err == nil { if u, err := url.Parse(href); err == nil {
raw = u.Query().Get("id") raw = u.Query().Get("id")
} }
case strings.HasPrefix(href, "computer:page?id="): case strings.HasPrefix(href, "superbrain:page?id="):
if u, err := url.Parse(href); err == nil { if u, err := url.Parse(href); err == nil {
raw = u.Query().Get("id") raw = u.Query().Get("id")
} }
case strings.HasPrefix(href, "computer://page?id="): case strings.HasPrefix(href, "superbrain://page?id="):
if u, err := url.Parse(href); err == nil { if u, err := url.Parse(href); err == nil {
raw = u.Query().Get("id") raw = u.Query().Get("id")
} }
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
) )
// Page revision history (trust phase). Every committed content version gets // Page revision history (trust phase). Every committed content version gets
+2 -2
View File
@@ -3,8 +3,8 @@ package handlers
import ( import (
"context" "context"
"database/sql" "database/sql"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/markdown" "github.com/andrew/superbrain/internal/markdown"
"net/http" "net/http"
"strings" "strings"
"time" "time"
+3 -3
View File
@@ -3,9 +3,9 @@ package handlers
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/outbound" "github.com/andrew/superbrain/internal/outbound"
"github.com/andrew/go-computer/internal/signals" "github.com/andrew/superbrain/internal/signals"
"net/http" "net/http"
"strings" "strings"
"time" "time"
+1 -1
View File
@@ -2,7 +2,7 @@ package handlers
import ( import (
"database/sql" "database/sql"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"net/http" "net/http"
"strings" "strings"
"time" "time"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
) )
// Recoverable deletions (trust phase). // Recoverable deletions (trust phase).
+1 -1
View File
@@ -1,7 +1,7 @@
package handlers package handlers
import ( import (
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"net/http" "net/http"
) )
+6 -6
View File
@@ -17,8 +17,8 @@ func collectionBookmark(t *testing.T, c apiClient, url string) string {
func TestCollectionsLifecycle(t *testing.T) { func TestCollectionsLifecycle(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "coll-life@computer.test") alice := newAPIUser(t, srv, "coll-life@superbrain.test")
bob := newAPIUser(t, srv, "coll-other@computer.test") bob := newAPIUser(t, srv, "coll-other@superbrain.test")
bm1 := collectionBookmark(t, alice, "https://127.0.0.1/one") bm1 := collectionBookmark(t, alice, "https://127.0.0.1/one")
@@ -149,7 +149,7 @@ func TestCollectionsLifecycle(t *testing.T) {
func TestCollectionViewsFilterSortPaginate(t *testing.T) { func TestCollectionViewsFilterSortPaginate(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "coll-views@computer.test") alice := newAPIUser(t, srv, "coll-views@superbrain.test")
col := alice.request("POST", "/api/collections", map[string]any{"name": "Pipeline"}, 201) col := alice.request("POST", "/api/collections", map[string]any{"name": "Pipeline"}, 201)
cid := col["id"].(string) cid := col["id"].(string)
@@ -278,9 +278,9 @@ func TestCollectionViewsFilterSortPaginate(t *testing.T) {
func TestCollectionRevocationReachesItems(t *testing.T) { func TestCollectionRevocationReachesItems(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "coll-rev@computer.test") alice := newAPIUser(t, srv, "coll-rev@superbrain.test")
aliceID := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["id"].(string) aliceID := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["id"].(string)
bob := newAPIUser(t, srv, "coll-rev-owner@computer.test") bob := newAPIUser(t, srv, "coll-rev-owner@superbrain.test")
// Bob owns a bookmark and shares it with Alice; Alice puts it in HER // Bob owns a bookmark and shares it with Alice; Alice puts it in HER
// collection. Revocation must make the item vanish from every surface // collection. Revocation must make the item vanish from every surface
@@ -338,7 +338,7 @@ func TestCollectionRevocationReachesItems(t *testing.T) {
// based on the pre-reorder / pre-deletion state get 409s. // based on the pre-reorder / pre-deletion state get 409s.
func TestCollectionIndirectMutationsAdvanceVersions(t *testing.T) { func TestCollectionIndirectMutationsAdvanceVersions(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "coll-rev@computer.test") alice := newAPIUser(t, srv, "coll-rev@superbrain.test")
bm1 := collectionBookmark(t, alice, "https://127.0.0.1/r1") bm1 := collectionBookmark(t, alice, "https://127.0.0.1/r1")
bm2 := collectionBookmark(t, alice, "https://127.0.0.1/r2") bm2 := collectionBookmark(t, alice, "https://127.0.0.1/r2")
col := alice.request("POST", "/api/collections", map[string]any{"name": "Revisions"}, 201) col := alice.request("POST", "/api/collections", map[string]any{"name": "Revisions"}, 201)
+8 -8
View File
@@ -17,8 +17,8 @@ func pageVersion(t *testing.T, c apiClient, id string) int {
func TestPageHierarchy(t *testing.T) { func TestPageHierarchy(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "pages-tree@computer.test") alice := newAPIUser(t, srv, "pages-tree@superbrain.test")
bob := newAPIUser(t, srv, "pages-tree-other@computer.test") bob := newAPIUser(t, srv, "pages-tree-other@superbrain.test")
root := alice.request("POST", "/api/pages", map[string]any{"title": "Root"}, 201)["id"].(string) root := alice.request("POST", "/api/pages", map[string]any{"title": "Root"}, 201)["id"].(string)
child := alice.request("POST", "/api/pages", map[string]any{"title": "Child", "parentId": root}, 201)["id"].(string) child := alice.request("POST", "/api/pages", map[string]any{"title": "Child", "parentId": root}, 201)["id"].(string)
@@ -71,8 +71,8 @@ func TestPageHierarchy(t *testing.T) {
func TestPageBacklinksAndEmbeds(t *testing.T) { func TestPageBacklinksAndEmbeds(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "pages-graph@computer.test") alice := newAPIUser(t, srv, "pages-graph@superbrain.test")
bob := newAPIUser(t, srv, "pages-graph-other@computer.test") bob := newAPIUser(t, srv, "pages-graph-other@superbrain.test")
target := alice.request("POST", "/api/pages", map[string]any{"title": "Target page"}, 201)["id"].(string) target := alice.request("POST", "/api/pages", map[string]any{"title": "Target page"}, 201)["id"].(string)
bobTarget := bob.request("POST", "/api/pages", map[string]any{"title": "Private title"}, 201)["id"].(string) bobTarget := bob.request("POST", "/api/pages", map[string]any{"title": "Private title"}, 201)["id"].(string)
@@ -82,9 +82,9 @@ func TestPageBacklinksAndEmbeds(t *testing.T) {
foreignCollection := bob.request("POST", "/api/collections", map[string]any{"name": "Bob private"}, 201)["id"].(string) foreignCollection := bob.request("POST", "/api/collections", map[string]any{"name": "Bob private"}, 201)["id"].(string)
content := "# Connected\n\n" + content := "# Connected\n\n" +
"- [Target](computer:page/" + target + ")\n" + "- [Target](superbrain:page/" + target + ")\n" +
"- [Alias](/pages?id=" + target + ")\n" + "- [Alias](/pages?id=" + target + ")\n" +
"- [Bob's page](computer:page/" + bobTarget + ")\n\n" + "- [Bob's page](superbrain:page/" + bobTarget + ")\n\n" +
"{{collection:" + collection + "|view=" + view + "}}\n" + "{{collection:" + collection + "|view=" + view + "}}\n" +
"{{collection:" + foreignCollection + "}}\n" "{{collection:" + foreignCollection + "}}\n"
source := alice.request("POST", "/api/pages", map[string]any{"title": "Source page", "content": content}, 201)["id"].(string) source := alice.request("POST", "/api/pages", map[string]any{"title": "Source page", "content": content}, 201)["id"].(string)
@@ -140,7 +140,7 @@ func TestPageBacklinksAndEmbeds(t *testing.T) {
// Re-linking re-establishes the edge; deleting the target removes it. // Re-linking re-establishes the edge; deleting the target removes it.
alice.request("PATCH", "/api/pages/"+source, map[string]any{ alice.request("PATCH", "/api/pages/"+source, map[string]any{
"content": "[Target](computer:page/" + target + ")", "version": pageVersion(t, alice, source), "content": "[Target](superbrain:page/" + target + ")", "version": pageVersion(t, alice, source),
}, 200) }, 200)
if b := alice.request("GET", "/api/pages/"+target, nil, 200)["backlinks"].([]any); len(b) != 1 { if b := alice.request("GET", "/api/pages/"+target, nil, 200)["backlinks"].([]any); len(b) != 1 {
t.Fatalf("re-link was not resolved: %v", b) t.Fatalf("re-link was not resolved: %v", b)
@@ -151,7 +151,7 @@ func TestPageBacklinksAndEmbeds(t *testing.T) {
} }
// Self-links are ignored (a page is not its own backlink). // Self-links are ignored (a page is not its own backlink).
selfContent := "[Me](computer:page/" + source + ")" selfContent := "[Me](superbrain:page/" + source + ")"
alice.request("PATCH", "/api/pages/"+source, map[string]any{ alice.request("PATCH", "/api/pages/"+source, map[string]any{
"content": selfContent, "version": pageVersion(t, alice, source), "content": selfContent, "version": pageVersion(t, alice, source),
}, 200) }, 200)
+20 -20
View File
@@ -16,8 +16,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/andrew/go-computer/internal/auth" "github.com/andrew/superbrain/internal/auth"
"github.com/andrew/go-computer/internal/signals" "github.com/andrew/superbrain/internal/signals"
"github.com/emersion/go-imap/backend/memory" "github.com/emersion/go-imap/backend/memory"
imapserver "github.com/emersion/go-imap/server" imapserver "github.com/emersion/go-imap/server"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
@@ -71,8 +71,8 @@ func newAPIUser(t *testing.T, srv *httptest.Server, email string) apiClient {
func TestPreviouslyUncoveredRoutes(t *testing.T) { func TestPreviouslyUncoveredRoutes(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "coverage-alice@computer.test") alice := newAPIUser(t, srv, "coverage-alice@superbrain.test")
newAPIUser(t, srv, "coverage-searchable@computer.test") newAPIUser(t, srv, "coverage-searchable@superbrain.test")
// GET /api/preview — handler plumbing (auth + query + parse). // GET /api/preview — handler plumbing (auth + query + parse).
html := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { html := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -98,15 +98,15 @@ func TestPreviouslyUncoveredRoutes(t *testing.T) {
// GET /api/users/search — name substring, exact email, masked output, // GET /api/users/search — name substring, exact email, masked output,
// no email-substring enumeration, 2-rune guard. // no email-substring enumeration, 2-rune guard.
users := alice.getJSON("/api/users/search?q=coverage-sea", 200) users := alice.getJSON("/api/users/search?q=coverage-sea", 200)
if len(users) != 1 || users[0]["email"] != "c***@computer.test" { if len(users) != 1 || users[0]["email"] != "c***@superbrain.test" {
t.Fatal("users/search name match:", users) t.Fatal("users/search name match:", users)
} }
if users := alice.getJSON("/api/users/search?q=coverage-searchable@computer.test", 200); len(users) != 1 { if users := alice.getJSON("/api/users/search?q=coverage-searchable@superbrain.test", 200); len(users) != 1 {
t.Fatal("users/search exact email:", users) t.Fatal("users/search exact email:", users)
} }
// "able@computer.test" is a substring of the target's email but not a // "able@superbrain.test" is a substring of the target's email but not a
// full email and not part of any name: must not match. // full email and not part of any name: must not match.
if users := alice.getJSON("/api/users/search?q=able%40computer.test", 200); len(users) != 0 { if users := alice.getJSON("/api/users/search?q=able%40superbrain.test", 200); len(users) != 0 {
t.Fatal("users/search must not substring-match emails:", users) t.Fatal("users/search must not substring-match emails:", users)
} }
if users := alice.getJSON("/api/users/search?q=c", 200); len(users) != 0 { if users := alice.getJSON("/api/users/search?q=c", 200); len(users) != 0 {
@@ -180,9 +180,9 @@ func TestPreviouslyUncoveredRoutes(t *testing.T) {
// cookie: a token copied before signout stops working. // cookie: a token copied before signout stops working.
func TestSignoutRevokesIssuedTokens(t *testing.T) { func TestSignoutRevokesIssuedTokens(t *testing.T) {
srv := testServer(t) srv := testServer(t)
u := newAPIUser(t, srv, "revoke@computer.test") u := newAPIUser(t, srv, "revoke@superbrain.test")
creds, _ := json.Marshal(map[string]any{"email": "revoke@computer.test", "password": "coverage-test-password"}) creds, _ := json.Marshal(map[string]any{"email": "revoke@superbrain.test", "password": "coverage-test-password"})
req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", bytes.NewReader(creds)) req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", bytes.NewReader(creds))
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
res, e := u.c.Do(req) res, e := u.c.Do(req)
@@ -192,7 +192,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) {
res.Body.Close() res.Body.Close()
var stale string var stale string
for _, c := range res.Cookies() { for _, c := range res.Cookies() {
if c.Name == "computer_session" { if c.Name == "superbrain_session" {
stale = c.Value stale = c.Value
} }
} }
@@ -205,7 +205,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) {
// Replay the pre-signout token directly (no jar): must be rejected. // Replay the pre-signout token directly (no jar): must be rejected.
replay := func(path string) int { replay := func(path string) int {
rq, _ := http.NewRequest("GET", srv.URL+path, nil) rq, _ := http.NewRequest("GET", srv.URL+path, nil)
rq.AddCookie(&http.Cookie{Name: "computer_session", Value: stale}) rq.AddCookie(&http.Cookie{Name: "superbrain_session", Value: stale})
rs, e := u.c.Do(rq) rs, e := u.c.Do(rq)
if e != nil { if e != nil {
t.Fatal(e) t.Fatal(e)
@@ -221,7 +221,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) {
t.Fatalf("stale cookie accepted on data route: %d", code) t.Fatalf("stale cookie accepted on data route: %d", code)
} }
rq, _ := http.NewRequest("GET", srv.URL+"/api/auth/session", nil) rq, _ := http.NewRequest("GET", srv.URL+"/api/auth/session", nil)
rq.AddCookie(&http.Cookie{Name: "computer_session", Value: stale}) rq.AddCookie(&http.Cookie{Name: "superbrain_session", Value: stale})
rs, e := u.c.Do(rq) rs, e := u.c.Do(rq)
if e != nil { if e != nil {
t.Fatal(e) t.Fatal(e)
@@ -236,7 +236,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) {
// One scheduler tick creates signals and marks sources checked (TEST-2). // One scheduler tick creates signals and marks sources checked (TEST-2).
func TestSignalSchedulerRunOnce(t *testing.T) { func TestSignalSchedulerRunOnce(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
alice := newAPIUser(t, srv, "scheduler@computer.test") alice := newAPIUser(t, srv, "scheduler@superbrain.test")
listener, e := net.Listen("tcp", "127.0.0.1:0") listener, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil { if e != nil {
@@ -282,7 +282,7 @@ func TestSignalSchedulerRunOnce(t *testing.T) {
// the per-user backoff so the next ticks are skipped. // the per-user backoff so the next ticks are skipped.
func TestSchedulerBacksOffAfterMailboxFailure(t *testing.T) { func TestSchedulerBacksOffAfterMailboxFailure(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
alice := newAPIUser(t, srv, "backoff@computer.test") alice := newAPIUser(t, srv, "backoff@superbrain.test")
id := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.org/backoff"}, 201)["id"].(string) id := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.org/backoff"}, 201)["id"].(string)
alice.request("POST", "/api/bookmarks/"+id+"/signals", map[string]any{"type": "email", "config": map[string]any{"subject": "anything"}}, 201) alice.request("POST", "/api/bookmarks/"+id+"/signals", map[string]any{"type": "email", "config": map[string]any{"subject": "anything"}}, 201)
// Deliberately no saved IMAP configuration: every pass fails in LoadMailbox. // Deliberately no saved IMAP configuration: every pass fails in LoadMailbox.
@@ -317,7 +317,7 @@ func TestSchedulerBacksOffAfterMailboxFailure(t *testing.T) {
// bodies (review PERF-01). // bodies (review PERF-01).
func TestPageVersionAndListProjection(t *testing.T) { func TestPageVersionAndListProjection(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "pagever@computer.test") alice := newAPIUser(t, srv, "pagever@superbrain.test")
created := alice.request("POST", "/api/pages", map[string]any{"title": "Doc", "content": "first"}, 201) created := alice.request("POST", "/api/pages", map[string]any{"title": "Doc", "content": "first"}, 201)
id := created["id"].(string) id := created["id"].(string)
if created["version"].(float64) != 1 { if created["version"].(float64) != 1 {
@@ -369,7 +369,7 @@ func TestPageVersionAndListProjection(t *testing.T) {
// competing writer's committed revision. // competing writer's committed revision.
func TestConcurrentPageSaveAckReportsOwnWrite(t *testing.T) { func TestConcurrentPageSaveAckReportsOwnWrite(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "pageack@computer.test") alice := newAPIUser(t, srv, "pageack@superbrain.test")
id := alice.request("POST", "/api/pages", map[string]any{"title": "Ack", "content": "v1"}, 201)["id"].(string) id := alice.request("POST", "/api/pages", map[string]any{"title": "Ack", "content": "v1"}, 201)["id"].(string)
const writers = 8 const writers = 8
@@ -426,7 +426,7 @@ func TestConcurrentPageSaveAckReportsOwnWrite(t *testing.T) {
// the revision, and tag replacement rides the same contract. // the revision, and tag replacement rides the same contract.
func TestBookmarkVersionContract(t *testing.T) { func TestBookmarkVersionContract(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "bmver@computer.test") alice := newAPIUser(t, srv, "bmver@superbrain.test")
created := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.org/ver", "title": "v0"}, 201) created := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.org/ver", "title": "v0"}, 201)
id := created["id"].(string) id := created["id"].(string)
if created["version"].(float64) != 0 { if created["version"].(float64) != 0 {
@@ -457,7 +457,7 @@ func TestBookmarkVersionContract(t *testing.T) {
// must revoke NextAuth-backed Bearer assertions, not just Go cookie sessions. // must revoke NextAuth-backed Bearer assertions, not just Go cookie sessions.
func TestAssertionRevocationFollowsTokenVersion(t *testing.T) { func TestAssertionRevocationFollowsTokenVersion(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
u := newAPIUser(t, srv, "assert-revoke@computer.test") u := newAPIUser(t, srv, "assert-revoke@superbrain.test")
uid := u.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["id"].(string) uid := u.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["id"].(string)
var ver int var ver int
if e := d.QueryRow(`SELECT "tokenVersion" FROM "User" WHERE id=$1`, uid).Scan(&ver); e != nil { if e := d.QueryRow(`SELECT "tokenVersion" FROM "User" WHERE id=$1`, uid).Scan(&ver); e != nil {
@@ -468,7 +468,7 @@ func TestAssertionRevocationFollowsTokenVersion(t *testing.T) {
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, auth.SessionClaims{ tok := jwt.NewWithClaims(jwt.SigningMethodHS256, auth.SessionClaims{
UserID: uid, Type: auth.TokenTypeAssertion, Ver: v, UserID: uid, Type: auth.TokenTypeAssertion, Ver: v,
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{
Issuer: "computer", Issuer: "superbrain",
IssuedAt: jwt.NewNumericDate(now), IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(60 * time.Second)), ExpiresAt: jwt.NewNumericDate(now.Add(60 * time.Second)),
}, },
+9 -9
View File
@@ -3,9 +3,9 @@ package http
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"github.com/andrew/go-computer/internal/auth" "github.com/andrew/superbrain/internal/auth"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"io" "io"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
@@ -128,16 +128,16 @@ func TestApplicationFlows(t *testing.T) {
post := func(email string) map[string]any { post := func(email string) map[string]any {
return map[string]any{"email": email, "password": "a-long-test-password"} return map[string]any{"email": email, "password": "a-long-test-password"}
} }
alice.request("POST", "/api/signup", post("alice@computer.test"), 201) alice.request("POST", "/api/signup", post("alice@superbrain.test"), 201)
bob.request("POST", "/api/signup", post("bob@computer.test"), 201) bob.request("POST", "/api/signup", post("bob@superbrain.test"), 201)
// Review SEC-4/CR-03: a duplicate signup returns the SAME 201 {"ok":true} // Review SEC-4/CR-03: a duplicate signup returns the SAME 201 {"ok":true}
// body as a fresh creation (no 409, no distinguishing field). // body as a fresh creation (no 409, no distinguishing field).
dup := alice.request("POST", "/api/signup", post("alice@computer.test"), 201) dup := alice.request("POST", "/api/signup", post("alice@superbrain.test"), 201)
if len(dup) != 1 || dup["ok"] != true { if len(dup) != 1 || dup["ok"] != true {
t.Fatalf("duplicate signup body differs from a fresh creation: %v", dup) t.Fatalf("duplicate signup body differs from a fresh creation: %v", dup)
} }
alice.request("POST", "/api/auth/login", post("alice@computer.test"), 200) alice.request("POST", "/api/auth/login", post("alice@superbrain.test"), 200)
bob.request("POST", "/api/auth/login", post("bob@computer.test"), 200) bob.request("POST", "/api/auth/login", post("bob@superbrain.test"), 200)
au := meID(alice) au := meID(alice)
bu := meID(bob) bu := meID(bob)
if alice.request("GET", "/api/me", nil, 200)["isAdmin"] != true { if alice.request("GET", "/api/me", nil, 200)["isAdmin"] != true {
@@ -189,7 +189,7 @@ func TestApplicationFlows(t *testing.T) {
t.Fatal("alert dismissal") t.Fatal("alert dismissal")
} }
putBookmark(alice, id, map[string]any{"alertAt": "2000-01-02"}, 200) putBookmark(alice, id, map[string]any{"alertAt": "2000-01-02"}, 200)
source := alice.request("POST", "/api/bookmarks/"+id+"/signals", map[string]any{"type": "email", "config": map[string]any{"from": "sender@computer.test"}}, 201)["id"].(string) source := alice.request("POST", "/api/bookmarks/"+id+"/signals", map[string]any{"type": "email", "config": map[string]any{"from": "sender@superbrain.test"}}, 201)["id"].(string)
alice.request("POST", "/api/bookmarks/"+id+"/signals", map[string]any{"action": "check"}, 200) alice.request("POST", "/api/bookmarks/"+id+"/signals", map[string]any{"action": "check"}, 200)
alice.request("PATCH", "/api/signal-sources/"+source, map[string]any{"enabled": false}, 200) alice.request("PATCH", "/api/signal-sources/"+source, map[string]any{"enabled": false}, 200)
bob.request("DELETE", "/api/signal-sources/"+source, nil, 404) bob.request("DELETE", "/api/signal-sources/"+source, nil, 404)
+10 -10
View File
@@ -3,8 +3,8 @@ package http
import ( import (
"context" "context"
"encoding/json" "encoding/json"
crypt "github.com/andrew/go-computer/internal/crypto" crypt "github.com/andrew/superbrain/internal/crypto"
"github.com/andrew/go-computer/internal/signals" "github.com/andrew/superbrain/internal/signals"
"github.com/emersion/go-imap/backend/memory" "github.com/emersion/go-imap/backend/memory"
imapserver "github.com/emersion/go-imap/server" imapserver "github.com/emersion/go-imap/server"
"io" "io"
@@ -22,7 +22,7 @@ func TestExternalIntegrations(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
jar, _ := cookiejar.New(nil) jar, _ := cookiejar.New(nil)
a := apiClient{t, &http.Client{Jar: jar}, srv.URL} a := apiClient{t, &http.Client{Jar: jar}, srv.URL}
credentials := map[string]any{"email": "integrations@computer.test", "password": "test-password"} credentials := map[string]any{"email": "integrations@superbrain.test", "password": "test-password"}
a.request("POST", "/api/signup", credentials, 201) a.request("POST", "/api/signup", credentials, 201)
a.request("POST", "/api/auth/login", credentials, 200) a.request("POST", "/api/auth/login", credentials, 200)
// CardDAV fixture (reviews CR-07/CR-08): the served multistatus is // CardDAV fixture (reviews CR-07/CR-08): the served multistatus is
@@ -48,14 +48,14 @@ func TestExternalIntegrations(t *testing.T) {
card1 := `<d:response><d:href>/card.vcf</d:href><d:propstat><d:prop><card:address-data>BEGIN:VCARD card1 := `<d:response><d:href>/card.vcf</d:href><d:propstat><d:prop><card:address-data>BEGIN:VCARD
UID:contact-1 UID:contact-1
FN:Contact Name FN:Contact Name
EMAIL:last@computer.test EMAIL:last@superbrain.test
EMAIL;TYPE=PREF:preferred@computer.test EMAIL;TYPE=PREF:preferred@superbrain.test
TEL:1234 TEL:1234
END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>` END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`
card2 := `<d:response><d:href>/card2.vcf</d:href><d:propstat><d:prop><card:address-data>BEGIN:VCARD card2 := `<d:response><d:href>/card2.vcf</d:href><d:propstat><d:prop><card:address-data>BEGIN:VCARD
UID:contact-2 UID:contact-2
FN:Second Contact FN:Second Contact
EMAIL:second@computer.test EMAIL:second@superbrain.test
END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>` END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`
card2Withheld := `<d:response><d:href>/card2.vcf</d:href><d:propstat><d:prop/><d:status>HTTP/1.1 404 Not Found</d:status></d:propstat></d:response>` card2Withheld := `<d:response><d:href>/card2.vcf</d:href><d:propstat><d:prop/><d:status>HTTP/1.1 404 Not Found</d:status></d:propstat></d:response>`
wrap := func(responses ...string) string { wrap := func(responses ...string) string {
@@ -85,7 +85,7 @@ END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:pr
t.Fatal("CardDAV import count", contacts) t.Fatal("CardDAV import count", contacts)
} }
for _, c := range contacts { for _, c := range contacts {
if c["uid"] == "contact-1" && c["email"] != "preferred@computer.test" { if c["uid"] == "contact-1" && c["email"] != "preferred@superbrain.test" {
t.Fatal("repeated EMAIL did not resolve to the PREF value:", c) t.Fatal("repeated EMAIL did not resolve to the PREF value:", c)
} }
} }
@@ -173,7 +173,7 @@ END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:pr
// Nextcloud URL is rejected at the API boundary — no dial, no credentials. // Nextcloud URL is rejected at the API boundary — no dial, no credentials.
func TestCardDAVRequiresTLSOutsideFixtures(t *testing.T) { func TestCardDAVRequiresTLSOutsideFixtures(t *testing.T) {
srv := testServer(t) srv := testServer(t)
a := newAPIUser(t, srv, "carddav-tls@computer.test") a := newAPIUser(t, srv, "carddav-tls@superbrain.test")
t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "") t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "")
a.request("POST", "/api/contacts/sync", map[string]any{ a.request("POST", "/api/contacts/sync", map[string]any{
"nextcloudUrl": "http://nextcloud.example.test", "username": "u", "password": "p", "nextcloudUrl": "http://nextcloud.example.test", "username": "u", "password": "p",
@@ -194,7 +194,7 @@ func TestCardDAVRequiresTLSOutsideFixtures(t *testing.T) {
// rewrites the password column at all. // rewrites the password column at all.
func TestImapCredentialWritesNeverRestoreStalePasswords(t *testing.T) { func TestImapCredentialWritesNeverRestoreStalePasswords(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
alice := newAPIUser(t, srv, "imap-stale@computer.test") alice := newAPIUser(t, srv, "imap-stale@superbrain.test")
t.Setenv("ENCRYPTION_KEY", "dedicated-encryption-key") t.Setenv("ENCRYPTION_KEY", "dedicated-encryption-key")
uid := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["id"].(string) uid := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["id"].(string)
@@ -246,6 +246,6 @@ func TestImapCredentialWritesNeverRestoreStalePasswords(t *testing.T) {
// A masked save with no stored configuration is a 400, never an empty // A masked save with no stored configuration is a 400, never an empty
// or resurrected password. // or resurrected password.
bob := newAPIUser(t, srv, "imap-nocfg@computer.test") bob := newAPIUser(t, srv, "imap-nocfg@superbrain.test")
bob.request("POST", "/api/settings/imap", map[string]any{"host": "h.example.test", "port": 993, "tls": true, "username": "user", "password": "••••••••", "folder": "INBOX"}, 400) bob.request("POST", "/api/settings/imap", map[string]any{"host": "h.example.test", "port": 993, "tls": true, "username": "user", "password": "••••••••", "folder": "INBOX"}, 400)
} }
+2 -2
View File
@@ -7,7 +7,7 @@ import "testing"
// still honors the bookmark concurrency version (review CR-04). // still honors the bookmark concurrency version (review CR-04).
func TestKanbanCardMovePersistsOrdering(t *testing.T) { func TestKanbanCardMovePersistsOrdering(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "kanban-order@computer.test") alice := newAPIUser(t, srv, "kanban-order@superbrain.test")
cols := alice.getJSON("/api/kanban/columns", 200) cols := alice.getJSON("/api/kanban/columns", 200)
if len(cols) < 2 { if len(cols) < 2 {
t.Fatalf("expected default columns, got %d", len(cols)) t.Fatalf("expected default columns, got %d", len(cols))
@@ -113,7 +113,7 @@ func TestKanbanCardMovePersistsOrdering(t *testing.T) {
} }
// Foreign columns are never accepted. // Foreign columns are never accepted.
bob := newAPIUser(t, srv, "kanban-other@computer.test") bob := newAPIUser(t, srv, "kanban-other@superbrain.test")
bobCols := bob.getJSON("/api/kanban/columns", 200) bobCols := bob.getJSON("/api/kanban/columns", 200)
foreign := bobCols[0]["id"].(string) foreign := bobCols[0]["id"].(string)
firstNow := alice.request("GET", "/api/bookmarks/"+first["id"].(string), nil, 200) firstNow := alice.request("GET", "/api/bookmarks/"+first["id"].(string), nil, 200)
+3 -3
View File
@@ -10,8 +10,8 @@ import (
// trigram indexes introduced alongside the escaping change. // trigram indexes introduced alongside the escaping change.
func TestPageSearchEscapesWildcards(t *testing.T) { func TestPageSearchEscapesWildcards(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
alice, _ := accountClient(t, srv.URL, "pagesearch@computer.test") alice, _ := accountClient(t, srv.URL, "pagesearch@superbrain.test")
other, _ := accountClient(t, srv.URL, "pagesearch-other@computer.test") other, _ := accountClient(t, srv.URL, "pagesearch-other@superbrain.test")
alice.request("POST", "/api/pages", map[string]any{"title": "100% done", "content": "literal percent"}, 201) alice.request("POST", "/api/pages", map[string]any{"title": "100% done", "content": "literal percent"}, 201)
alice.request("POST", "/api/pages", map[string]any{"title": "100x done", "content": "not a percent"}, 201) alice.request("POST", "/api/pages", map[string]any{"title": "100x done", "content": "not a percent"}, 201)
@@ -44,7 +44,7 @@ func TestPageSearchEscapesWildcards(t *testing.T) {
// instead of persisting them (the 1 MiB body cap alone is too coarse). // instead of persisting them (the 1 MiB body cap alone is too coarse).
func TestTextFieldSizeLimits(t *testing.T) { func TestTextFieldSizeLimits(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice, _ := accountClient(t, srv.URL, "limits@computer.test") alice, _ := accountClient(t, srv.URL, "limits@superbrain.test")
const ( const (
urlLimit = 2048 urlLimit = 2048
+1 -1
View File
@@ -12,7 +12,7 @@ import (
// every file twice in order cannot change the backfill guarantees. // every file twice in order cannot change the backfill guarantees.
func TestUpgradeBackfillsLegacyWatchesWithoutChangingExistingSources(t *testing.T) { func TestUpgradeBackfillsLegacyWatchesWithoutChangingExistingSources(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
_, uid := accountClient(t, srv.URL, "watcher@computer.test") _, uid := accountClient(t, srv.URL, "watcher@superbrain.test")
if _, err := d.Exec(`INSERT INTO "Bookmark"(id,url,"ownerId","imapWatchEnabled","imapQuery") VALUES('old','https://127.0.0.1',$1,true,'Invoices'),('paused','https://127.0.0.1',$1,true,'Receipts'),('off','https://127.0.0.1',$1,false,'Other')`, uid); err != nil { if _, err := d.Exec(`INSERT INTO "Bookmark"(id,url,"ownerId","imapWatchEnabled","imapQuery") VALUES('old','https://127.0.0.1',$1,true,'Invoices'),('paused','https://127.0.0.1',$1,true,'Receipts'),('off','https://127.0.0.1',$1,false,'Other')`, uid); err != nil {
t.Fatal(err) t.Fatal(err)
} }
+2 -2
View File
@@ -9,8 +9,8 @@ import (
func TestBookmarkPaginationPreservesCollectionAndOwnership(t *testing.T) { func TestBookmarkPaginationPreservesCollectionAndOwnership(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
owner, uid := accountClient(t, srv.URL, "owner@computer.test") owner, uid := accountClient(t, srv.URL, "owner@superbrain.test")
other, oid := accountClient(t, srv.URL, "other@computer.test") other, oid := accountClient(t, srv.URL, "other@superbrain.test")
for _, user := range []string{uid, oid} { for _, user := range []string{uid, oid} {
if _, err := d.Exec(`INSERT INTO "Bookmark"(id,url,title,"ownerId","updatedAt") SELECT $1||'-'||lpad(n::text,4,'0'),'https://127.0.0.1/test','Match '||n,$1,'2026-10-07T12:00:00Z' FROM generate_series(1,205) n`, user); err != nil { if _, err := d.Exec(`INSERT INTO "Bookmark"(id,url,title,"ownerId","updatedAt") SELECT $1||'-'||lpad(n::text,4,'0'),'https://127.0.0.1/test','Match '||n,$1,'2026-10-07T12:00:00Z' FROM generate_series(1,205) n`, user); err != nil {
t.Fatal(err) t.Fatal(err)
+12 -12
View File
@@ -42,8 +42,8 @@ func rawCall(t *testing.T, c apiClient, method, path string, body []byte, header
// one of them win and the other observe the committed count. // one of them win and the other observe the committed count.
func TestConcurrentAdminDemotionsKeepOneAdmin(t *testing.T) { func TestConcurrentAdminDemotionsKeepOneAdmin(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
a, _ := accountClient(t, srv.URL, "admin-a@computer.test") a, _ := accountClient(t, srv.URL, "admin-a@superbrain.test")
b, bID := accountClient(t, srv.URL, "admin-b@computer.test") b, bID := accountClient(t, srv.URL, "admin-b@superbrain.test")
a.request("PATCH", "/api/admin/users", map[string]any{"userId": bID, "role": "ADMIN"}, 200) a.request("PATCH", "/api/admin/users", map[string]any{"userId": bID, "role": "ADMIN"}, 200)
aID := meID(a) aID := meID(a)
@@ -93,7 +93,7 @@ func TestSignupTrimsWhitespaceName(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
jar, _ := cookiejar.New(nil) jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL} c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
body := map[string]any{"email": "trimmed@computer.test", "password": "test-long-password", "name": " "} body := map[string]any{"email": "trimmed@superbrain.test", "password": "test-long-password", "name": " "}
c.request("POST", "/api/signup", body, 201) c.request("POST", "/api/signup", body, 201)
c.request("POST", "/api/auth/login", body, 200) c.request("POST", "/api/auth/login", body, 200)
me := c.request("GET", "/api/me", nil, 200) me := c.request("GET", "/api/me", nil, 200)
@@ -107,7 +107,7 @@ func TestSignupTrimsWhitespaceName(t *testing.T) {
// INSERT per id inside a user-locked transaction. // INSERT per id inside a user-locked transaction.
func TestShareRecipientListsAreCapped(t *testing.T) { func TestShareRecipientListsAreCapped(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
owner, _ := accountClient(t, srv.URL, "cap-owner@computer.test") owner, _ := accountClient(t, srv.URL, "cap-owner@superbrain.test")
id := owner.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.com/cap"}, 201)["id"].(string) id := owner.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.com/cap"}, 201)["id"].(string)
tooMany := make([]string, maxTestShareRecipients+1) tooMany := make([]string, maxTestShareRecipients+1)
@@ -132,7 +132,7 @@ const (
// Review L-8: an oversized direct API body is 413, not a misleading 400. // Review L-8: an oversized direct API body is 413, not a misleading 400.
func TestOversizedDirectBodyReturns413(t *testing.T) { func TestOversizedDirectBodyReturns413(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
owner, _ := accountClient(t, srv.URL, "oversized@computer.test") owner, _ := accountClient(t, srv.URL, "oversized@superbrain.test")
body := []byte(`{"url":"https://example.com","notes":"` + strings.Repeat("a", 1<<20) + `"}`) body := []byte(`{"url":"https://example.com","notes":"` + strings.Repeat("a", 1<<20) + `"}`)
status, _ := rawCall(t, owner, "POST", "/api/bookmarks", body, nil) status, _ := rawCall(t, owner, "POST", "/api/bookmarks", body, nil)
if status != http.StatusRequestEntityTooLarge { if status != http.StatusRequestEntityTooLarge {
@@ -144,7 +144,7 @@ func TestOversizedDirectBodyReturns413(t *testing.T) {
// endpoints, while an idempotent same-origin call still succeeds. // endpoints, while an idempotent same-origin call still succeeds.
func TestSignoutRejectsCrossOrigin(t *testing.T) { func TestSignoutRejectsCrossOrigin(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
owner, _ := accountClient(t, srv.URL, "signout@computer.test") owner, _ := accountClient(t, srv.URL, "signout@superbrain.test")
body := []byte(`{}`) body := []byte(`{}`)
status, _ := rawCall(t, owner, "POST", "/api/auth/signout", body, map[string]string{"Origin": "https://attacker.invalid"}) status, _ := rawCall(t, owner, "POST", "/api/auth/signout", body, map[string]string{"Origin": "https://attacker.invalid"})
if status != http.StatusForbidden { if status != http.StatusForbidden {
@@ -160,7 +160,7 @@ func TestSignoutRejectsCrossOrigin(t *testing.T) {
// groups instead of trusting a client to keep them apart. // groups instead of trusting a client to keep them apart.
func TestPageReorderKeepsPinnedGrouping(t *testing.T) { func TestPageReorderKeepsPinnedGrouping(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
owner, _ := accountClient(t, srv.URL, "reorder@computer.test") owner, _ := accountClient(t, srv.URL, "reorder@superbrain.test")
pinned := owner.request("POST", "/api/pages", map[string]any{"title": "Pinned", "pinned": true}, 201)["id"].(string) pinned := owner.request("POST", "/api/pages", map[string]any{"title": "Pinned", "pinned": true}, 201)["id"].(string)
second := owner.request("POST", "/api/pages", map[string]any{"title": "Second"}, 201)["id"].(string) second := owner.request("POST", "/api/pages", map[string]any{"title": "Second"}, 201)["id"].(string)
third := owner.request("POST", "/api/pages", map[string]any{"title": "Third"}, 201)["id"].(string) third := owner.request("POST", "/api/pages", map[string]any{"title": "Third"}, 201)["id"].(string)
@@ -193,7 +193,7 @@ func TestPageReorderKeepsPinnedGrouping(t *testing.T) {
// rejected instead of silently discarded. // rejected instead of silently discarded.
func TestPropertyConfigRejectsMalformedValues(t *testing.T) { func TestPropertyConfigRejectsMalformedValues(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
owner, _ := accountClient(t, srv.URL, "props@computer.test") owner, _ := accountClient(t, srv.URL, "props@superbrain.test")
cid := owner.request("POST", "/api/collections", map[string]any{"name": "Config"}, 201)["id"].(string) cid := owner.request("POST", "/api/collections", map[string]any{"name": "Config"}, 201)["id"].(string)
for _, cfg := range []any{"x", []any{}, 5, true} { for _, cfg := range []any{"x", []any{}, 5, true} {
owner.request("POST", "/api/collections/"+cid+"/properties", map[string]any{"name": "Bad", "type": "TEXT", "config": cfg}, 400) owner.request("POST", "/api/collections/"+cid+"/properties", map[string]any{"name": "Bad", "type": "TEXT", "config": cfg}, 400)
@@ -206,8 +206,8 @@ func TestPropertyConfigRejectsMalformedValues(t *testing.T) {
// creating duplicate calendar entries. // creating duplicate calendar entries.
func TestSharedDateReshareIsIdempotent(t *testing.T) { func TestSharedDateReshareIsIdempotent(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
owner, _ := accountClient(t, srv.URL, "dates-owner@computer.test") owner, _ := accountClient(t, srv.URL, "dates-owner@superbrain.test")
_, recipientID := accountClient(t, srv.URL, "dates-recipient@computer.test") _, recipientID := accountClient(t, srv.URL, "dates-recipient@superbrain.test")
post := func(note string) []map[string]any { post := func(note string) []map[string]any {
body, _ := json.Marshal(map[string]any{"date": "2026-11-05", "note": note, "recipientIds": []string{recipientID}}) body, _ := json.Marshal(map[string]any{"date": "2026-11-05", "note": note, "recipientIds": []string{recipientID}})
@@ -258,7 +258,7 @@ func TestSharedDateReshareIsIdempotent(t *testing.T) {
func TestCardDAVRejectsNonStandardPort(t *testing.T) { func TestCardDAVRejectsNonStandardPort(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "0") t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "0")
owner, _ := accountClient(t, srv.URL, "carddav@computer.test") owner, _ := accountClient(t, srv.URL, "carddav@superbrain.test")
v := owner.request("POST", "/api/contacts/sync", map[string]any{ v := owner.request("POST", "/api/contacts/sync", map[string]any{
"nextcloudUrl": "https://198.51.100.10:8443", "nextcloudUrl": "https://198.51.100.10:8443",
"username": "user", "username": "user",
@@ -274,7 +274,7 @@ func TestCardDAVRejectsNonStandardPort(t *testing.T) {
// renumbers positions contiguously, so reload order is deterministic. // renumbers positions contiguously, so reload order is deterministic.
func TestColumnDeleteNormalizesMovedCardPositions(t *testing.T) { func TestColumnDeleteNormalizesMovedCardPositions(t *testing.T) {
srv, _ := testServerDB(t) srv, _ := testServerDB(t)
owner, _ := accountClient(t, srv.URL, "columns@computer.test") owner, _ := accountClient(t, srv.URL, "columns@superbrain.test")
var columns []map[string]any var columns []map[string]any
res, err := owner.c.Get(srv.URL + "/api/kanban/columns") res, err := owner.c.Get(srv.URL + "/api/kanban/columns")
if err != nil { if err != nil {
+26 -26
View File
@@ -7,7 +7,7 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"github.com/andrew/go-computer/internal/scripts" "github.com/andrew/superbrain/internal/scripts"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
"os" "os"
@@ -18,18 +18,18 @@ import (
func TestConfiguredAdminCannotBeBypassedDuringBootstrap(t *testing.T) { func TestConfiguredAdminCannotBeBypassedDuringBootstrap(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
t.Setenv("ADMIN_EMAILS", "operator@computer.test") t.Setenv("ADMIN_EMAILS", "operator@superbrain.test")
visitor, _ := accountClient(t, srv.URL, "visitor@computer.test") visitor, _ := accountClient(t, srv.URL, "visitor@superbrain.test")
if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != false { if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
t.Fatal("public signup bypassed reserved administrator bootstrap") t.Fatal("public signup bypassed reserved administrator bootstrap")
} }
visitor.request("GET", "/api/admin/users", nil, 403) visitor.request("GET", "/api/admin/users", nil, 403)
t.Setenv("SEED_EMAIL", "operator@computer.test") t.Setenv("SEED_EMAIL", "operator@superbrain.test")
t.Setenv("SEED_PASSWORD", "operator-test-password") t.Setenv("SEED_PASSWORD", "operator-test-password")
if err := scripts.Seed(context.Background(), d); err != nil { if err := scripts.Seed(context.Background(), d); err != nil {
t.Fatal(err) t.Fatal(err)
} }
visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@computer.test", "password": "operator-test-password"}, 200) visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@superbrain.test", "password": "operator-test-password"}, 200)
if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != true { if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != true {
t.Fatal("operator-provisioned account is not admin") t.Fatal("operator-provisioned account is not admin")
} }
@@ -37,7 +37,7 @@ func TestConfiguredAdminCannotBeBypassedDuringBootstrap(t *testing.T) {
if err := scripts.Seed(context.Background(), d); err != nil { if err := scripts.Seed(context.Background(), d); err != nil {
t.Fatal(err) t.Fatal(err)
} }
visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@computer.test", "password": "operator-test-password"}, 200) visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@superbrain.test", "password": "operator-test-password"}, 200)
} }
func accountClient(t *testing.T, base, email string) (apiClient, string) { func accountClient(t *testing.T, base, email string) (apiClient, string) {
@@ -54,14 +54,14 @@ func accountClient(t *testing.T, base, email string) (apiClient, string) {
func TestAdminEnrollmentRequiresTrustedIdentity(t *testing.T) { func TestAdminEnrollmentRequiresTrustedIdentity(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
admin, _ := accountClient(t, srv.URL, "admin@computer.test") admin, _ := accountClient(t, srv.URL, "admin@superbrain.test")
user, uid := accountClient(t, srv.URL, "unverified@computer.test") user, uid := accountClient(t, srv.URL, "unverified@superbrain.test")
t.Setenv("ADMIN_EMAILS", "reserved@computer.test,unverified@computer.test") t.Setenv("ADMIN_EMAILS", "reserved@superbrain.test,unverified@superbrain.test")
// Reserved addresses answer exactly like existing accounts (no 403 oracle). // Reserved addresses answer exactly like existing accounts (no 403 oracle).
// Review SEC-4/CR-03: operator-reserved addresses return the SAME uniform // Review SEC-4/CR-03: operator-reserved addresses return the SAME uniform
// 201 {"ok":true} body as every other accepted registration — no userId // 201 {"ok":true} body as every other accepted registration — no userId
// field, no 409. // field, no 409.
reserved := user.request("POST", "/api/signup", map[string]any{"email": "reserved@computer.test", "password": "test-password"}, 201) reserved := user.request("POST", "/api/signup", map[string]any{"email": "reserved@superbrain.test", "password": "test-password"}, 201)
if len(reserved) != 1 || reserved["ok"] != true { if len(reserved) != 1 || reserved["ok"] != true {
t.Fatalf("operator-reserved address body is distinguishable: %v", reserved) t.Fatalf("operator-reserved address body is distinguishable: %v", reserved)
} }
@@ -80,9 +80,9 @@ func TestAdminEnrollmentRequiresTrustedIdentity(t *testing.T) {
func TestPublicBookmarksDoNotExposePrivateMetadata(t *testing.T) { func TestPublicBookmarksDoNotExposePrivateMetadata(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
owner, uid := accountClient(t, srv.URL, "owner@computer.test") owner, uid := accountClient(t, srv.URL, "owner@superbrain.test")
viewer, vid := accountClient(t, srv.URL, "viewer@computer.test") viewer, vid := accountClient(t, srv.URL, "viewer@superbrain.test")
if _, err := d.Exec(`INSERT INTO "Contact"(id,uid,"displayName",email,phone,"userId") VALUES('contact','vcard','Private','private@computer.test','555-private',$1)`, uid); err != nil { if _, err := d.Exec(`INSERT INTO "Contact"(id,uid,"displayName",email,phone,"userId") VALUES('contact','vcard','Private','private@superbrain.test','555-private',$1)`, uid); err != nil {
t.Fatal(err) t.Fatal(err)
} }
id := owner.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/test", "isPublic": true, "contactId": "contact", "imapQuery": "private mailbox query", "alertAt": "2026-10-07"}, 201)["id"].(string) id := owner.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/test", "isPublic": true, "contactId": "contact", "imapQuery": "private mailbox query", "alertAt": "2026-10-07"}, 201)["id"].(string)
@@ -112,7 +112,7 @@ func TestPublicBookmarksDoNotExposePrivateMetadata(t *testing.T) {
t.Error("shared-reader response lost tags") t.Error("shared-reader response lost tags")
} }
full := owner.request("GET", "/api/bookmarks/"+id, nil, 200) full := owner.request("GET", "/api/bookmarks/"+id, nil, 200)
if c, _ := full["contact"].(map[string]any); c == nil || c["email"] != "private@computer.test" { if c, _ := full["contact"].(map[string]any); c == nil || c["email"] != "private@superbrain.test" {
t.Error("owner projection lost the contact record") t.Error("owner projection lost the contact record")
} }
if s, ok := full["sharedWith"].([]any); !ok || len(s) != 1 { if s, ok := full["sharedWith"].([]any); !ok || len(s) != 1 {
@@ -146,7 +146,7 @@ func TestPublicBookmarksDoNotExposePrivateMetadata(t *testing.T) {
func TestAdminBootstrapIsOneShot(t *testing.T) { func TestAdminBootstrapIsOneShot(t *testing.T) {
srv, d := testServerDB(t) srv, d := testServerDB(t)
// Fresh installation: the first signup completes bootstrap as admin. // Fresh installation: the first signup completes bootstrap as admin.
admin, adminID := accountClient(t, srv.URL, "first@computer.test") admin, adminID := accountClient(t, srv.URL, "first@superbrain.test")
if admin.request("GET", "/api/me", nil, 200)["isAdmin"] != true { if admin.request("GET", "/api/me", nil, 200)["isAdmin"] != true {
t.Fatal("first signup on a fresh installation was not admin") t.Fatal("first signup on a fresh installation was not admin")
} }
@@ -155,7 +155,7 @@ func TestAdminBootstrapIsOneShot(t *testing.T) {
if _, err := d.Exec(`UPDATE "User" SET role='USER' WHERE id=$1`, adminID); err != nil { if _, err := d.Exec(`UPDATE "User" SET role='USER' WHERE id=$1`, adminID); err != nil {
t.Fatal(err) t.Fatal(err)
} }
latecomer, _ := accountClient(t, srv.URL, "late@computer.test") latecomer, _ := accountClient(t, srv.URL, "late@superbrain.test")
if latecomer.request("GET", "/api/me", nil, 200)["isAdmin"] != false { if latecomer.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
t.Fatal("signup re-opened admin bootstrap after the last admin was demoted") t.Fatal("signup re-opened admin bootstrap after the last admin was demoted")
} }
@@ -163,7 +163,7 @@ func TestAdminBootstrapIsOneShot(t *testing.T) {
if _, err := d.Exec(`DELETE FROM "User" WHERE id=$1`, adminID); err != nil { if _, err := d.Exec(`DELETE FROM "User" WHERE id=$1`, adminID); err != nil {
t.Fatal(err) t.Fatal(err)
} }
successor, _ := accountClient(t, srv.URL, "successor@computer.test") successor, _ := accountClient(t, srv.URL, "successor@superbrain.test")
if successor.request("GET", "/api/me", nil, 200)["isAdmin"] != false { if successor.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
t.Fatal("signup re-opened admin bootstrap after the last admin was removed") t.Fatal("signup re-opened admin bootstrap after the last admin was removed")
} }
@@ -175,7 +175,7 @@ func TestAdminBootstrapIsOneShot(t *testing.T) {
func TestBootstrapSignupCanBeDisabled(t *testing.T) { func TestBootstrapSignupCanBeDisabled(t *testing.T) {
srv := testServer(t) srv := testServer(t)
t.Setenv("ALLOW_BOOTSTRAP_SIGNUP", "0") t.Setenv("ALLOW_BOOTSTRAP_SIGNUP", "0")
visitor, _ := accountClient(t, srv.URL, "unclaimed@computer.test") visitor, _ := accountClient(t, srv.URL, "unclaimed@superbrain.test")
if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != false { if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
t.Fatal("first signup became admin despite ALLOW_BOOTSTRAP_SIGNUP=0") t.Fatal("first signup became admin despite ALLOW_BOOTSTRAP_SIGNUP=0")
} }
@@ -191,7 +191,7 @@ func TestDirectLoginRejectsBrowserForgery(t *testing.T) {
{"text/plain", "https://attacker.invalid", 415}, {"text/plain", "https://attacker.invalid", 415},
{"application/json", "https://attacker.invalid", 403}, {"application/json", "https://attacker.invalid", 403},
} { } {
req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", bytes.NewBufferString(`{"email":"attacker@computer.test","password":"password"}`)) req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", bytes.NewBufferString(`{"email":"attacker@superbrain.test","password":"password"}`))
req.Header.Set("Content-Type", tc.contentType) req.Header.Set("Content-Type", tc.contentType)
req.Header.Set("Origin", tc.origin) req.Header.Set("Origin", tc.origin)
res, err := http.DefaultClient.Do(req) res, err := http.DefaultClient.Do(req)
@@ -222,9 +222,9 @@ func TestLoginLockoutHonorsSignedForwardedIdentity(t *testing.T) {
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
if ip != "" { if ip != "" {
hip, hts, sig := sign(ip, ts) hip, hts, sig := sign(ip, ts)
req.Header.Set("X-Computer-Client-Ip", hip) req.Header.Set("X-superbrain-Client-Ip", hip)
req.Header.Set("X-Computer-Client-Ts", hts) req.Header.Set("X-superbrain-Client-Ts", hts)
req.Header.Set("X-Computer-Client-Sig", sig) req.Header.Set("X-superbrain-Client-Sig", sig)
} }
res, e := http.DefaultClient.Do(req) res, e := http.DefaultClient.Do(req)
if e != nil { if e != nil {
@@ -236,21 +236,21 @@ func TestLoginLockoutHonorsSignedForwardedIdentity(t *testing.T) {
now := time.Now().Unix() now := time.Now().Unix()
// Browser A: five failures lock out its (IP, email) bucket. // Browser A: five failures lock out its (IP, email) bucket.
for i := 0; i < 5; i++ { // failureThreshold for i := 0; i < 5; i++ { // failureThreshold
if code := post("victim-a@computer.test", "wrong-password", "198.51.100.1", now); code != 401 { if code := post("victim-a@superbrain.test", "wrong-password", "198.51.100.1", now); code != 401 {
t.Fatalf("browser A attempt %d: %d", i+1, code) t.Fatalf("browser A attempt %d: %d", i+1, code)
} }
} }
if code := post("victim-a@computer.test", "wrong-password", "198.51.100.1", now); code != 429 { if code := post("victim-a@superbrain.test", "wrong-password", "198.51.100.1", now); code != 429 {
t.Fatalf("browser A not locked out: %d", code) t.Fatalf("browser A not locked out: %d", code)
} }
// Browser B behind the same proxy peer keeps its own buckets. // Browser B behind the same proxy peer keeps its own buckets.
if code := post("victim-a@computer.test", "wrong-password", "198.51.100.2", now); code != 401 { if code := post("victim-a@superbrain.test", "wrong-password", "198.51.100.2", now); code != 401 {
t.Fatalf("browser B locked out by browser A's failures: %d", code) t.Fatalf("browser B locked out by browser A's failures: %d", code)
} }
// A stale signature (outside the ~60s window) falls back to the peer, so // A stale signature (outside the ~60s window) falls back to the peer, so
// it cannot smuggle a fresh identity: these attempts count against the // it cannot smuggle a fresh identity: these attempts count against the
// peer bucket and stay 401. // peer bucket and stay 401.
if code := post("victim-b@computer.test", "wrong-password", "198.51.100.9", now-3600); code != 401 { if code := post("victim-b@superbrain.test", "wrong-password", "198.51.100.9", now-3600); code != 401 {
t.Fatalf("stale signature changed behavior: %d", code) t.Fatalf("stale signature changed behavior: %d", code)
} }
} }
+6 -6
View File
@@ -6,12 +6,12 @@ import (
"os" "os"
"time" "time"
"github.com/andrew/go-computer/internal/auth" "github.com/andrew/superbrain/internal/auth"
"github.com/andrew/go-computer/internal/authguard" "github.com/andrew/superbrain/internal/authguard"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/handlers" "github.com/andrew/superbrain/internal/handlers"
"github.com/andrew/go-computer/internal/oidc" "github.com/andrew/superbrain/internal/oidc"
) )
// NewServer builds the HTTP server with all routes registered. // NewServer builds the HTTP server with all routes registered.
+2 -2
View File
@@ -19,8 +19,8 @@ func TestRevocationAndForeignRelations(t *testing.T) {
// uniform signup body. // uniform signup body.
return meID(c) return meID(c)
} }
account(a, "owner@computer.test") account(a, "owner@superbrain.test")
bid := account(b, "recipient@computer.test") bid := account(b, "recipient@superbrain.test")
tag := a.request("POST", "/api/tags", map[string]any{"name": "Shared"}, 201)["id"].(string) tag := a.request("POST", "/api/tags", map[string]any{"name": "Shared"}, 201)["id"].(string)
id := a.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/test", "tagIds": []string{tag}, "dueDate": "2026-10-07"}, 201)["id"].(string) id := a.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/test", "tagIds": []string{tag}, "dueDate": "2026-10-07"}, 201)["id"].(string)
a.request("POST", "/api/bookmarks/"+id+"/share", map[string]any{"userIds": []string{bid}}, 200) a.request("POST", "/api/bookmarks/"+id+"/share", map[string]any{"userIds": []string{bid}}, 200)
+9 -9
View File
@@ -9,8 +9,8 @@ import (
func TestPageRevisionHistory(t *testing.T) { func TestPageRevisionHistory(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "trust-history@computer.test") alice := newAPIUser(t, srv, "trust-history@superbrain.test")
bob := newAPIUser(t, srv, "trust-history-other@computer.test") bob := newAPIUser(t, srv, "trust-history-other@superbrain.test")
page := alice.request("POST", "/api/pages", map[string]any{"title": "History", "content": "version one"}, 201)["id"].(string) page := alice.request("POST", "/api/pages", map[string]any{"title": "History", "content": "version one"}, 201)["id"].(string)
revisions := alice.getJSON("/api/pages/"+page+"/revisions", 200) revisions := alice.getJSON("/api/pages/"+page+"/revisions", 200)
@@ -52,8 +52,8 @@ func TestPageRevisionHistory(t *testing.T) {
func TestTrashRestoreNeverResurrectsGrants(t *testing.T) { func TestTrashRestoreNeverResurrectsGrants(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "trust-trash@computer.test") alice := newAPIUser(t, srv, "trust-trash@superbrain.test")
bob := newAPIUser(t, srv, "trust-trash-other@computer.test") bob := newAPIUser(t, srv, "trust-trash-other@superbrain.test")
bobID := meID(bob) bobID := meID(bob)
tag := alice.request("POST", "/api/tags", map[string]any{"name": "Restored tag"}, 201)["id"].(string) tag := alice.request("POST", "/api/tags", map[string]any{"name": "Restored tag"}, 201)["id"].(string)
@@ -162,9 +162,9 @@ func TestTrashRestoreNeverResurrectsGrants(t *testing.T) {
func TestCollectionSharingPermissionBoundary(t *testing.T) { func TestCollectionSharingPermissionBoundary(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "trust-coll-share@computer.test") alice := newAPIUser(t, srv, "trust-coll-share@superbrain.test")
bob := newAPIUser(t, srv, "trust-coll-recipient@computer.test") bob := newAPIUser(t, srv, "trust-coll-recipient@superbrain.test")
carol := newAPIUser(t, srv, "trust-coll-third@computer.test") carol := newAPIUser(t, srv, "trust-coll-third@superbrain.test")
bobID, carolID := meID(bob), meID(carol) bobID, carolID := meID(bob), meID(carol)
bm := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/collection-share", "title": "Shared via project", "notes": "secret owner notes", "isPublic": true}, 201) bm := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/collection-share", "title": "Shared via project", "notes": "secret owner notes", "isPublic": true}, 201)
@@ -249,7 +249,7 @@ func TestCollectionSharingPermissionBoundary(t *testing.T) {
func TestStructuredExport(t *testing.T) { func TestStructuredExport(t *testing.T) {
srv := testServer(t) srv := testServer(t)
alice := newAPIUser(t, srv, "trust-export@computer.test") alice := newAPIUser(t, srv, "trust-export@superbrain.test")
tag := alice.request("POST", "/api/tags", map[string]any{"name": "Export tag"}, 201)["id"].(string) tag := alice.request("POST", "/api/tags", map[string]any{"name": "Export tag"}, 201)["id"].(string)
bm := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/export", "title": "Exported bookmark", "tagIds": []string{tag}}, 201)["id"].(string) bm := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/export", "title": "Exported bookmark", "tagIds": []string{tag}}, 201)["id"].(string)
@@ -258,7 +258,7 @@ func TestStructuredExport(t *testing.T) {
alice.request("POST", "/api/collections/"+col+"/items", map[string]any{"bookmarkId": bm}, 201) alice.request("POST", "/api/collections/"+col+"/items", map[string]any{"bookmarkId": bm}, 201)
v := alice.request("GET", "/api/export", nil, 200) v := alice.request("GET", "/api/export", nil, 200)
if v["format"] != "computer-export" || v["version"].(float64) != 1 { if v["format"] != "superbrain-export" || v["version"].(float64) != 1 {
t.Fatalf("export envelope: %v", v) t.Fatalf("export envelope: %v", v)
} }
if len(v["bookmarks"].([]any)) != 1 || len(v["pages"].([]any)) != 1 || len(v["tags"].([]any)) != 1 || len(v["collections"].([]any)) != 1 { if len(v["bookmarks"].([]any)) != 1 || len(v["pages"].([]any)) != 1 || len(v["tags"].([]any)) != 1 || len(v["collections"].([]any)) != 1 {
+1 -1
View File
@@ -3,7 +3,7 @@ package kanban
import ( import (
"context" "context"
"database/sql" "database/sql"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
) )
var DefaultColumns = []struct{ Label, Color, Key string }{{"Inbox", "#64748b", "INBOX"}, {"To Do", "#3b82f6", "TODO"}, {"In Progress", "#f59e0b", "IN_PROGRESS"}, {"Done", "#22c55e", "DONE"}} var DefaultColumns = []struct{ Label, Color, Key string }{{"Inbox", "#64748b", "INBOX"}, {"To Do", "#3b82f6", "TODO"}, {"In Progress", "#f59e0b", "IN_PROGRESS"}, {"Done", "#22c55e", "DONE"}}
+2 -2
View File
@@ -2,7 +2,7 @@ package markdown
import ( import (
"fmt" "fmt"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"net/http" "net/http"
"regexp" "regexp"
"strings" "strings"
@@ -82,7 +82,7 @@ func PageDocument(p db.Object) string {
out += "\n" out += "\n"
} }
} }
return out + "\n<!-- exported from computer " + text(p, "updatedAt") + " -->\n" return out + "\n<!-- exported from superbrain " + text(p, "updatedAt") + " -->\n"
} }
func Send(w http.ResponseWriter, body, name string) { func Send(w http.ResponseWriter, body, name string) {
w.Header().Set("Content-Type", "text/markdown; charset=utf-8") w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
) )
// Review L-11: link destinations are wrapped and escaped so parentheses or // Review L-11: link destinations are wrapped and escaped so parentheses or
+3 -3
View File
@@ -3,8 +3,8 @@ package preview
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/andrew/go-computer/internal/netguard" "github.com/andrew/superbrain/internal/netguard"
"github.com/andrew/go-computer/internal/outbound" "github.com/andrew/superbrain/internal/outbound"
"golang.org/x/net/html" "golang.org/x/net/html"
"io" "io"
"net" "net"
@@ -109,7 +109,7 @@ func FetchPreview(ctx context.Context, key, raw string) Preview {
if e != nil { if e != nil {
return Preview{} return Preview{}
} }
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; computer/1.0)") req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; superbrain/1.0)")
resp, e := previewClient.Do(req) resp, e := previewClient.Do(req)
if e != nil { if e != nil {
return Preview{} return Preview{}
+1 -1
View File
@@ -3,7 +3,7 @@ package scripts
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"os" "os"
"strings" "strings"
+2 -2
View File
@@ -122,9 +122,9 @@ func newTestMailboxValidity(t *testing.T, n int, validity uint32) (Mailbox, *val
memMbox := mbox.(*memory.Mailbox) memMbox := mbox.(*memory.Mailbox)
memMbox.Messages = memMbox.Messages[:0] memMbox.Messages = memMbox.Messages[:0]
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
body := "From: sender@computer.test\r\n" + body := "From: sender@superbrain.test\r\n" +
"Subject: subject " + fmt.Sprint(i) + "\r\n" + "Subject: subject " + fmt.Sprint(i) + "\r\n" +
"Message-Id: <msg-" + fmt.Sprint(i) + "@computer.test>\r\n" + "Message-Id: <msg-" + fmt.Sprint(i) + "@superbrain.test>\r\n" +
"\r\n" + "body" "\r\n" + "body"
memMbox.Messages = append(memMbox.Messages, &memory.Message{ memMbox.Messages = append(memMbox.Messages, &memory.Message{
Uid: uint32(i + 1), Uid: uint32(i + 1),
+1 -1
View File
@@ -2,7 +2,7 @@ package signals
import ( import (
"context" "context"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"log" "log"
"sync" "sync"
"time" "time"
+4 -4
View File
@@ -6,10 +6,10 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"github.com/andrew/go-computer/internal/config" "github.com/andrew/superbrain/internal/config"
crypt "github.com/andrew/go-computer/internal/crypto" crypt "github.com/andrew/superbrain/internal/crypto"
"github.com/andrew/go-computer/internal/db" "github.com/andrew/superbrain/internal/db"
"github.com/andrew/go-computer/internal/netguard" "github.com/andrew/superbrain/internal/netguard"
"github.com/emersion/go-imap" "github.com/emersion/go-imap"
"github.com/emersion/go-imap/client" "github.com/emersion/go-imap/client"
"log" "log"
+1 -1
View File
@@ -66,7 +66,7 @@ func main() {
log.Fatalf("server failed: %v", err) log.Fatalf("server failed: %v", err)
} }
}() }()
log.Printf("computer API listening on %s", srv.Addr) log.Printf("superbrain API listening on %s", srv.Addr)
<-ctx.Done() <-ctx.Done()
stop() stop()
shutdown, cancel := context.WithTimeout(context.Background(), 15*time.Second) shutdown, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+10 -7
View File
@@ -1,10 +1,10 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Deploy the computer stack to a target server of your choice. # Deploy the superbrain stack to a target server of your choice.
# #
# Run from anywhere in the repository on your workstation. The deployment # Run from anywhere in the repository on your workstation. The deployment
# target is explicit — there are no built-in host or domain defaults: # target is explicit — there are no built-in host or domain defaults:
# #
# HOST=app-server DOMAIN=computer.example.tld CERTBOT_EMAIL=ops@example.tld \ # HOST=app-server DOMAIN=superbrain.example.tld CERTBOT_EMAIL=ops@example.tld \
# ./scripts/deploy.sh (or: make deploy with the same variables) # ./scripts/deploy.sh (or: make deploy with the same variables)
# #
# Flow: record the exact git revision, rsync the source tree to a UNIQUE # Flow: record the exact git revision, rsync the source tree to a UNIQUE
@@ -13,7 +13,7 @@
# lock (flock) BEFORE publishing the staged tree into the shared release # lock (flock) BEFORE publishing the staged tree into the shared release
# directory, provisions packages, backs up the database, builds the Compose # directory, provisions packages, backs up the database, builds the Compose
# stack (images are tagged with the revision), configures nginx + Let's # stack (images are tagged with the revision), configures nginx + Let's
# Encrypt from deploy/nginx/computer.conf.template, and records the revision # Encrypt from deploy/nginx/superbrain.conf.template, and records the revision
# marker only after everything passed (review CR-11: overlapping deploys can # marker only after everything passed (review CR-11: overlapping deploys can
# no longer mix source and release state — synchronization targets are # no longer mix source and release state — synchronization targets are
# per-release, mutation of the shared directory is serialized, and the last # per-release, mutation of the shared directory is serialized, and the last
@@ -24,12 +24,12 @@
# the server (.deployed-revision) and the built images are tagged with it. # the server (.deployed-revision) and the built images are tagged with it.
# Rollback: re-deploy an older revision (git checkout <rev> && ./scripts/deploy.sh, # Rollback: re-deploy an older revision (git checkout <rev> && ./scripts/deploy.sh,
# which reuses/rebuilds that known source), or restore one of the last 15 # which reuses/rebuilds that known source), or restore one of the last 15
# pre-deploy pg_dumps (+ its .env secret snapshot) from /var/backups/computer # pre-deploy pg_dumps (+ its .env secret snapshot) from /var/backups/superbrain
# on the server. Database migrations are additive. # on the server. Database migrations are additive.
# #
# Requirements: ssh access to HOST (an ssh config alias works well), rsync and # Requirements: ssh access to HOST (an ssh config alias works well), rsync and
# git locally. DNS for DOMAIN must already point at the server (certbot # git locally. DNS for DOMAIN must already point at the server (certbot
# HTTP-01). Optional overrides: REMOTE_DIR (default /var/www/computer), # HTTP-01). Optional overrides: REMOTE_DIR (default /var/www/superbrain),
# ALLOW_DIRTY=1. # ALLOW_DIRTY=1.
set -euo pipefail set -euo pipefail
@@ -37,12 +37,15 @@ usage="usage: HOST=ssh-host DOMAIN=app.domain.tld CERTBOT_EMAIL=ops@domain.tld .
HOST="${HOST:?${usage}}" HOST="${HOST:?${usage}}"
DOMAIN="${DOMAIN:?${usage}}" DOMAIN="${DOMAIN:?${usage}}"
CERTBOT_EMAIL="${CERTBOT_EMAIL:?${usage}}" CERTBOT_EMAIL="${CERTBOT_EMAIL:?${usage}}"
REMOTE_DIR="${REMOTE_DIR:-/var/www/computer}" REMOTE_DIR="${REMOTE_DIR:-/var/www/superbrain}"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
log() { printf '\033[1;34m==>\033[0m %s\n' "$*"; } log() { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; } die() {
printf '\033[1;31merror:\033[0m %s\n' "$*" >&2
exit 1
}
# --- 0. Record the revision being deployed (review OPS-04) ---------------------- # --- 0. Record the revision being deployed (review OPS-04) ----------------------
REV="$(git -C "$REPO_ROOT" rev-parse --short HEAD 2>/dev/null)" || die "git is required to deploy a known revision" REV="$(git -C "$REPO_ROOT" rev-parse --short HEAD 2>/dev/null)" || die "git is required to deploy a known revision"
+3 -3
View File
@@ -38,7 +38,7 @@ const accounts = []
const errors = [] const errors = []
let testFailed = false let testFailed = false
const password = 'qa-test-long-password' const password = 'qa-test-long-password'
const email = `qa-${Date.now()}@computer.test` const email = `qa-${Date.now()}@superbrain.test`
const context = await browser.newContext() const context = await browser.newContext()
const page = await context.newPage() const page = await context.newPage()
page.on('pageerror', error => errors.push(error.message)) page.on('pageerror', error => errors.push(error.message))
@@ -67,7 +67,7 @@ try {
// database — abort before creating further data. // database — abort before creating further data.
if (!keepData && loopback) { if (!keepData && loopback) {
assert.match(me.user.id, /^[a-z0-9]+$/i) assert.match(me.user.id, /^[a-z0-9]+$/i)
const found = execFileSync('docker', ['compose', 'exec', '-T', 'db', 'psql', '-U', 'computer', '-d', 'computer', '-Atc', const found = execFileSync('docker', ['compose', 'exec', '-T', 'db', 'psql', '-U', 'superbrain', '-d', 'superbrain', '-Atc',
`SELECT count(*) FROM "User" WHERE id='${me.user.id}';`], { cwd: repoRoot, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim() `SELECT count(*) FROM "User" WHERE id='${me.user.id}';`], { cwd: repoRoot, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim()
if (found !== '1') { if (found !== '1') {
throw new Error(`preflight failed: QA account ${me.user.id} created through ${base} is not present in the local compose database; target and cleanup environments differ (remove it on the target environment)`) throw new Error(`preflight failed: QA account ${me.user.id} created through ${base} is not present in the local compose database; target and cleanup environments differ (remove it on the target environment)`)
@@ -220,7 +220,7 @@ try {
// the run only when the tests themselves passed. // the run only when the tests themselves passed.
try { try {
assert.ok(accounts.every(id => /^[a-z0-9]+$/i.test(id))) assert.ok(accounts.every(id => /^[a-z0-9]+$/i.test(id)))
execFileSync('docker', ['compose', 'exec', '-T', 'db', 'psql', '-U', 'computer', '-d', 'computer', '-v', 'ON_ERROR_STOP=1', '-c', `DELETE FROM "User" WHERE id IN (${accounts.map(id => `'${id}'`).join(',')});`], { cwd: repoRoot, stdio: 'inherit' }) execFileSync('docker', ['compose', 'exec', '-T', 'db', 'psql', '-U', 'superbrain', '-d', 'superbrain', '-v', 'ON_ERROR_STOP=1', '-c', `DELETE FROM "User" WHERE id IN (${accounts.map(id => `'${id}'`).join(',')});`], { cwd: repoRoot, stdio: 'inherit' })
} catch (cleanupError) { } catch (cleanupError) {
console.error(`QA account cleanup failed (${accounts.join(',')}); delete manually.`, cleanupError.message) console.error(`QA account cleanup failed (${accounts.join(',')}); delete manually.`, cleanupError.message)
if (!testFailed) process.exitCode = 1 if (!testFailed) process.exitCode = 1
+6 -6
View File
@@ -192,7 +192,7 @@ for (let attempt = 1; attempt <= 3; attempt++) {
} }
const attacker = http.createServer((req, res) => { const attacker = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html') res.setHeader('Content-Type', 'text/html')
res.end(`<form method="POST" action="${base}/api/auth/login" enctype="text/plain"><input name='{"email":"attacker@computer.test","password":"password","extra":"' value='"}'></form><script>document.forms[0].submit()</script>`) res.end(`<form method="POST" action="${base}/api/auth/login" enctype="text/plain"><input name='{"email":"attacker@superbrain.test","password":"password","extra":"' value='"}'></form><script>document.forms[0].submit()</script>`)
}) })
await new Promise(resolve => attacker.listen(0, '127.0.0.1', resolve)) await new Promise(resolve => attacker.listen(0, '127.0.0.1', resolve))
async function eventually(check, label) { async function eventually(check, label) {
@@ -215,12 +215,12 @@ try {
await page.waitForURL(`${base}/api/auth/login`) await page.waitForURL(`${base}/api/auth/login`)
assert.equal((await context.request.get(`${base}/api/auth/session`).then(r => r.json()))?.user, undefined) assert.equal((await context.request.get(`${base}/api/auth/session`).then(r => r.json()))?.user, undefined)
for (const headers of [{ Origin: 'https://attacker.invalid' }, {}]) { for (const headers of [{ Origin: 'https://attacker.invalid' }, {}]) {
const response = await context.request.post(`${base}/api/auth/login`, { headers, data: { email: 'attacker@computer.test', password: 'password' } }) const response = await context.request.post(`${base}/api/auth/login`, { headers, data: { email: 'attacker@superbrain.test', password: 'password' } })
assert.equal(response.status(), 403) assert.equal(response.status(), 403)
} }
const plain = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base, 'Content-Type': 'text/plain' }, data: '{"email":"attacker@computer.test"}' }) const plain = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base, 'Content-Type': 'text/plain' }, data: '{"email":"attacker@superbrain.test"}' })
assert.equal(plain.status(), 415) assert.equal(plain.status(), 415)
const login = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@computer.test', password: 'password' } }) const login = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@superbrain.test', password: 'password' } })
assert.equal(login.status(), 200) assert.equal(login.status(), 200)
console.log('PASS: forged logins rejected; legitimate login works') console.log('PASS: forged logins rejected; legitimate login works')
@@ -326,7 +326,7 @@ try {
// saving over whatever the server holds. // saving over whatever the server holds.
await page.goto(`${base}/pages?id=a`) await page.goto(`${base}/pages?id=a`)
await eventually(() => page.getByRole('textbox', { name: 'Page title' }).inputValue().then(v => v === 'Page A'), 'Page A did not open') await eventually(() => page.getByRole('textbox', { name: 'Page title' }).inputValue().then(v => v === 'Page A'), 'Page A did not open')
await page.evaluate(() => sessionStorage.setItem('computer:page-draft:a', JSON.stringify('Legacy draft of unknown origin'))) await page.evaluate(() => sessionStorage.setItem('superbrain:page-draft:a', JSON.stringify('Legacy draft of unknown origin')))
const attemptsBeforeLegacy = patchAttempts const attemptsBeforeLegacy = patchAttempts
await page.reload() await page.reload()
await eventually(() => editor.inputValue().then(value => value === 'Legacy draft of unknown origin'), 'Legacy draft not recovered') await eventually(() => editor.inputValue().then(value => value === 'Legacy draft of unknown origin'), 'Legacy draft not recovered')
@@ -477,7 +477,7 @@ try {
// backstop) posts to Go /api/auth/signout with a signed assertion, so the // backstop) posts to Go /api/auth/signout with a signed assertion, so the
// tokenVersion bump kills Go cookie sessions and any previously minted // tokenVersion bump kills Go cookie sessions and any previously minted
// assertions — not just the local NextAuth JWT. // assertions — not just the local NextAuth JWT.
await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@computer.test', password: 'password' } }) await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@superbrain.test', password: 'password' } })
await page.goto(`${base}/pages`) await page.goto(`${base}/pages`)
const revoked = page.waitForResponse(r => r.url().includes('/api/session/revoke') && r.request().method() === 'POST') const revoked = page.waitForResponse(r => r.url().includes('/api/session/revoke') && r.request().method() === 'POST')
await page.getByRole('button', { name: 'Sign out', exact: true }).click() await page.getByRole('button', { name: 'Sign out', exact: true }).click()
+30 -19
View File
@@ -32,7 +32,10 @@ COMPOSE_VERSION="${COMPOSE_VERSION:-v5.6.0}"
BUILDX_VERSION="${BUILDX_VERSION:-v0.38.0}" BUILDX_VERSION="${BUILDX_VERSION:-v0.38.0}"
log() { printf '\033[1;34m[server]==>\033[0m %s\n' "$*"; } log() { printf '\033[1;34m[server]==>\033[0m %s\n' "$*"; }
die() { printf '\033[1;31m[server] error:\033[0m %s\n' "$*" >&2; exit 1; } die() {
printf '\033[1;31m[server] error:\033[0m %s\n' "$*" >&2
exit 1
}
[ "$(id -u)" = "0" ] || die "must run as root (the local deploy.sh does: ssh -t ... sudo bash $0)" [ "$(id -u)" = "0" ] || die "must run as root (the local deploy.sh does: ssh -t ... sudo bash $0)"
@@ -42,7 +45,7 @@ die() { printf '\033[1;31m[server] error:\033[0m %s\n' "$*" >&2; exit 1; }
# marker must never interleave with a second deployment. A waiter blocks (up # marker must never interleave with a second deployment. A waiter blocks (up
# to 30 minutes) instead of mixing source and release state; the lock dies # to 30 minutes) instead of mixing source and release state; the lock dies
# with this process, so a crashed deploy cannot wedge the server. # with this process, so a crashed deploy cannot wedge the server.
DEPLOY_LOCK="${DEPLOY_LOCK:-/var/lock/computer-deploy.lock}" DEPLOY_LOCK="${DEPLOY_LOCK:-/var/lock/superbrain-deploy.lock}"
exec 9>"$DEPLOY_LOCK" exec 9>"$DEPLOY_LOCK"
log "Waiting for the deployment lock ($DEPLOY_LOCK)" log "Waiting for the deployment lock ($DEPLOY_LOCK)"
flock -w 1800 9 || die "another deployment held $DEPLOY_LOCK for more than 30 minutes; refusing to overlap" flock -w 1800 9 || die "another deployment held $DEPLOY_LOCK for more than 30 minutes; refusing to overlap"
@@ -155,8 +158,8 @@ if [ ! -f .env ]; then
# A lost .env while the data volume remains would generate a fresh # A lost .env while the data volume remains would generate a fresh
# POSTGRES_PASSWORD that the existing database does not have, locking the # POSTGRES_PASSWORD that the existing database does not have, locking the
# app out of its own data. Refuse instead. # app out of its own data. Refuse instead.
if docker volume inspect computer_pgdata >/dev/null 2>&1; then if docker volume inspect superbrain_pgdata >/dev/null 2>&1; then
die ".env is missing but the computer_pgdata volume exists - restore the .env backup (it holds POSTGRES_PASSWORD and AUTH_SECRET); refusing to regenerate" die ".env is missing but the superbrain_pgdata volume exists - restore the .env backup (it holds POSTGRES_PASSWORD and AUTH_SECRET); refusing to regenerate"
fi fi
log "Creating .env with generated secrets (back it up with the database!)" log "Creating .env with generated secrets (back it up with the database!)"
umask 077 umask 077
@@ -170,9 +173,9 @@ ADMIN_EMAILS=
# and forward the browser identity for per-client rate limiting. # and forward the browser identity for per-client rate limiting.
TRUSTED_PROXY=1 TRUSTED_PROXY=1
# Review H-3: do not let the first visitor after DNS goes live claim the # Review H-3: do not let the first visitor after DNS goes live claim the
# instance. Provision the operator with ADMIN_EMAILS + `make seed` (below). # instance. Provision the operator with ADMIN_EMAILS + $(make seed) (below).
ALLOW_BOOTSTRAP_SIGNUP=0 ALLOW_BOOTSTRAP_SIGNUP=0
POSTGRES_VOLUME=computer_pgdata POSTGRES_VOLUME=superbrain_pgdata
POSTGRES_VOLUME_EXTERNAL=false POSTGRES_VOLUME_EXTERNAL=false
APP_HOST_PORT=$APP_HOST_PORT APP_HOST_PORT=$APP_HOST_PORT
WEB_HOST_PORT=$WEB_HOST_PORT WEB_HOST_PORT=$WEB_HOST_PORT
@@ -205,8 +208,10 @@ chown "$RUN_USER:" .env
chmod 600 .env chmod 600 .env
# Effective ports are whatever .env says (they may predate this run). # Effective ports are whatever .env says (they may predate this run).
APP_PORT="$(sed -n 's/^APP_HOST_PORT=//p' .env | tail -n1)"; APP_PORT="${APP_PORT:-8080}" APP_PORT="$(sed -n 's/^APP_HOST_PORT=//p' .env | tail -n1)"
WEB_PORT="$(sed -n 's/^WEB_HOST_PORT=//p' .env | tail -n1)"; WEB_PORT="${WEB_PORT:-3000}" APP_PORT="${APP_PORT:-8080}"
WEB_PORT="$(sed -n 's/^WEB_HOST_PORT=//p' .env | tail -n1)"
WEB_PORT="${WEB_PORT:-3000}"
# Fail early with a clear message if another process squats the ports while # Fail early with a clear message if another process squats the ports while
# our stack is not the thing holding them. # our stack is not the thing holding them.
@@ -224,8 +229,9 @@ fi
# existing database that is not running gets started for the backup, and a # existing database that is not running gets started for the backup, and a
# failed dump aborts the deploy. Dumps are 0600 in a 0700 directory; copy # failed dump aborts the deploy. Dumps are 0600 in a 0700 directory; copy
# them off-host — a same-disk backup does not survive disk loss. # them off-host — a same-disk backup does not survive disk loss.
BACKUP_DIR="${BACKUP_DIR:-/var/backups/computer}" BACKUP_DIR="${BACKUP_DIR:-/var/backups/superbrain}"
pg_volume="$(sed -n 's/^POSTGRES_VOLUME=//p' .env 2>/dev/null | tail -n1)"; pg_volume="${pg_volume:-computer_pgdata}" pg_volume="$(sed -n 's/^POSTGRES_VOLUME=//p' .env 2>/dev/null | tail -n1)"
pg_volume="${pg_volume:-superbrain_pgdata}"
have_existing_db() { have_existing_db() {
[ -n "$(docker compose ps -aq db 2>/dev/null)" ] || docker volume inspect "$pg_volume" >/dev/null 2>&1 [ -n "$(docker compose ps -aq db 2>/dev/null)" ] || docker volume inspect "$pg_volume" >/dev/null 2>&1
} }
@@ -243,13 +249,13 @@ if have_existing_db; then
mkdir -p "$BACKUP_DIR" mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR" chmod 700 "$BACKUP_DIR"
stamp="$(date -u +%Y%m%dT%H%M%SZ)" stamp="$(date -u +%Y%m%dT%H%M%SZ)"
dump="$BACKUP_DIR/computer-$stamp.sql.gz" dump="$BACKUP_DIR/superbrain-$stamp.sql.gz"
if docker compose exec -T db pg_dump -U computer -d computer | gzip > "$dump"; then if docker compose exec -T db pg_dump -U superbrain -d superbrain | gzip >"$dump"; then
chmod 600 "$dump" chmod 600 "$dump"
# Capture the secrets required to decrypt/restore integration data. # Capture the secrets required to decrypt/restore integration data.
cp -p .env "$BACKUP_DIR/env-$stamp.bak" cp -p .env "$BACKUP_DIR/env-$stamp.bak"
chmod 600 "$BACKUP_DIR/env-$stamp.bak" chmod 600 "$BACKUP_DIR/env-$stamp.bak"
ls -1t "$BACKUP_DIR"/computer-*.sql.gz 2>/dev/null | tail -n +16 | xargs -r rm -f ls -1t "$BACKUP_DIR"/superbrain-*.sql.gz 2>/dev/null | tail -n +16 | xargs -r rm -f
ls -1t "$BACKUP_DIR"/env-*.bak 2>/dev/null | tail -n +16 | xargs -r rm -f ls -1t "$BACKUP_DIR"/env-*.bak 2>/dev/null | tail -n +16 | xargs -r rm -f
log "Backup written: $dump ($(du -h "$dump" | cut -f1)) + env-$stamp.bak; copy both off-host" log "Backup written: $dump ($(du -h "$dump" | cut -f1)) + env-$stamp.bak; copy both off-host"
else else
@@ -270,8 +276,8 @@ if [ -n "$REVISION" ]; then
for svc in app web; do for svc in app web; do
img="$(docker compose images -q "$svc" 2>/dev/null | head -n1)" img="$(docker compose images -q "$svc" 2>/dev/null | head -n1)"
if [ -n "$img" ]; then if [ -n "$img" ]; then
docker tag "$img" "computer-$svc:$REVISION" docker tag "$img" "superbrain-$svc:$REVISION"
log "tagged computer-$svc:$REVISION" log "tagged superbrain-$svc:$REVISION"
fi fi
done done
fi fi
@@ -281,18 +287,22 @@ log "Waiting for app health and web /login"
deadline=$((SECONDS + 300)) deadline=$((SECONDS + 300))
app_id="$(docker compose ps -q app)" app_id="$(docker compose ps -q app)"
until [ -n "$app_id" ] && [ "$(docker inspect -f '{{.State.Health.Status}}' "$app_id" 2>/dev/null)" = "healthy" ]; do until [ -n "$app_id" ] && [ "$(docker inspect -f '{{.State.Health.Status}}' "$app_id" 2>/dev/null)" = "healthy" ]; do
[ $SECONDS -lt $deadline ] || { docker compose ps -a; docker compose logs --tail=50 app web; die "app never became healthy"; } [ $SECONDS -lt $deadline ] || {
docker compose ps -a
docker compose logs --tail=50 app web
die "app never became healthy"
}
sleep 3 sleep 3
done done
until curl -fsS -o /dev/null "http://127.0.0.1:$WEB_PORT/login"; do until curl -fsS -o /dev/null "http://127.0.0.1:$WEB_PORT/login"; do
[ $SECONDS -lt $deadline ] || die "web never answered on 127.0.0.1:$WEB_PORT"; [ $SECONDS -lt $deadline ] || die "web never answered on 127.0.0.1:$WEB_PORT"
sleep 3 sleep 3
done done
log "Stack is healthy" log "Stack is healthy"
# --- 5. nginx reverse proxy ------------------------------------------------------- # --- 5. nginx reverse proxy -------------------------------------------------------
log "Installing nginx config for $DOMAIN" log "Installing nginx config for $DOMAIN"
TEMPLATE="$REMOTE_DIR/deploy/nginx/computer.conf.template" TEMPLATE="$REMOTE_DIR/deploy/nginx/superbrain.conf.template"
[ -f "$TEMPLATE" ] || die "missing $TEMPLATE (should have been rsynced)" [ -f "$TEMPLATE" ] || die "missing $TEMPLATE (should have been rsynced)"
# Render the generic template with this deployment's domain and the server's # Render the generic template with this deployment's domain and the server's
# actual WEB_HOST_PORT binding. # actual WEB_HOST_PORT binding.
@@ -351,7 +361,8 @@ log "Verifying https://$DOMAIN/login via nginx"
ok="" ok=""
for _ in $(seq 10); do for _ in $(seq 10); do
if curl -fsS -o /dev/null --resolve "$DOMAIN:443:127.0.0.1" "https://$DOMAIN/login"; then if curl -fsS -o /dev/null --resolve "$DOMAIN:443:127.0.0.1" "https://$DOMAIN/login"; then
ok=1; break ok=1
break
fi fi
sleep 3 sleep 3
done done
+1 -1
View File
@@ -1,4 +1,4 @@
# computer — web UI # superbrain — web UI
This app runs inside the root Compose stack. The root [../README.md](../README.md) This app runs inside the root Compose stack. The root [../README.md](../README.md)
is the single authoritative deployment/operations guide; [../API.md](../API.md) is the single authoritative deployment/operations guide; [../API.md](../API.md)
+2 -2
View File
@@ -66,8 +66,8 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
useEffect(() => { useEffect(() => {
const timer = setTimeout(load, search ? 250 : 0) const timer = setTimeout(load, search ? 250 : 0)
const reload = () => { load(); void loadShared() } const reload = () => { load(); void loadShared() }
window.addEventListener('computer:bookmarks-changed', reload) window.addEventListener('superbrain:bookmarks-changed', reload)
return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', reload); abortRef.current?.abort() } return () => { clearTimeout(timer); window.removeEventListener('superbrain:bookmarks-changed', reload); abortRef.current?.abort() }
}, [load, loadShared, search]) }, [load, loadShared, search])
useEffect(() => { const timer = setTimeout(loadShared, 0); return () => clearTimeout(timer) }, [loadShared]) useEffect(() => { const timer = setTimeout(loadShared, 0); return () => clearTimeout(timer) }, [loadShared])
// Quick Find and the dashboard redirect land here with ?search=; the prop // Quick Find and the dashboard redirect land here with ?search=; the prop
+1 -1
View File
@@ -64,7 +64,7 @@ export function CalendarClient() {
finally { if (seq === loadSeq.current) setLoading(false) } finally { if (seq === loadSeq.current) setLoading(false) }
}, []) }, [])
useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('computer:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', load) } }, [load]) useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('superbrain:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('superbrain:bookmarks-changed', load) } }, [load])
const days = useMemo(() => { const days = useMemo(() => {
const start = startOfMonth(currentMonth) const start = startOfMonth(currentMonth)
+1 -1
View File
@@ -42,7 +42,7 @@ export function ContactsClient() {
useEffect(() => { const timer = setTimeout(loadContacts, 0); return () => clearTimeout(timer) }, [loadContacts]) useEffect(() => { const timer = setTimeout(loadContacts, 0); return () => clearTimeout(timer) }, [loadContacts])
useEffect(() => { const timer = setTimeout(() => { if (selectedContact) loadBookmarks(selectedContact) }, 0); return () => clearTimeout(timer) }, [selectedContact, loadBookmarks]) useEffect(() => { const timer = setTimeout(() => { if (selectedContact) loadBookmarks(selectedContact) }, 0); return () => clearTimeout(timer) }, [selectedContact, loadBookmarks])
useEffect(() => { const reload = () => { loadContacts(); if (selectedContact) loadBookmarks(selectedContact) }; window.addEventListener('computer:bookmarks-changed', reload); return () => window.removeEventListener('computer:bookmarks-changed', reload) }, [loadContacts, loadBookmarks, selectedContact]) useEffect(() => { const reload = () => { loadContacts(); if (selectedContact) loadBookmarks(selectedContact) }; window.addEventListener('superbrain:bookmarks-changed', reload); return () => window.removeEventListener('superbrain:bookmarks-changed', reload) }, [loadContacts, loadBookmarks, selectedContact])
const syncContacts = async () => { const syncContacts = async () => {
setSyncing(true) setSyncing(true)
+1 -1
View File
@@ -69,7 +69,7 @@ export function KanbanClient() {
setLoading(false) setLoading(false)
}, []) }, [])
useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('computer:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', load) } }, [load]) useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('superbrain:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('superbrain:bookmarks-changed', load) } }, [load])
const isOwned = useCallback((b: Bookmark) => !currentUserId || b.ownerId === currentUserId, [currentUserId]) const isOwned = useCallback((b: Bookmark) => !currentUserId || b.ownerId === currentUserId, [currentUserId])
+1 -1
View File
@@ -78,7 +78,7 @@ export function TagsClient({ initialTag = null }: { initialTag?: string | null }
}, 0) }, 0)
return () => clearTimeout(timer) return () => clearTimeout(timer)
}, [selectedTag, loadBookmarks]) }, [selectedTag, loadBookmarks])
useEffect(() => { const reload = () => { loadTags(); if (selectedTag) loadBookmarks(selectedTag) }; window.addEventListener('computer:bookmarks-changed', reload); return () => window.removeEventListener('computer:bookmarks-changed', reload) }, [loadTags, loadBookmarks, selectedTag]) useEffect(() => { const reload = () => { loadTags(); if (selectedTag) loadBookmarks(selectedTag) }; window.addEventListener('superbrain:bookmarks-changed', reload); return () => window.removeEventListener('superbrain:bookmarks-changed', reload) }, [loadTags, loadBookmarks, selectedTag])
const createTag = async () => { const createTag = async () => {
if (!newName) return if (!newName) return
+1 -1
View File
@@ -62,7 +62,7 @@ export function TrashClient() {
const url = URL.createObjectURL(blob) const url = URL.createObjectURL(blob)
const a = document.createElement('a') const a = document.createElement('a')
a.href = url a.href = url
a.download = `computer-export-${new Date().toISOString().slice(0, 10)}.json` a.download = `superbrain-export-${new Date().toISOString().slice(0, 10)}.json`
document.body.appendChild(a); a.click(); a.remove() document.body.appendChild(a); a.click(); a.remove()
URL.revokeObjectURL(url) URL.revokeObjectURL(url)
toast.success('Export downloaded') toast.success('Export downloaded')
+1 -1
View File
@@ -55,7 +55,7 @@ async function proxy(request: NextRequest) {
// does). X-Forwarded-For is deliberately ignored: its leftmost entry is // does). X-Forwarded-For is deliberately ignored: its leftmost entry is
// client-controlled. backendFetch adds the timestamped HMAC signature. // client-controlled. backendFetch adds the timestamped HMAC signature.
const clientIP = observedClientIP(request.headers) const clientIP = observedClientIP(request.headers)
if (clientIP) headers.set('x-computer-client-ip', clientIP) if (clientIP) headers.set('x-superbrain-client-ip', clientIP)
if (!['GET', 'HEAD'].includes(request.method)) { if (!['GET', 'HEAD'].includes(request.method)) {
const declared = Number(request.headers.get('content-length') || 0) const declared = Number(request.headers.get('content-length') || 0)
if (declared > MAX_BODY_BYTES) { if (declared > MAX_BODY_BYTES) {
+1 -1
View File
@@ -33,7 +33,7 @@ export async function POST(req: Request) {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// Same short-lived assertion the data proxy signs (lib/api.ts). // Same short-lived assertion the data proxy signs (lib/api.ts).
Authorization: `Bearer ${jwt.sign({ uid: id, ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'computer', expiresIn: '60s' })}`, Authorization: `Bearer ${jwt.sign({ uid: id, ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' })}`,
}, },
cache: 'no-store', cache: 'no-store',
signal: controller.signal, signal: controller.signal,
+2 -2
View File
@@ -10,14 +10,14 @@ const jetbrainsMono = JetBrains_Mono({ subsets: ['latin'], variable: '--font-mon
export const metadata = { export const metadata = {
metadataBase: new URL(process.env.NEXTAUTH_URL ?? 'http://localhost:3000'), metadataBase: new URL(process.env.NEXTAUTH_URL ?? 'http://localhost:3000'),
title: 'computer', title: 'Superbrain',
description: 'Your personal binder of life on the web', description: 'Your personal binder of life on the web',
icons: { icons: {
icon: '/favicon.svg', icon: '/favicon.svg',
shortcut: '/favicon.svg', shortcut: '/favicon.svg',
}, },
openGraph: { openGraph: {
title: 'computer', title: 'Superbrain',
description: 'Your personal binder of life on the web', description: 'Your personal binder of life on the web',
images: ['/og-image.png'], images: ['/og-image.png'],
}, },
+1 -1
View File
@@ -49,7 +49,7 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
<Link2 className="h-7 w-7" /> <Link2 className="h-7 w-7" />
</div> </div>
</div> </div>
<h1 className="font-display text-3xl font-bold tracking-tight">computer</h1> <h1 className="font-display text-3xl font-bold tracking-tight">Superbrain</h1>
<p className="text-sm text-muted-foreground mt-2">Your personal binder of life on the web</p> <p className="text-sm text-muted-foreground mt-2">Your personal binder of life on the web</p>
</div> </div>
+1 -1
View File
@@ -16,7 +16,7 @@ export function PublicBookmarkView({ bookmark }: { bookmark: any }) {
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground"> <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
<Link2 className="h-4 w-4" /> <Link2 className="h-4 w-4" />
</div> </div>
<span className="font-display font-bold">computer</span> <span className="font-display font-bold">Superbrain</span>
<span className="text-muted-foreground text-sm">— Shared Bookmark</span> <span className="text-muted-foreground text-sm">— Shared Bookmark</span>
</div> </div>
</header> </header>
+1 -1
View File
@@ -57,7 +57,7 @@ export function SignupClient() {
</div> </div>
</div> </div>
<h1 className="font-display text-3xl font-bold tracking-tight">Create Account</h1> <h1 className="font-display text-3xl font-bold tracking-tight">Create Account</h1>
<p className="text-sm text-muted-foreground mt-2">Join computer to start organizing your links</p> <p className="text-sm text-muted-foreground mt-2">Join Superbrain to start organizing your links</p>
</div> </div>
<form onSubmit={handleSignup} className="space-y-3"> <form onSubmit={handleSignup} className="space-y-3">
+4 -4
View File
@@ -54,9 +54,9 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
const ip = observedClientIP(request?.headers ?? new Headers()) const ip = observedClientIP(request?.headers ?? new Headers())
if (ip && secret) { if (ip && secret) {
const { ts, sig } = signClientIP(secret, ip) const { ts, sig } = signClientIP(secret, ip)
headers['x-computer-client-ip'] = ip headers['x-superbrain-client-ip'] = ip
headers['x-computer-client-ts'] = ts headers['x-superbrain-client-ts'] = ts
headers['x-computer-client-sig'] = sig headers['x-superbrain-client-sig'] = sig
} }
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/login`, { const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/login`, {
method: 'POST', headers, cache: 'no-store', method: 'POST', headers, cache: 'no-store',
@@ -124,7 +124,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// Same short-lived assertion the data proxy signs (lib/api.ts). // Same short-lived assertion the data proxy signs (lib/api.ts).
Authorization: `Bearer ${jwt.sign({ uid: id, ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'computer', expiresIn: '60s' })}`, Authorization: `Bearer ${jwt.sign({ uid: id, ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' })}`,
}, },
cache: 'no-store', cache: 'no-store',
signal: controller.signal, signal: controller.signal,
+2 -2
View File
@@ -96,7 +96,7 @@ export function AppShell({ children }: { children: React.ReactNode }) {
const id = String(a?.id ?? a?.bookmarkId ?? '') const id = String(a?.id ?? a?.bookmarkId ?? '')
if (!id || notifiedAlerts.current.has(id)) continue if (!id || notifiedAlerts.current.has(id)) continue
notifiedAlerts.current.add(id) notifiedAlerts.current.add(id)
new Notification('computer alert', { body: `${a?.title ?? 'Bookmark'} is due!`, icon: '/favicon.svg' }) new Notification('superbrain alert', { body: `${a?.title ?? 'Bookmark'} is due!`, icon: '/favicon.svg' })
} }
} }
} }
@@ -111,7 +111,7 @@ export function AppShell({ children }: { children: React.ReactNode }) {
// an explicit user action (top-bar.tsx), not on every app mount. // an explicit user action (top-bar.tsx), not on every app mount.
const refreshPage = useCallback(() => { const refreshPage = useCallback(() => {
window.dispatchEvent(new Event('computer:bookmarks-changed')) window.dispatchEvent(new Event('superbrain:bookmarks-changed'))
router.refresh() router.refresh()
}, [router]) }, [router])
+4 -4
View File
@@ -32,7 +32,7 @@ const viewItems = [
// Section collapse state persists per browser. useSyncExternalStore keeps it // Section collapse state persists per browser. useSyncExternalStore keeps it
// hydration-safe (server snapshot uses the default; the client snapshot reads // hydration-safe (server snapshot uses the default; the client snapshot reads
// localStorage after mount) without setState inside an effect. // localStorage after mount) without setState inside an effect.
const SECTION_STORE_EVENT = 'computer:sidebar-sections' const SECTION_STORE_EVENT = 'superbrain:sidebar-sections'
function readSection(key: string, fallback: boolean): boolean { function readSection(key: string, fallback: boolean): boolean {
try { try {
@@ -81,7 +81,7 @@ export function Sidebar({ open, onToggle, onQuickFind, pathname, isAdmin = false
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-primary text-primary-foreground"> <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-primary text-primary-foreground">
<Link2 className="h-3.5 w-3.5" /> <Link2 className="h-3.5 w-3.5" />
</div> </div>
{open && <span className="truncate font-display text-sm font-bold tracking-tight">computer</span>} {open && <span className="truncate font-display text-sm font-bold tracking-tight">superbrain</span>}
</Link> </Link>
</div> </div>
<Suspense fallback={<div className="flex-1" />}> <Suspense fallback={<div className="flex-1" />}>
@@ -147,8 +147,8 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
const router = useRouter() const router = useRouter()
const searchParams = useSearchParams() const searchParams = useSearchParams()
const [pages, setPages] = useState<PageSummary[]>([]) const [pages, setPages] = useState<PageSummary[]>([])
const [pagesExpanded, setPagesExpanded] = usePersistentState('computer:sidebar:pages', true) const [pagesExpanded, setPagesExpanded] = usePersistentState('superbrain:sidebar:pages', true)
const [viewsExpanded, setViewsExpanded] = usePersistentState('computer:sidebar:views', true) const [viewsExpanded, setViewsExpanded] = usePersistentState('superbrain:sidebar:views', true)
const [renamingId, setRenamingId] = useState<string | null>(null) const [renamingId, setRenamingId] = useState<string | null>(null)
const [renameValue, setRenameValue] = useState('') const [renameValue, setRenameValue] = useState('')
const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null) const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null)
+2 -2
View File
@@ -86,7 +86,7 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi
return () => document.removeEventListener('mousedown', handler) return () => document.removeEventListener('mousedown', handler)
}, []) }, [])
const section = SECTION_LABELS[pathname] ?? 'computer' const section = SECTION_LABELS[pathname] ?? 'superbrain'
const isMac = mounted && typeof navigator !== 'undefined' && /mac|iphone|ipad/i.test(navigator.userAgent) const isMac = mounted && typeof navigator !== 'undefined' && /mac|iphone|ipad/i.test(navigator.userAgent)
const quickFindHint = !mounted ? '⌘K' : isMac ? '⌘K' : 'Ctrl K' const quickFindHint = !mounted ? '⌘K' : isMac ? '⌘K' : 'Ctrl K'
@@ -122,7 +122,7 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi
<BreadcrumbList className="flex-nowrap"> <BreadcrumbList className="flex-nowrap">
<BreadcrumbItem> <BreadcrumbItem>
<BreadcrumbLink asChild className="font-medium"> <BreadcrumbLink asChild className="font-medium">
<Link href="/pages">computer</Link> <Link href="/pages">superbrain</Link>
</BreadcrumbLink> </BreadcrumbLink>
</BreadcrumbItem> </BreadcrumbItem>
<BreadcrumbSeparator /> <BreadcrumbSeparator />
+13 -13
View File
@@ -1,6 +1,6 @@
# Connecting computer to Authelia (OIDC) # Connecting superbrain to Authelia (OIDC)
computer includes an **Authelia OpenID Connect provider scaffold**, but superbrain includes an **Authelia OpenID Connect provider scaffold**, but
end-to-end sign-in is intentionally **stubbed**. Real credentials register end-to-end sign-in is intentionally **stubbed**. Real credentials register
the NextAuth provider; the login button and sign-in callback still block it the NextAuth provider; the login button and sign-in callback still block it
until a developer implements mapping to local Go users. until a developer implements mapping to local Go users.
@@ -62,10 +62,10 @@ docker run --rm authelia/authelia:4.39 authelia crypto hash generate pbkdf2 \
``` ```
This prints: This prints:
- **Random Password**: the *plain* secret. It goes into computer as `OIDC_CLIENT_SECRET`. - **Random Password**: the *plain* secret. It goes into superbrain as `OIDC_CLIENT_SECRET`.
- **Digest**: the *hashed* secret. It goes into Authelia's `client_secret`. - **Digest**: the *hashed* secret. It goes into Authelia's `client_secret`.
### 2.2 Register the computer client (`configuration.yml`) ### 2.2 Register the superbrain client (`configuration.yml`)
Merge this example into the existing OIDC provider configuration. Replace the Merge this example into the existing OIDC provider configuration. Replace the
client secret digest and public app hostname; keep your existing provider client secret digest and public app hostname; keep your existing provider
@@ -76,19 +76,19 @@ identity_providers:
oidc: oidc:
# jwks / hmac_secret must already be configured for OIDC to work # jwks / hmac_secret must already be configured for OIDC to work
claims_policies: claims_policies:
computer: superbrain:
# Include these identity claims in the ID token. # Include these identity claims in the ID token.
id_token: ['email', 'email_verified', 'name', 'preferred_username'] id_token: ['email', 'email_verified', 'name', 'preferred_username']
clients: clients:
- client_id: 'computer' - client_id: 'superbrain'
client_name: 'computer' client_name: 'superbrain'
client_secret: '$pbkdf2-sha512$310000$...' # Digest from 2.1 client_secret: '$pbkdf2-sha512$310000$...' # Digest from 2.1
public: false public: false
authorization_policy: 'two_factor' # or 'one_factor' authorization_policy: 'two_factor' # or 'one_factor'
consent_mode: 'explicit' consent_mode: 'explicit'
claims_policy: 'computer' claims_policy: 'superbrain'
redirect_uris: redirect_uris:
- 'https://<COMPUTER_HOST>/api/auth/callback/authelia' - 'https://<superbrain_HOST>/api/auth/callback/authelia'
scopes: ['openid', 'profile', 'email'] scopes: ['openid', 'profile', 'email']
grant_types: ['authorization_code'] grant_types: ['authorization_code']
response_types: ['code'] response_types: ['code']
@@ -100,7 +100,7 @@ Validate the configuration and restart your Authelia deployment after editing.
**Redirect URI rule:** it must exactly match **Redirect URI rule:** it must exactly match
`<NEXTAUTH_URL>/api/auth/callback/authelia`, including scheme, hostname, port `<NEXTAUTH_URL>/api/auth/callback/authelia`, including scheme, hostname, port
if present, and path. For an HTTPS deployment, use if present, and path. For an HTTPS deployment, use
`https://<COMPUTER_HOST>/api/auth/callback/authelia`. `https://<superbrain_HOST>/api/auth/callback/authelia`.
The callback is handled by NextAuth on the **web app**, not the Go API. The callback is handled by NextAuth on the **web app**, not the Go API.
Forward `/api/auth/*` to Next.js in your reverse proxy. The identically named Forward `/api/auth/*` to Next.js in your reverse proxy. The identically named
@@ -115,7 +115,7 @@ email/password account; matching an email string alone is not enough.
--- ---
## 3. What to configure in computer ## 3. What to configure in superbrain
Set these environment variables in the **root** `.env` or hosting environment. Set these environment variables in the **root** `.env` or hosting environment.
Compose passes the OIDC variables to the API and web containers. Replace the Compose passes the OIDC variables to the API and web containers. Replace the
@@ -123,10 +123,10 @@ sample hostnames with your actual hosts.
| Variable | Example | Notes | | Variable | Example | Notes |
|---|---|---| |---|---|---|
| `NEXTAUTH_URL` | `https://computer.company.tld` | Public web app URL; determines the callback | | `NEXTAUTH_URL` | `https://superbrain.company.tld` | Public web app URL; determines the callback |
| `COOKIE_SECURE` | `1` | For an HTTPS deployment | | `COOKIE_SECURE` | `1` | For an HTTPS deployment |
| `OIDC_ISSUER` | `https://auth.company.tld` | Exact issuer advertised in Authelia's discovery document | | `OIDC_ISSUER` | `https://auth.company.tld` | Exact issuer advertised in Authelia's discovery document |
| `OIDC_CLIENT_ID` | `computer` | Must match `client_id` in Authelia | | `OIDC_CLIENT_ID` | `superbrain` | Must match `client_id` in Authelia |
| `OIDC_CLIENT_SECRET` | *(plain secret from 2.1)* | The **plain** value, not the digest | | `OIDC_CLIENT_SECRET` | *(plain secret from 2.1)* | The **plain** value, not the digest |
Keep the existing `AUTH_SECRET`: changing it makes stored IMAP passwords Keep the existing `AUTH_SECRET`: changing it makes stored IMAP passwords
+9 -9
View File
@@ -33,9 +33,9 @@ export const forwardedClientHeaders = (source: Headers): Record<string, string>
if (!ip) return {} if (!ip) return {}
const { ts, sig } = signClientIP(ip) const { ts, sig } = signClientIP(ip)
return { return {
'x-computer-client-ip': ip, 'x-superbrain-client-ip': ip,
'x-computer-client-ts': ts, 'x-superbrain-client-ts': ts,
'x-computer-client-sig': sig, 'x-superbrain-client-sig': sig,
} }
} }
@@ -54,7 +54,7 @@ export async function backendFetch(path: string, init: RequestInit = {}) {
if (session?.user?.id) { if (session?.user?.id) {
if (!secret) throw new Error('Missing authentication secret') if (!secret) throw new Error('Missing authentication secret')
headers.set('Authorization', `Bearer ${jwt.sign({ uid: session.user.id, ver: session.user.ver, typ: 'assertion' }, secret, { headers.set('Authorization', `Bearer ${jwt.sign({ uid: session.user.id, ver: session.user.ver, typ: 'assertion' }, secret, {
algorithm: 'HS256', issuer: 'computer', expiresIn: '60s', algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s',
})}`) })}`)
} }
// Review AUTH-RATE/SEC-2: attest the browser IP for Go's login/signup // Review AUTH-RATE/SEC-2: attest the browser IP for Go's login/signup
@@ -62,14 +62,14 @@ export async function backendFetch(path: string, init: RequestInit = {}) {
// bucket. The timestamped HMAC keeps the header unforgeable and // bucket. The timestamped HMAC keeps the header unforgeable and
// short-lived; Go falls back to the direct peer when it is missing or // short-lived; Go falls back to the direct peer when it is missing or
// invalid. // invalid.
const clientIP = headers.get('x-computer-client-ip') const clientIP = headers.get('x-superbrain-client-ip')
if (clientIP && secret) { if (clientIP && secret) {
const { ts, sig } = signClientIP(clientIP) const { ts, sig } = signClientIP(clientIP)
headers.set('x-computer-client-ts', ts) headers.set('x-superbrain-client-ts', ts)
headers.set('x-computer-client-sig', sig) headers.set('x-superbrain-client-sig', sig)
} }
const viewAs = (await cookies()).get('computer_view_as')?.value const viewAs = (await cookies()).get('superbrain_view_as')?.value
if (viewAs) headers.set('Cookie', `computer_view_as=${encodeURIComponent(viewAs)}`) if (viewAs) headers.set('Cookie', `superbrain_view_as=${encodeURIComponent(viewAs)}`)
// Review M-7: bound server-side calls so a hung or blackholed backend // Review M-7: bound server-side calls so a hung or blackholed backend
// cannot stall a route/server component until the platform timeout. // cannot stall a route/server component until the platform timeout.
// Callers may provide their own signal to override this default. // Callers may provide their own signal to override this default.
+1 -1
View File
@@ -1,6 +1,6 @@
import { backendFetch } from '@/lib/api' import { backendFetch } from '@/lib/api'
export const VIEW_AS_COOKIE = 'computer_view_as' export const VIEW_AS_COOKIE = 'superbrain_view_as'
export type AuthUser = { id: string; name?: string | null; email?: string | null; image?: string | null; role: 'USER' | 'ADMIN'; actingAdminId?: string } export type AuthUser = { id: string; name?: string | null; email?: string | null; image?: string | null; role: 'USER' | 'ADMIN'; actingAdminId?: string }
// Review M-6: Go distinguishes "no session" (401) from backend degradation // Review M-6: Go distinguishes "no session" (401) from backend degradation
+1 -1
View File
@@ -43,7 +43,7 @@ export class PageAutosave {
setVersion(id: string, version: number) { this.versions.set(id, version) } setVersion(id: string, version: number) { this.versions.set(id, version) }
private key(id: string) { return `computer:page-draft:${id}` } private key(id: string) { return `superbrain:page-draft:${id}` }
private store(id: string, draft: Draft | null) { private store(id: string, draft: Draft | null) {
try { try {
if (draft === null) sessionStorage.removeItem(this.key(id)) if (draft === null) sessionStorage.removeItem(this.key(id))
+8 -8
View File
@@ -1,10 +1,10 @@
export const PAGES_CHANGED = 'computer:pages-changed' export const PAGES_CHANGED = 'superbrain:pages-changed'
export const notifyPagesChanged = () => window.dispatchEvent(new Event(PAGES_CHANGED)) export const notifyPagesChanged = () => window.dispatchEvent(new Event(PAGES_CHANGED))
// Notion-style breadcrumbs: the pages workspace announces which page is open // Notion-style breadcrumbs: the pages workspace announces which page is open
// so the top bar can show "computer / Pages / <title>" without refetching. // so the top bar can show "superbrain / Pages / <title>" without refetching.
export const ACTIVE_PAGE_CHANGED = 'computer:active-page-changed' export const ACTIVE_PAGE_CHANGED = 'superbrain:active-page-changed'
export const notifyActivePage = (title: string | null) => export const notifyActivePage = (title: string | null) =>
window.dispatchEvent(new CustomEvent<string | null>(ACTIVE_PAGE_CHANGED, { detail: title })) window.dispatchEvent(new CustomEvent<string | null>(ACTIVE_PAGE_CHANGED, { detail: title }))
@@ -20,15 +20,15 @@ export type PageSummary = {
// Connected pages (phase 3): the same link forms the editor understands, // Connected pages (phase 3): the same link forms the editor understands,
// shared by the page client, sidebar and Markdown preview. Page links use // shared by the page client, sidebar and Markdown preview. Page links use
// `computer:page/<id>`; /pages?id=<id> is accepted for hand-written links. // `superbrain:page/<id>`; /pages?id=<id> is accepted for hand-written links.
export function internalPageId(href: string): string | null { export function internalPageId(href: string): string | null {
const value = href.trim().replace(/^<|>$/g, '') const value = href.trim().replace(/^<|>$/g, '')
let raw = '' let raw = ''
if (value.startsWith('computer://page/')) raw = value.slice('computer://page/'.length) if (value.startsWith('superbrain://page/')) raw = value.slice('superbrain://page/'.length)
else if (value.startsWith('computer:page/')) raw = value.slice('computer:page/'.length) else if (value.startsWith('superbrain:page/')) raw = value.slice('superbrain:page/'.length)
else if (value.startsWith('page/')) raw = value.slice('page/'.length) else if (value.startsWith('page/')) raw = value.slice('page/'.length)
else if (value.startsWith('/pages/')) raw = value.slice('/pages/'.length) else if (value.startsWith('/pages/')) raw = value.slice('/pages/'.length)
else if (value.startsWith('/pages?') || value.startsWith('computer:page?id=') || value.startsWith('computer://page?id=')) { else if (value.startsWith('/pages?') || value.startsWith('superbrain:page?id=') || value.startsWith('superbrain://page?id=')) {
try { try {
const id = new URL(value, 'http://localhost').searchParams.get('id') const id = new URL(value, 'http://localhost').searchParams.get('id')
raw = id ?? '' raw = id ?? ''
@@ -39,7 +39,7 @@ export function internalPageId(href: string): string | null {
} }
export const pageLinkMarkdown = (page: Pick<PageSummary, 'id' | 'title'>) => export const pageLinkMarkdown = (page: Pick<PageSummary, 'id' | 'title'>) =>
`[${page.title.replace(/[\[\]\n]/g, ' ')}](computer:page/${page.id})` `[${page.title.replace(/[\[\]\n]/g, ' ')}](superbrain:page/${page.id})`
export type PageEmbedMarker = { collectionId: string; viewId: string | null } export type PageEmbedMarker = { collectionId: string; viewId: string | null }
@@ -1,6 +1,6 @@
# computer: porting guide # superbrain: porting guide
This guide lists every data object, server function, HTTP endpoint and client behavior in **computer**, so it can be rebuilt in another language or framework. It describes the code as it is today (October 2026), including the parts that are stubs or unfinished. This guide lists every data object, server function, HTTP endpoint and client behavior in **superbrain**, so it can be rebuilt in another language or framework. It describes the code as it is today (October 2026), including the parts that are stubs or unfinished.
The guide uses neutral terms wherever possible. "Session user" means the authenticated person; "effective user" means the account a request acts on (these differ only while an admin uses *View as*). The guide uses neutral terms wherever possible. "Session user" means the authenticated person; "effective user" means the account a request acts on (these differ only while an admin uses *View as*).
@@ -91,7 +91,7 @@ Composite PK (`tagId`, `userId`), `createdAt`; both Cascade.
Composite PK (`pageId`, `bookmarkId`), `position` int, `createdAt`; both Cascade. Composite PK (`pageId`, `bookmarkId`), `position` int, `createdAt`; both Cascade.
### 2.13b `PageLink` (resolved internal page link) ### 2.13b `PageLink` (resolved internal page link)
Composite PK (`sourcePageId`, `targetPageId`), `createdAt`; both Cascade, with a no-self check. Rebuilt from Markdown (`computer:page/<id>`) on every content save and only for pages owned by the author, so backlinks never cross accounts. Composite PK (`sourcePageId`, `targetPageId`), `createdAt`; both Cascade, with a no-self check. Rebuilt from Markdown (`superbrain:page/<id>`) on every content save and only for pages owned by the author, so backlinks never cross accounts.
### 2.13c `PageEmbed` (live collection view inside a page) ### 2.13c `PageEmbed` (live collection view inside a page)
Composite PK (`pageId`, `collectionId`), `viewId?` → CollectionView (SetNull), `position` int, `createdAt`; page and collection Cascade. Rebuilt from `{{collection:<id>|view=<viewId>}}` on every content save; only owned collections are stored. Item reads still go through the collection endpoint, so an embed displays, never publishes. Composite PK (`pageId`, `collectionId`), `viewId?` → CollectionView (SetNull), `position` int, `createdAt`; page and collection Cascade. Rebuilt from `{{collection:<id>|view=<viewId>}}` on every content save; only owned collections are stored. Item reads still go through the collection endpoint, so an embed displays, never publishes.
@@ -129,7 +129,7 @@ Secrets: `NEXTAUTH_SECRET` / `AUTH_SECRET` (same value) sign the cookie.
### 3.2 Authorization (`lib/auth-guard.ts`) ### 3.2 Authorization (`lib/auth-guard.ts`)
| Symbol | Signature | Behavior | | Symbol | Signature | Behavior |
|---|---|---| |---|---|---|
| `VIEW_AS_COOKIE` | const `"computer_view_as"` | Cookie holding the target user ID | | `VIEW_AS_COOKIE` | const `"superbrain_view_as"` | Cookie holding the target user ID |
| `AuthUser` | `{id, name?, email?, image?, role: USER\|ADMIN, actingAdminId?}` | | | `AuthUser` | `{id, name?, email?, image?, role: USER\|ADMIN, actingAdminId?}` | |
| `adminEmails()` | `→ string[]` | Splits env `ADMIN_EMAILS` on commas, trims, lowercases | | `adminEmails()` | `→ string[]` | Splits env `ADMIN_EMAILS` on commas, trims, lowercases |
| `resolveRole(user)` | `→ USER\|ADMIN` | ADMIN if DB role is ADMIN; otherwise if email is in `adminEmails()`, **writes** role ADMIN to the DB and returns ADMIN | | `resolveRole(user)` | `→ USER\|ADMIN` | ADMIN if DB role is ADMIN; otherwise if email is in `adminEmails()`, **writes** role ADMIN to the DB and returns ADMIN |
@@ -166,13 +166,13 @@ When porting, the real email check should: decrypt the IMAP password, connect, s
Changing the secret makes saved IMAP passwords unreadable. Changing the secret makes saved IMAP passwords unreadable.
### 3.6 Link preview (repeated in `/api/preview`, bookmark create and bookmark update) ### 3.6 Link preview (repeated in `/api/preview`, bookmark create and bookmark update)
`fetchPreview(url)` uses an 8-second timeout and User-Agent `Mozilla/5.0 (compatible; computer/1.0)`. It reads OpenGraph `ogTitle`, `ogDescription`, the first `ogImage` URL, and the favicon. A relative favicon is made absolute against the URL's origin; if none is found it uses `<origin>/favicon.ico`. On any failure it returns all nulls and never throws. **Port tip:** make this one shared function. `fetchPreview(url)` uses an 8-second timeout and User-Agent `Mozilla/5.0 (compatible; superbrain/1.0)`. It reads OpenGraph `ogTitle`, `ogDescription`, the first `ogImage` URL, and the favicon. A relative favicon is made absolute against the URL's origin; if none is found it uses `<origin>/favicon.ico`. On any failure it returns all nulls and never throws. **Port tip:** make this one shared function.
### 3.7 Markdown export (`lib/markdown-export.ts`) ### 3.7 Markdown export (`lib/markdown-export.ts`)
| Function | Output | | Function | Output |
|---|---| |---|---|
| `slugify(s)` | Lowercase, runs of non `[a-z0-9]` become `-`, trim dashes, max 60 chars, fallback `untitled` | | `slugify(s)` | Lowercase, runs of non `[a-z0-9]` become `-`, trim dashes, max 60 chars, fallback `untitled` |
| `pageToMarkdown(page)` | `# title`, blank line, trimmed content; if links exist, `## Links` then `- [title](url) — description` (title has `[` `]` removed; description whitespace collapsed, max 160 chars); final line `<!-- exported from computer <updatedAt ISO> -->` | | `pageToMarkdown(page)` | `# title`, blank line, trimmed content; if links exist, `## Links` then `- [title](url) — description` (title has `[` `]` removed; description whitespace collapsed, max 160 chars); final line `<!-- exported from superbrain <updatedAt ISO> -->` |
| `bookmarkToMarkdown(b)` | `# title-or-url`, then `- URL: <url>`, `- Date: YYYY-MM-DD` (if dueDate), `- Tags: a, b` (if any), blank line, trimmed notes | | `bookmarkToMarkdown(b)` | `# title-or-url`, then `- URL: <url>`, `- Date: YYYY-MM-DD` (if dueDate), `- Tags: a, b` (if any), blank line, trimmed notes |
| `markdownResponse(body, name)` | Content-Type `text/markdown; charset=utf-8`, `Content-Disposition: attachment; filename="<name>.md"` | | `markdownResponse(body, name)` | Content-Type `text/markdown; charset=utf-8`, `Content-Disposition: attachment; filename="<name>.md"` |
@@ -180,7 +180,7 @@ Changing the secret makes saved IMAP passwords unreadable.
`isRealValue(v)` is false when empty or matching a placeholder pattern: `replace_me`/`replace-me`/`replaceme`, `example.com/org/net`, `changeme`, `placeholder`, `<...>`, `your_…`/`your-…`, `todo`. `getOidcStatus()` returns `{enabled, issuerSet, clientIdSet, clientSecretSet, issuer}`, with `enabled` only when all three env values are real. It never exposes the secret. `isRealValue(v)` is false when empty or matching a placeholder pattern: `replace_me`/`replace-me`/`replaceme`, `example.com/org/net`, `changeme`, `placeholder`, `<...>`, `your_…`/`your-…`, `todo`. `getOidcStatus()` returns `{enabled, issuerSet, clientIdSet, clientSecretSet, issuer}`, with `enabled` only when all three env values are real. It never exposes the secret.
### 3.9 Seed script (`scripts/seed.ts`) ### 3.9 Seed script (`scripts/seed.ts`)
Upserts a hidden test account. If env `DEMO_PASSWORD` is set, it also upserts five demo users (maya = ADMIN, jordan, sam, priya, alex @computer.demo). Each gets default columns, tags, bookmarks and one page, created only if that user has no bookmarks yet, followed by idempotent share upserts. It never deletes anything. Upserts a hidden test account. If env `DEMO_PASSWORD` is set, it also upserts five demo users (maya = ADMIN, jordan, sam, priya, alex @superbrain.demo). Each gets default columns, tags, bookmarks and one page, created only if that user has no bookmarks yet, followed by idempotent share upserts. It never deletes anything.
--- ---
@@ -293,15 +293,15 @@ Moving a card = `PUT /api/bookmarks/:id {kanbanColumnId}`.
| Screen / component | Responsibilities | | Screen / component | Responsibilities |
|---|---| |---|---|
| **App shell** | Loads session and `/api/me`; shows the View as banner with an Exit button (`POST /api/admin/view-as {userId:null}`); asks for notification permission; polls `/api/alerts/check` on load and every **5 minutes**, showing a browser `Notification("computer alert", "<title> is due!")` per alert; provides search text, the add-bookmark dialog and the bookmark detail panel to child screens | | **App shell** | Loads session and `/api/me`; shows the View as banner with an Exit button (`POST /api/admin/view-as {userId:null}`); asks for notification permission; polls `/api/alerts/check` on load and every **5 minutes**, showing a browser `Notification("superbrain alert", "<title> is due!")` per alert; provides search text, the add-bookmark dialog and the bookmark detail panel to child screens |
| **Sidebar** | Pages first: full page list (pinned pages marked) plus a New page button creating the next "Untitled N", refreshing on the in-app event `computer:pages-changed`. Below, a Filters section (All Bookmarks, Calendar, Tags, Kanban, Contacts — views over the same bookmark collection) and Settings, plus Admin for admins | | **Sidebar** | Pages first: full page list (pinned pages marked) plus a New page button creating the next "Untitled N", refreshing on the in-app event `superbrain:pages-changed`. Below, a Filters section (All Bookmarks, Calendar, Tags, Kanban, Contacts — views over the same bookmark collection) and Settings, plus Admin for admins |
| **Dashboard** `/dashboard` | Removed as a screen; redirects to `/bookmarks` preserving `?search=` | | **Dashboard** `/dashboard` | Removed as a screen; redirects to `/bookmarks` preserving `?search=` |
| **Bookmarks** `/bookmarks` | Sortable table with Mine / Shared tabs and search (absorbed the old dashboard) | | **Bookmarks** `/bookmarks` | Sortable table with Mine / Shared tabs and search (absorbed the old dashboard) |
| **Calendar** `/calendar` | Month grid of bookmarks by `dueDate`, plus shared dates | | **Calendar** `/calendar` | Month grid of bookmarks by `dueDate`, plus shared dates |
| **Tags** `/tags` | Tag list (create, color, share) with filtered bookmarks | | **Tags** `/tags` | Tag list (create, color, share) with filtered bookmarks |
| **Contacts** `/contacts` | Synced contacts and their linked bookmarks | | **Contacts** `/contacts` | Synced contacts and their linked bookmarks |
| **Kanban** `/kanban` | Columns from `getColumns`; cards placed with `resolveColumnId`; drag and drop moves a card (PUT `kanbanColumnId`); add, rename, recolor, reorder and delete columns | | **Kanban** `/kanban` | Columns from `getColumns`; cards placed with `resolveColumnId`; drag and drop moves a card (PUT `kanbanColumnId`); add, rename, recolor, reorder and delete columns |
| **Pages** `/pages` | Tab bar of pages; Markdown editor with edit/preview toggle and **autosave 800 ms** after the last keystroke (states dirty → saving → saved); link picker searching bookmarks (250 ms delay, top 8); pin/unpin, rename, delete, .md download; sends `computer:pages-changed` after changes | | **Pages** `/pages` | Tab bar of pages; Markdown editor with edit/preview toggle and **autosave 800 ms** after the last keystroke (states dirty → saving → saved); link picker searching bookmarks (250 ms delay, top 8); pin/unpin, rename, delete, .md download; sends `superbrain:pages-changed` after changes |
| **Admin** `/admin` | User list with counts, role toggle, View as button | | **Admin** `/admin` | User list with counts, role toggle, View as button |
| **Settings** `/settings` | Profile; IMAP form (test + save); Nextcloud sync form; Authelia status and callback URL | | **Settings** `/settings` | Profile; IMAP form (test + save); Nextcloud sync form; Authelia status and callback URL |
| **Add bookmark dialog** | URL with live preview (`/api/preview`), title, notes, tags, dates | | **Add bookmark dialog** | URL with live preview (`/api/preview`), title, notes, tags, dates |
@@ -1,8 +1,8 @@
# LinkOS: Requirements # Superbrain: Requirements
## 1. Purpose ## 1. Purpose
LinkOS is a web-based "computer": a personal, multi-user collection of URLs that Superbrain: a personal, multi-user collection of URLs that
point to applications and sites. Users find links through several ways of point to applications and sites. Users find links through several ways of
organizing them (calendar, tags, contacts, kanban). Clicking a URL opens the organizing them (calendar, tags, contacts, kanban). Clicking a URL opens the
target application or site. target application or site.