This commit is contained in:
+4
-4
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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: `<PUBLIC_APP_URL>/api/auth/callback/authelia`, for example
|
||||
`https://computer.company.tld/api/auth/callback/authelia`.
|
||||
`https://superbrain.company.tld/api/auth/callback/authelia`.
|
||||
|
||||
Generate a client secret as described in the connection guide. Put its
|
||||
**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=<plain-client-secret>
|
||||
```
|
||||
|
||||
@@ -269,7 +269,7 @@ Optional operator-provisioned account: set its address in `ADMIN_EMAILS` in
|
||||
the root `.env`, run `docker compose up -d`, then:
|
||||
|
||||
```bash
|
||||
docker compose exec -e SEED_EMAIL=admin@company.tld -e SEED_PASSWORD='<chosen-password>' app /computer --seed
|
||||
docker compose exec -e SEED_EMAIL=admin@company.tld -e SEED_PASSWORD='<chosen-password>' app /superbrain --seed
|
||||
```
|
||||
|
||||
This trusted command creates an admin for an allowlisted address. It never
|
||||
@@ -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.
|
||||
|
||||
|
||||
+12
-8
@@ -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
|
||||
|
||||
|
||||
+56
-23
@@ -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)"
|
||||
|
||||
|
||||
+10
-4
@@ -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'")"
|
||||
|
||||
+2
-2
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
},
|
||||
|
||||
@@ -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 <ok@computer.test>", "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 <ok@superbrain.test>", "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) {
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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.
|
||||
|
||||
+1
-1
@@ -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"
|
||||
)
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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/<id>) links to another page. /pages?id=<id>
|
||||
// - [Any label](superbrain:page/<id>) links to another page. /pages?id=<id>
|
||||
// and page/<id> are accepted as aliases so hand-written links work too.
|
||||
// - {{collection:<id>}} embeds a live collection view; an optional
|
||||
// {{collection:<id>|view=<viewId>}} pins a saved view's filters/sorts.
|
||||
@@ -38,10 +38,10 @@ func internalPageID(href string) (string, bool) {
|
||||
href = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(href, "<"), ">"))
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/andrew/go-computer/internal/db"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)),
|
||||
},
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 := `<d:response><d:href>/card.vcf</d:href><d:propstat><d:prop><card:address-data>BEGIN: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:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`
|
||||
card2 := `<d:response><d:href>/card2.vcf</d:href><d:propstat><d:prop><card:address-data>BEGIN:VCARD
|
||||
UID:contact-2
|
||||
FN:Second Contact
|
||||
EMAIL:second@computer.test
|
||||
EMAIL:second@superbrain.test
|
||||
END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`
|
||||
card2Withheld := `<d:response><d:href>/card2.vcf</d:href><d:propstat><d:prop/><d:status>HTTP/1.1 404 Not Found</d:status></d:propstat></d:response>`
|
||||
wrap := func(responses ...string) string {
|
||||
@@ -85,7 +85,7 @@ END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:pr
|
||||
t.Fatal("CardDAV import count", contacts)
|
||||
}
|
||||
for _, c := range contacts {
|
||||
if c["uid"] == "contact-1" && c["email"] != "preferred@computer.test" {
|
||||
if c["uid"] == "contact-1" && c["email"] != "preferred@superbrain.test" {
|
||||
t.Fatal("repeated EMAIL did not resolve to the PREF value:", c)
|
||||
}
|
||||
}
|
||||
@@ -173,7 +173,7 @@ END:VCARD</card:address-data></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:pr
|
||||
// Nextcloud URL is rejected at the API boundary — no dial, no credentials.
|
||||
func TestCardDAVRequiresTLSOutsideFixtures(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
a := newAPIUser(t, srv, "carddav-tls@computer.test")
|
||||
a := newAPIUser(t, srv, "carddav-tls@superbrain.test")
|
||||
t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "")
|
||||
a.request("POST", "/api/contacts/sync", map[string]any{
|
||||
"nextcloudUrl": "http://nextcloud.example.test", "username": "u", "password": "p",
|
||||
@@ -194,7 +194,7 @@ func TestCardDAVRequiresTLSOutsideFixtures(t *testing.T) {
|
||||
// rewrites the password column at all.
|
||||
func TestImapCredentialWritesNeverRestoreStalePasswords(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
alice := newAPIUser(t, srv, "imap-stale@computer.test")
|
||||
alice := newAPIUser(t, srv, "imap-stale@superbrain.test")
|
||||
t.Setenv("ENCRYPTION_KEY", "dedicated-encryption-key")
|
||||
uid := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["id"].(string)
|
||||
|
||||
@@ -246,6 +246,6 @@ func TestImapCredentialWritesNeverRestoreStalePasswords(t *testing.T) {
|
||||
|
||||
// A masked save with no stored configuration is a 400, never an empty
|
||||
// or resurrected password.
|
||||
bob := newAPIUser(t, srv, "imap-nocfg@computer.test")
|
||||
bob := newAPIUser(t, srv, "imap-nocfg@superbrain.test")
|
||||
bob.request("POST", "/api/settings/imap", map[string]any{"host": "h.example.test", "port": 993, "tls": true, "username": "user", "password": "••••••••", "folder": "INBOX"}, 400)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import "testing"
|
||||
// still honors the bookmark concurrency version (review CR-04).
|
||||
func TestKanbanCardMovePersistsOrdering(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
alice := newAPIUser(t, srv, "kanban-order@computer.test")
|
||||
alice := newAPIUser(t, srv, "kanban-order@superbrain.test")
|
||||
cols := alice.getJSON("/api/kanban/columns", 200)
|
||||
if len(cols) < 2 {
|
||||
t.Fatalf("expected default columns, got %d", len(cols))
|
||||
@@ -113,7 +113,7 @@ func TestKanbanCardMovePersistsOrdering(t *testing.T) {
|
||||
}
|
||||
|
||||
// Foreign columns are never accepted.
|
||||
bob := newAPIUser(t, srv, "kanban-other@computer.test")
|
||||
bob := newAPIUser(t, srv, "kanban-other@superbrain.test")
|
||||
bobCols := bob.getJSON("/api/kanban/columns", 200)
|
||||
foreign := bobCols[0]["id"].(string)
|
||||
firstNow := alice.request("GET", "/api/bookmarks/"+first["id"].(string), nil, 200)
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
// trigram indexes introduced alongside the escaping change.
|
||||
func TestPageSearchEscapesWildcards(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
alice, _ := accountClient(t, srv.URL, "pagesearch@computer.test")
|
||||
other, _ := accountClient(t, srv.URL, "pagesearch-other@computer.test")
|
||||
alice, _ := accountClient(t, srv.URL, "pagesearch@superbrain.test")
|
||||
other, _ := accountClient(t, srv.URL, "pagesearch-other@superbrain.test")
|
||||
|
||||
alice.request("POST", "/api/pages", map[string]any{"title": "100% done", "content": "literal percent"}, 201)
|
||||
alice.request("POST", "/api/pages", map[string]any{"title": "100x done", "content": "not a percent"}, 201)
|
||||
@@ -44,7 +44,7 @@ func TestPageSearchEscapesWildcards(t *testing.T) {
|
||||
// instead of persisting them (the 1 MiB body cap alone is too coarse).
|
||||
func TestTextFieldSizeLimits(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
alice, _ := accountClient(t, srv.URL, "limits@computer.test")
|
||||
alice, _ := accountClient(t, srv.URL, "limits@superbrain.test")
|
||||
|
||||
const (
|
||||
urlLimit = 2048
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
// every file twice in order cannot change the backfill guarantees.
|
||||
func TestUpgradeBackfillsLegacyWatchesWithoutChangingExistingSources(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
_, uid := accountClient(t, srv.URL, "watcher@computer.test")
|
||||
_, uid := accountClient(t, srv.URL, "watcher@superbrain.test")
|
||||
if _, err := d.Exec(`INSERT INTO "Bookmark"(id,url,"ownerId","imapWatchEnabled","imapQuery") VALUES('old','https://127.0.0.1',$1,true,'Invoices'),('paused','https://127.0.0.1',$1,true,'Receipts'),('off','https://127.0.0.1',$1,false,'Other')`, uid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
|
||||
func TestBookmarkPaginationPreservesCollectionAndOwnership(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
owner, uid := accountClient(t, srv.URL, "owner@computer.test")
|
||||
other, oid := accountClient(t, srv.URL, "other@computer.test")
|
||||
owner, uid := accountClient(t, srv.URL, "owner@superbrain.test")
|
||||
other, oid := accountClient(t, srv.URL, "other@superbrain.test")
|
||||
for _, user := range []string{uid, oid} {
|
||||
if _, err := d.Exec(`INSERT INTO "Bookmark"(id,url,title,"ownerId","updatedAt") SELECT $1||'-'||lpad(n::text,4,'0'),'https://127.0.0.1/test','Match '||n,$1,'2026-10-07T12:00:00Z' FROM generate_series(1,205) n`, user); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -42,8 +42,8 @@ func rawCall(t *testing.T, c apiClient, method, path string, body []byte, header
|
||||
// one of them win and the other observe the committed count.
|
||||
func TestConcurrentAdminDemotionsKeepOneAdmin(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
a, _ := accountClient(t, srv.URL, "admin-a@computer.test")
|
||||
b, bID := accountClient(t, srv.URL, "admin-b@computer.test")
|
||||
a, _ := accountClient(t, srv.URL, "admin-a@superbrain.test")
|
||||
b, bID := accountClient(t, srv.URL, "admin-b@superbrain.test")
|
||||
a.request("PATCH", "/api/admin/users", map[string]any{"userId": bID, "role": "ADMIN"}, 200)
|
||||
|
||||
aID := meID(a)
|
||||
@@ -93,7 +93,7 @@ func TestSignupTrimsWhitespaceName(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
body := map[string]any{"email": "trimmed@computer.test", "password": "test-long-password", "name": " "}
|
||||
body := map[string]any{"email": "trimmed@superbrain.test", "password": "test-long-password", "name": " "}
|
||||
c.request("POST", "/api/signup", body, 201)
|
||||
c.request("POST", "/api/auth/login", body, 200)
|
||||
me := c.request("GET", "/api/me", nil, 200)
|
||||
@@ -107,7 +107,7 @@ func TestSignupTrimsWhitespaceName(t *testing.T) {
|
||||
// INSERT per id inside a user-locked transaction.
|
||||
func TestShareRecipientListsAreCapped(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
owner, _ := accountClient(t, srv.URL, "cap-owner@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "cap-owner@superbrain.test")
|
||||
id := owner.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.com/cap"}, 201)["id"].(string)
|
||||
|
||||
tooMany := make([]string, maxTestShareRecipients+1)
|
||||
@@ -132,7 +132,7 @@ const (
|
||||
// Review L-8: an oversized direct API body is 413, not a misleading 400.
|
||||
func TestOversizedDirectBodyReturns413(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
owner, _ := accountClient(t, srv.URL, "oversized@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "oversized@superbrain.test")
|
||||
body := []byte(`{"url":"https://example.com","notes":"` + strings.Repeat("a", 1<<20) + `"}`)
|
||||
status, _ := rawCall(t, owner, "POST", "/api/bookmarks", body, nil)
|
||||
if status != http.StatusRequestEntityTooLarge {
|
||||
@@ -144,7 +144,7 @@ func TestOversizedDirectBodyReturns413(t *testing.T) {
|
||||
// endpoints, while an idempotent same-origin call still succeeds.
|
||||
func TestSignoutRejectsCrossOrigin(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
owner, _ := accountClient(t, srv.URL, "signout@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "signout@superbrain.test")
|
||||
body := []byte(`{}`)
|
||||
status, _ := rawCall(t, owner, "POST", "/api/auth/signout", body, map[string]string{"Origin": "https://attacker.invalid"})
|
||||
if status != http.StatusForbidden {
|
||||
@@ -160,7 +160,7 @@ func TestSignoutRejectsCrossOrigin(t *testing.T) {
|
||||
// groups instead of trusting a client to keep them apart.
|
||||
func TestPageReorderKeepsPinnedGrouping(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
owner, _ := accountClient(t, srv.URL, "reorder@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "reorder@superbrain.test")
|
||||
pinned := owner.request("POST", "/api/pages", map[string]any{"title": "Pinned", "pinned": true}, 201)["id"].(string)
|
||||
second := owner.request("POST", "/api/pages", map[string]any{"title": "Second"}, 201)["id"].(string)
|
||||
third := owner.request("POST", "/api/pages", map[string]any{"title": "Third"}, 201)["id"].(string)
|
||||
@@ -193,7 +193,7 @@ func TestPageReorderKeepsPinnedGrouping(t *testing.T) {
|
||||
// rejected instead of silently discarded.
|
||||
func TestPropertyConfigRejectsMalformedValues(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
owner, _ := accountClient(t, srv.URL, "props@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "props@superbrain.test")
|
||||
cid := owner.request("POST", "/api/collections", map[string]any{"name": "Config"}, 201)["id"].(string)
|
||||
for _, cfg := range []any{"x", []any{}, 5, true} {
|
||||
owner.request("POST", "/api/collections/"+cid+"/properties", map[string]any{"name": "Bad", "type": "TEXT", "config": cfg}, 400)
|
||||
@@ -206,8 +206,8 @@ func TestPropertyConfigRejectsMalformedValues(t *testing.T) {
|
||||
// creating duplicate calendar entries.
|
||||
func TestSharedDateReshareIsIdempotent(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
owner, _ := accountClient(t, srv.URL, "dates-owner@computer.test")
|
||||
_, recipientID := accountClient(t, srv.URL, "dates-recipient@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "dates-owner@superbrain.test")
|
||||
_, recipientID := accountClient(t, srv.URL, "dates-recipient@superbrain.test")
|
||||
|
||||
post := func(note string) []map[string]any {
|
||||
body, _ := json.Marshal(map[string]any{"date": "2026-11-05", "note": note, "recipientIds": []string{recipientID}})
|
||||
@@ -258,7 +258,7 @@ func TestSharedDateReshareIsIdempotent(t *testing.T) {
|
||||
func TestCardDAVRejectsNonStandardPort(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "0")
|
||||
owner, _ := accountClient(t, srv.URL, "carddav@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "carddav@superbrain.test")
|
||||
v := owner.request("POST", "/api/contacts/sync", map[string]any{
|
||||
"nextcloudUrl": "https://198.51.100.10:8443",
|
||||
"username": "user",
|
||||
@@ -274,7 +274,7 @@ func TestCardDAVRejectsNonStandardPort(t *testing.T) {
|
||||
// renumbers positions contiguously, so reload order is deterministic.
|
||||
func TestColumnDeleteNormalizesMovedCardPositions(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
owner, _ := accountClient(t, srv.URL, "columns@computer.test")
|
||||
owner, _ := accountClient(t, srv.URL, "columns@superbrain.test")
|
||||
var columns []map[string]any
|
||||
res, err := owner.c.Get(srv.URL + "/api/kanban/columns")
|
||||
if err != nil {
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"github.com/andrew/go-computer/internal/scripts"
|
||||
"github.com/andrew/superbrain/internal/scripts"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"os"
|
||||
@@ -18,18 +18,18 @@ import (
|
||||
|
||||
func TestConfiguredAdminCannotBeBypassedDuringBootstrap(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
t.Setenv("ADMIN_EMAILS", "operator@computer.test")
|
||||
visitor, _ := accountClient(t, srv.URL, "visitor@computer.test")
|
||||
t.Setenv("ADMIN_EMAILS", "operator@superbrain.test")
|
||||
visitor, _ := accountClient(t, srv.URL, "visitor@superbrain.test")
|
||||
if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
|
||||
t.Fatal("public signup bypassed reserved administrator bootstrap")
|
||||
}
|
||||
visitor.request("GET", "/api/admin/users", nil, 403)
|
||||
t.Setenv("SEED_EMAIL", "operator@computer.test")
|
||||
t.Setenv("SEED_EMAIL", "operator@superbrain.test")
|
||||
t.Setenv("SEED_PASSWORD", "operator-test-password")
|
||||
if err := scripts.Seed(context.Background(), d); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@computer.test", "password": "operator-test-password"}, 200)
|
||||
visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@superbrain.test", "password": "operator-test-password"}, 200)
|
||||
if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != true {
|
||||
t.Fatal("operator-provisioned account is not admin")
|
||||
}
|
||||
@@ -37,7 +37,7 @@ func TestConfiguredAdminCannotBeBypassedDuringBootstrap(t *testing.T) {
|
||||
if err := scripts.Seed(context.Background(), d); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@computer.test", "password": "operator-test-password"}, 200)
|
||||
visitor.request("POST", "/api/auth/login", map[string]any{"email": "operator@superbrain.test", "password": "operator-test-password"}, 200)
|
||||
}
|
||||
|
||||
func accountClient(t *testing.T, base, email string) (apiClient, string) {
|
||||
@@ -54,14 +54,14 @@ func accountClient(t *testing.T, base, email string) (apiClient, string) {
|
||||
|
||||
func TestAdminEnrollmentRequiresTrustedIdentity(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
admin, _ := accountClient(t, srv.URL, "admin@computer.test")
|
||||
user, uid := accountClient(t, srv.URL, "unverified@computer.test")
|
||||
t.Setenv("ADMIN_EMAILS", "reserved@computer.test,unverified@computer.test")
|
||||
admin, _ := accountClient(t, srv.URL, "admin@superbrain.test")
|
||||
user, uid := accountClient(t, srv.URL, "unverified@superbrain.test")
|
||||
t.Setenv("ADMIN_EMAILS", "reserved@superbrain.test,unverified@superbrain.test")
|
||||
// Reserved addresses answer exactly like existing accounts (no 403 oracle).
|
||||
// Review SEC-4/CR-03: operator-reserved addresses return the SAME uniform
|
||||
// 201 {"ok":true} body as every other accepted registration — no userId
|
||||
// field, no 409.
|
||||
reserved := user.request("POST", "/api/signup", map[string]any{"email": "reserved@computer.test", "password": "test-password"}, 201)
|
||||
reserved := user.request("POST", "/api/signup", map[string]any{"email": "reserved@superbrain.test", "password": "test-password"}, 201)
|
||||
if len(reserved) != 1 || reserved["ok"] != true {
|
||||
t.Fatalf("operator-reserved address body is distinguishable: %v", reserved)
|
||||
}
|
||||
@@ -80,9 +80,9 @@ func TestAdminEnrollmentRequiresTrustedIdentity(t *testing.T) {
|
||||
|
||||
func TestPublicBookmarksDoNotExposePrivateMetadata(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
owner, uid := accountClient(t, srv.URL, "owner@computer.test")
|
||||
viewer, vid := accountClient(t, srv.URL, "viewer@computer.test")
|
||||
if _, err := d.Exec(`INSERT INTO "Contact"(id,uid,"displayName",email,phone,"userId") VALUES('contact','vcard','Private','private@computer.test','555-private',$1)`, uid); err != nil {
|
||||
owner, uid := accountClient(t, srv.URL, "owner@superbrain.test")
|
||||
viewer, vid := accountClient(t, srv.URL, "viewer@superbrain.test")
|
||||
if _, err := d.Exec(`INSERT INTO "Contact"(id,uid,"displayName",email,phone,"userId") VALUES('contact','vcard','Private','private@superbrain.test','555-private',$1)`, uid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := owner.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/test", "isPublic": true, "contactId": "contact", "imapQuery": "private mailbox query", "alertAt": "2026-10-07"}, 201)["id"].(string)
|
||||
@@ -112,7 +112,7 @@ func TestPublicBookmarksDoNotExposePrivateMetadata(t *testing.T) {
|
||||
t.Error("shared-reader response lost tags")
|
||||
}
|
||||
full := owner.request("GET", "/api/bookmarks/"+id, nil, 200)
|
||||
if c, _ := full["contact"].(map[string]any); c == nil || c["email"] != "private@computer.test" {
|
||||
if c, _ := full["contact"].(map[string]any); c == nil || c["email"] != "private@superbrain.test" {
|
||||
t.Error("owner projection lost the contact record")
|
||||
}
|
||||
if s, ok := full["sharedWith"].([]any); !ok || len(s) != 1 {
|
||||
@@ -146,7 +146,7 @@ func TestPublicBookmarksDoNotExposePrivateMetadata(t *testing.T) {
|
||||
func TestAdminBootstrapIsOneShot(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
// Fresh installation: the first signup completes bootstrap as admin.
|
||||
admin, adminID := accountClient(t, srv.URL, "first@computer.test")
|
||||
admin, adminID := accountClient(t, srv.URL, "first@superbrain.test")
|
||||
if admin.request("GET", "/api/me", nil, 200)["isAdmin"] != true {
|
||||
t.Fatal("first signup on a fresh installation was not admin")
|
||||
}
|
||||
@@ -155,7 +155,7 @@ func TestAdminBootstrapIsOneShot(t *testing.T) {
|
||||
if _, err := d.Exec(`UPDATE "User" SET role='USER' WHERE id=$1`, adminID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
latecomer, _ := accountClient(t, srv.URL, "late@computer.test")
|
||||
latecomer, _ := accountClient(t, srv.URL, "late@superbrain.test")
|
||||
if latecomer.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
|
||||
t.Fatal("signup re-opened admin bootstrap after the last admin was demoted")
|
||||
}
|
||||
@@ -163,7 +163,7 @@ func TestAdminBootstrapIsOneShot(t *testing.T) {
|
||||
if _, err := d.Exec(`DELETE FROM "User" WHERE id=$1`, adminID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
successor, _ := accountClient(t, srv.URL, "successor@computer.test")
|
||||
successor, _ := accountClient(t, srv.URL, "successor@superbrain.test")
|
||||
if successor.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
|
||||
t.Fatal("signup re-opened admin bootstrap after the last admin was removed")
|
||||
}
|
||||
@@ -175,7 +175,7 @@ func TestAdminBootstrapIsOneShot(t *testing.T) {
|
||||
func TestBootstrapSignupCanBeDisabled(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
t.Setenv("ALLOW_BOOTSTRAP_SIGNUP", "0")
|
||||
visitor, _ := accountClient(t, srv.URL, "unclaimed@computer.test")
|
||||
visitor, _ := accountClient(t, srv.URL, "unclaimed@superbrain.test")
|
||||
if visitor.request("GET", "/api/me", nil, 200)["isAdmin"] != false {
|
||||
t.Fatal("first signup became admin despite ALLOW_BOOTSTRAP_SIGNUP=0")
|
||||
}
|
||||
@@ -191,7 +191,7 @@ func TestDirectLoginRejectsBrowserForgery(t *testing.T) {
|
||||
{"text/plain", "https://attacker.invalid", 415},
|
||||
{"application/json", "https://attacker.invalid", 403},
|
||||
} {
|
||||
req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", bytes.NewBufferString(`{"email":"attacker@computer.test","password":"password"}`))
|
||||
req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", bytes.NewBufferString(`{"email":"attacker@superbrain.test","password":"password"}`))
|
||||
req.Header.Set("Content-Type", tc.contentType)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
@@ -222,9 +222,9 @@ func TestLoginLockoutHonorsSignedForwardedIdentity(t *testing.T) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if ip != "" {
|
||||
hip, hts, sig := sign(ip, ts)
|
||||
req.Header.Set("X-Computer-Client-Ip", hip)
|
||||
req.Header.Set("X-Computer-Client-Ts", hts)
|
||||
req.Header.Set("X-Computer-Client-Sig", sig)
|
||||
req.Header.Set("X-superbrain-Client-Ip", hip)
|
||||
req.Header.Set("X-superbrain-Client-Ts", hts)
|
||||
req.Header.Set("X-superbrain-Client-Sig", sig)
|
||||
}
|
||||
res, e := http.DefaultClient.Do(req)
|
||||
if e != nil {
|
||||
@@ -236,21 +236,21 @@ func TestLoginLockoutHonorsSignedForwardedIdentity(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
// Browser A: five failures lock out its (IP, email) bucket.
|
||||
for i := 0; i < 5; i++ { // failureThreshold
|
||||
if code := post("victim-a@computer.test", "wrong-password", "198.51.100.1", now); code != 401 {
|
||||
if code := post("victim-a@superbrain.test", "wrong-password", "198.51.100.1", now); code != 401 {
|
||||
t.Fatalf("browser A attempt %d: %d", i+1, code)
|
||||
}
|
||||
}
|
||||
if code := post("victim-a@computer.test", "wrong-password", "198.51.100.1", now); code != 429 {
|
||||
if code := post("victim-a@superbrain.test", "wrong-password", "198.51.100.1", now); code != 429 {
|
||||
t.Fatalf("browser A not locked out: %d", code)
|
||||
}
|
||||
// Browser B behind the same proxy peer keeps its own buckets.
|
||||
if code := post("victim-a@computer.test", "wrong-password", "198.51.100.2", now); code != 401 {
|
||||
if code := post("victim-a@superbrain.test", "wrong-password", "198.51.100.2", now); code != 401 {
|
||||
t.Fatalf("browser B locked out by browser A's failures: %d", code)
|
||||
}
|
||||
// A stale signature (outside the ~60s window) falls back to the peer, so
|
||||
// it cannot smuggle a fresh identity: these attempts count against the
|
||||
// peer bucket and stay 401.
|
||||
if code := post("victim-b@computer.test", "wrong-password", "198.51.100.9", now-3600); code != 401 {
|
||||
if code := post("victim-b@superbrain.test", "wrong-password", "198.51.100.9", now-3600); code != 401 {
|
||||
t.Fatalf("stale signature changed behavior: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/go-computer/internal/auth"
|
||||
"github.com/andrew/go-computer/internal/authguard"
|
||||
"github.com/andrew/go-computer/internal/config"
|
||||
"github.com/andrew/go-computer/internal/db"
|
||||
"github.com/andrew/go-computer/internal/handlers"
|
||||
"github.com/andrew/go-computer/internal/oidc"
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/authguard"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/handlers"
|
||||
"github.com/andrew/superbrain/internal/oidc"
|
||||
)
|
||||
|
||||
// NewServer builds the HTTP server with all routes registered.
|
||||
|
||||
@@ -19,8 +19,8 @@ func TestRevocationAndForeignRelations(t *testing.T) {
|
||||
// uniform signup body.
|
||||
return meID(c)
|
||||
}
|
||||
account(a, "owner@computer.test")
|
||||
bid := account(b, "recipient@computer.test")
|
||||
account(a, "owner@superbrain.test")
|
||||
bid := account(b, "recipient@superbrain.test")
|
||||
tag := a.request("POST", "/api/tags", map[string]any{"name": "Shared"}, 201)["id"].(string)
|
||||
id := a.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/test", "tagIds": []string{tag}, "dueDate": "2026-10-07"}, 201)["id"].(string)
|
||||
a.request("POST", "/api/bookmarks/"+id+"/share", map[string]any{"userIds": []string{bid}}, 200)
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
|
||||
func TestPageRevisionHistory(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
alice := newAPIUser(t, srv, "trust-history@computer.test")
|
||||
bob := newAPIUser(t, srv, "trust-history-other@computer.test")
|
||||
alice := newAPIUser(t, srv, "trust-history@superbrain.test")
|
||||
bob := newAPIUser(t, srv, "trust-history-other@superbrain.test")
|
||||
|
||||
page := alice.request("POST", "/api/pages", map[string]any{"title": "History", "content": "version one"}, 201)["id"].(string)
|
||||
revisions := alice.getJSON("/api/pages/"+page+"/revisions", 200)
|
||||
@@ -52,8 +52,8 @@ func TestPageRevisionHistory(t *testing.T) {
|
||||
|
||||
func TestTrashRestoreNeverResurrectsGrants(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
alice := newAPIUser(t, srv, "trust-trash@computer.test")
|
||||
bob := newAPIUser(t, srv, "trust-trash-other@computer.test")
|
||||
alice := newAPIUser(t, srv, "trust-trash@superbrain.test")
|
||||
bob := newAPIUser(t, srv, "trust-trash-other@superbrain.test")
|
||||
bobID := meID(bob)
|
||||
|
||||
tag := alice.request("POST", "/api/tags", map[string]any{"name": "Restored tag"}, 201)["id"].(string)
|
||||
@@ -162,9 +162,9 @@ func TestTrashRestoreNeverResurrectsGrants(t *testing.T) {
|
||||
|
||||
func TestCollectionSharingPermissionBoundary(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
alice := newAPIUser(t, srv, "trust-coll-share@computer.test")
|
||||
bob := newAPIUser(t, srv, "trust-coll-recipient@computer.test")
|
||||
carol := newAPIUser(t, srv, "trust-coll-third@computer.test")
|
||||
alice := newAPIUser(t, srv, "trust-coll-share@superbrain.test")
|
||||
bob := newAPIUser(t, srv, "trust-coll-recipient@superbrain.test")
|
||||
carol := newAPIUser(t, srv, "trust-coll-third@superbrain.test")
|
||||
bobID, carolID := meID(bob), meID(carol)
|
||||
|
||||
bm := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/collection-share", "title": "Shared via project", "notes": "secret owner notes", "isPublic": true}, 201)
|
||||
@@ -249,7 +249,7 @@ func TestCollectionSharingPermissionBoundary(t *testing.T) {
|
||||
|
||||
func TestStructuredExport(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
alice := newAPIUser(t, srv, "trust-export@computer.test")
|
||||
alice := newAPIUser(t, srv, "trust-export@superbrain.test")
|
||||
|
||||
tag := alice.request("POST", "/api/tags", map[string]any{"name": "Export tag"}, 201)["id"].(string)
|
||||
bm := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://127.0.0.1/export", "title": "Exported bookmark", "tagIds": []string{tag}}, 201)["id"].(string)
|
||||
@@ -258,7 +258,7 @@ func TestStructuredExport(t *testing.T) {
|
||||
alice.request("POST", "/api/collections/"+col+"/items", map[string]any{"bookmarkId": bm}, 201)
|
||||
|
||||
v := alice.request("GET", "/api/export", nil, 200)
|
||||
if v["format"] != "computer-export" || v["version"].(float64) != 1 {
|
||||
if v["format"] != "superbrain-export" || v["version"].(float64) != 1 {
|
||||
t.Fatalf("export envelope: %v", v)
|
||||
}
|
||||
if len(v["bookmarks"].([]any)) != 1 || len(v["pages"].([]any)) != 1 || len(v["tags"].([]any)) != 1 || len(v["collections"].([]any)) != 1 {
|
||||
|
||||
@@ -3,7 +3,7 @@ package kanban
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"github.com/andrew/go-computer/internal/db"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
)
|
||||
|
||||
var DefaultColumns = []struct{ Label, Color, Key string }{{"Inbox", "#64748b", "INBOX"}, {"To Do", "#3b82f6", "TODO"}, {"In Progress", "#f59e0b", "IN_PROGRESS"}, {"Done", "#22c55e", "DONE"}}
|
||||
|
||||
@@ -2,7 +2,7 @@ package markdown
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/andrew/go-computer/internal/db"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
@@ -82,7 +82,7 @@ func PageDocument(p db.Object) string {
|
||||
out += "\n"
|
||||
}
|
||||
}
|
||||
return out + "\n<!-- exported from computer " + text(p, "updatedAt") + " -->\n"
|
||||
return out + "\n<!-- exported from superbrain " + text(p, "updatedAt") + " -->\n"
|
||||
}
|
||||
func Send(w http.ResponseWriter, body, name string) {
|
||||
w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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{}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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: <msg-" + fmt.Sprint(i) + "@computer.test>\r\n" +
|
||||
"Message-Id: <msg-" + fmt.Sprint(i) + "@superbrain.test>\r\n" +
|
||||
"\r\n" + "body"
|
||||
memMbox.Messages = append(memMbox.Messages, &memory.Message{
|
||||
Uid: uint32(i + 1),
|
||||
|
||||
@@ -2,7 +2,7 @@ package signals
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/andrew/go-computer/internal/db"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
+10
-7
@@ -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 <rev> && ./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"
|
||||
|
||||
+3
-3
@@ -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
|
||||
|
||||
@@ -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(`<form method="POST" action="${base}/api/auth/login" enctype="text/plain"><input name='{"email":"attacker@computer.test","password":"password","extra":"' value='"}'></form><script>document.forms[0].submit()</script>`)
|
||||
res.end(`<form method="POST" action="${base}/api/auth/login" enctype="text/plain"><input name='{"email":"attacker@superbrain.test","password":"password","extra":"' value='"}'></form><script>document.forms[0].submit()</script>`)
|
||||
})
|
||||
await new Promise(resolve => attacker.listen(0, '127.0.0.1', resolve))
|
||||
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()
|
||||
|
||||
+46
-35
@@ -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 <<EOF
|
||||
cat >.env <<EOF
|
||||
POSTGRES_PASSWORD=$(openssl rand -hex 24)
|
||||
AUTH_SECRET=$(openssl rand -hex 32)
|
||||
NEXTAUTH_URL=https://$DOMAIN
|
||||
@@ -170,9 +173,9 @@ ADMIN_EMAILS=
|
||||
# and forward the browser identity for per-client rate limiting.
|
||||
TRUSTED_PROXY=1
|
||||
# Review H-3: do not let the first visitor after DNS goes live claim the
|
||||
# instance. Provision the operator with ADMIN_EMAILS + `make seed` (below).
|
||||
# instance. Provision the operator with ADMIN_EMAILS + $(make seed) (below).
|
||||
ALLOW_BOOTSTRAP_SIGNUP=0
|
||||
POSTGRES_VOLUME=computer_pgdata
|
||||
POSTGRES_VOLUME=superbrain_pgdata
|
||||
POSTGRES_VOLUME_EXTERNAL=false
|
||||
APP_HOST_PORT=$APP_HOST_PORT
|
||||
WEB_HOST_PORT=$WEB_HOST_PORT
|
||||
@@ -185,16 +188,16 @@ else
|
||||
log "Keeping existing .env"
|
||||
grep -q '^AUTH_SECRET=..*' .env || die ".env exists but AUTH_SECRET is empty"
|
||||
# Pin the host ports even on an .env created before port overrides existed.
|
||||
grep -q '^APP_HOST_PORT=' .env || echo "APP_HOST_PORT=$APP_HOST_PORT" >> .env
|
||||
grep -q '^WEB_HOST_PORT=' .env || echo "WEB_HOST_PORT=$WEB_HOST_PORT" >> .env
|
||||
grep -q '^APP_HOST_PORT=' .env || echo "APP_HOST_PORT=$APP_HOST_PORT" >>.env
|
||||
grep -q '^WEB_HOST_PORT=' .env || echo "WEB_HOST_PORT=$WEB_HOST_PORT" >>.env
|
||||
# Review H-1: every server deployment terminates TLS at the bundled nginx,
|
||||
# which pins X-Real-IP. Upgrade older .env files that predate the switch so
|
||||
# proxied users stop sharing one rate-limit bucket.
|
||||
grep -q '^TRUSTED_PROXY=' .env || echo "TRUSTED_PROXY=1" >> .env
|
||||
grep -q '^TRUSTED_PROXY=' .env || echo "TRUSTED_PROXY=1" >>.env
|
||||
# Review H-3: also stop later deploys from re-opening public bootstrap on a
|
||||
# .env that predates the flag. Operators who deliberately want it can set
|
||||
# ALLOW_BOOTSTRAP_SIGNUP=1 explicitly.
|
||||
grep -q '^ALLOW_BOOTSTRAP_SIGNUP=' .env || echo "ALLOW_BOOTSTRAP_SIGNUP=0" >> .env
|
||||
grep -q '^ALLOW_BOOTSTRAP_SIGNUP=' .env || echo "ALLOW_BOOTSTRAP_SIGNUP=0" >>.env
|
||||
url="$(sed -n 's/^NEXTAUTH_URL=//p' .env | tail -n1)"
|
||||
secure="$(sed -n 's/^COOKIE_SECURE=//p' .env | tail -n1)"
|
||||
[ "$url" = "https://$DOMAIN" ] || log "warning: NEXTAUTH_URL is '$url', expected 'https://$DOMAIN'"
|
||||
@@ -205,8 +208,10 @@ chown "$RUN_USER:" .env
|
||||
chmod 600 .env
|
||||
|
||||
# Effective ports are whatever .env says (they may predate this run).
|
||||
APP_PORT="$(sed -n 's/^APP_HOST_PORT=//p' .env | tail -n1)"; APP_PORT="${APP_PORT:-8080}"
|
||||
WEB_PORT="$(sed -n 's/^WEB_HOST_PORT=//p' .env | tail -n1)"; WEB_PORT="${WEB_PORT:-3000}"
|
||||
APP_PORT="$(sed -n 's/^APP_HOST_PORT=//p' .env | tail -n1)"
|
||||
APP_PORT="${APP_PORT:-8080}"
|
||||
WEB_PORT="$(sed -n 's/^WEB_HOST_PORT=//p' .env | tail -n1)"
|
||||
WEB_PORT="${WEB_PORT:-3000}"
|
||||
|
||||
# Fail early with a clear message if another process squats the ports while
|
||||
# our stack is not the thing holding them.
|
||||
@@ -224,8 +229,9 @@ fi
|
||||
# existing database that is not running gets started for the backup, and a
|
||||
# failed dump aborts the deploy. Dumps are 0600 in a 0700 directory; copy
|
||||
# them off-host — a same-disk backup does not survive disk loss.
|
||||
BACKUP_DIR="${BACKUP_DIR:-/var/backups/computer}"
|
||||
pg_volume="$(sed -n 's/^POSTGRES_VOLUME=//p' .env 2>/dev/null | tail -n1)"; pg_volume="${pg_volume:-computer_pgdata}"
|
||||
BACKUP_DIR="${BACKUP_DIR:-/var/backups/superbrain}"
|
||||
pg_volume="$(sed -n 's/^POSTGRES_VOLUME=//p' .env 2>/dev/null | tail -n1)"
|
||||
pg_volume="${pg_volume:-superbrain_pgdata}"
|
||||
have_existing_db() {
|
||||
[ -n "$(docker compose ps -aq db 2>/dev/null)" ] || docker volume inspect "$pg_volume" >/dev/null 2>&1
|
||||
}
|
||||
@@ -243,13 +249,13 @@ if have_existing_db; then
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
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" <<BOOT
|
||||
cat >"/etc/nginx/conf.d/$DOMAIN-bootstrap.conf" <<BOOT
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
@@ -336,7 +346,7 @@ BOOT
|
||||
# Reload nginx after each successful renewal.
|
||||
if [ ! -e /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh ]; then
|
||||
mkdir -p /etc/letsencrypt/renewal-hooks/deploy
|
||||
printf '#!/bin/sh\nsystemctl reload nginx\n' > /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
|
||||
|
||||
+1
-1
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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])
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
+2
-2
@@ -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'],
|
||||
},
|
||||
|
||||
@@ -49,7 +49,7 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
|
||||
<Link2 className="h-7 w-7" />
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">computer</h1>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Superbrain</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">Your personal binder of life on the web</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ export function PublicBookmarkView({ bookmark }: { bookmark: any }) {
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
|
||||
<Link2 className="h-4 w-4" />
|
||||
</div>
|
||||
<span className="font-display font-bold">computer</span>
|
||||
<span className="font-display font-bold">Superbrain</span>
|
||||
<span className="text-muted-foreground text-sm">— Shared Bookmark</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -57,7 +57,7 @@ export function SignupClient() {
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Create Account</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">Join computer to start organizing your links</p>
|
||||
<p className="text-sm text-muted-foreground mt-2">Join Superbrain to start organizing your links</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSignup} className="space-y-3">
|
||||
|
||||
+4
-4
@@ -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,
|
||||
|
||||
@@ -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])
|
||||
|
||||
|
||||
@@ -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
|
||||
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-primary text-primary-foreground">
|
||||
<Link2 className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
{open && <span className="truncate font-display text-sm font-bold tracking-tight">computer</span>}
|
||||
{open && <span className="truncate font-display text-sm font-bold tracking-tight">superbrain</span>}
|
||||
</Link>
|
||||
</div>
|
||||
<Suspense fallback={<div className="flex-1" />}>
|
||||
@@ -147,8 +147,8 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [pages, setPages] = useState<PageSummary[]>([])
|
||||
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<string | null>(null)
|
||||
const [renameValue, setRenameValue] = useState('')
|
||||
const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null)
|
||||
|
||||
@@ -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
|
||||
<BreadcrumbList className="flex-nowrap">
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild className="font-medium">
|
||||
<Link href="/pages">computer</Link>
|
||||
<Link href="/pages">superbrain</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
|
||||
+13
-13
@@ -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://<COMPUTER_HOST>/api/auth/callback/authelia'
|
||||
- 'https://<superbrain_HOST>/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
|
||||
`<NEXTAUTH_URL>/api/auth/callback/authelia`, including scheme, hostname, port
|
||||
if present, and path. For an HTTPS deployment, use
|
||||
`https://<COMPUTER_HOST>/api/auth/callback/authelia`.
|
||||
`https://<superbrain_HOST>/api/auth/callback/authelia`.
|
||||
|
||||
The callback is handled by NextAuth on the **web app**, not the Go API.
|
||||
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
|
||||
|
||||
+9
-9
@@ -33,9 +33,9 @@ export const forwardedClientHeaders = (source: Headers): Record<string, string>
|
||||
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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
+8
-8
@@ -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 / <title>" 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 }
|
||||
|
||||
|
||||
@@ -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 |
|
||||
@@ -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.
|
||||
Reference in New Issue
Block a user