wcz-layout
Version:
50 lines (49 loc) • 2.52 kB
JavaScript
import { n as getProviderByIssuer } from "./providers-DOFje2P6.mjs";
import { t as getSessionUser } from "./user-Bc2nLjAG.mjs";
import { i as buildUser, s as hasPermission } from "./utils-CgabUlDD.mjs";
import { createMiddleware } from "@tanstack/react-start";
import * as jose from "jose";
// src/middleware/authMiddleware.ts
/**
* Verifies a Bearer JWT from a sibling service. The unverified `iss` only selects
* which provider to check against — the real check pins that provider's JWKS,
* issuer and (where the provider has one) audience.
*/
async function verifyBearer(token) {
const provider = getProviderByIssuer(jose.decodeJwt(token).iss);
if (!provider) throw new Error("Unauthorized: Unknown token issuer");
const { payload } = await jose.jwtVerify(token, provider.jwks, {
issuer: provider.issuer,
audience: provider.audience
});
return buildUser(payload, provider.id);
}
async function resolveUser(request) {
const authHeader = request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) try {
return await verifyBearer(authHeader.substring(7));
} catch (error) {
throw Response.json({ message: error instanceof Error ? error.message : "Unauthorized: Invalid access token" }, { status: 401 });
}
return getSessionUser();
}
/**
* Puts the caller in `context.user` — Bearer or cookie, `null` when anonymous —
* without requiring one. Deliberately a single instance, not a factory:
* `flattenMiddlewares` dedupes by object identity, so every middleware that
* declares this one as a dependency shares one resolution per request.
*/
const userMiddleware = createMiddleware().server(async ({ next, request }) => next({ context: { user: await resolveUser(request) } }));
/**
* Server-function guard, the counterpart to `requireAuth` on routes.
*
* - `authMiddleware()` — 401 unless a user is signed in (cookie or Bearer).
* - `authMiddleware("admin")` — also 403 unless they hold that permission.
*/
const authMiddleware = (permissionKey) => createMiddleware().middleware([userMiddleware]).server(async ({ next, context: { user } }) => {
if (!user) throw Response.json({ message: "Unauthorized: User not signed in" }, { status: 401 });
if (permissionKey && !hasPermission(user, permissionKey)) throw Response.json({ message: `Forbidden: User ${user.name} is not authorized to access this resource` }, { status: 403 });
return next({ context: { user } });
});
export { userMiddleware as n, authMiddleware as t };
//# sourceMappingURL=authMiddleware-D4GSt7m9.mjs.map