mirror of
https://github.com/outline/outline.git
synced 2026-11-25 15:15:15 +03:00
* 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>
227 lines
6.8 KiB
TypeScript
227 lines
6.8 KiB
TypeScript
import { subHours, subMinutes } from "date-fns";
|
|
import Router from "@koa/router";
|
|
import { uniqBy } from "es-toolkit/compat";
|
|
import { TeamPreference } from "@shared/types";
|
|
import { parseDomain } from "@shared/utils/domains";
|
|
import { getActiveSessions } from "@shared/utils/sessions";
|
|
import env from "@server/env";
|
|
import auth from "@server/middlewares/authentication";
|
|
import { transaction } from "@server/middlewares/transaction";
|
|
import { Event, Team } from "@server/models";
|
|
import AuthenticationHelper from "@server/models/helpers/AuthenticationHelper";
|
|
import {
|
|
presentUser,
|
|
presentTeam,
|
|
presentPolicies,
|
|
presentProviderConfig,
|
|
presentAvailableTeam,
|
|
presentGroup,
|
|
presentGroupUser,
|
|
} from "@server/presenters";
|
|
import ValidateSSOAccessTask from "@server/queues/tasks/ValidateSSOAccessTask";
|
|
import type { Context } from "@server/types";
|
|
import { AuthenticationType } from "@server/types";
|
|
import { clearCSRFCookie } from "@server/utils/csrf";
|
|
import { getJWTPayload } from "@server/utils/jwt";
|
|
import { SessionsCookieHelper } from "@server/utils/SessionsCookieHelper";
|
|
import RateLimiter from "@server/utils/RateLimiter";
|
|
import type * as T from "./schema";
|
|
|
|
const router = new Router();
|
|
|
|
router.post("auth.config", async (ctx: Context<T.AuthConfigReq>) => {
|
|
// If self hosted AND there is only one team then that team becomes the
|
|
// brand for the knowledge base and its guest sign-in option is used for the
|
|
// root login page.
|
|
if (!env.isCloudHosted) {
|
|
const team = await Team.scope("withAuthenticationProviders").findOne({
|
|
order: [["createdAt", "DESC"]],
|
|
});
|
|
|
|
if (team) {
|
|
ctx.body = {
|
|
data: {
|
|
name: team.name,
|
|
customTheme: team.getPreference(TeamPreference.CustomTheme),
|
|
logo: team.getPreference(TeamPreference.PublicBranding)
|
|
? team.avatarUrl
|
|
: undefined,
|
|
providers: (await AuthenticationHelper.providersForTeam(team)).map(
|
|
presentProviderConfig
|
|
),
|
|
},
|
|
};
|
|
return;
|
|
}
|
|
}
|
|
|
|
const domain = parseDomain(ctx.request.hostname);
|
|
|
|
if (domain.custom) {
|
|
const team = await Team.scope("withAuthenticationProviders").findOne({
|
|
where: {
|
|
domain: ctx.request.hostname.toLowerCase(),
|
|
},
|
|
});
|
|
|
|
if (team) {
|
|
ctx.body = {
|
|
data: {
|
|
name: team.name,
|
|
customTheme: team.getPreference(TeamPreference.CustomTheme),
|
|
logo: team.getPreference(TeamPreference.PublicBranding)
|
|
? team.avatarUrl
|
|
: undefined,
|
|
hostname: ctx.request.hostname,
|
|
providers: (await AuthenticationHelper.providersForTeam(team)).map(
|
|
presentProviderConfig
|
|
),
|
|
},
|
|
};
|
|
return;
|
|
}
|
|
}
|
|
|
|
// If subdomain signin page then we return minimal team details to allow
|
|
// for a custom screen showing only relevant signin options for that team.
|
|
else if (env.isCloudHosted && domain.teamSubdomain) {
|
|
const team = await Team.scope("withAuthenticationProviders").findOne({
|
|
where: {
|
|
subdomain: domain.teamSubdomain,
|
|
},
|
|
});
|
|
|
|
if (team) {
|
|
ctx.body = {
|
|
data: {
|
|
name: team.name,
|
|
customTheme: team.getPreference(TeamPreference.CustomTheme),
|
|
logo: team.getPreference(TeamPreference.PublicBranding)
|
|
? team.avatarUrl
|
|
: undefined,
|
|
hostname: ctx.request.hostname,
|
|
providers: (await AuthenticationHelper.providersForTeam(team)).map(
|
|
presentProviderConfig
|
|
),
|
|
},
|
|
};
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Otherwise, we're requesting from the standard root signin page
|
|
ctx.body = {
|
|
data: {
|
|
providers: (await AuthenticationHelper.providersForTeam()).map(
|
|
presentProviderConfig
|
|
),
|
|
},
|
|
};
|
|
});
|
|
|
|
/** Authentication services that don't require SSO validation. */
|
|
const NON_SSO_SERVICES = ["email", "passkeys"];
|
|
|
|
router.post("auth.info", auth(), async (ctx: Context<T.AuthInfoReq>) => {
|
|
const { user, service, type, token } = ctx.auth;
|
|
const [team, groups, availableTeams] = await Promise.all([
|
|
Team.scope("withDomains").findByPk(user.teamId, {
|
|
rejectOnEmpty: true,
|
|
}),
|
|
user.groups(),
|
|
user.availableTeams(),
|
|
]);
|
|
const expiresAt =
|
|
type === AuthenticationType.APP
|
|
? getJWTPayload(token).expiresAt
|
|
: undefined;
|
|
const rememberedTeams = await SessionsCookieHelper.reconcile(
|
|
ctx,
|
|
type === AuthenticationType.APP ? team : undefined,
|
|
typeof expiresAt === "string" ? new Date(expiresAt) : undefined
|
|
);
|
|
const signedInTeamIds = new Set(
|
|
Object.keys(getActiveSessions(SessionsCookieHelper.read(ctx)))
|
|
);
|
|
|
|
// If the user did not _just_ sign in then we need to check if they continue
|
|
// to have access to the workspace they are signed into. This only applies
|
|
// to SSO sessions - email and passkey logins don't have associated
|
|
// UserAuthentication records that need validation.
|
|
const requiresSSOValidation = !service || !NON_SSO_SERVICES.includes(service);
|
|
if (
|
|
requiresSSOValidation &&
|
|
user.lastSignedInAt &&
|
|
user.lastSignedInAt < subHours(new Date(), 1)
|
|
) {
|
|
await new ValidateSSOAccessTask()
|
|
.schedule({
|
|
userId: user.id,
|
|
})
|
|
.catch(() => {
|
|
// Ignore errors from duplicate jobId when a validation is already queued
|
|
});
|
|
}
|
|
|
|
ctx.body = {
|
|
data: {
|
|
user: presentUser(user, {
|
|
includeDetails: true,
|
|
}),
|
|
team: presentTeam(team),
|
|
groups: await Promise.all(groups.map(presentGroup)),
|
|
groupUsers: groups.map((group) => presentGroupUser(group.groupUsers[0])),
|
|
// The collaboration token is only for the client and should not be issued
|
|
// to API or OAuth consumers
|
|
collaborationToken:
|
|
type === AuthenticationType.APP
|
|
? user.getCollaborationToken()
|
|
: undefined,
|
|
availableTeams: uniqBy([...rememberedTeams, ...availableTeams], "id").map(
|
|
(availableTeam) =>
|
|
presentAvailableTeam(
|
|
availableTeam,
|
|
signedInTeamIds.has(availableTeam.id) ||
|
|
availableTeam.id === user.teamId
|
|
)
|
|
),
|
|
},
|
|
policies: presentPolicies(user, [team, user, ...groups]),
|
|
};
|
|
});
|
|
|
|
router.post(
|
|
"auth.delete",
|
|
auth(),
|
|
transaction(),
|
|
async (ctx: Context<T.AuthDeleteReq>) => {
|
|
const { auth, transaction } = ctx;
|
|
const { user, token } = auth;
|
|
|
|
await user.rotateJwtSecret({ transaction });
|
|
await Event.createFromContext(ctx, {
|
|
name: "users.signout",
|
|
userId: user.id,
|
|
data: {
|
|
name: user.name,
|
|
reason: "manual",
|
|
},
|
|
});
|
|
|
|
void RateLimiter.clearCachedToken(token);
|
|
|
|
ctx.cookies.set("accessToken", "", {
|
|
sameSite: "lax",
|
|
expires: subMinutes(new Date(), 1),
|
|
});
|
|
clearCSRFCookie(ctx);
|
|
SessionsCookieHelper.logout(ctx, user.teamId);
|
|
|
|
ctx.body = {
|
|
success: true,
|
|
};
|
|
}
|
|
);
|
|
|
|
export default router;
|