From d870eece1eb87f398af83352256cf87eddaa65f2 Mon Sep 17 00:00:00 2001 From: Andrew S Erwin Date: Thu, 22 Oct 2026 00:33:44 -0500 Subject: [PATCH] Refactor all references to computer to Superbrain --- .env.example | 8 +- .github/workflows/check.yml | 2 +- PLAN.md | 2 +- README.md | 30 +++---- db/check-convergence.sh | 20 +++-- db/migrate-atomicity.sh | 79 ++++++++++++------ db/migrate.sh | 14 +++- db/schema.sql | 4 +- ...conf.template => superbrain.conf.template} | 2 +- internal/auth/handlers.go | 4 +- internal/auth/middleware.go | 8 +- internal/auth/ratelimit.go | 8 +- internal/auth/sessions.go | 8 +- internal/auth/sessions_test.go | 6 +- internal/auth/signup_validation_test.go | 10 +-- internal/authguard/handlers.go | 8 +- internal/crypto/crypto.go | 2 +- internal/db/db.go | 2 +- internal/db/users.go | 4 +- internal/handlers/bookmarks.go | 6 +- internal/handlers/collections.go | 2 +- internal/handlers/common.go | 4 +- internal/handlers/export.go | 6 +- internal/handlers/kanban.go | 4 +- internal/handlers/misc.go | 12 +-- internal/handlers/misc_test.go | 8 +- internal/handlers/page_graph.go | 16 ++-- internal/handlers/page_revisions.go | 2 +- internal/handlers/pages.go | 4 +- internal/handlers/signals.go | 6 +- internal/handlers/tags.go | 2 +- internal/handlers/trash.go | 2 +- internal/handlers/unshare.go | 2 +- internal/http/collections_test.go | 12 +-- internal/http/connected_pages_test.go | 16 ++-- internal/http/coverage_test.go | 40 ++++----- internal/http/integration_test.go | 18 ++--- internal/http/integrations_test.go | 20 ++--- internal/http/kanban_test.go | 4 +- internal/http/limits_search_test.go | 6 +- internal/http/migration_test.go | 2 +- internal/http/pagination_test.go | 4 +- internal/http/review_test.go | 24 +++--- internal/http/security_test.go | 52 ++++++------ internal/http/server.go | 12 +-- internal/http/sharing_test.go | 4 +- internal/http/trust_test.go | 18 ++--- internal/kanban/kanban.go | 2 +- internal/markdown/markdown.go | 4 +- internal/markdown/markdown_test.go | 2 +- internal/preview/preview.go | 6 +- internal/scripts/seed.go | 2 +- internal/signals/checkpoint_test.go | 4 +- internal/signals/scheduler.go | 2 +- internal/signals/signals.go | 8 +- main.go | 2 +- scripts/deploy.sh | 17 ++-- scripts/e2e.mjs | 6 +- scripts/regressions.mjs | 12 +-- scripts/server-deploy.sh | 81 +++++++++++-------- web/README.md | 2 +- web/app/(app)/bookmarks/client.tsx | 4 +- web/app/(app)/calendar/client.tsx | 2 +- web/app/(app)/contacts/client.tsx | 2 +- web/app/(app)/kanban/client.tsx | 2 +- web/app/(app)/tags/client.tsx | 2 +- web/app/(app)/trash/client.tsx | 2 +- web/app/api/[...path]/route.ts | 2 +- web/app/api/session/revoke/route.ts | 2 +- web/app/layout.tsx | 4 +- web/app/login/client.tsx | 2 +- web/app/share/bookmark/[id]/client.tsx | 2 +- web/app/signup/client.tsx | 2 +- web/auth.ts | 8 +- web/components/app-shell.tsx | 4 +- web/components/sidebar.tsx | 8 +- web/components/top-bar.tsx | 4 +- web/docs/AUTHELIA.md | 26 +++--- web/lib/api.ts | 18 ++--- web/lib/auth-guard.ts | 2 +- web/lib/page-autosave.ts | 2 +- web/lib/pages.ts | 16 ++-- ...g_guide.md => superbrain_porting_guide.md} | 20 ++--- ...irements.md => superbrain_requirements.md} | 4 +- 84 files changed, 438 insertions(+), 381 deletions(-) rename deploy/nginx/{computer.conf.template => superbrain.conf.template} (97%) rename web/{computer_porting_guide.md => superbrain_porting_guide.md} (94%) rename web/{computer_requirements.md => superbrain_requirements.md} (98%) diff --git a/.env.example b/.env.example index 8f06373..62144b3 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,6 @@ # docker compose reads this file for every command (even db-up/migrate), # 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. AUTH_SECRET=replace-with-a-random-secret NEXTAUTH_URL=http://localhost:3000 @@ -26,7 +26,7 @@ ADMIN_EMAILS= # directly — clients could then choose their own rate-limit bucket. #TRUSTED_PROXY=1 # 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 # 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). @@ -45,9 +45,9 @@ OIDC_CLIENT_SECRET=REPLACE_ME # Go API listen port (default 8080). #PORT=8080 # 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): -#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): #BASE_URL=http://localhost:3000 #CHROMIUM_PATH=/usr/bin/chromium diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 5d3a34a..7f5adaf 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -38,7 +38,7 @@ jobs: { echo "POSTGRES_PASSWORD=ci-only-$(openssl rand -hex 8)" echo "AUTH_SECRET=$(openssl rand -hex 32)" - echo "POSTGRES_VOLUME=computer_pgdata" + echo "POSTGRES_VOLUME=superbrain_pgdata" } > .env - name: Install web dependencies diff --git a/PLAN.md b/PLAN.md index e924bf8..7488a92 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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 yet, and what we can build over the next 3–6 months. diff --git a/README.md b/README.md index 4da475d..e30c712 100644 --- a/README.md +++ b/README.md @@ -6,15 +6,15 @@ saved views, pages, previews, sharing, contacts and email signals. ## 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, macOS, and Linux. Requires Docker with Compose v2 or newer. On a new installation: ```bash -git clone https://github.com/andrewthecodertx/computer.git -cd computer +git clone https://github.com/andrewthecodertx/superbrain.git +cd superbrain cp .env.example .env 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 Set `POSTGRES_VOLUME` to its existing Docker volume name and -`POSTGRES_VOLUME_EXTERNAL=true`. The volume must contain the `computer` -database and `computer` role. Stop the previous PostgreSQL container before +`POSTGRES_VOLUME_EXTERNAL=true`. The volume must contain the `superbrain` +database and `superbrain` role. Stop the previous PostgreSQL container before mounting that volume in this stack. `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 Go cookie sessions stop working. - 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. - Containers share the Compose backend network. The app runs as non-root 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 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`. - Grant type: `authorization_code`; response type: `code`. - Token endpoint authentication: `client_secret_basic`. - Redirect URI: `/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 **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 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: ```dotenv -NEXTAUTH_URL=https://computer.company.tld +NEXTAUTH_URL=https://superbrain.company.tld COOKIE_SECURE=1 OIDC_ISSUER=https://auth.company.tld -OIDC_CLIENT_ID=computer +OIDC_CLIENT_ID=superbrain OIDC_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: ```bash -docker compose exec -e SEED_EMAIL=admin@company.tld -e SEED_PASSWORD='' app /computer --seed +docker compose exec -e SEED_EMAIL=admin@company.tld -e SEED_PASSWORD='' app /superbrain --seed ``` 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: ```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 exact git revision, refuses dirty trees unless `ALLOW_DIRTY=1`, rsyncs the source, and on the server: provisions Docker/nginx/certbot, writes `.env` on 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 -`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 RUNNING.md → "Running on a remote server" for the operator checklist. diff --git a/db/check-convergence.sh b/db/check-convergence.sh index 58a6945..c2270ab 100755 --- a/db/check-convergence.sh +++ b/db/check-convergence.sh @@ -13,16 +13,20 @@ set -eu DB_HOST="${DB_HOST:-db}" -DB_USER="${DB_USER:-computer}" -[ -n "${PGPASSWORD:-}" ] || { echo "error: PGPASSWORD is required" >&2; exit 1; } +DB_USER="${DB_USER:-superbrain}" +[ -n "${PGPASSWORD:-}" ] || { + echo "error: PGPASSWORD is required" >&2 + exit 1 +} -BASE_DB=computer_conv_schema -CHAIN_DB=computer_conv_chain +BASE_DB=superbrain_conv_schema +CHAIN_DB=superbrain_conv_chain 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 "$BASE_DB"; drop "$CHAIN_DB" +drop "$BASE_DB" +drop "$CHAIN_DB" trap 'drop "$BASE_DB"; drop "$CHAIN_DB"' EXIT INT TERM psql -q -d postgres -c "CREATE DATABASE $BASE_DB" @@ -54,8 +58,8 @@ catalog() { ORDER BY 1" } -catalog "$BASE_DB" > /tmp/base.catalog -catalog "$CHAIN_DB" > /tmp/chain.catalog +catalog "$BASE_DB" >/tmp/base.catalog +catalog "$CHAIN_DB" >/tmp/chain.catalog fail() { echo "error: db/schema.sql and db/migrations disagree (diff above)." >&2 @@ -80,7 +84,7 @@ if [ -n "$tables" ]; then done psql -q -d "$CHAIN_DB" -c "DELETE FROM _migration" DB_NAME="$CHAIN_DB" sh /db/migrate.sh >/dev/null - catalog "$CHAIN_DB" > /tmp/chain.catalog + catalog "$CHAIN_DB" >/tmp/chain.catalog diff -u /tmp/base.catalog /tmp/chain.catalog || fail fi diff --git a/db/migrate-atomicity.sh b/db/migrate-atomicity.sh index 32f33e0..8340aa2 100755 --- a/db/migrate-atomicity.sh +++ b/db/migrate-atomicity.sh @@ -4,63 +4,96 @@ # scratch databases it creates and drops; app data is never touched. Invoked # by 'make db-converge' alongside the schema convergence check. set -u -FAIL_DB=computer_conv_atomicity -PSQL="psql -h db -U computer -v ON_ERROR_STOP=1" +FAIL_DB=superbrain_conv_atomicity +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 "CREATE DATABASE $FAIL_DB" mkdir -p /tmp/migs 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 -MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=computer DB_NAME=$FAIL_DB sh /db/migrate.sh +printf 'CREATE TABLE conv_probe(id text);\nSELECT 1/0;\n' >/tmp/migs/999_probe.sql +MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$FAIL_DB sh /db/migrate.sh 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") 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; } -[ "$probe" = "0" ] || { echo "FAIL: partial DDL survived the rollback"; exit 1; } +[ "$rows" = "0" ] || { + 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 2: successful migration applies and records atomically" -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 +printf 'CREATE TABLE conv_probe(id text);\n' >/tmp/migs/999_probe.sql +MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$FAIL_DB sh /db/migrate.sh 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") 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 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; } -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 || { + echo "FAIL: idempotent re-run failed" + exit 1 +} +printf 'CREATE TABLE conv_probe2(id text);\n' >/tmp/migs/999_probe.sql +MIGRATIONS=/tmp/migs DB_HOST=db DB_USER=superbrain DB_NAME=$FAIL_DB sh /db/migrate.sh 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" = "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 4: concurrent runners — exactly one applies, the loser aborts" -printf 'CREATE TABLE conv_race(id text);\n' > /tmp/migs/999_probe.sql -RACE_DB=computer_conv_race +printf 'CREATE TABLE conv_race(id text);\n' >/tmp/migs/999_probe.sql +RACE_DB=superbrain_conv_race $PSQL -d postgres -qc "DROP DATABASE IF EXISTS $RACE_DB WITH (FORCE)" $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=$! -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=$! -rc1=0; rc2=0 +rc1=0 +rc2=0 wait $p1 || rc1=$? wait $p2 || rc2=$? # 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 # 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") 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" $PSQL -d postgres -qc "DROP DATABASE IF EXISTS $RACE_DB WITH (FORCE)" diff --git a/db/migrate.sh b/db/migrate.sh index 6a8b668..ef86924 100755 --- a/db/migrate.sh +++ b/db/migrate.sh @@ -21,10 +21,13 @@ set -eu DB_HOST="${DB_HOST:-db}" -DB_USER="${DB_USER:-computer}" -DB_NAME="${DB_NAME:-computer}" +DB_USER="${DB_USER:-superbrain}" +DB_NAME="${DB_NAME:-superbrain}" 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() { 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 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")" sum="$(sha256sum "$f" | cut -d' ' -f1)" recorded="$(psql -Atc "SELECT checksum FROM _migration WHERE name='$name'")" diff --git a/db/schema.sql b/db/schema.sql index 7c79206..a02571f 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -1,5 +1,5 @@ --- computer database schema --- Derived from computer_porting_guide.md section 2 and prisma/schema.prisma. +-- superbrain database schema +-- Derived from superbrain_porting_guide.md section 2 and prisma/schema.prisma. -- IDs are text (CUID/UUID). CASCADE / SetNull per the guide. -- Run against an EMPTY database. Never drops or recreates a database. diff --git a/deploy/nginx/computer.conf.template b/deploy/nginx/superbrain.conf.template similarity index 97% rename from deploy/nginx/computer.conf.template rename to deploy/nginx/superbrain.conf.template index 5bcb6e5..d3935c9 100644 --- a/deploy/nginx/computer.conf.template +++ b/deploy/nginx/superbrain.conf.template @@ -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 # 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 diff --git a/internal/auth/handlers.go b/internal/auth/handlers.go index d43982a..a619faa 100644 --- a/internal/auth/handlers.go +++ b/internal/auth/handlers.go @@ -3,8 +3,8 @@ package auth import ( "encoding/json" "errors" - "github.com/andrew/go-computer/internal/config" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/config" + "github.com/andrew/superbrain/internal/db" "github.com/jackc/pgx/v5/pgconn" "log" "net/http" diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go index 8bbdc6b..61e88de 100644 --- a/internal/auth/middleware.go +++ b/internal/auth/middleware.go @@ -3,15 +3,15 @@ package auth import ( "context" "errors" - "github.com/andrew/go-computer/internal/config" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/models" + "github.com/andrew/superbrain/internal/config" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/models" "log" "net/http" "sync" ) -const ViewAsCookie = "computer_view_as" +const ViewAsCookie = "superbrain_view_as" type SessionUser struct { ID, Role, RealID, RealRole string diff --git a/internal/auth/ratelimit.go b/internal/auth/ratelimit.go index 31f462d..c95b617 100644 --- a/internal/auth/ratelimit.go +++ b/internal/auth/ratelimit.go @@ -25,7 +25,7 @@ import ( "crypto/hmac" "crypto/sha256" "encoding/hex" - "github.com/andrew/go-computer/internal/config" + "github.com/andrew/superbrain/internal/config" "net" "net/http" "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 // that overwrites X-Real-IP (the shipped nginx template does). const ( - headerClientIP = "X-Computer-Client-Ip" - headerClientTs = "X-Computer-Client-Ts" - headerClientSig = "X-Computer-Client-Sig" + headerClientIP = "X-superbrain-Client-Ip" + headerClientTs = "X-superbrain-Client-Ts" + headerClientSig = "X-superbrain-Client-Sig" // forwardSkew bounds clock skew and replay of the signed identity. forwardSkew = 60 * time.Second ) diff --git a/internal/auth/sessions.go b/internal/auth/sessions.go index 61f27a8..b5a35e2 100644 --- a/internal/auth/sessions.go +++ b/internal/auth/sessions.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/andrew/go-computer/internal/config" + "github.com/andrew/superbrain/internal/config" "github.com/golang-jwt/jwt/v5" ) @@ -15,7 +15,7 @@ import ( // 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). const ( - sessionCookieName = "computer_session" + sessionCookieName = "superbrain_session" // time.Duration is nanoseconds, so multiply by time.Second explicitly. sessionMaxAge = 30 * 24 * 60 * 60 * time.Second // 30 days @@ -58,7 +58,7 @@ func SignSession(u SessionUser, secret string) (string, error) { RegisteredClaims: jwt.RegisteredClaims{ IssuedAt: jwt.NewNumericDate(now), ExpiresAt: jwt.NewNumericDate(now.Add(sessionMaxAge)), - Issuer: "computer", + Issuer: "superbrain", }, }) 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) { 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 { return nil, err } diff --git a/internal/auth/sessions_test.go b/internal/auth/sessions_test.go index d78cd7f..ea3e07b 100644 --- a/internal/auth/sessions_test.go +++ b/internal/auth/sessions_test.go @@ -28,12 +28,12 @@ func TestSessionLifetimeAndVerification(t *testing.T) { if _, e = VerifySession(token, "wrong-secret"); e == nil { 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")) if _, e = VerifySession(v, "test-secret"); e == nil { 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")) if _, e = VerifySession(v, "test-secret"); e == nil { 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{ UserID: "alice", Type: typ, Ver: ver, RegisteredClaims: jwt.RegisteredClaims{ - Issuer: "computer", + Issuer: "superbrain", IssuedAt: jwt.NewNumericDate(now), ExpiresAt: jwt.NewNumericDate(now.Add(ttl)), }, diff --git a/internal/auth/signup_validation_test.go b/internal/auth/signup_validation_test.go index 7861827..416fe55 100644 --- a/internal/auth/signup_validation_test.go +++ b/internal/auth/signup_validation_test.go @@ -16,12 +16,12 @@ func TestSignupValidation(t *testing.T) { body 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"}}, - {"email with display name", map[string]any{"email": "Name ", "password": "long-enough-password"}}, - {"short password", map[string]any{"email": "ok@computer.test", "password": "short"}}, - {"7 boundary password", map[string]any{"email": "ok@computer.test", "password": "1234567"}}, - {"overlong password", map[string]any{"email": "ok@computer.test", "password": strings.Repeat("a", 73)}}, + {"email with display name", map[string]any{"email": "Name ", "password": "long-enough-password"}}, + {"short password", map[string]any{"email": "ok@superbrain.test", "password": "short"}}, + {"7 boundary password", map[string]any{"email": "ok@superbrain.test", "password": "1234567"}}, + {"overlong password", map[string]any{"email": "ok@superbrain.test", "password": strings.Repeat("a", 73)}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/authguard/handlers.go b/internal/authguard/handlers.go index 85f3d18..5ed5d9f 100644 --- a/internal/authguard/handlers.go +++ b/internal/authguard/handlers.go @@ -4,10 +4,10 @@ import ( "database/sql" "encoding/json" "errors" - "github.com/andrew/go-computer/internal/auth" - "github.com/andrew/go-computer/internal/config" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/handlers" + "github.com/andrew/superbrain/internal/auth" + "github.com/andrew/superbrain/internal/config" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/handlers" "log" "net/http" "time" diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index 41918fb..e137b8c 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -35,7 +35,7 @@ const ( tagLength = 16 versionByte = 1 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. diff --git a/internal/db/db.go b/internal/db/db.go index 68a8360..08fa34d 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -12,7 +12,7 @@ import ( "strings" "time" - "github.com/andrew/go-computer/internal/config" + "github.com/andrew/superbrain/internal/config" _ "github.com/jackc/pgx/v5/stdlib" ) diff --git a/internal/db/users.go b/internal/db/users.go index 9586468..dc55042 100644 --- a/internal/db/users.go +++ b/internal/db/users.go @@ -4,8 +4,8 @@ import ( "context" "database/sql" "encoding/json" - "github.com/andrew/go-computer/internal/config" - "github.com/andrew/go-computer/internal/models" + "github.com/andrew/superbrain/internal/config" + "github.com/andrew/superbrain/internal/models" ) type UserRepo struct{ db *DB } diff --git a/internal/handlers/bookmarks.go b/internal/handlers/bookmarks.go index 9911539..a3bf1a6 100644 --- a/internal/handlers/bookmarks.go +++ b/internal/handlers/bookmarks.go @@ -6,9 +6,9 @@ import ( "encoding/base64" "encoding/json" "fmt" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/markdown" - "github.com/andrew/go-computer/internal/preview" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/markdown" + "github.com/andrew/superbrain/internal/preview" "net/http" "strconv" "strings" diff --git a/internal/handlers/collections.go b/internal/handlers/collections.go index 7038d80..3c25f20 100644 --- a/internal/handlers/collections.go +++ b/internal/handlers/collections.go @@ -5,7 +5,7 @@ import ( "encoding/base64" "encoding/json" "fmt" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" "math" "net/http" "regexp" diff --git a/internal/handlers/common.go b/internal/handlers/common.go index 18a5e9d..dcfbbbd 100644 --- a/internal/handlers/common.go +++ b/internal/handlers/common.go @@ -5,8 +5,8 @@ import ( "encoding/json" "errors" "fmt" - "github.com/andrew/go-computer/internal/auth" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/auth" + "github.com/andrew/superbrain/internal/db" "github.com/jackc/pgx/v5/pgconn" "io" "log" diff --git a/internal/handlers/export.go b/internal/handlers/export.go index 3f46fa6..23b2428 100644 --- a/internal/handlers/export.go +++ b/internal/handlers/export.go @@ -4,7 +4,7 @@ import ( "net/http" "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 @@ -68,9 +68,9 @@ func HandleExport(w http.ResponseWriter, r *http.Request) { detail["items"], detail["sharedWith"] = items, shares 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{ - "format": "computer-export", + "format": "superbrain-export", "version": 1, "exportedAt": time.Now().UTC(), "user": me, diff --git a/internal/handlers/kanban.go b/internal/handlers/kanban.go index ebb9a0d..8b1714d 100644 --- a/internal/handlers/kanban.go +++ b/internal/handlers/kanban.go @@ -2,8 +2,8 @@ package handlers import ( "database/sql" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/kanban" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/kanban" "net/http" "strings" ) diff --git a/internal/handlers/misc.go b/internal/handlers/misc.go index 73c0001..e28f6a2 100644 --- a/internal/handlers/misc.go +++ b/internal/handlers/misc.go @@ -5,12 +5,12 @@ import ( "database/sql" "encoding/xml" "errors" - "github.com/andrew/go-computer/internal/config" - crypt "github.com/andrew/go-computer/internal/crypto" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/netguard" - "github.com/andrew/go-computer/internal/outbound" - "github.com/andrew/go-computer/internal/signals" + "github.com/andrew/superbrain/internal/config" + crypt "github.com/andrew/superbrain/internal/crypto" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/netguard" + "github.com/andrew/superbrain/internal/outbound" + "github.com/andrew/superbrain/internal/signals" "io" "net" "net/http" diff --git a/internal/handlers/misc_test.go b/internal/handlers/misc_test.go index 751dc14..5205bed 100644 --- a/internal/handlers/misc_test.go +++ b/internal/handlers/misc_test.go @@ -65,9 +65,9 @@ func TestParseVCardSubset(t *testing.T) { "UID:uid-1\r\n" + "item1.FN:Preferred Name\r\n" + "item1.X-ABLabel:Main\r\n" + - "EMAIL;TYPE=WORK:work@computer.test\r\n" + - "EMAIL;TYPE=PREF:pref@computer.test\r\n" + - "EMAIL:plain@computer.test\r\n" + + "EMAIL;TYPE=WORK:work@superbrain.test\r\n" + + "EMAIL;TYPE=PREF:pref@superbrain.test\r\n" + + "EMAIL:plain@superbrain.test\r\n" + "TEL;TYPE=HOME,VOICE:+1 555 0100\r\n" + "NOTE:folded line\r\n" + " continuation\r\n" + @@ -87,7 +87,7 @@ func TestParseVCardSubset(t *testing.T) { if len(v["EMAIL"]) != 3 { 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) } // vCard 4.0 numeric PREF ranks below any TYPE=PREF-free occurrence. diff --git a/internal/handlers/page_graph.go b/internal/handlers/page_graph.go index f4750cd..1e063b5 100644 --- a/internal/handlers/page_graph.go +++ b/internal/handlers/page_graph.go @@ -7,7 +7,7 @@ import ( "regexp" "strings" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" ) // Connected pages (Notion-like upgrades phase 3). @@ -15,7 +15,7 @@ import ( // Page hierarchy, internal links and embedded collection views are all // expressed in the page's Markdown, which stays the single source of truth: // -// - [Any label](computer:page/) links to another page. /pages?id= +// - [Any label](superbrain:page/) links to another page. /pages?id= // and page/ are accepted as aliases so hand-written links work too. // - {{collection:}} embeds a live collection view; an optional // {{collection:|view=}} 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, "<"), ">")) raw := "" switch { - case strings.HasPrefix(href, "computer://page/"): - raw = strings.TrimPrefix(href, "computer://page/") - case strings.HasPrefix(href, "computer:page/"): - raw = strings.TrimPrefix(href, "computer:page/") + case strings.HasPrefix(href, "superbrain://page/"): + raw = strings.TrimPrefix(href, "superbrain://page/") + case strings.HasPrefix(href, "superbrain:page/"): + raw = strings.TrimPrefix(href, "superbrain:page/") case strings.HasPrefix(href, "page/"): raw = strings.TrimPrefix(href, "page/") case strings.HasPrefix(href, "/pages/"): @@ -50,11 +50,11 @@ func internalPageID(href string) (string, bool) { if u, err := url.Parse(href); err == nil { 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 { 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 { raw = u.Query().Get("id") } diff --git a/internal/handlers/page_revisions.go b/internal/handlers/page_revisions.go index ac23300..385605f 100644 --- a/internal/handlers/page_revisions.go +++ b/internal/handlers/page_revisions.go @@ -5,7 +5,7 @@ import ( "net/http" "time" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" ) // Page revision history (trust phase). Every committed content version gets diff --git a/internal/handlers/pages.go b/internal/handlers/pages.go index 8872a19..f602aad 100644 --- a/internal/handlers/pages.go +++ b/internal/handlers/pages.go @@ -3,8 +3,8 @@ package handlers import ( "context" "database/sql" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/markdown" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/markdown" "net/http" "strings" "time" diff --git a/internal/handlers/signals.go b/internal/handlers/signals.go index 4a55b15..6525634 100644 --- a/internal/handlers/signals.go +++ b/internal/handlers/signals.go @@ -3,9 +3,9 @@ package handlers import ( "context" "encoding/json" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/outbound" - "github.com/andrew/go-computer/internal/signals" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/outbound" + "github.com/andrew/superbrain/internal/signals" "net/http" "strings" "time" diff --git a/internal/handlers/tags.go b/internal/handlers/tags.go index a4649cb..ea01f9a 100644 --- a/internal/handlers/tags.go +++ b/internal/handlers/tags.go @@ -2,7 +2,7 @@ package handlers import ( "database/sql" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" "net/http" "strings" "time" diff --git a/internal/handlers/trash.go b/internal/handlers/trash.go index 911e3c3..e1c2ae0 100644 --- a/internal/handlers/trash.go +++ b/internal/handlers/trash.go @@ -5,7 +5,7 @@ import ( "encoding/json" "net/http" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" ) // Recoverable deletions (trust phase). diff --git a/internal/handlers/unshare.go b/internal/handlers/unshare.go index 3c37a3e..1855839 100644 --- a/internal/handlers/unshare.go +++ b/internal/handlers/unshare.go @@ -1,7 +1,7 @@ package handlers import ( - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" "net/http" ) diff --git a/internal/http/collections_test.go b/internal/http/collections_test.go index 35d9a01..f842b95 100644 --- a/internal/http/collections_test.go +++ b/internal/http/collections_test.go @@ -17,8 +17,8 @@ func collectionBookmark(t *testing.T, c apiClient, url string) string { func TestCollectionsLifecycle(t *testing.T) { srv := testServer(t) - alice := newAPIUser(t, srv, "coll-life@computer.test") - bob := newAPIUser(t, srv, "coll-other@computer.test") + alice := newAPIUser(t, srv, "coll-life@superbrain.test") + bob := newAPIUser(t, srv, "coll-other@superbrain.test") bm1 := collectionBookmark(t, alice, "https://127.0.0.1/one") @@ -149,7 +149,7 @@ func TestCollectionsLifecycle(t *testing.T) { func TestCollectionViewsFilterSortPaginate(t *testing.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) cid := col["id"].(string) @@ -278,9 +278,9 @@ func TestCollectionViewsFilterSortPaginate(t *testing.T) { func TestCollectionRevocationReachesItems(t *testing.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) - 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 // 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. func TestCollectionIndirectMutationsAdvanceVersions(t *testing.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") bm2 := collectionBookmark(t, alice, "https://127.0.0.1/r2") col := alice.request("POST", "/api/collections", map[string]any{"name": "Revisions"}, 201) diff --git a/internal/http/connected_pages_test.go b/internal/http/connected_pages_test.go index fa1520d..1df69b2 100644 --- a/internal/http/connected_pages_test.go +++ b/internal/http/connected_pages_test.go @@ -17,8 +17,8 @@ func pageVersion(t *testing.T, c apiClient, id string) int { func TestPageHierarchy(t *testing.T) { srv := testServer(t) - alice := newAPIUser(t, srv, "pages-tree@computer.test") - bob := newAPIUser(t, srv, "pages-tree-other@computer.test") + alice := newAPIUser(t, srv, "pages-tree@superbrain.test") + bob := newAPIUser(t, srv, "pages-tree-other@superbrain.test") 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) @@ -71,8 +71,8 @@ func TestPageHierarchy(t *testing.T) { func TestPageBacklinksAndEmbeds(t *testing.T) { srv := testServer(t) - alice := newAPIUser(t, srv, "pages-graph@computer.test") - bob := newAPIUser(t, srv, "pages-graph-other@computer.test") + alice := newAPIUser(t, srv, "pages-graph@superbrain.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) 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) content := "# Connected\n\n" + - "- [Target](computer:page/" + target + ")\n" + + "- [Target](superbrain:page/" + 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:" + foreignCollection + "}}\n" 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. 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) if b := alice.request("GET", "/api/pages/"+target, nil, 200)["backlinks"].([]any); len(b) != 1 { 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). - selfContent := "[Me](computer:page/" + source + ")" + selfContent := "[Me](superbrain:page/" + source + ")" alice.request("PATCH", "/api/pages/"+source, map[string]any{ "content": selfContent, "version": pageVersion(t, alice, source), }, 200) diff --git a/internal/http/coverage_test.go b/internal/http/coverage_test.go index f038d22..7a4cec8 100644 --- a/internal/http/coverage_test.go +++ b/internal/http/coverage_test.go @@ -16,8 +16,8 @@ import ( "testing" "time" - "github.com/andrew/go-computer/internal/auth" - "github.com/andrew/go-computer/internal/signals" + "github.com/andrew/superbrain/internal/auth" + "github.com/andrew/superbrain/internal/signals" "github.com/emersion/go-imap/backend/memory" imapserver "github.com/emersion/go-imap/server" "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) { srv := testServer(t) - alice := newAPIUser(t, srv, "coverage-alice@computer.test") - newAPIUser(t, srv, "coverage-searchable@computer.test") + alice := newAPIUser(t, srv, "coverage-alice@superbrain.test") + newAPIUser(t, srv, "coverage-searchable@superbrain.test") // GET /api/preview — handler plumbing (auth + query + parse). 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, // no email-substring enumeration, 2-rune guard. 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) } - 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) } - // "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. - 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) } 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. func TestSignoutRevokesIssuedTokens(t *testing.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.Header.Set("Content-Type", "application/json") res, e := u.c.Do(req) @@ -192,7 +192,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) { res.Body.Close() var stale string for _, c := range res.Cookies() { - if c.Name == "computer_session" { + if c.Name == "superbrain_session" { stale = c.Value } } @@ -205,7 +205,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) { // Replay the pre-signout token directly (no jar): must be rejected. replay := func(path string) int { 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) if e != nil { t.Fatal(e) @@ -221,7 +221,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) { t.Fatalf("stale cookie accepted on data route: %d", code) } 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) if e != nil { t.Fatal(e) @@ -236,7 +236,7 @@ func TestSignoutRevokesIssuedTokens(t *testing.T) { // One scheduler tick creates signals and marks sources checked (TEST-2). func TestSignalSchedulerRunOnce(t *testing.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") if e != nil { @@ -282,7 +282,7 @@ func TestSignalSchedulerRunOnce(t *testing.T) { // the per-user backoff so the next ticks are skipped. func TestSchedulerBacksOffAfterMailboxFailure(t *testing.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) 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. @@ -317,7 +317,7 @@ func TestSchedulerBacksOffAfterMailboxFailure(t *testing.T) { // bodies (review PERF-01). func TestPageVersionAndListProjection(t *testing.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) id := created["id"].(string) if created["version"].(float64) != 1 { @@ -369,7 +369,7 @@ func TestPageVersionAndListProjection(t *testing.T) { // competing writer's committed revision. func TestConcurrentPageSaveAckReportsOwnWrite(t *testing.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) const writers = 8 @@ -426,7 +426,7 @@ func TestConcurrentPageSaveAckReportsOwnWrite(t *testing.T) { // the revision, and tag replacement rides the same contract. func TestBookmarkVersionContract(t *testing.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) id := created["id"].(string) 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. func TestAssertionRevocationFollowsTokenVersion(t *testing.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) var ver int 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{ UserID: uid, Type: auth.TokenTypeAssertion, Ver: v, RegisteredClaims: jwt.RegisteredClaims{ - Issuer: "computer", + Issuer: "superbrain", IssuedAt: jwt.NewNumericDate(now), ExpiresAt: jwt.NewNumericDate(now.Add(60 * time.Second)), }, diff --git a/internal/http/integration_test.go b/internal/http/integration_test.go index b74d1d6..4e2be45 100644 --- a/internal/http/integration_test.go +++ b/internal/http/integration_test.go @@ -3,9 +3,9 @@ package http import ( "bytes" "encoding/json" - "github.com/andrew/go-computer/internal/auth" - "github.com/andrew/go-computer/internal/config" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/auth" + "github.com/andrew/superbrain/internal/config" + "github.com/andrew/superbrain/internal/db" "io" "net/http" "net/http/cookiejar" @@ -128,16 +128,16 @@ func TestApplicationFlows(t *testing.T) { post := func(email string) map[string]any { return map[string]any{"email": email, "password": "a-long-test-password"} } - alice.request("POST", "/api/signup", post("alice@computer.test"), 201) - bob.request("POST", "/api/signup", post("bob@computer.test"), 201) + alice.request("POST", "/api/signup", post("alice@superbrain.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} // 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 { t.Fatalf("duplicate signup body differs from a fresh creation: %v", dup) } - alice.request("POST", "/api/auth/login", post("alice@computer.test"), 200) - bob.request("POST", "/api/auth/login", post("bob@computer.test"), 200) + alice.request("POST", "/api/auth/login", post("alice@superbrain.test"), 200) + bob.request("POST", "/api/auth/login", post("bob@superbrain.test"), 200) au := meID(alice) bu := meID(bob) if alice.request("GET", "/api/me", nil, 200)["isAdmin"] != true { @@ -189,7 +189,7 @@ func TestApplicationFlows(t *testing.T) { t.Fatal("alert dismissal") } 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("PATCH", "/api/signal-sources/"+source, map[string]any{"enabled": false}, 200) bob.request("DELETE", "/api/signal-sources/"+source, nil, 404) diff --git a/internal/http/integrations_test.go b/internal/http/integrations_test.go index 68a602c..7eae91a 100644 --- a/internal/http/integrations_test.go +++ b/internal/http/integrations_test.go @@ -3,8 +3,8 @@ package http import ( "context" "encoding/json" - crypt "github.com/andrew/go-computer/internal/crypto" - "github.com/andrew/go-computer/internal/signals" + crypt "github.com/andrew/superbrain/internal/crypto" + "github.com/andrew/superbrain/internal/signals" "github.com/emersion/go-imap/backend/memory" imapserver "github.com/emersion/go-imap/server" "io" @@ -22,7 +22,7 @@ func TestExternalIntegrations(t *testing.T) { srv, d := testServerDB(t) jar, _ := cookiejar.New(nil) 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/auth/login", credentials, 200) // CardDAV fixture (reviews CR-07/CR-08): the served multistatus is @@ -48,14 +48,14 @@ func TestExternalIntegrations(t *testing.T) { card1 := `/card.vcfBEGIN:VCARD UID:contact-1 FN:Contact Name -EMAIL:last@computer.test -EMAIL;TYPE=PREF:preferred@computer.test +EMAIL:last@superbrain.test +EMAIL;TYPE=PREF:preferred@superbrain.test TEL:1234 END:VCARDHTTP/1.1 200 OK` card2 := `/card2.vcfBEGIN:VCARD UID:contact-2 FN:Second Contact -EMAIL:second@computer.test +EMAIL:second@superbrain.test END:VCARDHTTP/1.1 200 OK` card2Withheld := `/card2.vcfHTTP/1.1 404 Not Found` wrap := func(responses ...string) string { @@ -85,7 +85,7 @@ END:VCARDHTTP/1.1 200 OKHTTP/1.1 200 OK\n" + return out + "\n\n" } func Send(w http.ResponseWriter, body, name string) { w.Header().Set("Content-Type", "text/markdown; charset=utf-8") diff --git a/internal/markdown/markdown_test.go b/internal/markdown/markdown_test.go index df54dba..49426cc 100644 --- a/internal/markdown/markdown_test.go +++ b/internal/markdown/markdown_test.go @@ -4,7 +4,7 @@ import ( "strings" "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 diff --git a/internal/preview/preview.go b/internal/preview/preview.go index da948d1..ff421a6 100644 --- a/internal/preview/preview.go +++ b/internal/preview/preview.go @@ -3,8 +3,8 @@ package preview import ( "context" "fmt" - "github.com/andrew/go-computer/internal/netguard" - "github.com/andrew/go-computer/internal/outbound" + "github.com/andrew/superbrain/internal/netguard" + "github.com/andrew/superbrain/internal/outbound" "golang.org/x/net/html" "io" "net" @@ -109,7 +109,7 @@ func FetchPreview(ctx context.Context, key, raw string) Preview { if e != nil { 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) if e != nil { return Preview{} diff --git a/internal/scripts/seed.go b/internal/scripts/seed.go index 7a7f1b1..a8240cd 100644 --- a/internal/scripts/seed.go +++ b/internal/scripts/seed.go @@ -3,7 +3,7 @@ package scripts import ( "context" "fmt" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" "golang.org/x/crypto/bcrypt" "os" "strings" diff --git a/internal/signals/checkpoint_test.go b/internal/signals/checkpoint_test.go index 86ae2ea..c0a57e8 100644 --- a/internal/signals/checkpoint_test.go +++ b/internal/signals/checkpoint_test.go @@ -122,9 +122,9 @@ func newTestMailboxValidity(t *testing.T, n int, validity uint32) (Mailbox, *val memMbox := mbox.(*memory.Mailbox) memMbox.Messages = memMbox.Messages[:0] 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" + - "Message-Id: \r\n" + + "Message-Id: \r\n" + "\r\n" + "body" memMbox.Messages = append(memMbox.Messages, &memory.Message{ Uid: uint32(i + 1), diff --git a/internal/signals/scheduler.go b/internal/signals/scheduler.go index ce1fc57..c5bcab3 100644 --- a/internal/signals/scheduler.go +++ b/internal/signals/scheduler.go @@ -2,7 +2,7 @@ package signals import ( "context" - "github.com/andrew/go-computer/internal/db" + "github.com/andrew/superbrain/internal/db" "log" "sync" "time" diff --git a/internal/signals/signals.go b/internal/signals/signals.go index 76c57e0..b58a3e2 100644 --- a/internal/signals/signals.go +++ b/internal/signals/signals.go @@ -6,10 +6,10 @@ import ( "database/sql" "errors" "fmt" - "github.com/andrew/go-computer/internal/config" - crypt "github.com/andrew/go-computer/internal/crypto" - "github.com/andrew/go-computer/internal/db" - "github.com/andrew/go-computer/internal/netguard" + "github.com/andrew/superbrain/internal/config" + crypt "github.com/andrew/superbrain/internal/crypto" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/netguard" "github.com/emersion/go-imap" "github.com/emersion/go-imap/client" "log" diff --git a/main.go b/main.go index 164c7eb..09709af 100644 --- a/main.go +++ b/main.go @@ -66,7 +66,7 @@ func main() { 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() stop() shutdown, cancel := context.WithTimeout(context.Background(), 15*time.Second) diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 66b1a27..876b950 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -1,10 +1,10 @@ #!/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 # 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) # # 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 # directory, provisions packages, backs up the database, builds the Compose # 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 # no longer mix source and release state — synchronization targets are # 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. # Rollback: re-deploy an older revision (git checkout && ./scripts/deploy.sh, # 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. # # 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 -# HTTP-01). Optional overrides: REMOTE_DIR (default /var/www/computer), +# HTTP-01). Optional overrides: REMOTE_DIR (default /var/www/superbrain), # ALLOW_DIRTY=1. set -euo pipefail @@ -37,12 +37,15 @@ usage="usage: HOST=ssh-host DOMAIN=app.domain.tld CERTBOT_EMAIL=ops@domain.tld . HOST="${HOST:?${usage}}" DOMAIN="${DOMAIN:?${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)" 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) ---------------------- REV="$(git -C "$REPO_ROOT" rev-parse --short HEAD 2>/dev/null)" || die "git is required to deploy a known revision" diff --git a/scripts/e2e.mjs b/scripts/e2e.mjs index 5ef088e..9de3b6d 100644 --- a/scripts/e2e.mjs +++ b/scripts/e2e.mjs @@ -38,7 +38,7 @@ const accounts = [] const errors = [] let testFailed = false 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 page = await context.newPage() page.on('pageerror', error => errors.push(error.message)) @@ -67,7 +67,7 @@ try { // database — abort before creating further data. if (!keepData && loopback) { 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() 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)`) @@ -220,7 +220,7 @@ try { // the run only when the tests themselves passed. try { 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) { console.error(`QA account cleanup failed (${accounts.join(',')}); delete manually.`, cleanupError.message) if (!testFailed) process.exitCode = 1 diff --git a/scripts/regressions.mjs b/scripts/regressions.mjs index 9aa4bc2..de04e5b 100644 --- a/scripts/regressions.mjs +++ b/scripts/regressions.mjs @@ -192,7 +192,7 @@ for (let attempt = 1; attempt <= 3; attempt++) { } const attacker = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html') - res.end(`
`) + res.end(`
`) }) await new Promise(resolve => attacker.listen(0, '127.0.0.1', resolve)) async function eventually(check, label) { @@ -215,12 +215,12 @@ try { await page.waitForURL(`${base}/api/auth/login`) assert.equal((await context.request.get(`${base}/api/auth/session`).then(r => r.json()))?.user, undefined) 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) } - 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) - 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) console.log('PASS: forged logins rejected; legitimate login works') @@ -326,7 +326,7 @@ try { // saving over whatever the server holds. 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 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 await page.reload() 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 // tokenVersion bump kills Go cookie sessions and any previously minted // 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`) 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() diff --git a/scripts/server-deploy.sh b/scripts/server-deploy.sh index 1b1b68e..422ab9e 100755 --- a/scripts/server-deploy.sh +++ b/scripts/server-deploy.sh @@ -32,7 +32,10 @@ COMPOSE_VERSION="${COMPOSE_VERSION:-v5.6.0}" BUILDX_VERSION="${BUILDX_VERSION:-v0.38.0}" 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)" @@ -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 # to 30 minutes) instead of mixing source and release state; the lock dies # 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" 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" @@ -75,8 +78,8 @@ if ! docker compose version >/dev/null 2>&1; then # GitHub release assets use uname -m names (x86_64/aarch64), not dpkg arches. arch="$(uname -m)" case "$arch" in - x86_64 | aarch64 | armv7l | s390x | ppc64le) ;; - *) die "no upstream Compose binary for architecture '$arch'" ;; + x86_64 | aarch64 | armv7l | s390x | ppc64le) ;; + *) die "no upstream Compose binary for architecture '$arch'" ;; esac asset="docker-compose-linux-$arch" tmp="$(mktemp -d)" @@ -101,10 +104,10 @@ buildx_ok() { if ! buildx_ok; then log "Installing pinned upstream buildx $BUILDX_VERSION (compose build needs >= 0.17.0; checksum-verified)" case "$(uname -m)" in - x86_64) barch=amd64 ;; - aarch64) barch=arm64 ;; - armv7l) barch=arm ;; - *) die "no upstream buildx binary for architecture '$(uname -m)'" ;; + x86_64) barch=amd64 ;; + aarch64) barch=arm64 ;; + armv7l) barch=arm ;; + *) die "no upstream buildx binary for architecture '$(uname -m)'" ;; esac asset="buildx-$BUILDX_VERSION.linux-$barch" tmp="$(mktemp -d)" @@ -113,7 +116,7 @@ if ! buildx_ok; then # checksums.txt covers every asset; verify exactly the pinned one (exact # field match — a substring grep would also catch .provenance/.sbom assets # and fail the check). - awk -v name="*$asset" '$2 == name' "$tmp/checksums.txt" > "$tmp/$asset.sha256" + awk -v name="*$asset" '$2 == name' "$tmp/checksums.txt" >"$tmp/$asset.sha256" [ -s "$tmp/$asset.sha256" ] || die "no published checksum for $asset" (cd "$tmp" && sha256sum -c "$asset.sha256") || die "buildx $BUILDX_VERSION checksum verification failed; refusing to install" mkdir -p /usr/local/libexec/docker/cli-plugins @@ -155,12 +158,12 @@ if [ ! -f .env ]; then # A lost .env while the data volume remains would generate a fresh # POSTGRES_PASSWORD that the existing database does not have, locking the # app out of its own data. Refuse instead. - if docker volume inspect computer_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" + if docker volume inspect superbrain_pgdata >/dev/null 2>&1; then + 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 log "Creating .env with generated secrets (back it up with the database!)" umask 077 - cat > .env <.env </dev/null)" ] || docker volume inspect "$pg_volume" >/dev/null 2>&1 } @@ -243,13 +249,13 @@ if have_existing_db; then mkdir -p "$BACKUP_DIR" chmod 700 "$BACKUP_DIR" stamp="$(date -u +%Y%m%dT%H%M%SZ)" - dump="$BACKUP_DIR/computer-$stamp.sql.gz" - if docker compose exec -T db pg_dump -U computer -d computer | gzip > "$dump"; then + dump="$BACKUP_DIR/superbrain-$stamp.sql.gz" + if docker compose exec -T db pg_dump -U superbrain -d superbrain | gzip >"$dump"; then chmod 600 "$dump" # Capture the secrets required to decrypt/restore integration data. cp -p .env "$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 log "Backup written: $dump ($(du -h "$dump" | cut -f1)) + env-$stamp.bak; copy both off-host" else @@ -270,8 +276,8 @@ if [ -n "$REVISION" ]; then for svc in app web; do img="$(docker compose images -q "$svc" 2>/dev/null | head -n1)" if [ -n "$img" ]; then - docker tag "$img" "computer-$svc:$REVISION" - log "tagged computer-$svc:$REVISION" + docker tag "$img" "superbrain-$svc:$REVISION" + log "tagged superbrain-$svc:$REVISION" fi done fi @@ -281,23 +287,27 @@ log "Waiting for app health and web /login" deadline=$((SECONDS + 300)) app_id="$(docker compose ps -q app)" 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 done 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 done log "Stack is healthy" # --- 5. nginx reverse proxy ------------------------------------------------------- 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)" # Render the generic template with this deployment's domain and the server's # actual WEB_HOST_PORT binding. RENDERED="/tmp/$DOMAIN.$$.conf" -sed -e "s|__DOMAIN__|$DOMAIN|g" -e "s|__WEB_PORT__|$WEB_PORT|g" "$TEMPLATE" > "$RENDERED" +sed -e "s|__DOMAIN__|$DOMAIN|g" -e "s|__WEB_PORT__|$WEB_PORT|g" "$TEMPLATE" >"$RENDERED" if [ -d /etc/nginx/sites-available ]; then install -m 644 "$RENDERED" "/etc/nginx/sites-available/$DOMAIN" ln -sfn "/etc/nginx/sites-available/$DOMAIN" "/etc/nginx/sites-enabled/$DOMAIN" @@ -319,7 +329,7 @@ if [ ! -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ]; then # Park the TLS config (nginx -t fails on missing cert files) and serve :80. mv "$SITE_CONF" "/etc/nginx/$DOMAIN.conf.pending" rm -f "/etc/nginx/sites-enabled/$DOMAIN" - cat > "/etc/nginx/conf.d/$DOMAIN-bootstrap.conf" <"/etc/nginx/conf.d/$DOMAIN-bootstrap.conf" < /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh + printf '#!/bin/sh\nsystemctl reload nginx\n' >/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh fi fi @@ -351,7 +361,8 @@ log "Verifying https://$DOMAIN/login via nginx" ok="" for _ in $(seq 10); do if curl -fsS -o /dev/null --resolve "$DOMAIN:443:127.0.0.1" "https://$DOMAIN/login"; then - ok=1; break + ok=1 + break fi sleep 3 done @@ -362,7 +373,7 @@ done # names the revision actually serving; a failed deploy leaves the previous # marker (and the previous revision-tagged images) intact for rollback. if [ -n "$REVISION" ]; then - printf '%s\n' "$REVISION" > "$REMOTE_DIR/.deployed-revision" + printf '%s\n' "$REVISION" >"$REMOTE_DIR/.deployed-revision" log "Recorded deployed revision $REVISION" fi # Review H-3: with bootstrap disabled, nobody is administrator until the diff --git a/web/README.md b/web/README.md index 9bb1103..831e669 100644 --- a/web/README.md +++ b/web/README.md @@ -1,4 +1,4 @@ -# computer — web UI +# superbrain — web UI 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) diff --git a/web/app/(app)/bookmarks/client.tsx b/web/app/(app)/bookmarks/client.tsx index 6aa9fa0..e982fdd 100644 --- a/web/app/(app)/bookmarks/client.tsx +++ b/web/app/(app)/bookmarks/client.tsx @@ -66,8 +66,8 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: { useEffect(() => { const timer = setTimeout(load, search ? 250 : 0) const reload = () => { load(); void loadShared() } - window.addEventListener('computer:bookmarks-changed', reload) - return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', reload); abortRef.current?.abort() } + window.addEventListener('superbrain:bookmarks-changed', reload) + return () => { clearTimeout(timer); window.removeEventListener('superbrain:bookmarks-changed', reload); abortRef.current?.abort() } }, [load, loadShared, search]) useEffect(() => { const timer = setTimeout(loadShared, 0); return () => clearTimeout(timer) }, [loadShared]) // Quick Find and the dashboard redirect land here with ?search=; the prop diff --git a/web/app/(app)/calendar/client.tsx b/web/app/(app)/calendar/client.tsx index 3a168d8..c0a21e1 100644 --- a/web/app/(app)/calendar/client.tsx +++ b/web/app/(app)/calendar/client.tsx @@ -64,7 +64,7 @@ export function CalendarClient() { 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 start = startOfMonth(currentMonth) diff --git a/web/app/(app)/contacts/client.tsx b/web/app/(app)/contacts/client.tsx index 8c91888..2eb6c83 100644 --- a/web/app/(app)/contacts/client.tsx +++ b/web/app/(app)/contacts/client.tsx @@ -42,7 +42,7 @@ export function ContactsClient() { 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 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 () => { setSyncing(true) diff --git a/web/app/(app)/kanban/client.tsx b/web/app/(app)/kanban/client.tsx index 678e792..929c1ea 100644 --- a/web/app/(app)/kanban/client.tsx +++ b/web/app/(app)/kanban/client.tsx @@ -69,7 +69,7 @@ export function KanbanClient() { 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]) diff --git a/web/app/(app)/tags/client.tsx b/web/app/(app)/tags/client.tsx index b230178..8f5ccd7 100644 --- a/web/app/(app)/tags/client.tsx +++ b/web/app/(app)/tags/client.tsx @@ -78,7 +78,7 @@ export function TagsClient({ initialTag = null }: { initialTag?: string | null } }, 0) return () => clearTimeout(timer) }, [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 () => { if (!newName) return diff --git a/web/app/(app)/trash/client.tsx b/web/app/(app)/trash/client.tsx index 3127d5c..e8a03a6 100644 --- a/web/app/(app)/trash/client.tsx +++ b/web/app/(app)/trash/client.tsx @@ -62,7 +62,7 @@ export function TrashClient() { const url = URL.createObjectURL(blob) const a = document.createElement('a') 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() URL.revokeObjectURL(url) toast.success('Export downloaded') diff --git a/web/app/api/[...path]/route.ts b/web/app/api/[...path]/route.ts index 13f37b8..8caf19a 100644 --- a/web/app/api/[...path]/route.ts +++ b/web/app/api/[...path]/route.ts @@ -55,7 +55,7 @@ async function proxy(request: NextRequest) { // does). X-Forwarded-For is deliberately ignored: its leftmost entry is // client-controlled. backendFetch adds the timestamped HMAC signature. 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)) { const declared = Number(request.headers.get('content-length') || 0) if (declared > MAX_BODY_BYTES) { diff --git a/web/app/api/session/revoke/route.ts b/web/app/api/session/revoke/route.ts index f65814b..288083e 100644 --- a/web/app/api/session/revoke/route.ts +++ b/web/app/api/session/revoke/route.ts @@ -33,7 +33,7 @@ export async function POST(req: Request) { headers: { 'Content-Type': 'application/json', // 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', signal: controller.signal, diff --git a/web/app/layout.tsx b/web/app/layout.tsx index 08e8f21..7a9f993 100644 --- a/web/app/layout.tsx +++ b/web/app/layout.tsx @@ -10,14 +10,14 @@ const jetbrainsMono = JetBrains_Mono({ subsets: ['latin'], variable: '--font-mon export const metadata = { metadataBase: new URL(process.env.NEXTAUTH_URL ?? 'http://localhost:3000'), - title: 'computer', + title: 'Superbrain', description: 'Your personal binder of life on the web', icons: { icon: '/favicon.svg', shortcut: '/favicon.svg', }, openGraph: { - title: 'computer', + title: 'Superbrain', description: 'Your personal binder of life on the web', images: ['/og-image.png'], }, diff --git a/web/app/login/client.tsx b/web/app/login/client.tsx index cf7ee9d..8d4b4a9 100644 --- a/web/app/login/client.tsx +++ b/web/app/login/client.tsx @@ -49,7 +49,7 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) { -

