task/31: Relay account whitelist + trust-gated access
## What was built
Full relay access control system: relay_accounts table, RelayAccountService,
trust hook integration, live policy enforcement, admin CRUD API, Timmy seed.
## DB change
`lib/db/src/schema/relay-accounts.ts` — new `relay_accounts` table:
pubkey (PK, FK → nostr_identities.pubkey ON DELETE CASCADE),
access_level ("none"|"read"|"write"), granted_by ("manual"|"auto-tier"),
granted_at, revoked_at (nullable), notes. Pushed via `pnpm run push`.
`lib/db/src/schema/index.ts` — exports relay-accounts.
## RelayAccountService (`artifacts/api-server/src/lib/relay-accounts.ts`)
- getAccess(pubkey) → RelayAccessLevel (none if missing or revoked)
- grant(pubkey, level, reason, grantedBy) — upsert; creates nostr_identity FK
- revoke(pubkey, reason) — sets revokedAt, access_level → none
- syncFromTrustTier(pubkey, tier) — auto-promotes by tier; never downgrades manual grants
- list(opts) — returns all accounts, optionally filtered to active
- Tier→access map: new=none, established/trusted/elite=write (env-overridable)
## Trust hook (`artifacts/api-server/src/lib/trust.ts`)
recordSuccess + recordFailure both call syncFromTrustTier after writing tier.
Failure is caught + logged (non-blocking — trust flow never fails on relay error).
## Policy endpoint (`artifacts/api-server/src/routes/relay.ts`)
evaluatePolicy() now async: queries relay_accounts.getAccess(pubkey).
"write" → accept; "read"/"none"/missing → reject with clear message.
DB error → reject with "policy service error" (safe fail-closed).
## Admin routes (`artifacts/api-server/src/routes/admin-relay.ts`)
ADMIN_SECRET Bearer token auth (localhost-only fallback in dev; error log in prod).
GET /api/admin/relay/accounts — list all accounts
POST /api/admin/relay/accounts/:pk/grant — grant (level + notes body)
POST /api/admin/relay/accounts/:pk/revoke — revoke (reason body)
pubkey validation: must be 64-char lowercase hex.
## Startup seed (`artifacts/api-server/src/index.ts`)
On every startup: grants Timmy's own pubkeyHex "write" access ("manual").
Idempotent upsert — safe across restarts.
## Smoke test results (all pass)
- Timmy pubkey → accept ✓; unknown pubkey → reject ✓
- Admin grant → accept ✓; admin revoke → reject ✓; admin list shows accounts ✓
- TypeScript: 0 errors in API server + lib/db
This commit is contained in:
@@ -17,14 +17,14 @@
|
||||
* Response: strfry plugin decision
|
||||
* { id: string, action: "accept" | "reject" | "shadowReject", msg?: string }
|
||||
*
|
||||
* Bootstrap state (Task #36):
|
||||
* All events are rejected until the account whitelist is implemented.
|
||||
* The endpoint and decision contract are stable; future tasks extend the
|
||||
* logic without changing the API shape.
|
||||
* GET /api/relay/policy
|
||||
* Health + roundtrip probe. No auth required — returns policy state and runs
|
||||
* a synthetic pubkey through evaluatePolicy().
|
||||
*/
|
||||
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import { makeLogger } from "../lib/logger.js";
|
||||
import { relayAccountService } from "../lib/relay-accounts.js";
|
||||
|
||||
const logger = makeLogger("relay-policy");
|
||||
const router = Router();
|
||||
@@ -33,8 +33,6 @@ const RELAY_POLICY_SECRET = process.env["RELAY_POLICY_SECRET"] ?? "";
|
||||
const IS_PROD = process.env["NODE_ENV"] === "production";
|
||||
|
||||
// Production enforcement: RELAY_POLICY_SECRET must be set in production.
|
||||
// An unprotected relay policy endpoint in production allows any caller on the
|
||||
// network to whitelist events — a serious trust-system bypass.
|
||||
if (!RELAY_POLICY_SECRET) {
|
||||
if (IS_PROD) {
|
||||
logger.error(
|
||||
@@ -78,41 +76,39 @@ interface PolicyDecision {
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
function reject(id: string, msg: string): PolicyDecision {
|
||||
function rejectDecision(id: string, msg: string): PolicyDecision {
|
||||
return { id, action: "reject", msg };
|
||||
}
|
||||
|
||||
// ── GET /relay/policy ─────────────────────────────────────────────────────────
|
||||
// Health + roundtrip probe. Returns the relay's current policy state and runs
|
||||
// a synthetic event through evaluatePolicy() so operators can verify the full
|
||||
// sidecar → API path with: curl https://alexanderwhitestone.com/api/relay/policy
|
||||
//
|
||||
// Not secret-gated — it contains no privileged information.
|
||||
function acceptDecision(id: string): PolicyDecision {
|
||||
return { id, action: "accept", msg: "" };
|
||||
}
|
||||
|
||||
router.get("/relay/policy", (_req: Request, res: Response) => {
|
||||
const probe = evaluatePolicy("0000000000000000000000000000000000000000000000000000000000000000", "probe", 1);
|
||||
// ── GET /relay/policy ─────────────────────────────────────────────────────────
|
||||
|
||||
router.get("/relay/policy", async (_req: Request, res: Response) => {
|
||||
const probeId = "0000000000000000000000000000000000000000000000000000000000000000";
|
||||
const probe = await evaluatePolicy(probeId, "probe-pubkey-not-real", 1);
|
||||
res.json({
|
||||
ok: true,
|
||||
secretConfigured: !!RELAY_POLICY_SECRET,
|
||||
bootstrapDecision: probe.action,
|
||||
bootstrapMsg: probe.msg,
|
||||
decision: probe.action,
|
||||
msg: probe.msg,
|
||||
});
|
||||
});
|
||||
|
||||
// ── POST /relay/policy ────────────────────────────────────────────────────────
|
||||
|
||||
router.post("/relay/policy", (req: Request, res: Response) => {
|
||||
// ── Authentication — Bearer token must match RELAY_POLICY_SECRET ──────────
|
||||
router.post("/relay/policy", async (req: Request, res: Response) => {
|
||||
// ── Authentication ───────────────────────────────────────────────────────
|
||||
if (RELAY_POLICY_SECRET) {
|
||||
const authHeader = req.headers["authorization"] ?? "";
|
||||
const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : "";
|
||||
if (token !== RELAY_POLICY_SECRET) {
|
||||
// Use constant-time-ish comparison for secret matching
|
||||
res.status(401).json({ error: "Unauthorized" });
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// No secret configured — warn and allow only from localhost/loopback
|
||||
const ip = req.ip ?? "";
|
||||
const isLocal = ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1";
|
||||
if (!isLocal) {
|
||||
@@ -120,10 +116,10 @@ router.post("/relay/policy", (req: Request, res: Response) => {
|
||||
res.status(401).json({ error: "Unauthorized" });
|
||||
return;
|
||||
}
|
||||
logger.warn("relay/policy: RELAY_POLICY_SECRET not set — accepting local-only calls");
|
||||
logger.warn("relay/policy: RELAY_POLICY_SECRET not set — accepting local-only call");
|
||||
}
|
||||
|
||||
// ── Validate request body ─────────────────────────────────────────────────
|
||||
// ── Validate body ────────────────────────────────────────────────────────
|
||||
const body = req.body as Partial<PolicyRequest>;
|
||||
const event = body.event;
|
||||
|
||||
@@ -136,18 +132,8 @@ router.post("/relay/policy", (req: Request, res: Response) => {
|
||||
const pubkey = typeof event.pubkey === "string" ? event.pubkey : "";
|
||||
const kind = typeof event.kind === "number" ? event.kind : -1;
|
||||
|
||||
// ── Policy decision ───────────────────────────────────────────────────────
|
||||
//
|
||||
// Bootstrap state: reject everything.
|
||||
//
|
||||
// This is intentional — the relay is deployed but closed until the account
|
||||
// whitelist (Task #37) is implemented. Once the whitelist route is live,
|
||||
// this function will:
|
||||
// 1. Check nostr_identities whitelist for pubkey
|
||||
// 2. Check event pre-approval queue for moderated content
|
||||
// 3. Return accept / shadowReject based on tier and moderation status
|
||||
//
|
||||
const decision = evaluatePolicy(eventId, pubkey, kind);
|
||||
// ── Policy decision ──────────────────────────────────────────────────────
|
||||
const decision = await evaluatePolicy(eventId, pubkey, kind);
|
||||
|
||||
logger.info("relay policy decision", {
|
||||
eventId: eventId.slice(0, 8),
|
||||
@@ -161,22 +147,40 @@ router.post("/relay/policy", (req: Request, res: Response) => {
|
||||
});
|
||||
|
||||
/**
|
||||
* Evaluate the write policy for an incoming event.
|
||||
* Core write-policy evaluation.
|
||||
*
|
||||
* Bootstrap: all events rejected until whitelist is implemented (Task #37).
|
||||
* The function signature is stable — future tasks replace the body.
|
||||
* Checks relay_accounts for the event's pubkey:
|
||||
* "write" access → accept
|
||||
* "read" / "none" / missing → reject
|
||||
*
|
||||
* Future tasks extend this function (moderation queue, shadowReject for spam).
|
||||
*/
|
||||
function evaluatePolicy(
|
||||
async function evaluatePolicy(
|
||||
eventId: string,
|
||||
pubkey: string,
|
||||
_kind: number,
|
||||
): PolicyDecision {
|
||||
void pubkey; // will be used in Task #37 whitelist check
|
||||
): Promise<PolicyDecision> {
|
||||
if (!pubkey) {
|
||||
return rejectDecision(eventId, "missing pubkey");
|
||||
}
|
||||
|
||||
return reject(
|
||||
eventId,
|
||||
"relay not yet open — whitelist pending (Task #37)",
|
||||
);
|
||||
let accessLevel: string;
|
||||
try {
|
||||
accessLevel = await relayAccountService.getAccess(pubkey);
|
||||
} catch (err) {
|
||||
logger.error("relay-accounts lookup failed — defaulting to reject", { err });
|
||||
return rejectDecision(eventId, "policy service error — try again later");
|
||||
}
|
||||
|
||||
if (accessLevel === "write") {
|
||||
return acceptDecision(eventId);
|
||||
}
|
||||
|
||||
if (accessLevel === "read") {
|
||||
return rejectDecision(eventId, "read-only access — write not permitted");
|
||||
}
|
||||
|
||||
return rejectDecision(eventId, "pubkey not whitelisted for this relay");
|
||||
}
|
||||
|
||||
export default router;
|
||||
|
||||
Reference in New Issue
Block a user