Manual
Almnck.
Price: 50ⓐ

Ed25519 Signature Verification Implementation Plan

For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

Goal: Add cryptographic signature verification to the membership API so only keypair owners can make requests.

Architecture: Derive Ed25519 signing keypairs from the existing identity seed using HKDF. Client signs timestamps; server verifies signatures before processing requests. Stored signing pubkeys enable verification without revealing private keys.

Tech Stack: @noble/ed25519, @noble/hashes (both browser and Cloudflare Workers compatible)


Task 1: Add Server Dependencies

Files: - Modify: workers/almanack-membership/package.json

Step 1: Install noble crypto libraries

cd workers/almanack-membership && npm install @noble/ed25519 @noble/hashes

Step 2: Verify installation

Run: cat workers/almanack-membership/package.json | grep noble Expected: Lines showing @noble/ed25519 and @noble/hashes in dependencies

Step 3: Commit

git add workers/almanack-membership/package.json workers/almanack-membership/package-lock.json
git commit -m "feat(membership): add noble crypto libraries for signature verification"

Task 2: Add Schema Migration

Files: - Modify: workers/almanack-membership/src/index.ts:91-111

Step 1: Add signing_pubkey column to initSchema()

Find the initSchema() method and add after the members table creation:

private initSchema() {
    this.sql.exec(`
        CREATE TABLE IF NOT EXISTS members (
            pubkey TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            balance INTEGER DEFAULT 0,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP,
            last_visit TEXT,
            streak INTEGER DEFAULT 0,
            signing_pubkey TEXT
        )
    `);
    this.sql.exec(`
        CREATE TABLE IF NOT EXISTS visits (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            pubkey TEXT NOT NULL,
            visited_on TEXT NOT NULL,
            page_type TEXT DEFAULT 'article',
            FOREIGN KEY (pubkey) REFERENCES members(pubkey)
        )
    `);
}

Step 2: Test schema loads without error

Run: cd workers/almanack-membership && npx wrangler dev & Wait 3 seconds, then: curl -s http://localhost:8787/health Expected: {"status":"ok"} Kill: pkill -f "wrangler dev"

Step 3: Commit

git add workers/almanack-membership/src/index.ts
git commit -m "feat(membership): add signing_pubkey column to members schema"

Task 3: Add Crypto Helpers

Files: - Modify: workers/almanack-membership/src/index.ts (add after imports, before types)

Step 1: Add imports and helper functions

At the top of the file, after the DurableObject import:

import { DurableObject } from "cloudflare:workers";
import * as ed from '@noble/ed25519';
import { sha512 } from '@noble/hashes/sha512';

// Configure noble for sync operations
ed.etc.sha512Sync = (...m) => sha512(ed.etc.concatBytes(...m));

// === Crypto Helpers ===

function hexToBytes(hex: string): Uint8Array {
    const bytes = new Uint8Array(hex.length / 2);
    for (let i = 0; i < bytes.length; i++) {
        bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
    }
    return bytes;
}

function bytesToHex(bytes: Uint8Array): string {
    return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}

async function verifySignature(
    signingPubkey: string,
    timestamp: string,
    signature: string
): Promise<{ valid: boolean; error?: string }> {
    // Check timestamp is within ±5 minutes
    const ts = new Date(timestamp);
    if (isNaN(ts.getTime())) {
        return { valid: false, error: 'Invalid timestamp format' };
    }
    const diff = Math.abs(Date.now() - ts.getTime());
    if (diff > 5 * 60 * 1000) {
        return { valid: false, error: 'Timestamp expired (±5 min tolerance)' };
    }

    // Verify Ed25519 signature
    try {
        const message = new TextEncoder().encode(`almanack:timestamp:${timestamp}`);
        const sig = hexToBytes(signature);
        const pub = hexToBytes(signingPubkey);
        const valid = await ed.verifyAsync(sig, message, pub);
        return { valid };
    } catch (e) {
        return { valid: false, error: 'Invalid signature format' };
    }
}

Step 2: Verify TypeScript compiles

Run: cd workers/almanack-membership && npx tsc --noEmit Expected: No errors

Step 3: Commit

git add workers/almanack-membership/src/index.ts
git commit -m "feat(membership): add Ed25519 signature verification helpers"

Task 4: Update RegisterRequest and Register Method

