auth-yes/server/rpc.ts
google-labs-jules[bot] 88821b80af feat: Phase 3 Monolith decomposition of server/main.ts
- Extracts Auth, Registration, and Passkey routes into `server/routes/auth.ts`.
- Extracts all Admin API endpoints into `server/routes/admin.ts`.
- Extracts RPC Connect setup and mTLS listener into `server/rpc.ts`.
- Extracts global rate limiters and IP helpers into `server/middleware.ts`.
- Reduces `server/main.ts` purely to an entrypoint mounting orchestrator.
- Ensures all existing tests and quality gates pass with zero regressions.

Co-authored-by: mrteye <1945243+mrteye@users.noreply.github.com>
2026-08-26 03:23:20 +00:00

174 lines
4.7 KiB
TypeScript

import { AuthService } from "../sdk/gen/auth_connect.ts";
import {
universalServerRequestFromFetch,
universalServerResponseToFetch,
} from "npm:@connectrpc/connect@^1.4.0/protocol";
import type { ConnectRouter } from "npm:@connectrpc/connect@^1.4.0";
import { createConnectRouter } from "npm:@connectrpc/connect@^1.4.0";
import type { Hono } from "jsr:@hono/hono@4";
import { spireWrapper } from "./spire_ffi.ts";
import { sqlWrapper } from "./db.ts";
import { valkey } from "./valkey.ts";
import { auditWrapper } from "./audit.ts";
export const connectRoutes = (router: ConnectRouter) => {
router.service(AuthService, {
async validateSession(req, context) {
try {
const spiffeId = spireWrapper.extractSpiffeIdFromCert(
context.requestHeader.get("x-peer-cert") || "",
);
if (!spiffeId) {
return {
valid: false,
uuid: "",
scopes: [],
error: "Validation failed", // Sanitized
};
}
// Check if the SPIFFE ID is a recognized application
const appRecord = await sqlWrapper
.sql`SELECT id FROM apps WHERE spiffe_id = ${spiffeId}`.then((
res: any,
) => res[0]);
if (!appRecord) {
auditWrapper.auditLog(null, "session_validation_failed", null, {
reason: "Unauthorized SPIFFE ID",
}, "internal-grpc");
return {
valid: false,
uuid: "",
scopes: [],
error: "Validation failed", // Sanitized
};
}
const token = req.token;
if (!token) {
return {
valid: false,
uuid: "",
scopes: [],
error: "Validation failed",
}; // Sanitized
}
let sessionDataStr;
try {
sessionDataStr = await valkey.get(token);
} catch (err: unknown) {
console.error("Valkey error during validateSession:", err);
return {
valid: false,
uuid: "",
scopes: [],
error: "Internal server error",
};
}
if (!sessionDataStr) {
auditWrapper.auditLog(
null,
"session_validation_failed",
appRecord.id,
{
reason: "Session invalid or expired",
},
"internal-grpc",
);
return {
valid: false,
uuid: "",
scopes: [],
error: "Validation failed", // Sanitized
};
}
let sessionData;
try {
sessionData = JSON.parse(sessionDataStr);
} catch (err: unknown) {
console.error("JSON parse error during validateSession:", err);
return {
valid: false,
uuid: "",
scopes: [],
error: "Internal server error", // Sanitized
};
}
if (!sessionData || !sessionData.uuid) {
return {
valid: false,
uuid: "",
scopes: [],
error: "Internal server error", // Sanitized
};
}
const userId = sessionData.uuid;
// Check RBAC grant for the user and app
const grantRecord = await sqlWrapper
.sql`SELECT role FROM grants WHERE user_id = ${userId} AND app_id = ${appRecord.id}`
.then((res: any) => res[0]);
if (!grantRecord) {
auditWrapper.auditLog(
userId,
"session_validation_failed",
appRecord.id,
{
reason: "Access denied (RBAC)",
},
"internal-grpc",
);
return {
valid: false,
uuid: "",
scopes: [],
error: "Validation failed",
}; // Sanitized
}
return {
valid: true,
uuid: userId,
scopes: [grantRecord.role],
error: "",
};
} catch (err: unknown) {
console.error("Unexpected error in validateSession:", err);
return {
valid: false,
uuid: "",
scopes: [],
error: "Internal server error",
};
}
},
});
};
export const startConnectRpcServer = (app: Hono) => {
const router = createConnectRouter();
connectRoutes(router);
const handlers = router.handlers;
app.all("/auth.v1.AuthService/*", async (c) => {
const url = new URL(c.req.url);
const handler = handlers.find((h) => h.requestPath === url.pathname);
if (!handler) {
return new Response("Not Found", { status: 404 });
}
const uReq = universalServerRequestFromFetch(c.req.raw, {});
const uRes = await handler(uReq);
return universalServerResponseToFetch(uRes);
});
};