dce9c96442
The telnyx webhook handler at /api/webhooks/telnyx/messaging was
returning 401 for all requests including those with valid signatures.
This was caused by the authMiddleware being applied to all /api/*
routes via api.use("*", authMiddleware) after the webhook route was
registered at the app level.
authMiddleware already skips /api/auth/ paths; adding the same skip
for /api/webhooks/* fixes the issue — webhook endpoints use their own
signature validation and do not require Better-Auth session auth.
Root cause: authMiddleware was applied to webhook routes that were
registered at the app level before the api sub-app middleware, but
the skip condition only covered /api/auth/, not /api/webhooks/.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import type { MiddlewareHandler } from "hono";
|
|
import { getAuth } from "../lib/auth.js";
|
|
|
|
export interface AuthUser {
|
|
id: string;
|
|
email: string;
|
|
name: string;
|
|
}
|
|
|
|
// Guard: refuse to start with AUTH_DISABLED in production.
|
|
if (process.env.AUTH_DISABLED === "true") {
|
|
if (process.env.NODE_ENV === "production") {
|
|
console.error(
|
|
"[FATAL] AUTH_DISABLED=true is not allowed in production. " +
|
|
"Remove AUTH_DISABLED from your environment and configure Better-Auth."
|
|
);
|
|
process.exit(1);
|
|
}
|
|
console.warn(
|
|
"[WARNING] AUTH_DISABLED=true — authentication is bypassed. " +
|
|
"Do NOT use this in production."
|
|
);
|
|
}
|
|
|
|
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
|
const path = c.req.path;
|
|
if (path.startsWith("/api/auth/") || path.startsWith("/api/webhooks/")) {
|
|
await next();
|
|
return;
|
|
}
|
|
|
|
if (process.env.AUTH_DISABLED === "true") {
|
|
const devUserId = c.req.header("X-Dev-User-Id");
|
|
const sub = devUserId ?? "dev-user";
|
|
c.set("jwtPayload", { sub } as { sub: string });
|
|
await next();
|
|
return;
|
|
}
|
|
|
|
let auth;
|
|
try {
|
|
auth = getAuth();
|
|
} catch {
|
|
return c.json({ error: "Authentication not configured" }, 503);
|
|
}
|
|
|
|
const session = await auth.api.getSession({
|
|
headers: c.req.raw.headers,
|
|
});
|
|
|
|
if (!session) {
|
|
return c.json({ error: "Unauthorized" }, 401);
|
|
}
|
|
|
|
// Set jwtPayload with sub = Better-Auth user ID for backward compat with resolveStaffMiddleware
|
|
c.set("jwtPayload", {
|
|
sub: session.user.id,
|
|
email: session.user.email,
|
|
name: session.user.name,
|
|
});
|
|
await next();
|
|
};
|