Files: - Modify: workers/almanack-membership/src/index.ts

Step 1: Update RegisterRequest interface

Find the RegisterRequest interface and add signing_pubkey:

interface RegisterRequest {
    pubkey: string;
    signing_pubkey?: string;
}

Step 2: Update the register method in MembershipDB class

Replace the existing register method:

async register(pubkey: string, signingPubkey?: string): Promise<ProfileResponse> {
    // Check if member exists
    const existing = this.sql.exec(
        "SELECT name, balance, streak, signing_pubkey FROM members WHERE pubkey = ?",
        pubkey
    ).toArray();

    if (existing.length > 0) {
        const member = existing[0];
        // Update signing_pubkey if provided and not already set
        if (signingPubkey && !member.signing_pubkey) {
            this.sql.exec(
                "UPDATE members SET signing_pubkey = ? WHERE pubkey = ?",
                signingPubkey, pubkey
            );
        }
        return {
            name: member.name as string,
            balance: member.balance as number,
            streak: member.streak as number
        };
    }

    // Create new member
    const name = generateName();
    this.sql.exec(
        "INSERT INTO members (pubkey, name, balance, streak, signing_pubkey) VALUES (?, ?, 0, 0, ?)",
        pubkey, name, signingPubkey || null
    );

    return { name, balance: 0, streak: 0 };
}

Step 3: Update the /register route handler

Find the /register case and update:

case "/register": {
    if (request.method !== "POST") {
        return errorResponse("Method not allowed", 405);
    }
    const body = await request.json() as RegisterRequest;
    if (!body.pubkey) {
        return errorResponse("pubkey required", 400);
    }
    const profile = await db.register(body.pubkey, body.signing_pubkey);
    return jsonResponse(profile);
}

Step 4: Test registration with signing_pubkey

Run: cd workers/almanack-membership && npx wrangler dev & Wait 3 seconds, then:

curl -s -X POST http://localhost:8787/register \
  -H "Content-Type: application/json" \
  -d '{"pubkey":"age1testcrypto","signing_pubkey":"abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234"}'

Expected: {"name":"...", "balance":0, "streak":0} Kill: pkill -f "wrangler dev"

Step 5: Commit

git add workers/almanack-membership/src/index.ts
git commit -m "feat(membership): accept signing_pubkey on registration"

Task 5: Add Signature Verification to /visit

Files: - Modify: workers/almanack-membership/src/index.ts

Step 1: Update visit method to return signing_pubkey status

Add a helper method to MembershipDB class:

async getSigningPubkey(pubkey: string): Promise<string | null> {
    const result = this.sql.exec(
        "SELECT signing_pubkey FROM members WHERE pubkey = ?",
        pubkey
    ).toArray();
    if (result.length === 0) return null;
    return result[0].signing_pubkey as string | null;
}

Step 2: Update /visit route handler with verification

Replace the /visit case:

case "/visit": {
    if (request.method !== "POST") {
        return errorResponse("Method not allowed", 405);
    }
    const body = await request.json() as VisitRequest;
    if (!body.pubkey) {
        return errorResponse("pubkey required", 400);
    }
    if (!body.timestamp || !body.signature) {
        return errorResponse("timestamp and signature required", 400);
    }

    // Get member's signing pubkey
    const signingPubkey = await db.getSigningPubkey(body.pubkey);
    if (!signingPubkey) {
        return errorResponse("Member not found or missing signing key. Please re-register.", 400);
    }

    // Verify signature
    const verification = await verifySignature(signingPubkey, body.timestamp, body.signature);
    if (!verification.valid) {
        return errorResponse(verification.error || "Invalid signature", 401);
    }

    const result = await db.visit(body.pubkey);
    return jsonResponse(result);
}

Step 3: Test visit rejects missing signature

Run: cd workers/almanack-membership && npx wrangler dev & Wait 3 seconds, then:

curl -s -X POST http://localhost:8787/visit \
  -H "Content-Type: application/json" \
  -d '{"pubkey":"age1test"}'

Expected: {"error":"timestamp and signature required"} Kill: pkill -f "wrangler dev"

Step 4: Commit

git add workers/almanack-membership/src/index.ts
git commit -m "feat(membership): require signature verification on /visit"

Task 6: Add Signature Verification to /me

