Files
outline/server/middlewares/authentication.ts
T
Tom MoorandClaude Opus 5.5 00b124d03c chore: Rename APIContext to Context and flatten its fields (#14684)
* chore: Rename APIContext to Context and flatten its fields

Auth and transaction now live directly on the context instead of in
ctx.state and a nested ctx.context, and model helpers read them directly.
APIContext remains as a deprecated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove deprecated APIContext alias

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* fix: Read auth from context in OAuth provider callbacks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Add withUser and withTransaction context helpers

Replaces manual createContext rebuilds that copy fields from an existing context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove arbitrary property access from Koa context types

AppContext and Context no longer inherit the any index signature from
Koa's DefaultContext, custom fields are declared explicitly, and importing
Koa's loose Context type is disallowed by lint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-23 23:17:06 -05:00

320 lines
8.3 KiB
TypeScript

import type { Next } from "koa";
import { capitalize } from "es-toolkit/compat";
import httpErrors from "http-errors";
import type { UserRole } from "@shared/types";
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
import tracer, {
addTags,
getRootSpanFromRequestContext,
} from "@server/logging/tracer";
import { User, Team, ApiKey, OAuthAuthentication } from "@server/models";
import { optionalWrite } from "@server/storage/database";
import type { AppContext } from "@server/types";
import { AuthenticationType } from "@server/types";
import { getUserForJWT } from "@server/utils/jwt";
import {
AuthenticationError,
AuthorizationError,
UserSuspendedError,
} from "../errors";
type BaseAuthenticationOptions = {
/** Role required to access the route. */
role?: UserRole;
/** Type of authentication required to access the route. */
type?: AuthenticationType | AuthenticationType[];
/** Transports the token may be received from, defaults to all. */
transports?: AuthTransport[];
};
type AuthenticationOptions =
| (BaseAuthenticationOptions & {
/** Authentication is required. */
optional?: false;
skip?: never;
})
| (BaseAuthenticationOptions & {
/** Authentication is parsed, but optional. */
optional: true;
/**
* Returns true when the request is authorized by other means, in which
* case any credentials on the request are ignored rather than parsed.
*/
skip?: (ctx: AppContext) => boolean;
});
type AuthTransport = "cookie" | "header" | "body" | "query";
type AuthInput = {
/** The authentication token extracted from the request, if any. */
token?: string;
/** The method used to receive the authentication token. */
transport?: AuthTransport;
};
export default function auth(options: AuthenticationOptions = {}) {
return async function authMiddleware(ctx: AppContext, next: Next) {
if (options.skip?.(ctx)) {
ctx.auth = {};
return next();
}
try {
const { type, token, user, service, scope } =
await validateAuthentication(ctx, options);
await optionalWrite(() =>
Promise.all([user.updateActiveAt(ctx), user.team?.updateActiveAt()])
);
ctx.auth = {
user,
token,
type,
service,
scope,
};
if (tracer) {
addTags(
{
"request.userId": user.id,
"request.teamId": user.teamId,
"request.authType": type,
},
getRootSpanFromRequestContext(ctx)
);
}
} catch (err) {
// Credentials that are valid but insufficient are always surfaced,
// otherwise the request would be silently downgraded to anonymous.
if (options.optional && !(err instanceof httpErrors.Forbidden)) {
ctx.auth = {};
} else {
throw err;
}
}
return next();
};
}
/**
* Parses the authentication token from the request context.
*
* @param ctx The application context containing the request information.
* @param transports The transports to read the token from, defaults to all.
* @returns An object containing the token and its transport method.
*/
export function parseAuthentication(
ctx: AppContext,
transports?: AuthTransport[]
): AuthInput {
const isAllowed = (transport: AuthTransport) =>
!transports || transports.includes(transport);
const authorizationHeader = isAllowed("header")
? ctx.request.get("authorization")
: undefined;
if (authorizationHeader) {
const parts = authorizationHeader.split(" ");
if (parts.length === 2) {
const scheme = parts[0];
const credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
return {
token: credentials,
transport: "header",
};
}
} else {
throw AuthenticationError(
`Bad Authorization header format. Format is "Authorization: Bearer <token>"`
);
}
} else if (
isAllowed("body") &&
ctx.request.body &&
typeof ctx.request.body === "object" &&
"token" in ctx.request.body
) {
return {
token: String(ctx.request.body.token),
transport: "body",
};
} else if (isAllowed("query") && ctx.request.query?.token) {
return {
token: String(ctx.request.query.token),
transport: "query",
};
} else if (isAllowed("cookie")) {
const accessToken = ctx.cookies.get("accessToken");
if (accessToken) {
return {
token: accessToken,
transport: "cookie",
};
}
}
return {
token: undefined,
transport: undefined,
};
}
async function validateAuthentication(
ctx: AppContext,
options: AuthenticationOptions
): Promise<{
user: User;
token: string;
type: AuthenticationType;
service?: string;
scope?: string[];
}> {
const { token, transport } = parseAuthentication(ctx, options.transports);
if (!token) {
throw AuthenticationError("Authentication required");
}
let user: User | null;
let type: AuthenticationType;
let service: string | undefined;
let scope: string[] | undefined;
if (OAuthAuthentication.match(token)) {
if (transport !== "header") {
throw AuthenticationError(
"OAuth access token must be passed in the Authorization header"
);
}
type = AuthenticationType.OAUTH;
let authentication;
try {
authentication = await OAuthAuthentication.findByAccessToken(token, {
rejectOnEmpty: true,
});
} catch (_err) {
throw AuthenticationError("Invalid access token");
}
if (!authentication) {
throw AuthenticationError("Invalid access token");
}
if (authentication.accessTokenExpiresAt < new Date()) {
throw AuthenticationError("Access token is expired");
}
if (!authentication.canAccess(ctx.originalUrl)) {
throw AuthorizationError(
"Access token does not have access to this resource"
);
}
user = await User.findByPk(authentication.userId, {
include: [
{
model: Team,
as: "team",
required: true,
},
],
});
if (!user) {
throw AuthenticationError("Invalid access token");
}
scope = authentication.scope;
await optionalWrite(authentication.updateActiveAt);
} else if (ApiKey.match(token)) {
if (transport === "cookie") {
throw AuthenticationError("API key must not be passed in the cookie");
}
type = AuthenticationType.API;
let apiKey;
try {
apiKey = await ApiKey.findByToken(token);
} catch (_err) {
throw AuthenticationError("Invalid API key");
}
if (!apiKey) {
throw AuthenticationError("Invalid API key");
}
if (apiKey.expiresAt && apiKey.expiresAt < new Date()) {
throw AuthenticationError("API key is expired");
}
if (!apiKey.canAccess(ctx.originalUrl)) {
throw AuthorizationError("API key does not have access to this resource");
}
user = await User.findByPk(apiKey.userId, {
include: [
{
model: Team,
as: "team",
required: true,
},
],
});
if (!user) {
throw AuthenticationError("Invalid API key");
}
scope = apiKey.scope ?? ["*"];
await optionalWrite(apiKey.updateActiveAt);
} else {
// Session tokens are long-lived, so keep them out of transports that end up
// in browser history, referrers, and request logs.
if (transport !== "cookie" && transport !== "header") {
throw AuthenticationError(
"Session token must be passed in the cookie or Authorization header"
);
}
type = AuthenticationType.APP;
const result = await getUserForJWT(token);
user = result.user;
service = result.service;
}
if (user.isSuspended) {
const suspendingAdmin = user.suspendedById
? await User.findByPk(user.suspendedById)
: undefined;
throw UserSuspendedError({
adminEmail: suspendingAdmin?.email || undefined,
});
}
if (options.role && UserRoleHelper.isRoleLower(user.role, options.role)) {
throw AuthorizationError(`${capitalize(options.role)} role required`);
}
if (
options.type &&
(Array.isArray(options.type)
? !options.type.includes(type)
: type !== options.type)
) {
throw AuthorizationError(`Invalid authentication type`);
}
return {
user,
type,
token,
service,
scope,
};
}