computer

+

Superbrain

Your personal binder of life on the web

diff --git a/web/app/share/bookmark/[id]/client.tsx b/web/app/share/bookmark/[id]/client.tsx index d75dcad..d3712b2 100644 --- a/web/app/share/bookmark/[id]/client.tsx +++ b/web/app/share/bookmark/[id]/client.tsx @@ -16,7 +16,7 @@ export function PublicBookmarkView({ bookmark }: { bookmark: any }) {
- computer + Superbrain — Shared Bookmark diff --git a/web/app/signup/client.tsx b/web/app/signup/client.tsx index 76f0f24..0ea6575 100644 --- a/web/app/signup/client.tsx +++ b/web/app/signup/client.tsx @@ -57,7 +57,7 @@ export function SignupClient() {

Create Account

-

Join computer to start organizing your links

+

Join Superbrain to start organizing your links

diff --git a/web/auth.ts b/web/auth.ts index 076111f..be0f52a 100644 --- a/web/auth.ts +++ b/web/auth.ts @@ -54,9 +54,9 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ const ip = observedClientIP(request?.headers ?? new Headers()) if (ip && secret) { const { ts, sig } = signClientIP(secret, ip) - headers['x-computer-client-ip'] = ip - headers['x-computer-client-ts'] = ts - headers['x-computer-client-sig'] = sig + headers['x-superbrain-client-ip'] = ip + headers['x-superbrain-client-ts'] = ts + headers['x-superbrain-client-sig'] = sig } const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/login`, { method: 'POST', headers, cache: 'no-store', @@ -124,7 +124,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ headers: { 'Content-Type': 'application/json', // 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', signal: controller.signal, diff --git a/web/components/app-shell.tsx b/web/components/app-shell.tsx index 2e16fbf..07aaa95 100644 --- a/web/components/app-shell.tsx +++ b/web/components/app-shell.tsx @@ -96,7 +96,7 @@ export function AppShell({ children }: { children: React.ReactNode }) { const id = String(a?.id ?? a?.bookmarkId ?? '') if (!id || notifiedAlerts.current.has(id)) continue 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. const refreshPage = useCallback(() => { - window.dispatchEvent(new Event('computer:bookmarks-changed')) + window.dispatchEvent(new Event('superbrain:bookmarks-changed')) router.refresh() }, [router]) diff --git a/web/components/sidebar.tsx b/web/components/sidebar.tsx index e4b7583..96dec87 100644 --- a/web/components/sidebar.tsx +++ b/web/components/sidebar.tsx @@ -32,7 +32,7 @@ const viewItems = [ // Section collapse state persists per browser. useSyncExternalStore keeps it // hydration-safe (server snapshot uses the default; the client snapshot reads // 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 { try { @@ -81,7 +81,7 @@ export function Sidebar({ open, onToggle, onQuickFind, pathname, isAdmin = false
- {open && computer} + {open && superbrain} }> @@ -147,8 +147,8 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna const router = useRouter() const searchParams = useSearchParams() const [pages, setPages] = useState([]) - const [pagesExpanded, setPagesExpanded] = usePersistentState('computer:sidebar:pages', true) - const [viewsExpanded, setViewsExpanded] = usePersistentState('computer:sidebar:views', true) + const [pagesExpanded, setPagesExpanded] = usePersistentState('superbrain:sidebar:pages', true) + const [viewsExpanded, setViewsExpanded] = usePersistentState('superbrain:sidebar:views', true) const [renamingId, setRenamingId] = useState(null) const [renameValue, setRenameValue] = useState('') const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null) diff --git a/web/components/top-bar.tsx b/web/components/top-bar.tsx index 397b342..194ab52 100644 --- a/web/components/top-bar.tsx +++ b/web/components/top-bar.tsx @@ -86,7 +86,7 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi 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 quickFindHint = !mounted ? '⌘K' : isMac ? '⌘K' : 'Ctrl K' @@ -122,7 +122,7 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi - computer + superbrain diff --git a/web/docs/AUTHELIA.md b/web/docs/AUTHELIA.md index c6356d5..a5de64d 100644 --- a/web/docs/AUTHELIA.md +++ b/web/docs/AUTHELIA.md @@ -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 the NextAuth provider; the login button and sign-in callback still block it 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: -- **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`. -### 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 client secret digest and public app hostname; keep your existing provider @@ -76,19 +76,19 @@ identity_providers: oidc: # jwks / hmac_secret must already be configured for OIDC to work claims_policies: - computer: + superbrain: # Include these identity claims in the ID token. id_token: ['email', 'email_verified', 'name', 'preferred_username'] clients: - - client_id: 'computer' - client_name: 'computer' + - client_id: 'superbrain' + client_name: 'superbrain' client_secret: '$pbkdf2-sha512$310000$...' # Digest from 2.1 public: false authorization_policy: 'two_factor' # or 'one_factor' consent_mode: 'explicit' - claims_policy: 'computer' + claims_policy: 'superbrain' redirect_uris: - - 'https:///api/auth/callback/authelia' + - 'https:///api/auth/callback/authelia' scopes: ['openid', 'profile', 'email'] grant_types: ['authorization_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 `/api/auth/callback/authelia`, including scheme, hostname, port if present, and path. For an HTTPS deployment, use -`https:///api/auth/callback/authelia`. +`https:///api/auth/callback/authelia`. 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 @@ -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. 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 | |---|---|---| -| `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 | | `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 | Keep the existing `AUTH_SECRET`: changing it makes stored IMAP passwords diff --git a/web/lib/api.ts b/web/lib/api.ts index 71fdcd4..c853a2b 100644 --- a/web/lib/api.ts +++ b/web/lib/api.ts @@ -33,9 +33,9 @@ export const forwardedClientHeaders = (source: Headers): Record if (!ip) return {} const { ts, sig } = signClientIP(ip) return { - 'x-computer-client-ip': ip, - 'x-computer-client-ts': ts, - 'x-computer-client-sig': sig, + 'x-superbrain-client-ip': ip, + 'x-superbrain-client-ts': ts, + 'x-superbrain-client-sig': sig, } } @@ -54,7 +54,7 @@ export async function backendFetch(path: string, init: RequestInit = {}) { if (session?.user?.id) { 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, { - 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 @@ -62,14 +62,14 @@ export async function backendFetch(path: string, init: RequestInit = {}) { // bucket. The timestamped HMAC keeps the header unforgeable and // short-lived; Go falls back to the direct peer when it is missing or // invalid. - const clientIP = headers.get('x-computer-client-ip') + const clientIP = headers.get('x-superbrain-client-ip') if (clientIP && secret) { const { ts, sig } = signClientIP(clientIP) - headers.set('x-computer-client-ts', ts) - headers.set('x-computer-client-sig', sig) + headers.set('x-superbrain-client-ts', ts) + headers.set('x-superbrain-client-sig', sig) } - const viewAs = (await cookies()).get('computer_view_as')?.value - if (viewAs) headers.set('Cookie', `computer_view_as=${encodeURIComponent(viewAs)}`) + const viewAs = (await cookies()).get('superbrain_view_as')?.value + if (viewAs) headers.set('Cookie', `superbrain_view_as=${encodeURIComponent(viewAs)}`) // Review M-7: bound server-side calls so a hung or blackholed backend // cannot stall a route/server component until the platform timeout. // Callers may provide their own signal to override this default. diff --git a/web/lib/auth-guard.ts b/web/lib/auth-guard.ts index 317a30d..499ba7b 100644 --- a/web/lib/auth-guard.ts +++ b/web/lib/auth-guard.ts @@ -1,6 +1,6 @@ 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 } // Review M-6: Go distinguishes "no session" (401) from backend degradation diff --git a/web/lib/page-autosave.ts b/web/lib/page-autosave.ts index d885839..408f5e2 100644 --- a/web/lib/page-autosave.ts +++ b/web/lib/page-autosave.ts @@ -43,7 +43,7 @@ export class PageAutosave { 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) { try { if (draft === null) sessionStorage.removeItem(this.key(id)) diff --git a/web/lib/pages.ts b/web/lib/pages.ts index 3aac2d8..4cb7347 100644 --- a/web/lib/pages.ts +++ b/web/lib/pages.ts @@ -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)) // Notion-style breadcrumbs: the pages workspace announces which page is open -// so the top bar can show "computer / Pages / " without refetching. -export const ACTIVE_PAGE_CHANGED = 'computer:active-page-changed' +// so the top bar can show "superbrain / Pages / <title>" without refetching. +export const ACTIVE_PAGE_CHANGED = 'superbrain:active-page-changed' export const notifyActivePage = (title: string | null) => 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, // 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 { const value = href.trim().replace(/^<|>$/g, '') let raw = '' - if (value.startsWith('computer://page/')) raw = value.slice('computer://page/'.length) - else 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('superbrain:page/')) raw = value.slice('superbrain: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?') || 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 { const id = new URL(value, 'http://localhost').searchParams.get('id') raw = id ?? '' @@ -39,7 +39,7 @@ export function internalPageId(href: string): string | null { } 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 } diff --git a/web/computer_porting_guide.md b/web/superbrain_porting_guide.md similarity index 94% rename from web/computer_porting_guide.md rename to web/superbrain_porting_guide.md index 1375cbd..cb247be 100644 --- a/web/computer_porting_guide.md +++ b/web/superbrain_porting_guide.md @@ -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*). @@ -91,7 +91,7 @@ Composite PK (`tagId`, `userId`), `createdAt`; both Cascade. Composite PK (`pageId`, `bookmarkId`), `position` int, `createdAt`; both Cascade. ### 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) 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`) | 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?}` | | | `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 | @@ -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. ### 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`) | Function | Output | |---|---| | `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 | | `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. ### 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 | |---|---| -| **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 | -| **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 | +| **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 `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=` | | **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 | | **Tags** `/tags` | Tag list (create, color, share) with filtered 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 | -| **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 | | **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 | diff --git a/web/computer_requirements.md b/web/superbrain_requirements.md similarity index 98% rename from web/computer_requirements.md rename to web/superbrain_requirements.md index f64a5dc..0a693f9 100644 --- a/web/computer_requirements.md +++ b/web/superbrain_requirements.md @@ -1,8 +1,8 @@ -# LinkOS: Requirements +# Superbrain: Requirements ## 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 organizing them (calendar, tags, contacts, kanban). Clicking a URL opens the target application or site.