Files: - Modify: workers/almanack-membership/src/index.ts

Step 1: Update /me route handler

Replace the /me case:

case "/me": {
    if (request.method !== "GET") {
        return errorResponse("Method not allowed", 405);
    }
    const pubkey = url.searchParams.get("pubkey");
    const timestamp = url.searchParams.get("ts");
    const signature = url.searchParams.get("sig");

    if (!pubkey) {
        return errorResponse("pubkey required", 400);
    }
    if (!timestamp || !signature) {
        return errorResponse("ts and sig query params required", 400);
    }

    // Get member's signing pubkey
    const signingPubkey = await db.getSigningPubkey(pubkey);
    if (!signingPubkey) {
        return errorResponse("Member not found or missing signing key", 404);
    }

    // Verify signature
    const verification = await verifySignature(signingPubkey, timestamp, signature);
    if (!verification.valid) {
        return errorResponse(verification.error || "Invalid signature", 401);
    }

    const profile = await db.getProfile(pubkey);
    if (!profile) {
        return errorResponse("Member not found", 404);
    }
    return jsonResponse(profile);
}

Step 2: Commit

git add workers/almanack-membership/src/index.ts
git commit -m "feat(membership): require signature verification on /me"

Task 7: Add Client Crypto Library

Files: - Create: src/almnck/static/js/noble-ed25519.min.js - Modify: src/almnck/templates/base.html

Step 1: Download noble-ed25519 browser bundle

curl -sL "https://unpkg.com/@noble/ed25519@2.1.0/lib/index.js" > src/almnck/static/js/noble-ed25519.min.js

Step 2: Download noble-hashes for HKDF

curl -sL "https://unpkg.com/@noble/hashes@1.4.0/esm/hkdf.js" > src/almnck/static/js/noble-hkdf.min.js
curl -sL "https://unpkg.com/@noble/hashes@1.4.0/esm/sha256.js" > src/almnck/static/js/noble-sha256.min.js
curl -sL "https://unpkg.com/@noble/hashes@1.4.0/esm/sha512.js" > src/almnck/static/js/noble-sha512.min.js

Note: These may need adjustment based on actual bundle format. Alternative: use ES module imports with importmap.

Step 3: Add script tags to base.html

Before the identity.js script tag, add:

<script type="module">
  import * as ed from '/static/js/noble-ed25519.min.js';
  import { hkdf } from '/static/js/noble-hkdf.min.js';
  import { sha256 } from '/static/js/noble-sha256.min.js';
  window.nobleEd25519 = ed;
  window.nobleHkdf = hkdf;
  window.nobleSha256 = sha256;
</script>

Step 4: Commit

git add src/almnck/static/js/noble-*.js src/almnck/templates/base.html
git commit -m "feat(membership): add noble crypto libraries to frontend"

Task 8: Implement Client Key Derivation

Files: - Modify: src/almnck/static/js/identity.js

Step 1: Add hex conversion helpers

After the existing helper functions, add:

function hexToBytes(hex) {
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < bytes.length; i++) {
    bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
  }
  return bytes;
}

function bytesToHex(bytes) {
  return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}

Step 2: Add signing keypair derivation

let signingPrivateKey = null;
let signingPublicKey = null;

async function deriveSigningKeypair() {
  if (signingPrivateKey && signingPublicKey) {
    return { privateKey: signingPrivateKey, publicKey: signingPublicKey };
  }

  if (!privateKey) {
    throw new Error('Identity not initialized');
  }

  // Extract seed from AGE-SECRET-KEY-1... format (hex after prefix)
  const seedHex = privateKey.replace('AGE-SECRET-KEY-1', '').toLowerCase();
  const seed = hexToBytes(seedHex.slice(0, 64));

  // Use HKDF to derive Ed25519 seed
  const info = new TextEncoder().encode('almanack-ed25519-signing-key');
  const derivedKey = await window.nobleHkdf(window.nobleSha256, seed, new Uint8Array(0), info, 32);

  // Generate Ed25519 keypair
  signingPrivateKey = derivedKey;
  signingPublicKey = await window.nobleEd25519.getPublicKeyAsync(derivedKey);

  return { privateKey: signingPrivateKey, publicKey: signingPublicKey };
}

Step 3: Add sign function

