Files
Tom MoorandClaude Opus 5.5 5647621224 chore: Prune redundant comments and type suppressions (#14124)
* chore: Prune redundant comments and normalize lint directives

Removes comments that restate the following line and stale TODOs, drops
the passive event listener feature check now that all supported browsers
support it, and renames eslint directives to oxlint.

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

* fix: Evaluate restricted team domains at validation time

The restricted email provider list was captured when the model loaded, so
it could not follow the hosting environment and the tests that covered it
never reached the model.

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

* chore: Replace type suppressions with accurate types

Adds a Concrete helper type for registries of abstract classes, declares
missing Sequelize and refractor typings, uses public ProseMirror APIs, a
typed mock context helper in middleware tests, and a StaticLink component
for sidebar rows being edited.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-17 17:07:39 -04:00

453 lines
14 KiB
TypeScript

import crypto from "node:crypto";
import { addMinutes, subMinutes } from "date-fns";
import { HttpsProxyAgent } from "https-proxy-agent";
import type { JwtPayload } from "jsonwebtoken";
import type { Context, Next } from "koa";
import type { Strategy } from "@outlinewiki/koa-passport";
import type { StateStoreStoreCallback } from "passport-oauth2";
import type { Primitive } from "utility-types";
import { errToString, toError } from "@shared/utils/error";
import { Client } from "@shared/types";
import { getCookieDomain, parseDomain } from "@shared/utils/domains";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import { Team, User } from "@server/models";
import Redis from "@server/storage/redis";
import { InternalError, OAuthStateMismatchError } from "../errors";
import { hash, safeEqual } from "./crypto";
import fetch from "./fetch";
import { getUserForJWT } from "./jwt";
import { parseUserInfoResponse } from "./oauth";
import {
hashOAuthStateNonce,
signOAuthIntent,
signOAuthState,
verifyOAuthIntent,
verifyOAuthState,
} from "./oauthState";
// With PKCE the library expects the code verifier in place of the boolean result.
type PKCEStateStoreVerifyCallback = (
err: Error | null,
result: string | boolean,
state: string
) => void;
const FLOW_QUERY_PARAM = "flow";
const OAUTH_CSRF_COOKIE = "oauth_csrf";
const OAUTH_INTENT_PREFIX = "oauth:intent:";
const OAUTH_INTENT_TTL_SECONDS = 10 * 60;
const ACTOR_SESSION_HASH_KEYLEN = 64;
/**
* Middleware for OAuth start routes that bridges cookie scopes between custom
* team domains and the apex (env.URL) where the OAuth callback always lands.
*
* The OAuth callback always lands on the apex domain, while a user's
* `accessToken` session cookie may be host-scoped to a custom team domain. To
* make the "connect a new auth provider while signed in" flow work from a
* custom domain:
*
* 1. On a custom team domain — create a short-lived signed intent containing
* the original host and actor id, then bounce to the apex with it.
* 2. On the apex — verify the signed intent and stash it on `ctx.state` so
* `StateStore.store` can fold it into the signed OAuth `state` parameter.
*
* Non-custom team subdomains skip the bounce because the start route can read
* the host-scoped session and set the OAuth CSRF cookie on the base domain for
* the apex callback. Self-hosted deployments have a single domain and pass
* through.
*/
export async function startOAuthFlow(ctx: Context, next: Next) {
if (!env.isCloudHosted) {
return next();
}
const apex = new URL(env.URL);
const onApex = ctx.hostname === apex.hostname;
const isCustom = parseDomain(ctx.hostname).custom;
if (isCustom && !onApex) {
const url = new URL(ctx.originalUrl, apex);
const client = getClientFromInput(ctx);
const actor = await getOAuthActor(ctx);
const flow = signOAuthIntent({
host: ctx.hostname,
actorId: actor?.id,
actorSessionHash: actor ? getActorSessionHash(actor) : undefined,
client,
});
url.searchParams.delete(FLOW_QUERY_PARAM);
url.searchParams.set(FLOW_QUERY_PARAM, flow);
await storeOAuthIntent(flow);
return ctx.redirect(url.toString());
}
const flow = ctx.query[FLOW_QUERY_PARAM];
if (onApex && typeof flow === "string" && flow) {
try {
const intent = verifyOAuthIntent(flow);
if (await consumeOAuthIntent(flow)) {
ctx.state.oauthIntent = intent;
}
} catch {
// Invalid or expired intent — proceed without an actor.
// The user can still complete the OAuth flow as a fresh sign-in.
}
}
return next();
}
/**
* Routes a passport OAuth2 strategy's outbound token and userinfo requests
* through the HTTPS proxy configured in the environment, when present.
*
* Passport OAuth2 strategies build their own HTTP client and do not honor the
* standard proxy environment variables, so the agent must be attached to the
* strategy's internal `_oauth2` client explicitly. This is a no-op when no
* proxy is configured.
*
* @param strategy the OAuth2-based passport strategy to configure.
* @returns the same strategy instance, for convenient chaining.
*/
export function withProxyAgent<T extends Strategy>(strategy: T): T {
const proxy = process.env.https_proxy ?? process.env.HTTPS_PROXY;
if (!proxy) {
return strategy;
}
// `_oauth2` is a private internal, so degrade gracefully if upstream removes it.
// @ts-expect-error _oauth2 is not part of the public strategy type
const client = strategy._oauth2;
if (typeof client?.setAgent !== "function") {
Logger.warn(
"Unable to apply HTTPS proxy to auth strategy; the OAuth2 client is not available",
{ strategy: strategy.name }
);
return strategy;
}
client.setAgent(new HttpsProxyAgent(proxy));
return strategy;
}
/**
* Passport OAuth state store backed by signed state and a CSRF nonce cookie.
*/
export class StateStore {
constructor(private pkce = false) {}
key = "state";
store = (
ctx: Context,
verifierOrCallback: StateStoreStoreCallback | string,
_state?: Record<string, Primitive>,
_meta?: unknown,
cb?: StateStoreStoreCallback
) => {
const context = getKoaContext(ctx);
const csrfNonce = crypto.randomBytes(16).toString("hex");
// Note parameters are based on whether PKCE is in use or not, this is parameters
// of how the underlying library is architected, see:
// https://github.com/jaredhanson/passport-oauth2/blob/be9bf58cee75938c645a9609f0cc87c4c724e7c8/lib/strategy.js#L289-L298
const callback =
typeof verifierOrCallback === "function" ? verifierOrCallback : cb;
if (!callback) {
throw InternalError("Callback is required");
}
const codeVerifier =
typeof verifierOrCallback === "function" ? undefined : verifierOrCallback;
// We expect host to be a team subdomain, custom domain, or apex domain
// that is passed via query param from the auth provider component.
const client =
context.state.oauthIntent?.client ?? getClientFromInput(context);
const host =
context.state.oauthIntent?.host ??
context.query.host?.toString() ??
parseDomain(context.hostname).host;
const actorId =
context.state.oauthIntent?.actorId ?? getAuthenticatedUserId(context);
const actorSessionHash =
context.state.oauthIntent?.actorSessionHash ??
getAuthenticatedUserSessionHash(context);
const state = signOAuthState({
host,
actorId,
actorSessionHash,
client,
codeVerifier,
nonceHash: hashOAuthStateNonce(csrfNonce),
});
context.cookies.set(OAUTH_CSRF_COOKIE, csrfNonce, {
httpOnly: true,
sameSite: "lax",
secure: context.request.secure,
expires: addMinutes(new Date(), 10),
domain: getCookieDomain(context.hostname, env.isCloudHosted),
});
callback(null, state);
};
verify = (
ctx: Context,
providedToken: string,
callback: PKCEStateStoreVerifyCallback
) => {
const context = getKoaContext(ctx);
const csrfNonce = context.cookies.get(OAUTH_CSRF_COOKIE);
context.cookies.set(OAUTH_CSRF_COOKIE, "", {
httpOnly: true,
sameSite: "lax",
secure: context.request.secure,
expires: subMinutes(new Date(), 1),
domain: getCookieDomain(context.hostname, env.isCloudHosted),
});
let state;
try {
state = verifyOAuthState(providedToken);
} catch (err) {
return callback(toError(err), false, providedToken);
}
if (!safeEqual(hashOAuthStateNonce(csrfNonce ?? ""), state.nonceHash)) {
return callback(
OAuthStateMismatchError("OAuth CSRF nonce mismatched"),
false,
providedToken
);
}
context.state.oauthState = state;
callback(null, state.codeVerifier ?? true, providedToken);
};
}
/**
* Perform an authenticated request against an OAuth provider endpoint and
* parse the response body. Handles both JSON responses and, for OIDC userinfo
* endpoints configured for signed responses, `application/jwt` bodies.
*
* @param method The HTTP method to use.
* @param endpoint The endpoint to request.
* @param accessToken The access token to authenticate with.
* @returns The parsed response body.
* @throws {InternalError} When the response body cannot be parsed.
*/
export async function request<T = JwtPayload>(
method: "GET" | "POST",
endpoint: string,
accessToken: string
): Promise<T> {
const response = await fetch(endpoint, {
method,
allowPrivateIPAddress: true,
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
try {
return await parseUserInfoResponse<T>(response);
} catch (err) {
throw InternalError(
`Failed to parse response from ${endpoint}. ${errToString(err)}`
);
}
}
/**
* Parses the state string into its components.
*
* @param state The state string
* @returns An object containing the parsed components, if valid.
*/
export function parseState(state: string) {
try {
return verifyOAuthState(state);
} catch {
return undefined;
}
}
/**
* Returns the client type from the context if available. Used to redirect
* the user back to the correct client after the OAuth flow.
*
* @param ctx The Koa context
* @returns The client type, defaults to Client.Web
*/
export function getClientFromOAuthState(ctx: Context): Client {
const context = getKoaContext(ctx);
const client = context.state.oauthState?.client;
return client === Client.Desktop ? Client.Desktop : Client.Web;
}
/**
* Returns the actor referenced by verified OAuth state, if available. This is
* used to restore the originating user during the OAuth flow when connecting
* additional providers to an existing team.
*
* @param ctx The Koa context
* @returns The actor if available, otherwise undefined
*/
export async function getUserFromOAuthState(ctx: Context) {
const context = getKoaContext(ctx);
const state = context.state.oauthState;
if (!state?.actorId || !state.actorSessionHash) {
return undefined;
}
const user = await User.scope("withTeam").findByPk(state.actorId);
if (!user) {
return undefined;
}
if (!safeEqual(getActorSessionHash(user), state.actorSessionHash)) {
return undefined;
}
return user;
}
type TeamFromContextOptions = {
/**
* Whether to consider OAuth state in the context when determining the team.
* If true, OAuth state will be used to determine the host and infer the team
* this should only be used in the authentication process.
*/
includeOAuthState?: boolean;
/**
* Whether to consider the host query parameter in the context when determining the team.
* If true, the host query parameter will be used to determine the host and infer the team
*/
includeHostQueryParam?: boolean;
};
/**
* Infers the team from the context based on the hostname or OAuth state.
*
* @param ctx The Koa context
* @param options Options for determining the team
* @returns The inferred team or undefined if not found
*/
export async function getTeamFromContext(
ctx: Context,
options: TeamFromContextOptions = { includeOAuthState: true }
) {
const context = getKoaContext(ctx);
// "domain" is the domain the user came from when attempting auth
// we use it to infer the team they intend on signing into
const includeOAuthState = options.includeOAuthState ?? true;
const state = includeOAuthState
? (context.state.oauthState ?? context.state.oauthIntent)
: undefined;
const queryHost =
options.includeHostQueryParam && typeof context.query.host === "string"
? context.query.host
: undefined;
const host = state?.host ?? queryHost ?? context.hostname;
const domain = parseDomain(host);
let team;
if (!env.isCloudHosted) {
if (env.ENVIRONMENT === "test") {
team = await Team.findByDomain(env.URL);
} else {
team = await Team.findOne({
order: [["createdAt", "DESC"]],
});
}
} else if (context.state?.rootShare) {
team = await Team.findByPk(context.state.rootShare.teamId);
} else if (domain.custom) {
team = await Team.findByDomain(domain.host);
} else if (domain.teamSubdomain) {
team = await Team.findBySubdomain(domain.teamSubdomain);
}
return team;
}
function getClientFromInput(ctx: Context): Client {
const clientInput = ctx.query.client?.toString();
return clientInput === Client.Desktop ? Client.Desktop : Client.Web;
}
function getAuthenticatedUser(ctx: Context): User | undefined {
return ctx.state.auth && "user" in ctx.state.auth
? ctx.state.auth.user
: undefined;
}
function getAuthenticatedUserId(ctx: Context): string | undefined {
return getAuthenticatedUser(ctx)?.id;
}
function getAuthenticatedUserSessionHash(ctx: Context): string | undefined {
const user = getAuthenticatedUser(ctx);
return user ? getActorSessionHash(user) : undefined;
}
async function getOAuthActor(ctx: Context): Promise<User | undefined> {
const authenticatedUser = getAuthenticatedUser(ctx);
if (authenticatedUser) {
return authenticatedUser;
}
const accessToken = ctx.cookies.get("accessToken");
if (!accessToken) {
return undefined;
}
try {
const { user } = await getUserForJWT(accessToken);
return user;
} catch {
return undefined;
}
}
function getActorSessionHash(user: User): string {
return crypto
.scryptSync(
user.jwtSecret,
`oauth-actor-session:${env.SECRET_KEY}:${user.id}`,
ACTOR_SESSION_HASH_KEYLEN
)
.toString("hex");
}
async function storeOAuthIntent(token: string): Promise<void> {
await Redis.defaultClient.set(
getOAuthIntentKey(token),
"1",
"EX",
OAUTH_INTENT_TTL_SECONDS
);
}
async function consumeOAuthIntent(token: string): Promise<boolean> {
const result = await Redis.defaultClient.getdel(getOAuthIntentKey(token));
return result === "1";
}
function getOAuthIntentKey(token: string): string {
return `${OAUTH_INTENT_PREFIX}${hash(token)}`;
}
function getKoaContext(ctx: Context): Context {
return (ctx as Context & { ctx?: Context }).ctx ?? ctx;
}