nekoarch-backend: NekoArch Won't Write Until It Proves It's Safe
Inside the Fastify and Supabase backend for architectural design, where authorization lives in Postgres, configuration fails closed, and every signed write begins with an HMAC handshake.
- NekoArch refuses signed writes unless the API process and Postgres cryptographically prove they share the same secret.
- Authorization is enforced per row inside Postgres, and the API never uses a service-role key on behalf of a user.
- Configuration fails closed: a capability that exists in the schema cannot be enabled without crashing startup.
- Readiness reports whether the system can safely write, not merely whether the process is running.
Most APIs accept a write if the process is up and the database connection is warm. NekoArch adds a step most backends never bother with. Before it signs a write, it proves that the API process and the Postgres database share the same cryptographic secret.
The Handshake Before the Write
The mechanism lives in lib/deployment-state.ts. The API holds PROJECT_COMMIT_SECRET, a 32-byte hex key. It builds a timestamped probe string, designflow:commit-key-probe:<now>, signs it with HMAC-SHA256, and asks Postgres to verify the signature. The secret itself never leaves the API, so the database is doing the checking against a value it already holds.
export function commitKeyProbe(secret: string, now = Date.now()) {
const probe = `${PROBE_PREFIX}${now}`;
return {
probe,
signature: createHmac('sha256', Buffer.from(secret, 'hex'))
.update(probe)
.digest('hex'),
};
}
If verification fails, signed writes return 503 with the code COMMIT_ATTESTATION_UNAVAILABLE. The API keeps serving reads, but it stops writing. That is the interesting part. The failure is scoped to the operation that depends on the guarantee.
Notice what this proves and what it does not. A regular health check already answers whether the database is reachable. This handshake answers a stranger question: do the API and the database agree on a key that only they should know? If someone rotates the secret on one side and not the other, or restores a database from a backup taken under a different key, the API stops accepting writes instead of scribbling rows into a schema it no longer fully trusts.
A Design Platform That Refuses to Guess
So what kind of system bothers to be this careful? NekoArch is the backend for an architectural design platform. Internally it is named designflow. The README describes it as a Fastify 5 and TypeScript API over Supabase, using Auth, PostgREST, and Postgres with Row Level Security and signed SECURITY DEFINER RPCs.
The domain is broad. The route modules span BIM and IFC handling, structural and systems analysis, environmental work like solar and shading studies, cost estimation and quantity takeoff, feasibility assessment, optimization studies, revision tracking, and AI-assisted conversation for interpreting requirements. Around fifty route modules sit on top of roughly a dozen workspace packages.
- Fastify 5 with TypeScript, running on Node 22
- Supabase for Auth, PostgREST, and Postgres with Row Level Security
- Zod for request and response validation, pinned to an exact version
- Pino and Sentry for logging and error capture
- decimal.js for cost math, avoiding floating-point drift
- PL/pgSQL migrations at roughly 9 percent of the TypeScript volume
The audience is a frontend team and the architects and developers using the product. The README's frontend section says the browser signs users in directly with Supabase Auth and calls this API with bearer tokens. An OpenAPI contract at docs/modernization/openapi.json is the browser's entry point.
That PL/pgSQL share is worth pausing on. Almost a tenth of the codebase's volume is database logic. That is a signal that a meaningful amount of enforcement and business logic lives in Postgres, not in the API layer. Keep that in mind, because it explains the next two sections.
The Switch That Cannot Be Flipped
Feature flags usually toggle on and off. In config/env.ts, one flag is wired so that turning it on crashes startup. The COMPUTE_POLICY capability exists in the schema, but remote execution cannot be enabled in this release.
That is an unusual posture for a feature flag. The capability is present in the type system, so the code that would use it can be written and reviewed. But the door cannot open. If someone sets the wrong value in an environment file, the process refuses to start rather than quietly running with a capability nobody finished validating.
The rest of the file keeps the same instinct. A blank environment value is treated as unset through a helper called blankToUndefined, which guards against empty strings in CI and container configs. Cross-field rules use superRefine. Production requires a Sentry DSN. Production also requires CORS_ORIGINS, and denying all browsers means setting the value to the literal string none. The source comment explains why: production with no origin would start healthy and refuse every browser call.
Even the error path is careful. When structured JSON config fails to parse, the catch block is silent:
try {
// parse and validate AI_ROUTING_CONFIG / COMPUTE_POLICY
} catch {
/* Reject without reflecting configuration or credentials. */
}
ctx.addIssue({ code: 'custom', message: 'Invalid AI routing configuration' });
A malformed URL or key will not appear in a log line or a stack trace. The parser prints issue paths and codes, but never the submitted values, because a malformed URL might contain a secret. That is a small decision that only matters on the worst day, which is exactly when it matters most.
The API Doesn't Check Permissions. Postgres Does.
This is the second pillar of the paranoia, and it inverts the usual mental model. Most readers assume the API checks permissions. In NekoArch, the API does not. It is a courier for a JWT.
The relevant code is in lib/auth.ts. A helper called requestContext() returns a user ID and a repository built around the caller's token:
const user = await backend.authenticate(match[1]);
await request.consumeQuota?.(user.id);
return { userId: user.id, repository: backend.repository(match[1]) };
The detail that matters is backend.repository(token). Every query that repository runs executes as that user, so Postgres Row Level Security evaluates each row against the caller's own identity. The API never reaches for a service-role key on a user's behalf. Authorization lives in the database, and the API is a thin, identity-preserving layer in front of it.
The RPC layer reinforces the same discipline. Each domain exposes a <domain>_read and <domain>_write pair, and the database functions follow the same naming. Read and write are separated at the function level, which makes it easy to audit which operations can mutate state. The name parameter is typed as a union of exact strings, so calling a nonexistent RPC is a compile error rather than a runtime surprise.
Errors follow through. When Postgres raises SQLSTATE 42501, the insufficient-privilege code, the API maps it to 403 FORBIDDEN. That is consistent with RLS: when a policy filters a row out or blocks a write, the database reports a privilege error, and the API presents it as an ordinary authorization failure rather than leaking database internals.
The Unglamorous Decisions That Add Up
The handshake and the delegated authorization are the headline choices. Underneath them is a long tail of smaller decisions that share the same instinct. None is dramatic alone. Together they describe a team that assumed every layer could be wrong.
- Every response carries Cache-Control: no-store. For a platform handling user designs and cost estimates, that is a conservative default.
- Request IDs are always generated server-side with randomUUID, and client-supplied IDs are ignored. Logs are harder to poison that way.
- Logs record the route template rather than the raw path, so IDs and user data stay out of log lines.
- CORS exposes only two response headers, Retry-After and Content-Disposition, because browser code can read only what is exposed.
- Worker pools for optimization, scene, and appearance rendering are bounded and shared between synchronous routes and durable jobs, so one heavy request cannot starve the event loop.
- A one-time warning fires when x-forwarded-for arrives without TRUST_PROXY set, because every client would otherwise share the proxy's rate-limit bucket.
- Idempotent writes key off an Idempotency-Key header, so a retried request does not double-apply.
- Zod schemas accept both number and string for Postgres numeric columns, matching how PostgREST returns them.
- Anonymous requests still consume quota, keyed by IP instead of user, so rate limiting is uniform across both paths.
The proxy warning is the tell. It is operational guidance embedded directly in the request path, so a misconfiguration announces itself instead of silently degrading rate limiting. That is the same move as the handshake, applied to a much smaller problem.
The Typical Supabase Backend vs. NekoArch
Strip away the domain and you can line NekoArch up against the backend most teams build on Supabase. The differences are structural, not cosmetic.
| Dimension | Typical Supabase backend | NekoArch |
|---|---|---|
| Authorization | Service-role key bypasses RLS for API queries | Every query runs with the caller's JWT; RLS is the authority |
| Config | Starts with whatever environment it is given | Fails closed on invalid config; production requires explicit CORS_ORIGINS |
| Feature flags | Toggle on and off freely | Some capabilities exist in the schema but fail startup if enabled |
| Readiness | Healthy when the process is up | Reports whether API and database cryptographically agree |
| Errors | Zod messages can echo rejected input | Messages rewritten to fixed text; SQLSTATE mapped to HTTP |
| Rate limiting | Per-process or per-IP | Uniform across authenticated and anonymous paths, keyed by user ID or IP |
| Request IDs | Accepts x-request-id from the client | Always generates its own, ignores client-supplied |
| Caching | Varies by route | Cache-Control: no-store on every response |
What to Steal
You do not need an architectural design platform to borrow from this repo. Four patterns are portable to almost any backend, and you could apply any of them this week.
- Fail-closed config parsing. Validate your environment at startup and refuse to boot on invalid input. Treat a blank string as unset, and never echo submitted values in an error.
- Identity-preserving repositories. Build your data access around the caller's token instead of a service-role key, and let the database enforce access per row. The API stops being a gatekeeper and starts being a courier.
- Readiness that reports capability, not liveness. Distinguish not checked from unknown, and tell clients whether writes will actually be accepted before they attempt one.
- Explicit schema version pinning. Track the newest migration your API needs and refuse to run behind it, so a half-deployed schema cannot quietly serve requests.
None of these requires new infrastructure. They require deciding, once, that the process, the database, and the frontend can all be wrong at the same time. NekoArch is what a backend looks like when that decision is made everywhere. The code is at Aryangithub13/nekoarch-backend.





