From d1106dc1b8659a9970440bdb2531479f55ecf48c Mon Sep 17 00:00:00 2001 From: Bendik Aagaard Lynghaug Date: Tue, 24 Nov 2026 11:43:35 +0100 Subject: [PATCH 1/2] move-1.0: the records from 0.19 into a 1.0 store, rehearsed move.sh exports with 0.19.3, rewrites and imports with 1.0, takes the sign-ups again through their form on a site only the host reaches, and holds the store to the export. What that site would have mailed is posted to sink.py and let go: left in the store, it goes out when gdo first dials. README.md has the order of the switch and what it waits for: no gdo or kron release dials a 1.0 site yet. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L5fbDjTQg4CJsNqEo7hhE7 --- move-1.0/README.md | 107 ++++++++++++++++++++++++++++++ move-1.0/compare.py | 88 +++++++++++++++++++++++++ move-1.0/move.sh | 157 ++++++++++++++++++++++++++++++++++++++++++++ move-1.0/sink.py | 27 ++++++++ 4 files changed, 379 insertions(+) create mode 100644 move-1.0/README.md create mode 100644 move-1.0/compare.py create mode 100755 move-1.0/move.sh create mode 100644 move-1.0/sink.py diff --git a/move-1.0/README.md b/move-1.0/README.md new file mode 100644 index 0000000..1967734 --- /dev/null +++ b/move-1.0/README.md @@ -0,0 +1,107 @@ +# The move to portal 1.0 + +Portal 0.19 keeps the vel's records on NATS. Portal 1.0 keeps them in one +file of its own, and starts empty. This folder is what carries the records +across, on kasse, and the order the whole switch goes in. + +| | | +|---|---| +| `move.sh rehearse` | the whole middle of the move beside the running site, into a volume it removes again | +| `move.sh move` | the same for real: stops the 0.19 site first, and fills `tomtervel_portal_data`, the volume the 1.0 stack starts on | +| `compare.py` | holds a 1.0 store to the export: every record, its state, its fields, its files, and the sign-ups in the order they came | +| `sink.py` | takes what the site would have sent while the sign-ups are taken again, and lets it go | + +Everything is run as root on kasse. The export holds names and addresses: +it stays in `/srv/tomtervel/move-1.0` (root only) and nothing here prints +a name, an address or a text, only counts and the names of fields. + +## What `move.sh` does + +1. **Export** with portal 0.19.3 (`portal export`), reading NATS only. +2. **Rewrite** for the 1.0 content with `flytting/fra-0.19.py` from + tomtervel/questions: the committees become `gruppe` on each record. +3. **Import** with portal 1.0 into the volume, after a dry run. +4. **A 1.0 site on the store** that only kasse can reach (127.0.0.1:3997), + with the stack's garage for the files and no sign-in. +5. **The sign-ups** again, through their form + (`flytting/pameldinger.py`), in the order they came. A sign-up cannot + be imported: in 1.0 a seat is taken through the event's own count. +6. **Compare**, with every picture and document fetched as a visitor + would. Anything that differs is counted and the run ends non-zero. +7. **Stop** the site again. + +### No mail leaves + +Taking a sign-up again makes the mail the form makes ("Dere har plass"), +and what the site says in the chat's rooms. With no mail service beside +it, the site does not drop them: they wait in the store, and go out the +moment gdo dials it. A store filled on a preview and then started on in +production would mail every sign-up on its first start. + +So while the site of step 4 runs, its `mail`, `rooms` and `answers` +outboxes are posted to `sink.py` (`DHD_HOOKS`), which acknowledges each +row and delivers nothing. The run says how many mails it took, and fails +if that is not one per sign-up. `payments` is left alone: nothing the +move does asks for money. + +The cost: nobody gets a new link to withdraw by, and the links in the +mail 0.19 sent stop working at the move. Someone who cannot come tells +the board, who takes them off on the event's page. + +## The switch, in order + +Rehearsed on 2026-11-24 against the live site: 91 records and 15 sign-ups +(25 guests) across, all 53 files fetched, 15 mails taken by the sink, +nothing differing. Steps 1 to 3 are done or can be done any time; 4 on +are the switch itself, with the site down from 4 to 6. + +1. **Programs that speak to a 1.0 site.** 1.0 has no NATS; the programs + beside the site dial it over `dhd/1`. As of 2026-11-24 none of what + the stack runs can: + - **gdo** (mail): v0.3.1 is NATS only. The `one-oh` branch dials a + site, built against portal v1.0.0-rc.10. + - **kron** (Vipps): 0.2.0 is NATS only. `one-oh` likewise. + - **cnats** (the chat) is NATS only. Its successor kino 0.1.1 dials a + site, but is published as an Arch package, not an image, and takes + no history over. + + Until gdo has a release, a 1.0 site here sends no mail at all: no + invites, no confirmations. That is what the switch waits for. +2. **The stack for 1.0** (`compose.yml`, `deploy.yml`, a pull request of + its own once step 1 has releases to try it with): a volume for the + store, `PORTAL_STORE`, `DHD_KEYS` naming each program's key, + `DHD_TOKENS` with the hash of `LOAD_TOKEN` named `load`, the programs + in portal's network namespace (they dial loopback), sealed backups + (`PORTAL_BACKUP_TO`), and NATS out. +3. **`LOAD_TOKEN`** as a secret of the tomtervel org: the content repo's + reload posts it to `/dhd/1/load`. +4. **`move.sh rehearse`** once more on the day, then **`move.sh move`**. + The 0.19 site is down from here. +5. **The 1.0 stack up**: `PORTAL_RELEASE=v1.0.2` (the org's variable), + questions#48 merged so `main` is the 1.0 content, then the deploy. + The reload that merge sets off fails while the site is down; the site + reads `main` as it starts. +6. **Look**: `/hva-skjer` says 25 of 100 seats, a document opens, a + sign-in lands on `/styret` with its lists, and a test invite arrives. +7. **Rauthy's groups**: from `komiteer__medlem` and `_leder` to the + group named as its page (questions' README has the names). + +### Going back + +- **Before step 5**: `podman start tomtervel-portal-1`, and remove + `tomtervel_portal_data`. Nothing else was touched. +- **After**: `PORTAL_RELEASE` and the stack back to what they were, and + the content's `main` reverted. NATS still holds everything 0.19 had as + long as `tomtervel_nats_data` is kept, so keep it for some weeks. What + people did on 1.0 in between does not go back with it. + +### What does not come across + +- **Sign-ins.** Everyone signs in again. Their accounts and groups are in + Rauthy and are not touched. +- **Invites nobody has answered yet** stay valid in Rauthy, but the + site's list of them starts empty. +- **Each record's history.** A record arrives with one event saying it + was imported, and its date. +- **The chat's history,** and **payments under way in kron** (none may be + open when the switch is made: a fee paid in between would not be seen). diff --git a/move-1.0/compare.py b/move-1.0/compare.py new file mode 100644 index 0000000..57d1990 --- /dev/null +++ b/move-1.0/compare.py @@ -0,0 +1,88 @@ +# Compares a 1.0 store (read over /dhd/1/read) with the 0.19 export. +# Prints counts and field NAMES only: never a name, an address or a text. +# +# compare.py [--files] [bucket ...] +# +# The token must be named `read` in the site's DHD_TOKENS. With buckets +# named, only those are held to the store; --files also fetches every +# file a record names, as a visitor would. +import json, sys, re, hashlib, urllib.request, urllib.error, yaml, collections +args = [a for a in sys.argv[1:] if not a.startswith('--')] +files = '--files' in sys.argv +site, tokfile, records, places = args[:4] +buckets = args[4:] +tok=open(tokfile).read().strip() +def read(bucket): + r=urllib.request.Request(site+'/dhd/1/read',data=json.dumps({'bucket':bucket}).encode(), + headers={'Authorization':'Bearer '+tok,'Content-Type':'application/json'}) + return json.load(urllib.request.urlopen(r)) +def h(s): return hashlib.sha256(str(s).encode()).hexdigest()[:8] +def norm(s): return re.sub(r'\s+',' ',re.sub(r'<[^>]+>',' ',str(s))).strip() +bad=0 +y=yaml.safe_load(open(records)) +for b,recs in y.items(): + if buckets and b not in buckets: continue + if not isinstance(recs,list): print(f'{b}: not a list in the export, skipped'); continue + st=read(b); c=collections.Counter(); diff=collections.Counter(); kinds=collections.Counter() + ids={str(r['id']) for r in recs} + for r in recs: + s=st.get(str(r['id'])) + if s is None: c['missing in store']+=1; continue + c['found']+=1 + if r.get('state') and r['state']!=s['state']: c['state differs']+=1 + at=r.get('at') + if at is not None: + got=(s.get('at') or {}).get('text','') + if not str(got).startswith(str(at)[:10]): c['at differs']+=1 + f=r.get('fields') or {}; g=s.get('responses') or {} + for k,v in f.items(): + if k not in g: diff[k+': not in store']+=1 + elif str(g[k])==str(v): pass + elif norm(g[k])==norm(v): diff[k+': differs in markup or spacing only']+=1 + else: diff[k+': DIFFERS']+=1 + for k in g: + if k not in f and g[k] not in ('',None): diff[k+': in store only']+=1 + for k in ('vedlegg','bilde'): + v=g.get(k) + if not v: continue + if not files: kinds[k+' named']+=1; continue + try: + with urllib.request.urlopen(f'{site}/attachment/{b}/{r["id"]}/{k}', timeout=30) as a: + kinds[f'{k} fetched' if len(a.read())>0 else f'{k} EMPTY']+=1 + except urllib.error.HTTPError as e: + # a list that needs a sign-in keeps its files to those signed in + kinds[f'{k} needs a sign-in' if e.code in (401,403) else f'{k} FAILED {e.code}']+=1 + extra=[k for k in st if k not in ids] + states=collections.Counter(s['state'] for s in st.values()) + print(f'{b}: export {len(recs)}, store {len(st)}, {dict(c)}, extra in store {len(extra)}') + print(f' states in store {dict(states)}') + if diff: print(f' fields {dict(diff)}') + if kinds: print(f' files {dict(kinds)}') + bad+=c['missing in store']+c['state differs']+c['at differs']+len(extra)+sum(n for k,n in diff.items() if 'DIFFERS' in k or 'not in store' in k) + bad+=sum(n for k,n in kinds.items() if 'FAILED' in k or 'EMPTY' in k) +# the sign-ups +p=yaml.safe_load(open(places)); st=read('pameldinger'); led=read('portal_places') +for b,recs in p.items(): + live=sorted([r for r in recs if r.get('state') in ('tatt','venter')], key=lambda r:str(r['at'])) + print(f'{b}: export {len(recs)} ({dict(collections.Counter(r.get("state") for r in recs))}), store {len(st)} ({dict(collections.Counter(s["state"] for s in st.values()))})') + sig=lambda f:(str(f.get('arrangement')),h(str(f.get('email','')).lower()),h(f.get('navn')),str(f.get('antall') or 1)) + want=collections.Counter(sig(r['fields']) for r in live); got=collections.Counter(sig(s['responses']) for s in st.values()) + print(f' same people, events and numbers: {want==got} (only in export {sum((want-got).values())}, only in store {sum((got-want).values())})') + bad+=sum((want-got).values())+sum((got-want).values()) + seats=lambda rs,key:sum(int(key(r).get('antall') or 1) for r in rs) + print(f' guests: export {seats(live,lambda r:r["fields"])}, store {seats(st.values(),lambda s:s["responses"])}') + # the state each has: a seat stays a seat, a place in line a place in line + wst=collections.Counter((sig(r['fields']),r['state']) for r in live) + gst=collections.Counter((sig(s['responses']),s['state']) for s in st.values()) + print(f' same state each: {wst==gst}'); bad+= (wst!=gst) + # the order: the ledger's against the order they came in 0.19 + for key,l in led.items(): + for line in ('taken','waiting'): + ids=[e['id'] for e in l.get(line,[])] + order=[sig(st[i]['responses']) for i in ids if i in st] + wanted=[sig(r['fields']) for r in live if r['state']==('tatt' if line=='taken' else 'venter') and str(r['fields'].get('arrangement')) in key] + ok = order==wanted + print(f' ledger {h(key)} {line}: {len(ids)} entries, each a record: {len(order)==len(ids)}, in the order they came: {ok}') + bad+= (not ok) or len(order)!=len(ids) + dup=[k for k,n in got.items() if n>1]; print(f' taken twice: {len(dup)}'); bad+=len(dup) +print('OK' if not bad else f'{bad} THINGS TO LOOK AT'); sys.exit(1 if bad else 0) diff --git a/move-1.0/move.sh b/move-1.0/move.sh new file mode 100755 index 0000000..7b72ec8 --- /dev/null +++ b/move-1.0/move.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# The vel's records from portal 0.19 (NATS) into a 1.0 store, on kasse, as +# root. README.md beside this has the whole switch; this is its middle. +# +# move.sh rehearse beside the running site, into a throwaway volume +# move.sh move stops the 0.19 site first, and fills the volume the +# 1.0 stack starts on (tomtervel_portal_data) +# +# Either way it: exports with portal 0.19.3, rewrites for the 1.0 content +# (flytting/fra-0.19.py in the content repo), imports with 1.0, starts a +# 1.0 site on the store that only this host can reach, takes the sign-ups +# again through their form (flytting/pameldinger.py), holds the store to +# the export (compare.py) and stops the site again. +# +# No mail leaves: while that site runs, what it would send (the mail to +# each sign-up, what it says in the chat's rooms) is posted to sink.py, +# which counts it and lets it go. A store started on without that step +# mails every sign-up as soon as gdo dials it. +# +# Nothing is printed that names anyone: counts, and the names of fields. +set -euo pipefail +umask 077 + +mode=${1:-} +case "$mode" in rehearse|move) ;; *) sed -n '2,20p' "$0" >&2; exit 2 ;; esac + +here=$(dirname "$(readlink -f "$0")") +infra=/srv/tomtervel/infrastructure +base=/srv/tomtervel/move-1.0 +release=${PORTAL_RELEASE:-v1.0.2} +image=localhost/tomtervel-portal:$release +branch=${CONTENT_BRANCH_1_0:-innhold-1-0} # the content the 1.0 site will run +repo=https://prosjekt.klingenbergbygg.no/tomtervel/questions +old=tomtervel-portal-1 # the 0.19 site +stage=tomtervel-move-stage +port=3997; sink_port=3996 +export_sha=e417cbfddb7d3710a36c7b3b0b6a86ff1ed6d08dcffc66417760f9b20fbdfe4f # portal-x86_64-linux v0.19.3 + +if [ "$mode" = move ]; then volume=tomtervel_portal_data; else volume=tomtervel-move-rehearsal; fi +work=$base/$mode-$(date +%Y%m%d-%H%M%S) + +podman image exists "$image" || { echo "no image $image: build it first (README.md)" >&2; exit 1; } +if [ "$mode" = move ] && podman volume exists "$volume"; then + echo "the volume $volume is already there: a move was made, or begun. Look before removing it." >&2; exit 1 +fi +podman rm -f "$stage" >/dev/null 2>&1 || true +for p in $port $sink_port; do + if (exec 3<>"/dev/tcp/127.0.0.1/$p") 2>/dev/null; then echo "something already answers on 127.0.0.1:$p" >&2; exit 1; fi +done +[ "$mode" = rehearse ] && podman volume rm -f "$volume" >/dev/null 2>&1 || true + +install -d -m 0700 "$base" "$work" +cd "$work" +sink= +cleanup() { + [ -n "$sink" ] && kill "$sink" 2>/dev/null || true + podman rm -f "$stage" >/dev/null 2>&1 || true +} +trap cleanup EXIT + +step() { printf '\n== %s\n' "$*"; } + +if [ "$mode" = move ]; then + step "stopping the 0.19 site, so nothing is answered after the export" + podman stop -t 30 "$old" >/dev/null + echo "to go back before the 1.0 stack is up: podman start $old" +fi + +step "export from 0.19" +if [ ! -x "$base/portal" ]; then + curl -sfL -o "$base/portal.part" https://project.uhhm.no/uhhm/portal/releases/download/v0.19.3/portal-x86_64-linux + echo "$export_sha $base/portal.part" | sha256sum -c --quiet + chmod 0700 "$base/portal.part"; mv "$base/portal.part" "$base/portal" +fi +# The content the 0.19 site runs, to read its buckets by. +old_branch=$(grep -m1 '^CONTENT_BRANCH=' "$infra/portal.env" | cut -d= -f2-) +old_at=${CONTENT_AT_0_19:-$old_branch} +git clone --quiet "$repo" content-0.19 +git -C content-0.19 checkout --quiet "$old_at" +echo "0.19 content: $(git -C content-0.19 rev-parse --short HEAD)" +url=$(grep -m1 '^NATS_URL=' "$infra/portal.env" | cut -d= -f2-) +url=${url/@nats:4222/@127.0.0.1:4223} +case "$url" in *@127.0.0.1:4223*) ;; *) echo "NATS_URL is not the expected shape" >&2; exit 1 ;; esac +pay=$(grep -m1 '^PAY_URL=' "$infra/portal.env" | cut -d= -f2- || true) +( cd content-0.19 && PAY_URL="$pay" NATS_URL="$url" SITE_NAME=tomtervel "$base/portal" export --path questions --out ../export ) \ + | grep -vE '@|[0-9]{8}' || true +ls export + +step "rewrite for the 1.0 content ($branch)" +git clone --quiet --depth 1 -b "$branch" "$repo" content +echo "1.0 content: $(git -C content rev-parse --short HEAD)" +python3 content/flytting/fra-0.19.py export/records.yaml records-1.0.yaml +chmod -R a+rX content; chmod 711 "$base" "$work"; chmod 644 records-1.0.yaml + +step "import into $volume" +podman volume create "$volume" >/dev/null +run() { podman run --rm --user 0 -v "$volume:/data" -v "$work:/w:ro" -e PORTAL_STORE=/data/site.redb -e PAY_URL="$pay" "$image" "$@"; } +run /app/portal import --path /w/content/questions /w/records-1.0.yaml --dry-run | tail -3 +run /app/portal import --path /w/content/questions /w/records-1.0.yaml | tail -1 +chmod 600 records-1.0.yaml; chmod 700 "$base" + +step "a 1.0 site on the store, for this host only, its outboxes posted to the sink" +token=$(head -c 32 /dev/urandom | base64 | tr -dc A-Za-z0-9); printf %s "$token" > token +hash=$(printf %s "$token" | sha256sum | cut -d' ' -f1) +python3 "$here/sink.py" "$sink_port" > sink.out 2>&1 & sink=$! +# The files are in the stack's garage, which answers on the compose +# network only; the host reaches its address there. Compose doubles each +# "$" in an env file, podman does not. +grep -E '^GARAGE_' "$infra/portal.env" | sed 's/\$\$/$/g' > stage.env +garage=$(podman inspect tomtervel-garage-1 --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}') +podman run -d --name "$stage" --user 0 --network host --add-host "garage:$garage" --env-file stage.env \ + -v "$volume:/data" -v "$work/content:/w:ro" \ + -e CONTENT_DIR=/w -e PORTAL_STORE=/data/site.redb -e SITE_NAME=tomtervel -e PUBLIC_URL="https://$(grep -m1 '^PORTAL_HOST=' "$infra/.env" | cut -d= -f2-)" \ + -e LEPTOS_SITE_ADDR=127.0.0.1:$port -e LEPTOS_SITE_ROOT=site -e LEPTOS_HASH_FILES=true -e PAY_URL="$pay" \ + -e DHD_TOKENS="$hash=submit:pameldinger,read" -e DHD_HOOK_SECRET="$token" \ + -e DHD_HOOKS="mail=http://127.0.0.1:$sink_port/;rooms=http://127.0.0.1:$sink_port/;answers=http://127.0.0.1:$sink_port/" \ + "$image" >/dev/null +code=000 +for _ in $(seq 1 45); do + code=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$port/" || true) + [ "$code" = 200 ] && break; sleep 1 +done +[ "$code" = 200 ] || { echo "the site did not come up ($code)" >&2; podman logs "$stage" 2>&1 | tail -20 >&2; exit 1; } + +step "the sign-ups, through their form, in the order they came" +SUBMIT_TOKEN=$token python3 content/flytting/pameldinger.py export/places.yaml "http://127.0.0.1:$port" --send \ + | sed -E 's/ på [0-9a-f]+,/,/' | tee replay.out | tail -3 +sent=$(grep -c '^sendt' replay.out || true) + +step "the store against the export" +ok=0 +python3 "$here/compare.py" "http://127.0.0.1:$port" token records-1.0.yaml export/places.yaml --files || ok=1 + +step "what the site would have sent, taken by the sink" +# A hook looks every 10 seconds; wait until the mail is all there and nothing more comes. +for _ in $(seq 1 12); do sleep 10; kill -USR1 "$sink"; sleep 1; [ "$(tail -1 sink.out | cut -d' ' -f2)" = "$sent" ] && break; done +sleep 15 +podman stop -t 30 "$stage" >/dev/null +kill "$sink"; wait "$sink" 2>/dev/null || true; sink= +grep -v '^count ' sink.out +mails=$(grep -m1 '^mail: ' sink.out | sed -E 's/^mail: ([0-9]+) rows.*/\1/' || true) +if [ "${mails:-0}" != "$sent" ]; then echo "MAIL: $sent sign-ups sent, ${mails:-0} mails taken by the sink"; ok=1; fi +podman logs "$stage" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | grep -E ' (WARN|ERROR) ' | grep -v '@' > site-warnings.out || true +echo "warnings and errors in the site's log: $(wc -l < site-warnings.out)" +cut -d' ' -f2- site-warnings.out | cut -c1-200 | sort | uniq -c | head -15 +run chown -R portal /data +podman rm -f "$stage" >/dev/null + +step "done" +if [ "$mode" = rehearse ]; then + podman volume rm "$volume" >/dev/null + echo "rehearsal volume removed; the export and the logs are in $work (root only)" +else + echo "the 1.0 store is in $volume; the export is in $work (root only)" + if [ "$ok" = 0 ]; then echo "next: the 1.0 stack on it (README.md, step 5)"; else echo "not as it should be: podman start $old brings the 0.19 site back; remove $volume before trying again"; fi +fi +exit "$ok" diff --git a/move-1.0/sink.py b/move-1.0/sink.py new file mode 100644 index 0000000..8cce0e6 --- /dev/null +++ b/move-1.0/sink.py @@ -0,0 +1,27 @@ +# Takes what a 1.0 site posts from its outboxes (DHD_HOOKS) and lets each row go: +# sink.py on 127.0.0.1; SIGUSR1 prints `count `, SIGTERM the sums. +# Nothing is delivered and nothing kept: it counts rows per outbox, and for +# mail how many addresses and which subjects. Never an address or a body. +import sys, json, hashlib, collections, http.server, signal +port=int(sys.argv[1]); rows=collections.Counter(); who=collections.defaultdict(set); subj=collections.Counter(); keys=collections.defaultdict(set) +class H(http.server.BaseHTTPRequestHandler): + def do_POST(s): + b=s.rfile.read(int(s.headers.get('Content-Length',0))); o=s.headers.get('Dhd-Outbox','?'); rows[o]+=1 + try: + d=json.loads(b); keys[o].update(d.keys()) + if o=='mail': + to=d.get('to'); to=to if isinstance(to,list) else [to] + for t in to: who[o].add(hashlib.sha256(str(t).encode()).hexdigest()) + subj[str(d.get('subject'))[:60]]+=1 + except Exception: pass + s.send_response(204); s.end_headers() + def log_message(s,*a): pass +def done(*a): + print(f'mail: {rows["mail"]} rows to {len(who["mail"])} different addresses; subjects {dict(subj)}') + for o,n in rows.items(): + if o!='mail': print(f'{o}: {n} rows; fields {sorted(keys[o])}') + sys.stdout.flush(); sys.exit(0) +def count(*a): print('count',rows['mail']); sys.stdout.flush() +signal.signal(signal.SIGUSR1,count) +signal.signal(signal.SIGTERM,done); signal.signal(signal.SIGINT,done) +http.server.HTTPServer(('127.0.0.1',port),H).serve_forever() From 1f37681696246c7a5967ffdf309e4a3c656730c3 Mon Sep 17 00:00:00 2001 From: Bendik Aagaard Lynghaug Date: Tue, 24 Nov 2026 12:40:41 +0100 Subject: [PATCH 2/2] The stack for portal 1.0: a store of its own, gdo and kron dialling the site Portal 1.0 keeps everything in one file (portal_data) and has no NATS. gdo and kron dial it over dhd/1 from loopback, so the three share one network namespace, held by a container of its own: held by portal, a restart of portal cut the other two off. NATS stays behind a profile nothing turns on, for going back; the chat (cnats) is out. The deploy writes DHD_KEYS and the hash of LOAD_TOKEN, and no NATS or chat settings. gdo is built from uhhm/gdo at GDO_RELEASE, since the gdo that dials a site is not in the registry. move.sh reads the programs' keys and prints what the deploy wants. Run on kasse beside the live stack, on other ports, with made-up records: mail out, a payment settled, content loaded over /dhd/1/load, and both programs back after portal was restarted and made anew. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L5fbDjTQg4CJsNqEo7hhE7 --- .gitea/workflows/deploy.yml | 75 +++++++------ README.md | 151 +++++++++++++++----------- compose.yml | 204 ++++++++++++++++++++---------------- deploy-tomtervel | 2 +- gdo/Dockerfile | 66 ++++++------ move-1.0/README.md | 81 +++++++------- move-1.0/move.sh | 43 +++++++- portal/Dockerfile | 6 +- 8 files changed, 368 insertions(+), 260 deletions(-) diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 1cd6e44..aa7f51b 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -2,7 +2,8 @@ # Actions variable (vars.*: hosts, versions, where the content comes from) # or secret (secrets.*: passwords, tokens, the first person's address) of # this repo, or of the tomtervel org for what other repos share -# (NATS_PASSWORD, which the content repo's reload uses too). The table is +# (LOAD_TOKEN, which the content repo's reload posts to the site, and +# PORTAL_RELEASE, which its lint runs). The table is # in README.md. A new host name or a portal bump is a variable changed and # then Run workflow; a change to the files here deploys on push. # @@ -21,7 +22,6 @@ on: - gdo/** - rauthy-providers.sh - rauthy-theme.sh - - nats/nats.conf - rauthy/config.toml - deploy-tomtervel - .gitea/workflows/deploy.yml @@ -35,11 +35,9 @@ jobs: STAGE: /var/lib/gitea-runner/tomtervel-env # What the stack is. PORTAL_HOST: ${{ vars.PORTAL_HOST }} - CHAT_HOST: ${{ vars.CHAT_HOST }} PAY_HOST: ${{ vars.PAY_HOST }} PORTAL_RELEASE: ${{ vars.PORTAL_RELEASE }} GDO_RELEASE: ${{ vars.GDO_RELEASE }} - CNATS_TAG: ${{ vars.CNATS_TAG }} KRON_RELEASE: ${{ vars.KRON_RELEASE }} COMPOSE_PROFILES: ${{ vars.COMPOSE_PROFILES }} CONTENT_REPO: ${{ vars.CONTENT_REPO }} @@ -48,14 +46,24 @@ jobs: PEOPLE_BACKEND: ${{ vars.PEOPLE_BACKEND }} RESPONSIBLE_GROUP: ${{ vars.RESPONSIBLE_GROUP }} OAUTH2_CLIENT_ID: ${{ vars.OAUTH2_CLIENT_ID }} - CHAT_OAUTH2_CLIENT_ID: ${{ vars.CHAT_OAUTH2_CLIENT_ID }} - NATS_ADOPT_LEGACY: ${{ vars.NATS_ADOPT_LEGACY }} GARAGE_S3_ENDPOINT: ${{ vars.GARAGE_S3_ENDPOINT }} GARAGE_UPLOADS_BUCKET: ${{ vars.GARAGE_UPLOADS_BUCKET }} + # The programs beside the site (README.md, "The site's own + # network"): each one's key and what it may do, and the site's own + # key and where it listens. Public keys, said in the logs; set + # once, from what move-1.0/move.sh prints. + DHD_KEYS: ${{ vars.DHD_KEYS }} + PORTAL_DHD: ${{ vars.PORTAL_DHD }} + # Optional: sealed copies of the site's store, every six hours + # (README.md, "Backups"). PORTAL_BACKUP_TO is an age public key + # whose private half is kept off this host. + PORTAL_BACKUP_TO: ${{ vars.PORTAL_BACKUP_TO }} + GARAGE_BACKUPS_BUCKET: ${{ vars.GARAGE_BACKUPS_BUCKET }} # What it runs with. - NATS_PASSWORD: ${{ secrets.NATS_PASSWORD }} + # The token the content repo's reload posts; the site is given + # its hash alone. + LOAD_TOKEN: ${{ secrets.LOAD_TOKEN }} OAUTH2_CLIENT_SECRET: ${{ secrets.OAUTH2_CLIENT_SECRET }} - CHAT_OAUTH2_CLIENT_SECRET: ${{ secrets.CHAT_OAUTH2_CLIENT_SECRET }} GARAGE_ACCESS_KEY: ${{ secrets.GARAGE_ACCESS_KEY }} GARAGE_SECRET_KEY: ${{ secrets.GARAGE_SECRET_KEY }} SEED_ADMIN_EMAIL: ${{ secrets.SEED_ADMIN_EMAIL }} @@ -65,7 +73,7 @@ jobs: MAPBOX_TOKEN: ${{ secrets.MAPBOX_TOKEN }} MAPBOX_STYLE: ${{ vars.MAPBOX_STYLE }} # Who is who: Rauthy (README.md, "Rauthy"). RAUTHY_HOST and the - # three secrets run it; portal and the chat sign in at OIDC_ISSUER; + # three secrets run it; portal signs in at OIDC_ISSUER; # RAUTHY_API_KEY lets portal make accounts there. RAUTHY_HOST: ${{ vars.RAUTHY_HOST }} RAUTHY_ENC_KEY: ${{ secrets.RAUTHY_ENC_KEY }} @@ -80,10 +88,8 @@ jobs: RAUTHY_API_KEY: ${{ secrets.RAUTHY_API_KEY }} RAUTHY_LANGUAGE: ${{ vars.RAUTHY_LANGUAGE }} # The money service (README.md, "Payments"): Vipps's keys for the - # Medlemskap sales unit, read by kron alone. Unset, kron starts - # without them and asks for them on the treasurer's desk - # ("Tjenester som venter"), sealed to its own identity; set, they - # are kron's from the env. VIPPS_WEBHOOK_SECRET may wait, kron + # Medlemskap sales unit, read by kron alone, from its env: with + # all four set kron asks the site for nothing. VIPPS_WEBHOOK_SECRET may wait, kron # then settles by asking Vipps every minute instead. VIPPS_MSN: ${{ vars.VIPPS_MSN }} VIPPS_CLIENT_ID: ${{ secrets.VIPPS_CLIENT_ID }} @@ -101,11 +107,11 @@ jobs: - name: Write the env files run: | missing= - for v in PORTAL_HOST CHAT_HOST RAUTHY_HOST OIDC_ISSUER PORTAL_RELEASE GDO_RELEASE CNATS_TAG \ + for v in PORTAL_HOST RAUTHY_HOST OIDC_ISSUER PORTAL_RELEASE GDO_RELEASE \ KRON_RELEASE CONTENT_REPO CONTENT_BRANCH SITE_NAME PEOPLE_BACKEND \ - RESPONSIBLE_GROUP OAUTH2_CLIENT_ID CHAT_OAUTH2_CLIENT_ID \ + RESPONSIBLE_GROUP OAUTH2_CLIENT_ID \ GARAGE_S3_ENDPOINT GARAGE_UPLOADS_BUCKET \ - NATS_PASSWORD OAUTH2_CLIENT_SECRET CHAT_OAUTH2_CLIENT_SECRET \ + DHD_KEYS PORTAL_DHD LOAD_TOKEN OAUTH2_CLIENT_SECRET \ RAUTHY_ENC_KEY RAUTHY_SECRET_RAFT RAUTHY_SECRET_API RAUTHY_API_KEY \ GARAGE_ACCESS_KEY GARAGE_SECRET_KEY SEED_ADMIN_EMAIL; do [ -n "${!v}" ] || missing="$missing $v" @@ -125,20 +131,21 @@ jobs: # Interpolated by compose: hosts, versions, profiles. No secret. cat > "$STAGE/.env" < "$STAGE/portal.env" <> "$STAGE/portal.env" + echo "PAY_URL=http://127.0.0.1:3080" >> "$STAGE/portal.env" fi - # NATS itself (nats.conf reads NATS_PASSWORD), gdo and the chat. - cat > "$STAGE/nats.env" < "$STAGE/chat.env" <> "$STAGE/portal.env" + fi + # kron: Vipps's keys for the Medlemskap sales unit (kron refuses + # some set and some not). Written even without the profile, so + # the file compose names is there. { echo "WEBHOOK_SECRET=$VIPPS_WEBHOOK_SECRET" for name in VIPPS_MSN VIPPS_CLIENT_ID VIPPS_CLIENT_SECRET VIPPS_SUBSCRIPTION_KEY; do @@ -208,7 +207,7 @@ jobs: # "$$" is compose's literal "$". Without this, RAUTHY_API_KEY reached # portal as "portal" alone, Rauthy answered 401, and every invite # failed. .env is left alone: it is what compose.yml interpolates. - sed -i 's/\$/$$/g' "$STAGE/portal.env" "$STAGE/nats.env" "$STAGE/chat.env" "$STAGE/rauthy.env" "$STAGE/kron.env" + sed -i 's/\$/$$/g' "$STAGE/portal.env" "$STAGE/rauthy.env" "$STAGE/kron.env" - name: Pull and bring the stack up run: sudo /usr/local/bin/deploy-tomtervel diff --git a/README.md b/README.md index c27028d..a3deef9 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,34 @@ # Tomter Vel — infrastructure -Everything the vel's own site needs on one host, as containers: NATS -with JetStream for the records, Rauthy for who is who, portal, the site -itself, and the chat. The content (pages, forms, desks) lives in +Everything the vel's own site needs on one host, as containers: portal, +the site itself, which keeps its records in one file of its own; Rauthy +for who is who; gdo for its mail and kron for Vipps. The content (pages, +forms, desks) lives in [tomtervel/questions](https://prosjekt.klingenbergbygg.no/tomtervel/questions) and is fetched from there; this repo owns the host. ``` Internet ──► Caddy (Let's Encrypt) - ├── PORTAL_HOST ──► portal:3000 ──► NATS (records) + Rauthy (login) - ├── RAUTHY_HOST ──► rauthy:8080 - └── CHAT_HOST ────► cnats:3000 + ├── PORTAL_HOST ──► portal:3000 ──► its store (portal_data) + Rauthy (login) + ├── RAUTHY_HOST ──► rauthy:8080 ▲ dhd/1, on loopback + └── PAY_HOST ─────► kron:3080 ───────────┤ + gdo ─────────────────┘──► the host's mail server ``` Nothing about the vel's members or records depends on anyone else's -host: the login, the bus and the site are the vel's own. +host: the login and the site are the vel's own. + +The site ran portal 0.19 on NATS until the move to 1.0, which +`move-1.0/` is. The chat (cnats) spoke to portal over NATS and went +with it; the one that dials a 1.0 site (uhhm/kino) has no image yet. ## First start On a fresh Linux host with podman + podman-compose (run rootful, so Caddy can bind 80/443 and Rauthy sees a stable source IP), with a Gitea runner -on it, and the variables and secrets below set (`NATS_PASSWORD` is any +on it, and the variables and secrets below set (`LOAD_TOKEN` is any long random string: `openssl rand -hex 24`; Rauthy's are under -[Rauthy](#rauthy)): +[Rauthy](#rauthy); the keys are under [The site's own network](#the-sites-own-network)): ```sh git clone https://prosjekt.klingenbergbygg.no/tomtervel/infrastructure /srv/tomtervel/infrastructure @@ -40,14 +46,13 @@ it, and `host-caddy/tomtervel.no` is its file for them (`/etc/caddy/conf.d/tomtervel.no`): - portal → `127.0.0.1:3050` +- kron → `127.0.0.1:3080` - rauthy → `127.0.0.1:8090` -- cnats → `127.0.0.1:3070` -- nats → `127.0.0.1:4223` (kasse's shared platform NATS owns 4222) ## Accounts and groups Rauthy holds the accounts: sign-in, passkeys, the account pages and the -account mail, in Norwegian. Portal and the chat sign in there +account mail, in Norwegian. Portal signs in there (`OIDC_ISSUER`), and portal makes the accounts there itself (`RAUTHY_API_KEY`): @@ -72,15 +77,36 @@ rooms alike. Records in `portal_memberships` are left from before ## Content changes -A push to tomtervel/questions is linted on push and tells the portal -to reload over NATS. That reload reaches the host it runs on: today -Klingenberg Bygg's. On this host the runner is a **host service** -(`pacman -S gitea-runner`, registered against prosjekt.klingenbergbygg.no) — -not an in-compose container — so it reaches NATS on the published -`127.0.0.1:4222`. Give the content repo's `lint-and-reload.yml` a reload job -whose `runs-on` matches that runner's host label, running -`nats --server nats://portal:$NATS_PASSWORD@127.0.0.1:4222 pub portal.content.reload ""`. -Until then, `podman compose restart portal` picks up new content. +A push to tomtervel/questions is linted, and its CI then asks the site +to load that commit: `POST https:///dhd/1/load` with the +org secret `LOAD_TOKEN`. The site fetches the commit, checks it whole +and swaps it in; if anything fails, the last good content goes on +serving, and the answer says why. The site is given the token's hash +alone (`DHD_TOKENS`, written by the deploy). It also reads the branch's +head every time it starts. + +## The site's own network + +gdo and kron dial the site over `dhd/1`; the site dials no one. They +know each other by key: + +- **The site's key** is `site.key` beside its store, made the first + time a program is named. gdo and kron are told it, and where the site + listens, as `PORTAL_DHD=@127.0.0.1:4300`. +- **Each program's key** is in its own volume (`gdo_data`, `kron_data`), + made the first time it starts. The site names them, and what each may + do, in `DHD_KEYS==mail,note;=payments`. + +Both are Actions variables (public keys; every start says them in the +log). `move-1.0/move.sh` makes the keys and prints the two values. A +program whose volume is lost gets a new key, which the site does not +know until `DHD_KEYS` names it: read it from the program's log. + +They dial from loopback to loopback, so portal, gdo and kron share one +network namespace, which the `net` container holds (`compose.yml` says +why it is not portal's own). Tried on kasse, 2026-11-24: after a restart +of portal, and after it was made anew, gdo and kron dialled again within +half a minute and the mail and the payment that had waited went through. ## Upgrading portal @@ -93,26 +119,26 @@ two cannot drift apart. Every value the stack runs with is an Actions variable or secret in Gitea, never a file in the repo (it is public) and never edited on the host. The deploy workflow writes them into the env files on kasse -(`.env`, `portal.env`, `nats.env`, `chat.env`) on every run, so a host +(`.env`, `portal.env`, `kron.env`, `rauthy.env`) on every run, so a host name or a version is changed in Gitea, and then **Actions -> deploy -> Run workflow**. Set them with `gt` (`gt variable set NAME --body ...`, `gt secret set NAME`, `-o tomtervel` for the org's). | name | kind | where | what | |---|---|---|---| -| `PORTAL_HOST`, `RAUTHY_HOST`, `CHAT_HOST` | variable | repo | the site, the login, the chat; each needs DNS (`dns/`) and a kasse Caddy block | +| `PORTAL_HOST`, `RAUTHY_HOST` | variable | repo | the site, the login; each needs DNS (`dns/`) and a kasse Caddy block | | `PORTAL_RELEASE` | variable | **org** | a uhhm/portal tag; the content repo's lint reads the same one | -| `GDO_RELEASE`, `CNATS_TAG`, `KRON_RELEASE` | variable | repo | the mailer, the chat, the money service | -| `COMPOSE_PROFILES` | variable | repo | `chat` | +| `GDO_RELEASE`, `KRON_RELEASE` | variable | repo | the mailer, a tag or a commit of uhhm/gdo that the image is built from (`gdo/Dockerfile` says why), and the money service's image tag (`0.3.0` and on): the ones that dial a 1.0 site | +| `COMPOSE_PROFILES` | variable | repo | `pay` | +| `DHD_KEYS`, `PORTAL_DHD` | variable | repo | the programs' keys and what each may do, and the site's key and address ([The site's own network](#the-sites-own-network)) | +| `PORTAL_BACKUP_TO`, `GARAGE_BACKUPS_BUCKET` | variable | repo | optional: an age public key and a bucket, for sealed copies of the store ([Backups](#backups)) | | `CONTENT_REPO`, `CONTENT_BRANCH` | variable | repo | the content this site serves | -| `SITE_NAME` | variable | repo | `tomtervel`; never changed (a new name is a new, empty site) | +| `SITE_NAME` | variable | repo | `tomtervel`; never changed (kron and the mail name the site by it) | | `PEOPLE_BACKEND`, `RESPONSIBLE_GROUP` | variable | repo | `rauthy`, `redaktor` | -| `OAUTH2_CLIENT_ID`, `CHAT_OAUTH2_CLIENT_ID` | variable | repo | the Rauthy clients of the site and the chat: `portal`, `chat` | -| `NATS_ADOPT_LEGACY` | variable | repo | `sole` | +| `OAUTH2_CLIENT_ID` | variable | repo | the site's Rauthy client: `portal` | | `GARAGE_S3_ENDPOINT`, `GARAGE_UPLOADS_BUCKET` | variable | repo | uploads | -| `NATS_PASSWORD` | secret | **org** | the stack's NATS; the content repo's reload uses it too | +| `LOAD_TOKEN` | secret | **org** | what the content repo's reload posts to the site; the site gets its hash | | `OAUTH2_CLIENT_SECRET` | secret | repo | the site's Rauthy client | -| `CHAT_OAUTH2_CLIENT_SECRET` | secret | repo | the chat's Rauthy client | | `GARAGE_ACCESS_KEY`, `GARAGE_SECRET_KEY` | secret | repo | uploads | | `SEED_ADMIN_EMAIL`, `SEED_ADMIN_NAME` | secret | repo | the first person in; an address, so not a variable | | `CLOUDFLARE_API_TOKEN` | secret | repo | DNS edit for tomtervel.no only (`dns/`) | @@ -120,13 +146,13 @@ Run workflow**. Set them with `gt` (`gt variable set NAME --body ...`, | `MAPBOX_STYLE` | variable | repo | optional: `/