async function sign(message) {
  const { privateKey } = await deriveSigningKeypair();
  const messageBytes = new TextEncoder().encode(message);
  const signature = await window.nobleEd25519.signAsync(messageBytes, privateKey);
  return bytesToHex(signature);
}

Step 4: Add getSigningPublicKey function

async function getSigningPublicKey() {
  const { publicKey } = await deriveSigningKeypair();
  return bytesToHex(publicKey);
}

Step 5: Commit

git add src/almnck/static/js/identity.js
git commit -m "feat(membership): add Ed25519 key derivation to identity.js"

Task 9: Update Client API Calls

Files: - Modify: src/almnck/static/js/identity.js

Step 1: Update register() to include signing_pubkey

async function register() {
  const signingPubkey = await getSigningPublicKey();
  const response = await apiPost('/register', {
    pubkey: publicKey,
    signing_pubkey: signingPubkey
  });
  if (response) {
    profile = response;
    localStorage.setItem(PROFILE_KEY, JSON.stringify(profile));
  }
  return profile;
}

Step 2: Update visit() with signature

async function visit() {
  const timestamp = new Date().toISOString();
  const message = `almanack:timestamp:${timestamp}`;
  const signature = await sign(message);

  try {
    const response = await apiPost('/visit', {
      pubkey: publicKey,
      timestamp: timestamp,
      signature: signature
    });
    if (response) {
      profile = { ...profile, ...response };
      localStorage.setItem(PROFILE_KEY, JSON.stringify(profile));
    }
    return response;
  } catch (err) {
    // If missing signing key, re-register and retry
    if (err.message && err.message.includes('re-register')) {
      await register();
      return visit();
    }
    // Jubilee mode - use cached data
    console.warn('Visit failed, using cached profile:', err);
    return { ...profile, jubilee: true };
  }
}

Step 3: Update getMe() with signature

async function getMe() {
  const timestamp = new Date().toISOString();
  const message = `almanack:timestamp:${timestamp}`;
  const signature = await sign(message);

  const params = new URLSearchParams({
    pubkey: publicKey,
    ts: timestamp,
    sig: signature
  });

  try {
    const response = await apiGet(`/me?${params}`);
    if (response) {
      profile = response;
      localStorage.setItem(PROFILE_KEY, JSON.stringify(profile));
    }
    return profile;
  } catch (err) {
    console.warn('getMe failed, using cached profile:', err);
    return profile;
  }
}

Step 4: Commit

git add src/almnck/static/js/identity.js
git commit -m "feat(membership): sign all API requests with Ed25519"

Task 10: Deploy and Integration Test

Step 1: Deploy worker

cd workers/almanack-membership && npx wrangler deploy

Expected: Successful deployment message with URL

Step 2: Test in browser

  1. Open browser dev tools
  2. Clear localStorage: localStorage.clear()
  3. Navigate to http://localhost:8001/
  4. Check console for any errors
  5. Verify identity dropdown shows a whimsical name
  6. Check Network tab - /register and /visit should include signature fields
  7. Refresh page - verify /visit works on second load

Step 3: Verify signature rejection

curl -s -X POST https://almanack-membership.almnck.workers.dev/visit \
  -H "Content-Type: application/json" \
  -d '{"pubkey":"age1fake","timestamp":"2026-01-17T00:00:00Z","signature":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"}'

Expected: {"error":"..."} (either “Member not found” or “Invalid signature”)

Step 4: Final commit

git add -A
git commit -m "feat(membership): complete Ed25519 signature verification implementation"
git push

Verification Checklist

  • [ ] wrangler dev starts without errors
  • [ ] /register accepts and stores signing_pubkey
  • [ ] /visit rejects requests without signature
  • [ ] /visit rejects requests with invalid signature
  • [ ] /visit rejects requests with expired timestamp
  • [ ] /me requires ts and sig params
  • [ ] Browser: identity dropdown shows name
  • [ ] Browser: Network tab shows signed requests
  • [ ] Browser: page refresh works (visit with valid signature)
  • [ ] Production deployment successful

Addendum (2026-01-17): This plan is OBSOLETE. The membership API was migrated from Cloudflare Workers/Durable Objects to FastAPI on a self-hosted VM. Ed25519 signing was implemented in Python. The workers/ directory has been removed from the repository.