P0 Live-Breakage & Security Fixes Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Fix the four Priority-0 findings from doc/05-process/critiques/2026-07-06-full-codebase-critique.md (items 1, 2, 2a, 3): the crashing masthead, the destructive sync prune, the unauthenticated account-seizure in /register, and the identity key scheme that leaks its own secret.
Architecture: Four independent, individually-committable fixes. Two are one-line-ish code changes guarded by a regression test (celestial masthead, sync prune). Two form the “identity” pair: the server (api/) makes the signing key mandatory-at-creation and immutable, and the client (assets/js/identity.js) is rewritten so the member identifier is derived from the Ed25519 public key rather than from secret bytes. Per the agreed migration decision, existing members are not migrated — the new client scheme produces new identifiers, old members re-register fresh with a zero balance (“fresh start, reset balances”).
Tech Stack: Django 5 management commands + pytest-django (src/tests/); FastAPI + SQLModel + PyNaCl + standalone pytest (api/tests/); vanilla-JS IIFE with @noble/ed25519 + @noble/hashes (assets/js/); Playwright browser tests (marked browser, autostart the dev server via the dev_server_url fixture); TAP output through bin/a-test.
Global Constraints
- Environment: every command assumes
source bin/a-activatehas been run (setsALMANACK_ROOT, activates.venv, putsbin/onPATH). Run from$ALMANACK_ROOT. - Python: >= 3.11 (project uses hatchling; do not “fix” this to uv_build).
- License: AGPL-3.0-or-later; no license headers needed in existing files.
- Shell aliases:
rm/mv/cpare interactive; escape as\rmetc. if a script needs them non-interactively (not needed in this plan). - TDD: red first. Every code change lands with a test that failed before it and passes after.
- Commits: one concern per commit. First line = brief what; body = why. Never bundle unrelated changes.
- Fresh-start migration is a deliberate product decision: do NOT add a re-key/migration endpoint. Existing members losing their balance is expected and accepted.
- Do not touch
web/(generated) or edit files underdocs/(the stray tree slated for removal in item 31).
File Structure
assets/js/celestial.js— masthead sphere (Task 1). Modify only the twodateAnimreads.src/tests/test_celestial_masthead.py— new browser regression test (Task 1).src/almnck/units/management/commands/sync_with_repo.py— sync command (Task 2). Add--force-prune, guard the empty-scan prune.src/tests/test_sync_prune_guard.py— new django_db regression test (Task 2).api/main.py—/registerendpoint andRegisterRequestmodel (Task 3).api/tests/test_register.py— extend with contract + seizure tests; update two existing tests (Task 3).assets/js/identity.js— client identity/crypto rewrite (Task 4).src/tests/test_identity_keyscheme.py— new browser regression test for the key-derivation invariant (Task 4).
Task 1: Celestial masthead — remove leftover dateAnim reads (critique item 1)
Commit b936c5b5 deleted the date-sweep animation and its dateAnim variable but left two reads. celestial.js is a "use strict" IIFE, so each read throws ReferenceError; doRender() hits the first on initial paint (called from init()), so the sphere never renders and later init steps never run.
Files:
- Modify: assets/js/celestial.js (the if (!dateAnim) block near line 1120; the minuteUpdate guard near line 1643)
- Test: src/tests/test_celestial_masthead.py (create)
Interfaces:
- Consumes: the existing window.__sunPosition hook (set by doRender once the sun is projected) and console messages, both already used by test_celestial_interaction.py.
- Produces: nothing other tasks depend on.
- [ ] Step 1: Write the failing test
Create src/tests/test_celestial_masthead.py:
"""Regression test for critique item 1: the masthead sphere must render
without throwing a ReferenceError (the leftover `dateAnim` reads crashed
doRender under strict mode).
"""
import pytest
pytestmark = [pytest.mark.browser, pytest.mark.regression]
FRONTPAGE_URL = "/?fp=2026-02-13"
@pytest.fixture(scope="session")
def desktop_browser(playwright_instance):
browser = playwright_instance.chromium.launch()
yield browser
browser.close()
@pytest.fixture
def desktop_context(desktop_browser, dev_server_url):
context = desktop_browser.new_context(
viewport={"width": 1280, "height": 900},
base_url=dev_server_url,
)
yield context
context.close()
@pytest.fixture
def page(desktop_context):
page = desktop_context.new_page()
yield page
page.close()
def test_masthead_renders_without_reference_error(page):
errors = []
page.on("pageerror", lambda exc: errors.append(str(exc)))
page.goto(FRONTPAGE_URL)
# doRender exposes the projected sun position only if it ran to completion.
page.wait_for_function(
"() => window.__sunPosition && window.__sunPosition.x > 0",
timeout=10000,
)
assert not any("dateAnim" in e for e in errors), (
f"celestial.js threw a ReferenceError: {errors}"
)
assert not any("ReferenceError" in e for e in errors), errors
- [ ] Step 2: Run test to verify it fails
Run: python -m pytest src/tests/test_celestial_masthead.py -v
Expected: FAIL — either the pageerror list contains a dateAnim ReferenceError, or wait_for_function times out because __sunPosition never gets set (the crash aborts doRender).
- [ ] Step 3: Make the theme update unconditional
In assets/js/celestial.js, replace this block (near line 1120):
// Skip during date animation to avoid strobing.
if (!dateAnim) {
updateTheme(realSunAltNow());
}
with:
updateTheme(realSunAltNow());
- [ ] Step 4: Remove
dateAnimfrom the minute-tick guard
In assets/js/celestial.js, replace this line (near line 1643):
if (state.dragging || timeAnimating || timeReturning || dateAnim) return;
with:
if (state.dragging || timeAnimating || timeReturning) return;
- [ ] Step 5: Confirm no other
dateAnimreads remain
Run: grep -n dateAnim assets/js/celestial.js
Expected: no output (exit status 1). If anything prints, remove those reads too — the variable is gone for good.
- [ ] Step 6: Run test to verify it passes
Run: python -m pytest src/tests/test_celestial_masthead.py -v
Expected: PASS.
- [ ] Step 7: Commit
git add assets/js/celestial.js src/tests/test_celestial_masthead.py
git commit -m "Fix masthead crash from leftover dateAnim references
Commit b936c5b5 removed the date-sweep animation and its dateAnim
variable but left two reads. Under the file's strict-mode IIFE these
threw a ReferenceError in doRender on first paint, so the sphere never
rendered. Make the theme update unconditional and drop dateAnim from the
minute-tick guard. Regression test asserts the sphere renders with no
pageerror."
Task 2: Sync — refuse to prune the whole DB on an empty scan (critique item 3)
sync_with_repo deletes every Unit whose source_path was not seen in the scan. When a full scan finds zero units (empty-but-present editorial/, bad mount, misdirected ALMANACK_ROOT, partial clone) it deletes them all — and make prod-deploy chains sync → build → rsync --delete, so an empty DB becomes an empty live site.
Files:
- Modify: src/almnck/units/management/commands/sync_with_repo.py (add_arguments near line 19; the prune block near line 47)
- Test: src/tests/test_sync_prune_guard.py (create)
Interfaces:
- Consumes: settings.EDITORIAL_DIR (overridable via monkeypatch, as in test_sync_margin_boxes.py); call_command("sync_with_repo", ...).
- Produces: a new --force-prune flag on the command.
- [ ] Step 1: Write the failing test
Create src/tests/test_sync_prune_guard.py:
"""Regression test for critique item 3: a full scan that finds zero units
must not delete existing units unless --force-prune is given.
"""
import pytest
from django.conf import settings
from django.core.management import call_command
from almnck.units.models import Unit
@pytest.mark.django_db
class TestSyncPruneGuard:
def _make_unit(self):
return Unit.objects.create(
source_path="articles/ghost",
unit_type=Unit.UnitType.ARTICLE,
status=Unit.Status.PUBLISHED,
title="Ghost",
)
def test_empty_scan_does_not_delete_units(self, tmp_path, monkeypatch):
"""An empty editorial dir must leave existing units untouched."""
self._make_unit()
# tmp_path exists but contains no unit directories.
monkeypatch.setattr(settings, "EDITORIAL_DIR", str(tmp_path))
call_command("sync_with_repo")
assert Unit.objects.filter(source_path="articles/ghost").exists(), (
"sync deleted all units when the scan found none"
)
def test_force_prune_still_deletes(self, tmp_path, monkeypatch):
"""--force-prune preserves the old delete-everything behaviour."""
self._make_unit()
monkeypatch.setattr(settings, "EDITORIAL_DIR", str(tmp_path))
call_command("sync_with_repo", force_prune=True)
assert not Unit.objects.filter(source_path="articles/ghost").exists()
(source_path, unit_type, title, and status are the fields this test needs; frontmatter defaults to {} and the rest are blank/auto, verified against src/almnck/units/models.py.)
- [ ] Step 2: Run test to verify it fails
Run: python -m pytest src/tests/test_sync_prune_guard.py -v
Expected: test_empty_scan_does_not_delete_units FAILS (unit was deleted); test_force_prune_still_deletes ERRORS with unrecognized arguments/unexpected kwarg because --force-prune does not exist yet.
- [ ] Step 3: Add the
--force-pruneargument
In src/almnck/units/management/commands/sync_with_repo.py, in add_arguments, after the existing --path argument (line 24), add:
parser.add_argument(
"--force-prune",
action="store_true",
help="Delete DB units even when the scan finds zero units on disk",
)
- [ ] Step 4: Guard the prune block
In the same file, replace this block (near line 47):
# Mark units that no longer exist on disk
if not subpath:
missing = Unit.objects.exclude(source_path__in=units_found)
if missing.exists():
self.stdout.write(f"Removing {missing.count()} units no longer on disk")
missing.delete()
with:
# Mark units that no longer exist on disk. Never prune on an empty
# scan (bad mount, misdirected ALMANACK_ROOT, partial clone) unless
# the caller explicitly opts in — otherwise a stray empty directory
# wipes the whole site on the next deploy.
if not subpath:
if not units_found and not options.get("force_prune"):
self.stderr.write(
self.style.WARNING(
"Scan found zero units; refusing to prune the database. "
"Pass --force-prune to delete all units anyway."
)
)
else:
missing = Unit.objects.exclude(source_path__in=units_found)
if missing.exists():
self.stdout.write(
f"Removing {missing.count()} units no longer on disk"
)
missing.delete()
- [ ] Step 5: Run test to verify it passes
Run: python -m pytest src/tests/test_sync_prune_guard.py -v
Expected: both tests PASS.
- [ ] Step 6: Commit
git add src/almnck/units/management/commands/sync_with_repo.py src/tests/test_sync_prune_guard.py
git commit -m "Guard sync against pruning the DB on an empty scan
A full scan that found zero units deleted every Unit, and prod-deploy
chains sync -> build -> rsync --delete, so a stray empty editorial dir
would wipe the live site. Refuse to prune when the scan is empty unless
--force-prune is passed."
Task 3: API — make the signing key mandatory-at-creation and immutable (critique item 2a)
POST /register writes signing_pubkey onto an existing member that lacks one, with no authentication — so knowing a keyless member’s public pubkey is enough to seize the account. Under the fresh-start decision, every member is created with a signing key, and registration must never mutate an existing row’s key.
Files:
- Modify: api/main.py (RegisterRequest near line 76; register near lines 121-144)
- Test: api/tests/test_register.py (extend; update two existing tests)
Interfaces:
- Consumes: create_signed_member / make_signature from api/tests/helpers.py; the client and session fixtures from api/tests/conftest.py.
- Produces: the register contract Task 4’s client relies on — signing_pubkey is now required (missing → HTTP 422), and an existing member’s key is never rebound.
- [ ] Step 1: Write the failing tests
In api/tests/test_register.py, add these tests (keep the existing imports; add the two new ones shown):
from api.models import Member
from api.tests.helpers import make_signature
from nacl.signing import SigningKey
def test_register_requires_signing_pubkey(client):
"""Registration without a signing key is rejected (fresh-start contract)."""
response = client.post("/register", json={"pubkey": "age1nokey"})
assert response.status_code == 422
def test_register_does_not_rebind_keyless_member(client, session):
"""A legacy member with no signing key cannot be seized via /register."""
# Simulate a pre-signing-key row directly in the DB.
session.add(Member(pubkey="age1legacy", name="Old Timer", signing_pubkey=None))
session.commit()
attacker = SigningKey.generate()
attacker_pub = attacker.verify_key.encode().hex()
resp = client.post(
"/register",
json={"pubkey": "age1legacy", "signing_pubkey": attacker_pub},
)
assert resp.status_code == 200 # returns the profile, does not rebind
# The attacker's key must NOT authenticate as this member. With no key
# bound, /visit rejects it as a member missing its signing key.
ts, sig = make_signature(attacker)
visit = client.post(
"/visit",
json={"pubkey": "age1legacy", "timestamp": ts, "signature": sig},
)
assert visit.status_code in (400, 401)
Then update the two existing tests, which currently register with no signing key (they will now 422). Replace test_register_new_member and test_register_existing_member with:
def test_register_new_member(client: TestClient):
"""POST /register with pubkey + signing key creates member and returns name"""
response = client.post(
"/register",
json={"pubkey": "age1testkey123", "signing_pubkey": "aa" * 32},
)
assert response.status_code == 200
data = response.json()
assert "name" in data
assert data["balance"] == 0
assert data["streak"] == 0
def test_register_existing_member(client: TestClient):
"""POST /register with existing pubkey returns existing profile"""
pubkey = "age1existingkey456"
body = {"pubkey": pubkey, "signing_pubkey": "bb" * 32}
response1 = client.post("/register", json=body)
name1 = response1.json()["name"]
response2 = client.post("/register", json=body)
name2 = response2.json()["name"]
assert name1 == name2, "Should return same name for existing member"
- [ ] Step 2: Run tests to verify they fail
Run: python -m pytest api/tests/test_register.py -v
Expected: test_register_requires_signing_pubkey FAILS (current code returns 200, not 422); test_register_does_not_rebind_keyless_member FAILS (current code rebinds the attacker’s key, so /visit returns 200 instead of 400/401). The two updated tests pass against current code but confirm the new contract.
- [ ] Step 3: Make
signing_pubkeyrequired on the request model
In api/main.py, replace the RegisterRequest model (near line 76):
class RegisterRequest(BaseModel):
pubkey: str
signing_pubkey: Optional[str] = None
with:
class RegisterRequest(BaseModel):
pubkey: str
signing_pubkey: str
- [ ] Step 4: Bind the key only at creation; never mutate an existing row
In api/main.py, replace the register function body (near lines 121-144):
@app.post("/register", response_model=ProfileResponse)
def register(request: RegisterRequest, session: Session = Depends(get_session)):
# Check if member exists
member = session.get(Member, request.pubkey)
if member:
# Update signing_pubkey if provided and not already set
if request.signing_pubkey and not member.signing_pubkey:
member.signing_pubkey = request.signing_pubkey
session.add(member)
session.commit()
session.refresh(member)
return ProfileResponse(name=member.name, balance=member.balance, streak=member.streak)
# Create new member
name = generate_name()
member = Member(
pubkey=request.pubkey,
name=name,
signing_pubkey=request.signing_pubkey
)
session.add(member)
session.commit()
session.refresh(member)
return ProfileResponse(name=member.name, balance=member.balance, streak=member.streak)
with:
@app.post("/register", response_model=ProfileResponse)
def register(request: RegisterRequest, session: Session = Depends(get_session)):
# An existing member's signing key is bound at creation and never changed
# here. Rebinding it would let anyone who knows a member's public pubkey
# seize an account that has no key yet (critique item 2a). Re-keying, if
# ever needed, must go through an authenticated recovery flow, not this
# endpoint.
member = session.get(Member, request.pubkey)
if member:
return ProfileResponse(
name=member.name, balance=member.balance, streak=member.streak
)
name = generate_name()
member = Member(
pubkey=request.pubkey,
name=name,
signing_pubkey=request.signing_pubkey,
)
session.add(member)
session.commit()
session.refresh(member)
return ProfileResponse(
name=member.name, balance=member.balance, streak=member.streak
)
- [ ] Step 5: Run the full register suite to verify it passes
Run: python -m pytest api/tests/test_register.py -v
Expected: all four tests PASS.
- [ ] Step 6: Run the whole API suite to confirm no regressions
Run: python -m pytest api/tests -v
Expected: all pass (the visit/me/checkout/webhook tests use create_signed_member, which already sends a signing_pubkey, so the required-field change does not break them).
- [ ] Step 7: Commit
git add api/main.py api/tests/test_register.py
git commit -m "Bind member signing key only at registration
/register wrote signing_pubkey onto an existing keyless member with no
auth, so knowing a member's public pubkey was enough to seize the
account. Make signing_pubkey required at creation and never rebind an
existing row. Fresh-start migration means legacy keyless members
re-register as new identities rather than being upgraded in place."
Task 4: Client identity — derive the identifier from the public key, not the secret (critique item 2)
generateKeypair() builds both pubkey (first 29 bytes) and secretKey (all 32 bytes) from one random array, and the Ed25519 signing seed is HKDF’d from those same bytes — so a member’s public pubkey, sent on every request, exposes all but 3 bytes of the private key. Rewrite so the member identifier is 'age1' + hex(ed25519_public_key), generated from an independent secret that never leaves the browser. Old-scheme identities in localStorage are discarded (fresh start).
Files:
- Modify: assets/js/identity.js (storage helpers ~21-27; crypto ~47-62; init() ~156-174)
- Test: src/tests/test_identity_keyscheme.py (create)
Interfaces:
- Consumes: the Task 3 register contract (signing_pubkey required — the client already sends it); the vendor globals window.nobleHkdf, window.nobleSha512, window.nobleEd25519 wired in base.html; bytesToHex/getSigningPublicKey/deriveSigningKeypair already in the file.
- Produces: window.AlmanackIdentity with an unchanged public surface (init, register, visit, getMe, getPublicKey, getSigningPublicKey, sign, isInitialized) — topup.js and the identity margin box keep working unchanged.
- [ ] Step 1: Write the failing test
Create src/tests/test_identity_keyscheme.py:
"""Regression test for critique item 2: the member identifier must be derived
from the Ed25519 public key, never from secret bytes. The old scheme embedded
29 of the 32 secret bytes in the public 'pubkey'.
"""
import pytest
pytestmark = [pytest.mark.browser, pytest.mark.regression]
@pytest.fixture(scope="session")
def desktop_browser(playwright_instance):
browser = playwright_instance.chromium.launch()
yield browser
browser.close()
@pytest.fixture
def desktop_context(desktop_browser, dev_server_url):
context = desktop_browser.new_context(
viewport={"width": 1280, "height": 900},
base_url=dev_server_url,
)
yield context
context.close()
@pytest.fixture
def page(desktop_context):
page = desktop_context.new_page()
yield page
page.close()
def test_pubkey_does_not_leak_secret(page):
# Stub the network so init() can register without a live API.
page.route(
"**/register",
lambda route: route.fulfill(
status=200,
content_type="application/json",
body='{"name": "Test Traveler", "balance": 0, "streak": 0}',
),
)
page.goto("/")
page.wait_for_function("() => !!window.AlmanackIdentity", timeout=10000)
result = page.evaluate(
"""async () => {
localStorage.clear();
await window.AlmanackIdentity.init();
const pub = window.AlmanackIdentity.getPublicKey();
const sigpub = await window.AlmanackIdentity.getSigningPublicKey();
const secretRaw = JSON.parse(
localStorage.getItem('almanack:identity')
).sk;
const secretHex = secretRaw
.replace('AGE-SECRET-KEY-1', '')
.toLowerCase();
return { pub, sigpub, secretHex };
}"""
)
# Identifier is derived from the public signing key.
assert result["pub"] == "age1" + result["sigpub"]
# And it contains none of the secret material.
assert result["secretHex"][:40] not in result["pub"].lower(), (
"member pubkey leaks secret-key bytes"
)
- [ ] Step 2: Run test to verify it fails
Run: python -m pytest src/tests/test_identity_keyscheme.py -v
Expected: FAIL. Under the current scheme getPublicKey() returns 'age1' + hex(array).slice(0,58), so pub != 'age1' + sigpub, and secretHex[:40] is a substring of pub — the leak assertion trips. (It may also error on JSON.parse of the pre-v2 raw-string identity; that still counts as red.)
- [ ] Step 3: Version the stored identity and discard old-scheme keys
In assets/js/identity.js, replace the storage helpers (lines 21-27):
function saveIdentity(secretKey) {
localStorage.setItem(STORAGE_KEYS.identity, secretKey);
}
function loadIdentity() {
return localStorage.getItem(STORAGE_KEYS.identity);
}
with:
const SCHEME_VERSION = 2;
function saveIdentity(secretKey) {
localStorage.setItem(
STORAGE_KEYS.identity,
JSON.stringify({ v: SCHEME_VERSION, sk: secretKey })
);
}
function loadIdentity() {
const raw = localStorage.getItem(STORAGE_KEYS.identity);
if (!raw) return null;
try {
const parsed = JSON.parse(raw);
if (parsed && parsed.v === SCHEME_VERSION && typeof parsed.sk === 'string') {
return parsed.sk;
}
} catch (_) {
// Pre-v2 identities were stored as a raw secret string.
}
// Old-scheme or corrupt identity: discard it (and any stale profile) so
// the client starts fresh under the current key scheme.
localStorage.removeItem(STORAGE_KEYS.identity);
localStorage.removeItem(STORAGE_KEYS.profile);
return null;
}
- [ ] Step 4: Replace key generation with independent secret + public-key-derived identifier
In assets/js/identity.js, replace the crypto block (lines 43-62 — the generateKeypair and derivePublicKey functions and their comments):
// === Crypto ===
// Note: Full age crypto requires typage library
// For MVP, we use a simplified approach with random keys
function generateKeypair() {
// Simplified: generate random 32 bytes as hex for "pubkey"
// Real implementation would use typage for age keys
const array = new Uint8Array(32);
crypto.getRandomValues(array);
const pubkey = 'age1' + Array.from(array).map(b => b.toString(16).padStart(2, '0')).join('').slice(0, 58);
const secretKey = 'AGE-SECRET-KEY-1' + Array.from(array).map(b => b.toString(16).padStart(2, '0')).join('').toUpperCase();
return { pubkey, secretKey };
}
function derivePublicKey(secretKey) {
// For MVP, pubkey is stored alongside secret
// Real implementation would derive from secret
const stored = loadProfile();
return stored?.pubkey || null;
}
with:
// === Crypto ===
//
// The 32-byte secret is generated independently and never leaves the
// browser. The public member identifier is derived from the Ed25519
// *public* signing key, so it exposes no secret material. (The earlier MVP
// built the identifier from the secret bytes, leaking all but 3 of them.)
function generateSecret() {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return 'AGE-SECRET-KEY-1' + bytesToHex(array).toUpperCase();
}
// Public member identifier, derived from the Ed25519 signing public key.
async function derivePublicId() {
const signingPubHex = await getSigningPublicKey();
return 'age1' + signingPubHex;
}
- [ ] Step 5: Rewrite
init()to derive the identifier from the secret
In assets/js/identity.js, replace the init() method (lines 156-174):
async init() {
return dedupe('init', async () => {
const stored = loadIdentity();
if (stored) {
privateKey = stored;
loadProfile();
publicKey = profile?.pubkey;
return true;
}
// Generate new identity
const { pubkey, secretKey } = generateKeypair();
privateKey = secretKey;
publicKey = pubkey;
saveIdentity(secretKey);
// Register with server
await this.register();
return true;
});
},
with:
async init() {
return dedupe('init', async () => {
const stored = loadIdentity();
if (stored) {
privateKey = stored;
loadProfile();
// Always derive the identifier from the secret; never trust the
// stored profile, which may be cleared or stale.
publicKey = await derivePublicId();
if (!profile || profile.pubkey !== publicKey) {
await this.register();
}
return true;
}
// No usable identity: generate a fresh one under the current scheme.
privateKey = generateSecret();
saveIdentity(privateKey);
publicKey = await derivePublicId();
await this.register();
return true;
});
},
- [ ] Step 6: Confirm the old symbols are gone
Run: grep -n "generateKeypair\|derivePublicKey" assets/js/identity.js
Expected: no output (exit status 1). Both were removed; nothing else references them.
- [ ] Step 7: Run test to verify it passes
Run: python -m pytest src/tests/test_identity_keyscheme.py -v
Expected: PASS — pub == 'age1' + sigpub and the secret hex is absent from the identifier.
- [ ] Step 8: Commit
git add assets/js/identity.js src/tests/test_identity_keyscheme.py
git commit -m "Derive member identifier from public key, not secret bytes
generateKeypair built both the public pubkey and the secret from one
random array, so a member's public identifier (sent on every request)
exposed all but 3 bytes of the private key. Generate an independent
secret, derive the identifier from the Ed25519 public signing key, and
discard old-scheme identities from localStorage on load (fresh start,
per the agreed migration decision)."
Final verification (after all four tasks)
- [ ] Fast local suites, no browser:
Run: python -m pytest api/tests src/tests -m "not browser and not regression" -q
Expected: PASS (baseline unaffected).
- [ ] The four new regressions together (needs a dev server; the fixture autostarts one):
Run: python -m pytest src/tests/test_celestial_masthead.py src/tests/test_identity_keyscheme.py src/tests/test_sync_prune_guard.py api/tests/test_register.py -v
Expected: all PASS.
- [ ] End-to-end smoke of the masthead in a real browser: run
make serve, openhttp://localhost:1969/, confirm the sphere renders and dragging it opens the armillary (item 1 is user-visible; do not rely on the test alone).
Notes for the implementer
- Task independence: Tasks 1, 2, and 3 are fully independent and can be done or reviewed in any order. Task 4 depends on Task 3 only in spirit (the client sends
signing_pubkey, which the server now requires — the current client already sends it, so nothing breaks if Task 4 lands before Task 3, but land them in order for a clean history). - Browser tests are not in the default
make test(that gate omits thebrowsermarker). Run them explicitly as shown, or viamake test-browser. This is exactly why item 1’s crash went unnoticed — treat the browser suite as required for this branch even though CI doesn’t yet enforce it (that gap is critique item 4, out of scope here). - Do not attempt items 2’s cousin problems in this plan: the plaintext-localStorage secret (item 12d), the signed-message-lacks-endpoint issue (item 27), and the webhook/visit concurrency contracts (items 6/6a) are separate findings with their own risk/decision profile. Keep these four commits clean.
Self-review (completed by plan author)
- Spec coverage: items 1, 2, 2a, 3 each map to a task (1→Task 1, 3→Task 2, 2a→Task 3, 2→Task 4). The fresh-start migration decision is encoded in Tasks 3 and 4 (no re-key endpoint; discard old identities).
- Placeholder scan: no TBD/”handle edge cases”/”write tests for the above” — every code and test step shows literal content.
- Type/name consistency:
generateSecret/derivePublicId(Task 4) are used exactly as defined;getSigningPublicKey/bytesToHex/deriveSigningKeypairare pre-existing and unchanged;--force-prunemaps tooptions.get("force_prune")(Django’s argparse dest); Task 2’sUnit(...)fields are verified againstmodels.py(noslugfield exists — removed).