API Auth Hardening (critique item 27) 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: Bind each member signature to the HTTP method + path (v2 format), move /me off a credential-leaking GET, and pin CORS — so a captured signature can’t be replayed against another endpoint and credentials stop landing in logs.
Architecture: The signed message becomes almanack:v2:{METHOD}:{path}:{timestamp}. The server (api/main.py) rebuilds and verifies that string from the actual request; the client (assets/js/) signs the endpoint it is about to call. Hard cutover — the server verifies only v2, and client + server deploy together. No database changes.
Tech Stack: FastAPI + PyNaCl (server), noble-ed25519 IIFE client JS, pytest + Playwright (page.evaluate) tests.
Global Constraints
- The v2 signed message is exactly
almanack:v2:{METHOD}:{path}:{timestamp}—{METHOD}uppercase (alwaysPOSTfor signed endpoints),{path}the endpoint path only (/visit,/checkout,/me),{timestamp}the existing ISO-8601 string. The oldalmanack:timestamp:{ts}format is removed entirely (hard cutover — no dual-accept). - Each server handler passes a literal method/path matching its own route decorator; a test asserts each literal matches its route so the two cannot drift.
- Python
>=3.11, hatchling. API tests are host-run against in-memory SQLite (pytest api/tests); client tests are Playwright browser tests insrc/tests/marked@pytest.mark.browser, emitting TAP. - CORS allow-list is exactly
https://almnck.com,https://www.almnck.com,http://localhost:1969, withallow_credentials=False(auth is the signed body, not cookies). - No database schema change; no migration.
- Deploy is a hard cutover:
make prod-deploy(new client JS) +make prod-api-deploy(new API) together. Out of scope: body digests, nonce stores, timestamp-window tightening (see the design doc’s “Deferred, with intent”). - Keep each commit to a single concern; do not stage the pre-existing
editorial/inbox/packets-from-davos/brigadoon.mdchurn.
File Structure
api/main.py—verify_signaturegainsmethod/path;/visit,/checkout,/mebind their endpoint;/mebecomes POST; CORS pinned; negative-balance comment. (Task 1)api/tests/helpers.py—make_signature(signing_key, method, path)builds v2;SignedMemberdrops the baked sig; newsign_for(member, method, path)convenience. (Task 1)api/tests/test_visit.py,test_checkout.py,test_me.py,test_visit_idempotency.py— updated tosign_for; newapi/tests/test_auth_hardening.pyfor the cross-endpoint + CORS assertions. (Task 1)assets/js/identity.js—Identity.signRequest(method, path)owns the v2 format;visit(×2) andgetMeuse it;getMebecomes a POST; deadapiGetremoved. (Task 2)assets/js/topup.js—/checkoutsigns viaIdentity.signRequest('POST', '/checkout'). (Task 2)src/tests/test_auth_v2_signing.py— new Playwright test: client signs the v2 message and/megoes out as POST. (Task 2)doc/04-services/01-membership-api.md— v2 format,/meis POST, ownership-claim correction. (Task 3)
Task 1: Server — v2 endpoint-bound signatures, /me POST, CORS, negative-balance
Files:
- Modify: api/main.py (verify_signature, CORS block, MeRequest model, /visit//checkout//me handlers, negative-balance comment)
- Modify: api/tests/helpers.py
- Modify: api/tests/test_visit.py, api/tests/test_checkout.py, api/tests/test_me.py, api/tests/test_visit_idempotency.py
- Create: api/tests/test_auth_hardening.py
Interfaces:
- Produces: v2 message almanack:v2:{METHOD}:{path}:{timestamp}. verify_signature(signing_pubkey, method, path, timestamp, signature) -> (bool, Optional[str]). /me is now POST taking MeRequest{pubkey, signature, timestamp}.
- Produces (tests): make_signature(signing_key, method, path) -> (timestamp, signature); SignedMember = (pubkey, signing_key, name); sign_for(member, method, path) -> {"pubkey","timestamp","signature"}. Task 2’s client must sign the identical message.
- [ ] Step 1: Update the test helpers to v2
Replace the body of api/tests/helpers.py with:
# api/tests/helpers.py
"""Shared helpers for API tests."""
from collections import namedtuple
from datetime import datetime, timezone
from nacl.signing import SigningKey
SignedMember = namedtuple("SignedMember", ["pubkey", "signing_key", "name"])
def make_signature(
signing_key: SigningKey, method: str, path: str
) -> tuple[str, str]:
"""Create a fresh (timestamp, signature) over the v2 endpoint-bound message
`almanack:v2:{METHOD}:{path}:{timestamp}`."""
timestamp = datetime.now(timezone.utc).isoformat()
message = f"almanack:v2:{method}:{path}:{timestamp}".encode("utf-8")
signature = signing_key.sign(message).signature.hex()
return timestamp, signature
def create_signed_member(client) -> SignedMember:
"""Register a member with a real Ed25519 signing key. The pubkey is derived
from the signing key ('age1' + hex), matching the self-certifying-identity
rule. Signatures are endpoint-specific, so none is baked in — call
`sign_for` per endpoint."""
signing_key = SigningKey.generate()
signing_pubkey = signing_key.verify_key.encode().hex()
pubkey = "age1" + signing_pubkey
response = client.post(
"/register",
json={"pubkey": pubkey, "signing_pubkey": signing_pubkey},
)
assert response.status_code == 200
return SignedMember(pubkey, signing_key, response.json()["name"])
def sign_for(member: SignedMember, method: str, path: str) -> dict:
"""A signed request body {pubkey, timestamp, signature} for one endpoint."""
timestamp, signature = make_signature(member.signing_key, method, path)
return {
"pubkey": member.pubkey,
"timestamp": timestamp,
"signature": signature,
}
- [ ] Step 2: Write the new failing tests
Create api/tests/test_auth_hardening.py:
# api/tests/test_auth_hardening.py
"""Critique item 27: signatures bind the endpoint; /me is POST; CORS is pinned."""
from api.tests.helpers import create_signed_member, sign_for
def test_visit_signature_is_rejected_on_checkout(client):
"""A signature made for /visit must NOT authorize /checkout (no cross-
endpoint replay)."""
member = create_signed_member(client)
visit_body = sign_for(member, "POST", "/visit")
# Replay the /visit-scoped signature against /checkout.
resp = client.post(
"/checkout",
json={**visit_body, "amount": 1000, "recurring": None},
)
assert resp.status_code == 401
def test_checkout_signature_is_rejected_on_visit(client):
member = create_signed_member(client)
checkout_body = sign_for(member, "POST", "/checkout")
resp = client.post(
"/visit",
json={
"pubkey": checkout_body["pubkey"],
"timestamp": checkout_body["timestamp"],
"signature": checkout_body["signature"],
},
)
assert resp.status_code == 401
def test_correctly_scoped_visit_is_accepted(client):
member = create_signed_member(client)
resp = client.post("/visit", json=sign_for(member, "POST", "/visit"))
assert resp.status_code == 200
assert resp.json()["debited"] is True
def test_me_is_post_and_verifies(client):
member = create_signed_member(client)
resp = client.post("/me", json=sign_for(member, "POST", "/me"))
assert resp.status_code == 200
assert resp.json()["name"] == member.name
def test_me_get_no_longer_exists(client):
resp = client.get("/me?pubkey=age1x&ts=x&sig=x")
assert resp.status_code == 405 # Method Not Allowed — /me is POST-only now
def test_cors_pins_origin_not_wildcard(client):
resp = client.options(
"/visit",
headers={
"Origin": "https://almnck.com",
"Access-Control-Request-Method": "POST",
},
)
allow = resp.headers.get("access-control-allow-origin")
assert allow == "https://almnck.com"
assert allow != "*"
- [ ] Step 3: Run the new tests to verify they fail
Run: pytest api/tests/test_auth_hardening.py -v
Expected: FAILs — cross-endpoint replay currently succeeds (sig only binds timestamp), /me is still GET (POST → 405/404 mismatch), CORS returns *.
- [ ] Step 4: Rewrite
verify_signaturefor v2
In api/main.py, replace verify_signature (lines 28-56) with:
def verify_signature(
signing_pubkey: str,
method: str,
path: str,
timestamp: str,
signature: str,
) -> tuple[bool, Optional[str]]:
"""Verify an Ed25519 signature over the v2 request-scoped message
`almanack:v2:{METHOD}:{path}:{timestamp}`. Binding the method and path means
a signature captured from one endpoint cannot be replayed against another.
Returns (valid, error_message)."""
try:
ts = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
except ValueError:
return False, "Invalid timestamp format"
now = datetime.now(timezone.utc)
diff = abs((now - ts).total_seconds())
if diff > TIMESTAMP_TOLERANCE_SECONDS:
return False, "Timestamp expired (±5 min tolerance)"
try:
message = f"almanack:v2:{method}:{path}:{timestamp}".encode("utf-8")
sig_bytes = bytes.fromhex(signature)
pubkey_bytes = bytes.fromhex(signing_pubkey)
verify_key = VerifyKey(pubkey_bytes)
verify_key.verify(message, sig_bytes)
return True, None
except (ValueError, BadSignatureError):
return False, "Invalid signature"
- [ ] Step 5: Pin CORS
In api/main.py, replace the add_middleware block (lines 70-76) with:
app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://almnck.com",
"https://www.almnck.com",
"http://localhost:1969", # local `make serve` dev origin
],
allow_credentials=False, # auth travels in the signed body, not cookies
allow_methods=["GET", "POST"],
allow_headers=["Content-Type"],
)
- [ ] Step 6: Add the
MeRequestmodel and make/mea POST
In api/main.py, add MeRequest next to the other request models (after VisitResponse, near line 103):
class MeRequest(BaseModel):
pubkey: str
signature: str
timestamp: str
Replace the /me handler (lines 165-183) with a POST:
@app.post("/me", response_model=ProfileResponse)
def get_me(request: MeRequest, session: Session = Depends(get_session)):
member = session.get(Member, request.pubkey)
if not member:
raise HTTPException(status_code=404, detail="Member not found")
if not member.signing_pubkey:
raise HTTPException(
status_code=400, detail="Member missing signing key. Please re-register."
)
valid, error = verify_signature(
member.signing_pubkey, "POST", "/me", request.timestamp, request.signature
)
if not valid:
raise HTTPException(status_code=401, detail=error)
return ProfileResponse(
name=member.name, balance=member.balance, streak=member.streak
)
- [ ] Step 7: Bind the endpoint in
/visitand/checkout, and comment the negative balance
In /visit (the verify_signature call at lines 200-202):
valid, error = verify_signature(
member.signing_pubkey, "POST", "/visit", request.timestamp, request.signature
)
Add the intentional-negative-balance comment immediately above member.balance -= DAILY_DEBIT (line 212):
# Balance may go unbounded-negative: membership dues accrue as a
# negative balance rather than being capped. Intentional.
member.balance -= DAILY_DEBIT
In /checkout (the verify_signature call at lines 258-260):
valid, error = verify_signature(
member.signing_pubkey, "POST", "/checkout", request.timestamp, request.signature
)
- [ ] Step 8: Run the new tests to verify they pass
Run: pytest api/tests/test_auth_hardening.py -v
Expected: PASS (6 tests).
- [ ] Step 9: Update the existing signed-member tests to
sign_for
The helper change removed SignedMember.timestamp/.signature, so every test that
signed a request must switch to sign_for (or make_signature). Update these files:
api/tests/test_visit.py, api/tests/test_checkout.py, api/tests/test_me.py,
api/tests/test_visit_idempotency.py.
Transformation rule — a call that used the baked fields, e.g.:
member = create_signed_member(client)
resp = client.post("/visit", json={
"pubkey": member.pubkey,
"timestamp": member.timestamp,
"signature": member.signature,
})
becomes:
member = create_signed_member(client)
resp = client.post("/visit", json=sign_for(member, "POST", "/visit"))
For /checkout tests, merge the extra fields:
json={**sign_for(member, "POST", "/checkout"), "amount": 5000, "recurring": None}.
For /me tests, the call becomes client.post("/me", json=sign_for(member, "POST", "/me"))
(it was a GET with query params — update both the method and the params).
For a fresh second signature within one test (e.g. the idempotency double-visit),
call sign_for(member, "POST", "/visit") again for a new timestamp.
Add sign_for (and drop now-unused make_signature/SignedMember field) imports as needed.
- [ ] Step 10: Run the full API suite
Run: pytest api/tests -q
Expected: all pass (the six new + every updated existing test; webhook/register/names tests are unaffected — they don’t sign member requests).
- [ ] Step 11: Commit
git add api/main.py api/tests/helpers.py api/tests/test_auth_hardening.py \
api/tests/test_visit.py api/tests/test_checkout.py api/tests/test_me.py \
api/tests/test_visit_idempotency.py
git commit -m "api: bind signatures to the endpoint; /me POST; pin CORS
The signed message becomes almanack:v2:{METHOD}:{path}:{timestamp}, so a
captured signature can no longer be replayed against another endpoint. /me
moves from a credential-leaking GET to a POST. CORS is pinned to the site
origins with credentials off. Negative balance documented as intentional."
Task 2: Client — v2 signing in identity.js and topup.js
Files:
- Modify: assets/js/identity.js (add signRequest; update visit ×2 and getMe; remove dead apiGet)
- Modify: assets/js/topup.js (/checkout uses signRequest)
- Create: src/tests/test_auth_v2_signing.py
Interfaces:
- Consumes: the v2 message and the /me POST contract from Task 1.
- Produces: Identity.signRequest(method, path) -> {timestamp, signature} (the sole client-side owner of the v2 format).
- [ ] Step 1: Write the failing browser test
Create src/tests/test_auth_v2_signing.py (mirrors the harness in
src/tests/test_identity_keyscheme.py):
"""Critique item 27 (client): requests are signed over the v2 endpoint-bound
message, and /me is sent as a POST."""
import json
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 _stub_register(page):
page.route(
"**/register",
lambda route: route.fulfill(
status=200,
content_type="application/json",
body='{"name": "Test Traveler", "balance": 0, "streak": 0}',
),
)
def _capture(page, url_glob, response_body):
"""Capture the first request to url_glob; fulfill it with response_body."""
box = {}
def handler(route):
req = route.request
box["method"] = req.method
box["post_data"] = req.post_data
route.fulfill(
status=200, content_type="application/json", body=response_body
)
page.route(url_glob, handler)
return box
def _sig_verifies(page, sigpub_hex, expected_message, signature_hex):
"""Verify, in-page, that signature_hex is a valid Ed25519 signature over
expected_message under sigpub_hex — i.e. the client signed exactly that."""
return page.evaluate(
"""async ({ sigpub, msg, sig }) => {
const bytes = (h) => Uint8Array.from(h.match(/../g).map((b) => parseInt(b, 16)));
const message = new TextEncoder().encode(msg);
return await window.nobleEd25519.verifyAsync(bytes(sig), message, bytes(sigpub));
}""",
{"sigpub": sigpub_hex, "msg": expected_message, "sig": signature_hex},
)
def test_visit_signs_v2_endpoint_message(page):
_stub_register(page)
visit = _capture(page, "**/visit", '{"balance": 0, "streak": 1, "debited": true}')
page.goto("/")
page.wait_for_function("() => !!window.AlmanackIdentity", timeout=10000)
sigpub = page.evaluate(
"""async () => {
localStorage.clear();
await window.AlmanackIdentity.init();
await window.AlmanackIdentity.visit();
return await window.AlmanackIdentity.getSigningPublicKey();
}"""
)
assert visit["method"] == "POST"
body = json.loads(visit["post_data"])
expected = f"almanack:v2:POST:/visit:{body['timestamp']}"
assert _sig_verifies(page, sigpub, expected, body["signature"]) is True
def test_me_is_posted_and_signs_v2(page):
_stub_register(page)
me = _capture(page, "**/me", '{"name": "Test Traveler", "balance": 0, "streak": 0}')
page.goto("/")
page.wait_for_function("() => !!window.AlmanackIdentity", timeout=10000)
sigpub = page.evaluate(
"""async () => {
localStorage.clear();
await window.AlmanackIdentity.init();
await window.AlmanackIdentity.getMe();
return await window.AlmanackIdentity.getSigningPublicKey();
}"""
)
assert me["method"] == "POST", "/me must be a POST, not a GET with query params"
body = json.loads(me["post_data"])
expected = f"almanack:v2:POST:/me:{body['timestamp']}"
assert _sig_verifies(page, sigpub, expected, body["signature"]) is True
- [ ] Step 2: Run the test to verify it fails
Run (needs the dev server; the browser suite manages it): bin/a-test --suite browser 2>&1 | grep -i v2_signing or pytest src/tests/test_auth_v2_signing.py -v
Expected: FAIL — visit still signs almanack:timestamp:… and getMe sends a GET.
- [ ] Step 3: Add
signRequestand updatevisitinidentity.js
In assets/js/identity.js, add a public signRequest to the Identity object (it
becomes the single client-side owner of the v2 format). Place it beside sign in the
public API:
// Sign a request for a specific endpoint. The signed message binds the HTTP
// method and path (almanack:v2:{METHOD}:{path}:{timestamp}) so a captured
// signature can't be replayed against another endpoint.
async signRequest(method, path) {
const timestamp = new Date().toISOString();
const signature = await sign(`almanack:v2:${method}:${path}:${timestamp}`);
return { timestamp, signature };
},
Update visit — replace the initial signing (lines 221-223) with:
const { timestamp, signature } = await this.signRequest('POST', '/visit');
and the retry signing (lines 238-240) with:
const { timestamp: ts2, signature: sig2 } = await this.signRequest('POST', '/visit');
(The subsequent apiPost('/visit', { pubkey: publicKey, timestamp, signature }) and the
retry { ..., timestamp: ts2, signature: sig2 } bodies are unchanged.)
- [ ] Step 4: Make
getMea POST inidentity.js
Replace the getMe body (lines 261-288) with:
async getMe() {
return dedupe('getMe', async () => {
if (!publicKey) await this.init();
const { timestamp, signature } = await this.signRequest('POST', '/me');
try {
const data = await apiPost('/me', {
pubkey: publicKey,
timestamp: timestamp,
signature: signature
});
saveProfile({ ...data, pubkey: publicKey });
return data;
} catch (err) {
console.error('Profile fetch failed:', err);
return profile;
}
});
},
- [ ] Step 5: Remove the now-dead
apiGet
apiGet (lines 149-157) was only used by the old GET /me; nothing calls it now.
Delete the apiGet function. Confirm no other references:
Run: grep -n "apiGet" assets/js/identity.js
Expected: no matches.
- [ ] Step 6: Update
topup.js/checkoutsigning
In assets/js/topup.js, replace lines 86-87:
const pubkey = Identity.getPublicKey();
const timestamp = new Date().toISOString();
const signature = await Identity.sign(`almanack:timestamp:${timestamp}`);
with:
const pubkey = Identity.getPublicKey();
const { timestamp, signature } = await Identity.signRequest('POST', '/checkout');
(The fetch('/checkout', … body: JSON.stringify({ pubkey, signature, timestamp, amount, recurring }))
call is unchanged.)
- [ ] Step 7: Run the browser test to verify it passes
Run: pytest src/tests/test_auth_v2_signing.py -v
Expected: PASS (2 tests) — visit and getMe both sign the v2 message and /me is a POST.
- [ ] Step 8: Commit
git add assets/js/identity.js assets/js/topup.js src/tests/test_auth_v2_signing.py
git commit -m "client: sign the v2 endpoint-bound message; POST /me
Identity.signRequest(method, path) is the sole owner of the
almanack:v2:{METHOD}:{path}:{timestamp} format; visit, getMe and checkout use
it. getMe moves to a POST body (no more credentials in the /me query string);
the now-dead apiGet helper is removed."
Task 3: Docs — membership manual
Files:
- Modify: doc/04-services/01-membership-api.md (lines 124 and 202, and the ownership claim)
Interfaces:
- Consumes: the v2 format and /me POST from Tasks 1–2. No code.
- [ ] Step 1: Read the two signature sections
Run: sed -n '118,130p;198,208p' doc/04-services/01-membership-api.md
Note the exact surrounding wording so the edits fit.
- [ ] Step 2: Update the signature-format references
Replace the line (near 124) that reads the signature is over
almanack:timestamp:<timestamp> with:
The signature must be over the message `almanack:v2:<METHOD>:<path>:<timestamp>`
— e.g. `almanack:v2:POST:/visit:<timestamp>`. Binding the method and path means
a signature made for one endpoint cannot be replayed against another.
And the numbered step (near 202) that reads “Client signs almanack:timestamp:<ISO-timestamp>“ with:
2. **Client signs** `almanack:v2:<METHOD>:<path>:<ISO-timestamp>` for the exact
endpoint it is calling.
- [ ] Step 3: Correct the
/memethod and the ownership claim
Wherever the manual documents /me as a GET with query parameters, change it to a
POST taking a JSON body {pubkey, signature, timestamp} (same shape as /visit).
Remove any statement that a timestamp-only signature proves the caller owns the key;
replace with: the signature binds the endpoint, and the identity is self-certifying
(the pubkey is derived from the signing key), so a valid signature proves the caller
holds the signing key for that pubkey and intends that specific endpoint.
- [ ] Step 4: Verify doc links still pass
Run: bin/a-test --suite doc
Expected: all link checks pass (edits are prose only).
- [ ] Step 5: Commit
git add doc/04-services/01-membership-api.md
git commit -m "docs: membership manual — v2 signature format, /me is POST
Document the endpoint-bound almanack:v2:{METHOD}:{path}:{timestamp} message and
the /me POST; drop the claim that a timestamp-only signature proves ownership."
Deploy (after all tasks merge)
Hard cutover — new client and server go out together:
make prod-deploy— publishes the v2-signingidentity.js/topup.jsto the static site (cache-busted, so browsers fetch it on next load).make prod-api-deploy— publishes the API that verifies only v2.
Open tabs running old JS get 401s on signed calls until the page reloads; there is no server-side dual-accept path. No database migration.
Self-Review
Spec coverage (against doc/05-process/specs/2026-07-25-api-auth-hardening-design.md):
- §1 v2 endpoint binding → Task 1 Steps 4, 7, and 6 (/me); literal-path-per-handler with each handler passing its route’s method/path. ✅
- §2 /me GET→POST → Task 1 Step 6; client Task 2 Step 4. ✅
- §3 CORS pinned + credentials off → Task 1 Step 5 + test in Step 2. ✅
- §4 negative-balance comment → Task 1 Step 7. ✅
- §5 client v2 signing (identity.js visit ×2 + getMe POST, topup.js checkout) → Task 2. ✅
- §6 docs → Task 3. ✅
- Testing: cross-endpoint replay rejected, /me POST works, /me GET gone, CORS preflight pinned (Task 1); client signs v2 + /me POST (Task 2). ✅
- Deferred items (body digest, nonce, timestamp window) correctly absent from the tasks.
Note on the literal-path drift test: the design calls for “a test asserts each literal matches its route.” The Task 1 tests enforce this behaviourally — a signature scoped to POST /visit only verifies on /visit (Steps 2, 8) — which fails if a handler’s literal path drifts from its route. This is stronger than a static string check; no separate assertion is added.
Placeholder scan: every code step carries complete code; the existing-test updates (Task 1 Step 9) give a transformation rule with a worked before/after and name the exact files, not a vague “update tests”.
Type consistency: verify_signature(signing_pubkey, method, path, timestamp, signature) is used identically in all three handlers; make_signature(signing_key, method, path) / sign_for(member, method, path) / Identity.signRequest(method, path) all take (method, path) in that order and all build the identical almanack:v2:{METHOD}:{path}:{timestamp} string; MeRequest{pubkey, signature, timestamp} matches the client’s /me POST body.