mirror of
https://github.com/outline/outline.git
synced 2026-11-25 23:24:06 +03:00
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>
This commit is contained in:
1 parent
fd66b5e020
commit
00b124d03c
164 files changed
+1574
-1592
No files matched your search
@@ -144,6 +144,11 @@
|
||||
"addColumnAfter"
|
||||
],
|
||||
"message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell."
|
||||
},
|
||||
{
|
||||
"name": "koa",
|
||||
"importNames": ["Context", "DefaultContext"],
|
||||
"message": "Use AppContext or Context from @server/types, which do not allow arbitrary properties."
|
||||
}
|
||||
],
|
||||
"patterns": [
|
||||
|
||||
@@ -10,7 +10,7 @@ import { parseEmail } from "@shared/utils/email";
|
||||
import accountProvisioner from "@server/commands/accountProvisioner";
|
||||
import passportMiddleware from "@server/middlewares/passport";
|
||||
import type { User } from "@server/models";
|
||||
import type { AuthenticationResult } from "@server/types";
|
||||
import type { AuthenticationResult, AppContext } from "@server/types";
|
||||
import {
|
||||
StateStore,
|
||||
request,
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
} from "@server/utils/passport";
|
||||
import config from "../../plugin.json";
|
||||
import env from "../env";
|
||||
import { createContext } from "@server/context";
|
||||
import { withUser } from "@server/context";
|
||||
import UploadUserAvatarTask from "@server/queues/tasks/UploadUserAvatarTask";
|
||||
import { UserFlag } from "@server/models/User";
|
||||
import { getEmailVerified } from "./getEmailVerified";
|
||||
@@ -57,7 +57,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
|
||||
result?: AuthenticationResult
|
||||
) => void
|
||||
) {
|
||||
const context = req.ctx;
|
||||
const context: AppContext = req.ctx;
|
||||
try {
|
||||
// see docs for what the fields in profile represent here:
|
||||
// https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens
|
||||
@@ -106,7 +106,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
|
||||
const team = await getTeamFromContext(context);
|
||||
const client = getClientFromOAuthState(context);
|
||||
const user =
|
||||
context.state?.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
context.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
|
||||
const emailVerified = getEmailVerified(
|
||||
email,
|
||||
@@ -122,11 +122,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
|
||||
const subdomain = slugifyDomain(domain);
|
||||
|
||||
const teamName = organization.displayName;
|
||||
const ctx = createContext({
|
||||
ip: context.ip,
|
||||
user,
|
||||
authType: context.state?.auth?.type,
|
||||
});
|
||||
const ctx = withUser(context, user);
|
||||
const result = await accountProvisioner(ctx, {
|
||||
team: {
|
||||
teamId: team?.id,
|
||||
|
||||
@@ -18,7 +18,7 @@ import accountProvisioner from "@server/commands/accountProvisioner";
|
||||
import { InvalidRequestError, TeamDomainRequiredError } from "@server/errors";
|
||||
import passportMiddleware from "@server/middlewares/passport";
|
||||
import type { User } from "@server/models";
|
||||
import type { AuthenticationResult } from "@server/types";
|
||||
import type { AuthenticationResult, AppContext } from "@server/types";
|
||||
import {
|
||||
StateStore,
|
||||
getTeamFromContext,
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
import config from "../../plugin.json";
|
||||
import env from "../env";
|
||||
import { DiscordGuildError, DiscordGuildRoleError } from "../errors";
|
||||
import { createContext } from "@server/context";
|
||||
import { withUser } from "@server/context";
|
||||
|
||||
const router = new Router();
|
||||
|
||||
@@ -72,7 +72,7 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
|
||||
result?: AuthenticationResult
|
||||
) => void
|
||||
) {
|
||||
const context = req.ctx;
|
||||
const context: AppContext = req.ctx;
|
||||
try {
|
||||
const team = await getTeamFromContext(context);
|
||||
const client = getClientFromOAuthState(context);
|
||||
@@ -185,17 +185,12 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
|
||||
}
|
||||
}
|
||||
const user =
|
||||
context.state?.auth?.user ??
|
||||
(await getUserFromOAuthState(context));
|
||||
context.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
|
||||
// if a team can be inferred, we assume the user is only interested in signing into
|
||||
// that team in particular; otherwise, we will do a best effort at finding their account
|
||||
// or provisioning a new one (within AccountProvisioner)
|
||||
const ctx = createContext({
|
||||
ip: context.ip,
|
||||
user,
|
||||
authType: context.state?.auth?.type,
|
||||
});
|
||||
const ctx = withUser(context, user);
|
||||
const result = await accountProvisioner(ctx, {
|
||||
team: {
|
||||
teamId: team?.id,
|
||||
|
||||
@@ -10,7 +10,7 @@ import Logger from "@server/logging/Logger";
|
||||
import { rateLimiter } from "@server/middlewares/rateLimiter";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { Event, User, Team } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
|
||||
import { VerificationCode } from "@server/utils/VerificationCode";
|
||||
import { signIn } from "@server/utils/authentication";
|
||||
@@ -26,7 +26,7 @@ router.post(
|
||||
"email",
|
||||
rateLimiter(RateLimiterStrategy.TenPerHour),
|
||||
validate(T.EmailSchema),
|
||||
async (ctx: APIContext<T.EmailReq>) => {
|
||||
async (ctx: Context<T.EmailReq>) => {
|
||||
const { email, client, preferOTP } = ctx.input.body;
|
||||
|
||||
const domain = parseDomain(ctx.request.hostname);
|
||||
@@ -99,7 +99,7 @@ router.post(
|
||||
}
|
||||
);
|
||||
|
||||
const emailCallback = async (ctx: APIContext<T.EmailCallbackReq>) => {
|
||||
const emailCallback = async (ctx: Context<T.EmailCallbackReq>) => {
|
||||
const { query, body } = ctx.input;
|
||||
const token = query?.token || body?.token;
|
||||
const client = query?.client || body?.client || Client.Web;
|
||||
|
||||
@@ -3,7 +3,7 @@ import auth from "@server/middlewares/authentication";
|
||||
import Router from "@koa/router";
|
||||
import * as T from "./schema";
|
||||
import apexAuthRedirect from "@server/middlewares/apexAuthRedirect";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import {
|
||||
FigmaOAuthNonceCookie,
|
||||
@@ -36,7 +36,7 @@ router.get(
|
||||
getErrorPath: () => FigmaUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.FigmaCallbackReq>) => {
|
||||
async (ctx: Context<T.FigmaCallbackReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
|
||||
// Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain.
|
||||
@@ -52,8 +52,8 @@ router.get(
|
||||
|
||||
verifyOAuthStateNonce(ctx, FigmaOAuthNonceCookie, parsedState.nonce);
|
||||
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
try {
|
||||
// validation middleware ensures that code is non-null at this point.
|
||||
|
||||
@@ -11,7 +11,7 @@ import { transaction } from "@server/middlewares/transaction";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { IntegrationAuthentication, Integration } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import {
|
||||
generateOAuthStateNonce,
|
||||
verifyOAuthStateNonce,
|
||||
@@ -28,12 +28,12 @@ router.post(
|
||||
auth(),
|
||||
validate(T.GiteaConnectSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.GiteaConnectReq>) => {
|
||||
async (ctx: Context<T.GiteaConnectReq>) => {
|
||||
const { clientId, clientSecret } = ctx.input.body;
|
||||
const parsedUrl = new URL(ctx.input.body.url);
|
||||
const url = `${parsedUrl.origin}${parsedUrl.pathname}`.replace(/\/+$/, "");
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
authorize(user, "createIntegration", user.team);
|
||||
await validateUrlNotPrivate(url);
|
||||
@@ -119,10 +119,10 @@ router.get(
|
||||
getErrorPath: () => GiteaUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.GiteaCallbackReq>) => {
|
||||
async (ctx: Context<T.GiteaCallbackReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
if (error) {
|
||||
ctx.redirect(GiteaUtils.errorUrl(error));
|
||||
|
||||
@@ -10,7 +10,7 @@ import validate from "@server/middlewares/validate";
|
||||
import validateWebhook from "@server/middlewares/validateWebhook";
|
||||
import { IntegrationAuthentication, Integration } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { verifyOAuthStateNonce } from "@server/utils/oauth";
|
||||
import { RequestHelper } from "@server/utils/RequestHelper";
|
||||
import { GitHubOAuthNonceCookie, GitHubUtils } from "../../shared/GitHubUtils";
|
||||
@@ -35,7 +35,7 @@ router.get(
|
||||
getErrorPath: () => GitHubUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.GitHubCallbackReq>) => {
|
||||
async (ctx: Context<T.GitHubCallbackReq>) => {
|
||||
const {
|
||||
code,
|
||||
state,
|
||||
@@ -43,8 +43,8 @@ router.get(
|
||||
installation_id: installationId,
|
||||
setup_action: setupAction,
|
||||
} = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
if (error) {
|
||||
ctx.redirect(GitHubUtils.errorUrl(error));
|
||||
@@ -129,7 +129,7 @@ router.post(
|
||||
return signature?.split("=")[1];
|
||||
},
|
||||
}),
|
||||
async (ctx: APIContext) => {
|
||||
async (ctx: Context) => {
|
||||
const { headers } = ctx.request;
|
||||
const body = RequestHelper.getBodyObject(ctx.request);
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import validate from "@server/middlewares/validate";
|
||||
import validateWebhook from "@server/middlewares/validateWebhook";
|
||||
import { IntegrationAuthentication, Integration } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { safeEqual } from "@server/utils/crypto";
|
||||
import { RequestHelper } from "@server/utils/RequestHelper";
|
||||
import {
|
||||
@@ -29,7 +29,7 @@ import * as T from "./schema";
|
||||
|
||||
const router = new Router();
|
||||
|
||||
function getGitLabWebhookToken(ctx: APIContext): string | undefined {
|
||||
function getGitLabWebhookToken(ctx: Context): string | undefined {
|
||||
const signatureHeader = ctx.request.headers["x-gitlab-token"];
|
||||
return Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
|
||||
}
|
||||
@@ -39,11 +39,11 @@ router.post(
|
||||
auth(),
|
||||
validate(T.GitLabConnectSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.GitLabConnectReq>) => {
|
||||
async (ctx: Context<T.GitLabConnectReq>) => {
|
||||
const { url: rawUrl, clientId, clientSecret } = ctx.input.body;
|
||||
const url = rawUrl?.replace(/\/+$/, "");
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
authorize(user, "createIntegration", user.team);
|
||||
|
||||
@@ -150,10 +150,10 @@ router.get(
|
||||
getErrorPath: () => GitLabUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.GitLabCallbackReq>) => {
|
||||
async (ctx: Context<T.GitLabCallbackReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
if (error) {
|
||||
ctx.redirect(GitLabUtils.errorUrl(error));
|
||||
@@ -355,7 +355,7 @@ router.post(
|
||||
},
|
||||
getSignatureFromHeader: getGitLabWebhookToken,
|
||||
}),
|
||||
async (ctx: APIContext) => {
|
||||
async (ctx: Context) => {
|
||||
const { headers } = ctx.request;
|
||||
const body = RequestHelper.getBodyObject(ctx.request);
|
||||
const teamIds: Array<string | null> = ctx.state.webhookTeamIds ?? [null];
|
||||
|
||||
@@ -11,7 +11,7 @@ import accountProvisioner from "@server/commands/accountProvisioner";
|
||||
import { TeamDomainRequiredError } from "@server/errors";
|
||||
import passportMiddleware from "@server/middlewares/passport";
|
||||
import { AuthenticationProvider, User } from "@server/models";
|
||||
import type { AuthenticationResult } from "@server/types";
|
||||
import type { AuthenticationResult, AppContext } from "@server/types";
|
||||
import {
|
||||
StateStore,
|
||||
getTeamFromContext,
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
} from "@server/utils/passport";
|
||||
import config from "../../plugin.json";
|
||||
import env from "../env";
|
||||
import { createContext } from "@server/context";
|
||||
import { withUser } from "@server/context";
|
||||
import { GmailAccountCreationError } from "../errors";
|
||||
|
||||
const router = new Router();
|
||||
@@ -65,14 +65,14 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
|
||||
result?: AuthenticationResult
|
||||
) => void
|
||||
) {
|
||||
const context = req.ctx;
|
||||
const context: AppContext = req.ctx;
|
||||
try {
|
||||
// "domain" is the Google Workspaces domain
|
||||
const domain = profile._json.hd;
|
||||
let team = await getTeamFromContext(context);
|
||||
const client = getClientFromOAuthState(context);
|
||||
const user =
|
||||
context.state?.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
context.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
|
||||
// No profile domain means a personal gmail account, and no team means
|
||||
// the request came from the apex domain rather than a workspace
|
||||
@@ -125,11 +125,7 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
|
||||
// if a team can be inferred, we assume the user is only interested in signing into
|
||||
// that team in particular; otherwise, we will do a best effort at finding their account
|
||||
// or provisioning a new one (within AccountProvisioner)
|
||||
const ctx = createContext({
|
||||
ip: context.ip,
|
||||
user,
|
||||
authType: context.state?.auth?.type,
|
||||
});
|
||||
const ctx = withUser(context, user);
|
||||
const result = await accountProvisioner(ctx, {
|
||||
team: {
|
||||
teamId: team?.id,
|
||||
|
||||
@@ -10,7 +10,7 @@ import validate from "@server/middlewares/validate";
|
||||
import { IntegrationAuthentication, Integration } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import { afterCommit } from "@server/storage/transaction";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { verifyOAuthStateNonce } from "@server/utils/oauth";
|
||||
import { Linear } from "../linear";
|
||||
import UploadIntegrationLogoTask from "@server/queues/tasks/UploadIntegrationLogoTask";
|
||||
@@ -39,10 +39,10 @@ router.get(
|
||||
getErrorPath: () => LinearUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.LinearCallbackReq>) => {
|
||||
async (ctx: Context<T.LinearCallbackReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
// Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain.
|
||||
if (error) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { transaction } from "@server/middlewares/transaction";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { Integration, IntegrationAuthentication } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { verifyOAuthStateNonce } from "@server/utils/oauth";
|
||||
import { NotionClient } from "../notion";
|
||||
import * as T from "./schema";
|
||||
@@ -32,10 +32,10 @@ router.get(
|
||||
getErrorPath: () => NotionUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.NotionCallbackReq>) => {
|
||||
async (ctx: Context<T.NotionCallbackReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
// Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain.
|
||||
if (error) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import passport from "@outlinewiki/koa-passport";
|
||||
import JWT from "jsonwebtoken";
|
||||
import type { Context, Request } from "koa";
|
||||
import type { Request } from "koa";
|
||||
import type Router from "@koa/router";
|
||||
import { get } from "es-toolkit/compat";
|
||||
import { toError } from "@shared/utils/error";
|
||||
@@ -13,7 +13,7 @@ import { AuthenticationError } from "@server/errors";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import passportMiddleware from "@server/middlewares/passport";
|
||||
import type { User } from "@server/models";
|
||||
import type { AuthenticationResult } from "@server/types";
|
||||
import type { AuthenticationResult, AppContext } from "@server/types";
|
||||
import { LogoutTokenStore } from "@server/utils/LogoutTokenStore";
|
||||
import {
|
||||
StateStore,
|
||||
@@ -28,7 +28,7 @@ import config from "../../plugin.json";
|
||||
import env from "../env";
|
||||
import { OIDCStrategy } from "./OIDCStrategy";
|
||||
import { resolveProviderId } from "./resolveProviderId";
|
||||
import { createContext } from "@server/context";
|
||||
import { withUser } from "@server/context";
|
||||
import { OIDCMalformedUserInfoError } from "../errors";
|
||||
|
||||
export interface OIDCEndpoints {
|
||||
@@ -84,7 +84,7 @@ export function createOIDCRouter(
|
||||
result?: AuthenticationResult
|
||||
) => void
|
||||
) {
|
||||
const context = req.ctx;
|
||||
const context: AppContext = req.ctx;
|
||||
try {
|
||||
// Some providers require a POST request to the userinfo endpoint, add them as exceptions here.
|
||||
const usePostMethod = [
|
||||
@@ -142,8 +142,7 @@ export function createOIDCRouter(
|
||||
const team = await getTeamFromContext(context);
|
||||
const client = getClientFromOAuthState(context);
|
||||
const user =
|
||||
context.state?.auth?.user ??
|
||||
(await getUserFromOAuthState(context));
|
||||
context.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
const { domain } = parseEmail(email);
|
||||
|
||||
const providerId = await resolveProviderId(
|
||||
@@ -193,11 +192,7 @@ export function createOIDCRouter(
|
||||
avatarUrl = null;
|
||||
}
|
||||
|
||||
const ctx = createContext({
|
||||
ip: context.ip,
|
||||
user,
|
||||
authType: context.state?.auth?.type,
|
||||
});
|
||||
const ctx = withUser(context, user);
|
||||
const result = await accountProvisioner(ctx, {
|
||||
team: {
|
||||
teamId: team?.id,
|
||||
@@ -252,7 +247,7 @@ export function createOIDCRouter(
|
||||
// ended so the provider can scope the logout and skip a confirmation prompt,
|
||||
// while `post_logout_redirect_uri` returns the user to Outline afterwards.
|
||||
// https://openid.net/specs/openid-connect-rpinitiated-1_0.html
|
||||
router.get(`${config.id}.logout`, async (ctx: Context) => {
|
||||
router.get(`${config.id}.logout`, async (ctx: AppContext) => {
|
||||
const idToken = await logoutTokens.consume(ctx);
|
||||
|
||||
if (!endpoints.logoutURL) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { UserPasskey } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { AuthenticationType } from "@server/types";
|
||||
import Router from "@koa/router";
|
||||
import * as T from "./schema";
|
||||
@@ -17,8 +17,8 @@ router.post(
|
||||
auth({ type: AuthenticationType.APP }),
|
||||
pagination(),
|
||||
validate(T.PasskeysListSchema),
|
||||
async (ctx: APIContext<T.PasskeysListReq>) => {
|
||||
const { user } = ctx.state.auth;
|
||||
async (ctx: Context<T.PasskeysListReq>) => {
|
||||
const { user } = ctx.auth;
|
||||
const { pagination } = ctx.state;
|
||||
|
||||
const passkeys = await UserPasskey.findAll({
|
||||
@@ -40,10 +40,10 @@ router.post(
|
||||
auth({ type: AuthenticationType.APP }),
|
||||
validate(T.PasskeysUpdateSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.PasskeysUpdateReq>) => {
|
||||
async (ctx: Context<T.PasskeysUpdateReq>) => {
|
||||
const { id, name } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const passkey = await UserPasskey.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
@@ -64,10 +64,10 @@ router.post(
|
||||
auth({ type: AuthenticationType.APP }),
|
||||
validate(T.PasskeysDeleteSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.PasskeysDeleteReq>) => {
|
||||
async (ctx: Context<T.PasskeysDeleteReq>) => {
|
||||
const { id } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const passkey = await UserPasskey.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { getTestServer } from "@server/test/support";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { PasskeyBrand } from "@shared/utils/passkeys";
|
||||
import {
|
||||
getExpectedOrigin,
|
||||
@@ -82,13 +82,13 @@ function buildNoneAttestationResponse(challenge: string, rpId: string) {
|
||||
}
|
||||
|
||||
describe("getExpectedOrigin", () => {
|
||||
// Helper to mock APIContext for testing
|
||||
// Helper to mock Context for testing
|
||||
const createMockContext = (options: {
|
||||
protocol: string;
|
||||
hostname: string;
|
||||
host: string;
|
||||
forwardedPort?: string;
|
||||
}): APIContext =>
|
||||
}): Context =>
|
||||
({
|
||||
protocol: options.protocol,
|
||||
request: {
|
||||
@@ -101,7 +101,7 @@ describe("getExpectedOrigin", () => {
|
||||
return undefined;
|
||||
},
|
||||
} as unknown,
|
||||
}) as unknown as APIContext;
|
||||
}) as unknown as Context;
|
||||
|
||||
it("should construct origin with non-standard HTTPS port from X-Forwarded-Port", () => {
|
||||
const ctx = createMockContext({
|
||||
|
||||
@@ -10,13 +10,12 @@ import Router from "@koa/router";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import { User, UserPasskey, Team } from "@server/models";
|
||||
import { apiContext } from "@server/middlewares/apiContext";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import { transaction } from "@server/middlewares/transaction";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import env from "@server/env";
|
||||
import { AuthorizationError, ValidationError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { AuthenticationType } from "@server/types";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import Redis from "@server/storage/redis";
|
||||
@@ -32,16 +31,16 @@ const rpName = env.APP_NAME;
|
||||
const CHALLENGE_EXPIRY_MS = Minute.ms * 5;
|
||||
|
||||
// Helper to get RP ID (domain) - for simplicity, we can use the hostname but strip port.
|
||||
const getRpID = (ctx: APIContext) => ctx.request.hostname;
|
||||
const getRpID = (ctx: Context) => ctx.request.hostname;
|
||||
|
||||
/**
|
||||
* Helper to get the expected origin for WebAuthn.
|
||||
* Properly handles non-standard ports by checking X-Forwarded-Port header.
|
||||
*
|
||||
* @param ctx - the API context.
|
||||
* @param ctx - the context.
|
||||
* @returns the expected origin (protocol://host:port).
|
||||
*/
|
||||
export const getExpectedOrigin = (ctx: APIContext): string => {
|
||||
export const getExpectedOrigin = (ctx: Context): string => {
|
||||
const protocol = ctx.protocol;
|
||||
const hostname = ctx.request.hostname;
|
||||
|
||||
@@ -108,8 +107,8 @@ export const isUniqueAuthenticator = (aaguid: string | undefined): boolean =>
|
||||
router.post(
|
||||
"passkeys.generateRegistrationOptions",
|
||||
auth({ type: AuthenticationType.APP }),
|
||||
async (ctx: APIContext) => {
|
||||
const { user } = ctx.state.auth;
|
||||
async (ctx: Context) => {
|
||||
const { user } = ctx.auth;
|
||||
authorize(user, "createUserPasskey", user.team);
|
||||
|
||||
// Fetch existing passkeys to exclude them from registration
|
||||
@@ -148,12 +147,9 @@ router.post(
|
||||
"passkeys.verifyRegistration",
|
||||
auth({ type: AuthenticationType.APP }),
|
||||
validate(T.PasskeysVerifyRegistrationSchema),
|
||||
// Auth routes have no API context by default, without it the resulting event
|
||||
// has no actor or team and cannot appear in the audit log.
|
||||
apiContext(),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.PasskeysVerifyRegistrationReq>) => {
|
||||
const { user } = ctx.state.auth;
|
||||
async (ctx: Context<T.PasskeysVerifyRegistrationReq>) => {
|
||||
const { user } = ctx.auth;
|
||||
const body = ctx.input.body;
|
||||
authorize(user, "createUserPasskey", user.team);
|
||||
|
||||
@@ -266,14 +262,14 @@ export const getPasskeyLoginRedirect = (
|
||||
* ceremony and returns the authenticated session via the outline:// deep link,
|
||||
* mirroring the existing SSO desktop flow.
|
||||
*/
|
||||
router.get("passkey", (ctx: APIContext) => {
|
||||
router.get("passkey", (ctx: Context) => {
|
||||
ctx.redirect(getPasskeyLoginRedirect(ctx.query.client));
|
||||
});
|
||||
|
||||
router.post(
|
||||
"passkeys.generateAuthenticationOptions",
|
||||
validate(T.PasskeysGenerateAuthenticationOptionsSchema),
|
||||
async (ctx: APIContext<T.PasskeysGenerateAuthenticationOptionsReq>) => {
|
||||
async (ctx: Context<T.PasskeysGenerateAuthenticationOptionsReq>) => {
|
||||
const options = await generateAuthenticationOptions({
|
||||
rpID: getRpID(ctx),
|
||||
userVerification: "preferred",
|
||||
@@ -295,7 +291,7 @@ router.post(
|
||||
router.post(
|
||||
"passkeys.verifyAuthentication",
|
||||
validate(T.PasskeysVerifyAuthenticationSchema),
|
||||
async (ctx: APIContext<T.PasskeysVerifyAuthenticationReq>) => {
|
||||
async (ctx: Context<T.PasskeysVerifyAuthenticationReq>) => {
|
||||
const body = ctx.input.body;
|
||||
const { challengeId, client = Client.Web } = body;
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import SearchProviderManager from "@server/utils/SearchProviderManager";
|
||||
import { can } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { safeEqual } from "@server/utils/crypto";
|
||||
import { opts } from "@server/utils/i18n";
|
||||
import env from "../env";
|
||||
@@ -38,7 +38,7 @@ const router = new Router();
|
||||
router.post(
|
||||
"hooks.unfurl",
|
||||
validate(T.HooksUnfurlSchema),
|
||||
async (ctx: APIContext<T.HooksUnfurlReq>) => {
|
||||
async (ctx: Context<T.HooksUnfurlReq>) => {
|
||||
// See URL verification handshake documentation on this page:
|
||||
// https://api.slack.com/apis/connections/events-api
|
||||
if ("challenge" in ctx.input.body) {
|
||||
@@ -133,7 +133,7 @@ router.post(
|
||||
router.post(
|
||||
"hooks.interactive",
|
||||
validate(T.HooksInteractiveSchema),
|
||||
async (ctx: APIContext<T.HooksInteractiveReq>) => {
|
||||
async (ctx: Context<T.HooksInteractiveReq>) => {
|
||||
const { payload } = ctx.input.body;
|
||||
let parsed;
|
||||
|
||||
@@ -208,7 +208,7 @@ router.post(
|
||||
router.post(
|
||||
"hooks.slack",
|
||||
validate(T.HooksSlackCommandSchema),
|
||||
async (ctx: APIContext<T.HooksSlackCommandReq>) => {
|
||||
async (ctx: Context<T.HooksSlackCommandReq>) => {
|
||||
const { token, team_id, user_id, text } = ctx.input.body;
|
||||
verifySlackToken(token);
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
} from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import type { APIContext, AuthenticationResult } from "@server/types";
|
||||
import type { Context, AuthenticationResult, AppContext } from "@server/types";
|
||||
import { verifyOAuthStateNonce } from "@server/utils/oauth";
|
||||
import {
|
||||
getClientFromOAuthState,
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
SlackUtils,
|
||||
SlackOAuthNonceCookie,
|
||||
} from "plugins/slack/shared/SlackUtils";
|
||||
import { createContext } from "@server/context";
|
||||
import { withUser } from "@server/context";
|
||||
|
||||
type SlackProfile = Profile & {
|
||||
team: {
|
||||
@@ -88,20 +88,16 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) {
|
||||
result?: AuthenticationResult
|
||||
) => void
|
||||
) {
|
||||
const context = req.ctx;
|
||||
const context: AppContext = req.ctx;
|
||||
try {
|
||||
const team = await getTeamFromContext(context);
|
||||
const client = getClientFromOAuthState(context);
|
||||
const user =
|
||||
context.state?.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
context.auth?.user ?? (await getUserFromOAuthState(context));
|
||||
|
||||
const { domain } = parseEmail(profile.user.email);
|
||||
|
||||
const ctx = createContext({
|
||||
ip: context.ip,
|
||||
user,
|
||||
authType: context.state?.auth?.type,
|
||||
});
|
||||
const ctx = withUser(context, user);
|
||||
const result = await accountProvisioner(ctx, {
|
||||
team: {
|
||||
teamId: team?.id,
|
||||
@@ -156,9 +152,9 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) {
|
||||
}),
|
||||
getErrorPath: () => SlackUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
async (ctx: APIContext<T.SlackPostReq>) => {
|
||||
async (ctx: Context<T.SlackPostReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
if (error) {
|
||||
ctx.redirect(SlackUtils.errorUrl(error));
|
||||
|
||||
@@ -20,7 +20,7 @@ import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
|
||||
import { authorize } from "@server/policies";
|
||||
import FileStorage from "@server/storage/files";
|
||||
import type LocalStorage from "@server/storage/files/LocalStorage";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
|
||||
import { getJWTPayload } from "@server/utils/jwt";
|
||||
import { ByteRangeHelper } from "../utils/ByteRangeHelper";
|
||||
@@ -40,8 +40,8 @@ router.post(
|
||||
env.FILE_STORAGE_IMPORT_MAX_SIZE
|
||||
),
|
||||
}),
|
||||
async (ctx: APIContext<T.FilesCreateReq>) => {
|
||||
const actor = ctx.state.auth.user;
|
||||
async (ctx: Context<T.FilesCreateReq>) => {
|
||||
const actor = ctx.auth.user;
|
||||
const { key, sig } = ctx.input.body;
|
||||
const file = ctx.input.file;
|
||||
|
||||
@@ -104,8 +104,8 @@ router.get(
|
||||
// Signed requests are authorized by their signature alone.
|
||||
auth({ optional: true, skip: (ctx) => !!ctx.query.sig }),
|
||||
validate(T.FilesGetSchema),
|
||||
async (ctx: APIContext<T.FilesGetReq>) => {
|
||||
const actor = ctx.state.auth.user;
|
||||
async (ctx: Context<T.FilesGetReq>) => {
|
||||
const actor = ctx.auth.user;
|
||||
const key = getKeyFromContext(ctx);
|
||||
const forceDownload = !!ctx.input.query.download;
|
||||
const isSignedRequest = !!ctx.input.query.sig;
|
||||
@@ -206,7 +206,7 @@ function verifyUploadSignature(sig: string, key: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function getKeyFromContext(ctx: APIContext<T.FilesGetReq>): string {
|
||||
function getKeyFromContext(ctx: Context<T.FilesGetReq>): string {
|
||||
const { key, sig } = ctx.input.query;
|
||||
if (sig) {
|
||||
const payload = getJWTPayload(sig);
|
||||
|
||||
@@ -10,7 +10,7 @@ import { authorize } from "@server/policies";
|
||||
import pagination, {
|
||||
paginateQuery,
|
||||
} from "@server/routes/api/middlewares/pagination";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { AuthenticationType } from "@server/types";
|
||||
import { QueryHelper } from "@server/storage/QueryHelper";
|
||||
import presentWebhookSubscription from "../presenters/webhookSubscription";
|
||||
@@ -23,9 +23,9 @@ router.post(
|
||||
auth({ role: UserRole.Admin }),
|
||||
pagination(),
|
||||
validate(T.WebhookSubscriptionsListSchema),
|
||||
async (ctx: APIContext<T.WebhookSubscriptionsListReq>) => {
|
||||
async (ctx: Context<T.WebhookSubscriptionsListReq>) => {
|
||||
const { sort, direction, query } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
authorize(user, "listWebhookSubscription", user.team);
|
||||
|
||||
@@ -84,9 +84,9 @@ router.post(
|
||||
}),
|
||||
validate(T.WebhookSubscriptionsCreateSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.WebhookSubscriptionsCreateReq>) => {
|
||||
async (ctx: Context<T.WebhookSubscriptionsCreateReq>) => {
|
||||
const { name, url, secret, events } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
authorize(user, "createWebhookSubscription", user.team);
|
||||
|
||||
@@ -114,10 +114,10 @@ router.post(
|
||||
}),
|
||||
validate(T.WebhookSubscriptionsDeleteSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.WebhookSubscriptionsDeleteReq>) => {
|
||||
async (ctx: Context<T.WebhookSubscriptionsDeleteReq>) => {
|
||||
const { id } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const webhookSubscription = await WebhookSubscription.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
@@ -145,10 +145,10 @@ router.post(
|
||||
}),
|
||||
validate(T.WebhookSubscriptionsUpdateSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.WebhookSubscriptionsUpdateReq>) => {
|
||||
async (ctx: Context<T.WebhookSubscriptionsUpdateReq>) => {
|
||||
const { id, name, url, secret, events } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const webhookSubscription = await WebhookSubscription.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
|
||||
@@ -23,9 +23,9 @@ import { sequelize } from "@server/storage/database";
|
||||
import SyncUserGroupsTask from "@server/queues/tasks/SyncUserGroupsTask";
|
||||
import teamProvisioner from "./teamProvisioner";
|
||||
import userProvisioner from "./userProvisioner";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { addSeconds } from "date-fns";
|
||||
import { createContext } from "@server/context";
|
||||
import { withTransaction, withUser } from "@server/context";
|
||||
|
||||
type Props = {
|
||||
/** Details of the user logging in from SSO provider */
|
||||
@@ -89,7 +89,7 @@ export type AccountProvisionerResult = {
|
||||
};
|
||||
|
||||
async function accountProvisioner(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{
|
||||
user: userParams,
|
||||
team: teamParams,
|
||||
@@ -100,7 +100,7 @@ async function accountProvisioner(
|
||||
let result;
|
||||
let emailMatchOnly;
|
||||
|
||||
const actor = ctx.state.auth?.user;
|
||||
const actor = ctx.auth?.user;
|
||||
|
||||
// If the user is already logged in and is an admin of the team then we
|
||||
// allow them to connect or reconnect an authentication provider.
|
||||
@@ -120,15 +120,9 @@ async function accountProvisioner(
|
||||
if (!isConnected && providers.length === 1) {
|
||||
// Update in place so that existing user authentications stay linked.
|
||||
await sequelize.transaction((transaction) =>
|
||||
providers[0].updateWithCtx(
|
||||
createContext({
|
||||
user: actor,
|
||||
authType: ctx.context.auth?.type,
|
||||
ip: ctx.context.ip,
|
||||
transaction,
|
||||
}),
|
||||
{ providerId: authenticationProviderParams.providerId }
|
||||
)
|
||||
providers[0].updateWithCtx(withTransaction(ctx, transaction), {
|
||||
providerId: authenticationProviderParams.providerId,
|
||||
})
|
||||
);
|
||||
} else if (!isConnected) {
|
||||
await team.$create<AuthenticationProvider>(
|
||||
@@ -230,9 +224,9 @@ async function accountProvisioner(
|
||||
userId: user.id,
|
||||
actorId: user.id,
|
||||
teamId: user.teamId,
|
||||
ip: ctx.context.ip,
|
||||
ip: ctx.ip,
|
||||
},
|
||||
{ transaction: ctx.state.transaction }
|
||||
{ transaction: ctx.transaction }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -287,17 +281,12 @@ async function accountProvisioner(
|
||||
* @returns a promise that resolves when the collection has been created.
|
||||
*/
|
||||
export async function provisionFirstCollection(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
team: Team,
|
||||
user: User
|
||||
) {
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const context = createContext({
|
||||
user,
|
||||
authType: ctx.context.auth?.type,
|
||||
ip: ctx.context.ip,
|
||||
transaction,
|
||||
});
|
||||
const context = withTransaction(withUser(ctx, user), transaction);
|
||||
|
||||
const collection = await Collection.createWithCtx(context, {
|
||||
name: "Welcome",
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { User } from "@server/models";
|
||||
import { Attachment } from "@server/models";
|
||||
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
|
||||
import FileStorage from "@server/storage/files";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import type { RequestInit } from "@server/utils/fetch";
|
||||
|
||||
type BaseProps = {
|
||||
@@ -19,7 +19,7 @@ type BaseProps = {
|
||||
/** The preset to use for the attachment */
|
||||
preset: AttachmentPreset;
|
||||
/** The request context */
|
||||
ctx: APIContext;
|
||||
ctx: Context;
|
||||
/** Options to pass to fetch when downloading the attachment */
|
||||
fetchOptions?: RequestInit;
|
||||
};
|
||||
@@ -51,7 +51,7 @@ export default async function attachmentCreator({
|
||||
if (id) {
|
||||
const existing = await Attachment.findOne({
|
||||
where: { id, teamId: user.teamId },
|
||||
transaction: ctx.context.transaction,
|
||||
transaction: ctx.transaction,
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import Logger from "@server/logging/Logger";
|
||||
import { Collection } from "@server/models";
|
||||
import DuplicateCollectionDocumentsTask from "@server/queues/tasks/DuplicateCollectionDocumentsTask";
|
||||
import { afterCommit } from "@server/storage/transaction";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** The collection to duplicate */
|
||||
@@ -17,16 +17,16 @@ type Props = {
|
||||
* published documents within the collection are duplicated asynchronously by a
|
||||
* background task once the new collection is committed.
|
||||
*
|
||||
* @param ctx the API context containing the acting user and transaction.
|
||||
* @param ctx the context containing the acting user and transaction.
|
||||
* @param props the collection to duplicate and optional overrides.
|
||||
* @returns the duplicated collection.
|
||||
*/
|
||||
export default async function collectionDuplicator(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ collection, name }: Props
|
||||
): Promise<Collection> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const duplicated = Collection.build({
|
||||
name: name ?? collection.name,
|
||||
@@ -54,7 +54,7 @@ export default async function collectionDuplicator(
|
||||
collectionId: duplicated.id,
|
||||
originalCollectionId: collection.id,
|
||||
actorId: user.id,
|
||||
ip: ctx.context.ip ?? null,
|
||||
ip: ctx.ip ?? null,
|
||||
});
|
||||
|
||||
if (transaction) {
|
||||
|
||||
@@ -7,14 +7,14 @@ import {
|
||||
buildFileOperation,
|
||||
buildTemplate,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import documentCreator from "./documentCreator";
|
||||
|
||||
describe("documentCreator", () => {
|
||||
it("should attribute Markdown mentions to the authenticated writer", async () => {
|
||||
const user = await buildUser();
|
||||
const mentioned = await buildUser({ teamId: user.teamId });
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Mentions",
|
||||
text: `@[${mentioned.name}](mention://user/${mentioned.id})`,
|
||||
@@ -40,7 +40,7 @@ describe("documentCreator", () => {
|
||||
"This is rich content"
|
||||
).toJSON();
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Test Document",
|
||||
text: testText,
|
||||
@@ -63,7 +63,7 @@ describe("documentCreator", () => {
|
||||
|
||||
const testText = "This is plain text";
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Test Document",
|
||||
text: testText,
|
||||
@@ -81,7 +81,7 @@ describe("documentCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Empty Document",
|
||||
collectionId: collection.id,
|
||||
@@ -101,7 +101,7 @@ describe("documentCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Test Document",
|
||||
text: "This is a test document",
|
||||
@@ -124,7 +124,7 @@ describe("documentCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Custom Document",
|
||||
text: "Custom content",
|
||||
@@ -147,7 +147,7 @@ describe("documentCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Draft Document",
|
||||
text: "Draft content",
|
||||
@@ -166,7 +166,7 @@ describe("documentCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Published Document",
|
||||
text: "Published content",
|
||||
@@ -182,7 +182,7 @@ describe("documentCreator", () => {
|
||||
const user = await buildUser();
|
||||
|
||||
await expect(
|
||||
withAPIContext(user, (ctx) =>
|
||||
withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Invalid Document",
|
||||
text: "Content",
|
||||
@@ -212,7 +212,7 @@ describe("documentCreator", () => {
|
||||
collectionId: collection.id,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "From Template",
|
||||
template,
|
||||
@@ -241,7 +241,7 @@ describe("documentCreator", () => {
|
||||
collectionId: collection.id,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
template,
|
||||
collectionId: collection.id,
|
||||
@@ -267,7 +267,7 @@ describe("documentCreator", () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
withAPIContext(user, (ctx) =>
|
||||
withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
template,
|
||||
state: Buffer.from("some state"),
|
||||
@@ -296,7 +296,7 @@ describe("documentCreator", () => {
|
||||
collectionId: collection.id,
|
||||
});
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Child Document",
|
||||
text: "Child content",
|
||||
@@ -323,7 +323,7 @@ describe("documentCreator", () => {
|
||||
|
||||
const sourceMetadata = { fileName: "test" };
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "fileOperation Document",
|
||||
text: "fileOperation content",
|
||||
@@ -349,7 +349,7 @@ describe("documentCreator", () => {
|
||||
const customEmojiId = "550e8400-e29b-41d4-a716-446655440000";
|
||||
const text = `Check this :${customEmojiId}: custom emoji`;
|
||||
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
const document = await withContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Custom Emoji Test",
|
||||
text,
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Collection, Document, type Template } from "@server/models";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
|
||||
import { authorize } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { assertPresent } from "@server/validation";
|
||||
import personalCollectionLoader from "./personalCollectionLoader";
|
||||
|
||||
@@ -56,20 +56,20 @@ type CreateLocation = {
|
||||
* "personal" refers to the personal collection of the user, which is created
|
||||
* when it does not exist yet.
|
||||
*
|
||||
* @param ctx the API context containing the acting user.
|
||||
* @param ctx the context containing the acting user.
|
||||
* @param location the requested collection and/or parent document.
|
||||
* @returns the resolved collection and parent document, when applicable.
|
||||
* @throws AuthorizationError when the user may not create the document.
|
||||
*/
|
||||
export async function authorizeDocumentCreate(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ collectionId, parentDocumentId }: CreateLocation
|
||||
): Promise<{
|
||||
collection?: Collection | null;
|
||||
parentDocument?: Document | null;
|
||||
}> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
if (parentDocumentId) {
|
||||
const parentDocument = await Document.findByPk(parentDocumentId, {
|
||||
@@ -109,19 +109,19 @@ export async function authorizeDocumentCreate(
|
||||
* requires create permission on the destination — separate from the update
|
||||
* permission that governs editing a draft's content.
|
||||
*
|
||||
* @param ctx the API context containing the acting user.
|
||||
* @param ctx the context containing the acting user.
|
||||
* @param document the document being published.
|
||||
* @param collectionId the destination collection, required when publishing a draft that has none.
|
||||
* @returns the resolved destination collection.
|
||||
* @throws AuthorizationError when the user may not publish into the collection.
|
||||
*/
|
||||
export async function authorizeDocumentPublish(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
document: Document,
|
||||
collectionId?: string | null
|
||||
): Promise<Collection | null | undefined> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
let collection = document.collection;
|
||||
|
||||
if (document.isDraft) {
|
||||
@@ -157,7 +157,7 @@ export async function authorizeDocumentPublish(
|
||||
}
|
||||
|
||||
export default async function documentCreator(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{
|
||||
title,
|
||||
text,
|
||||
@@ -186,8 +186,8 @@ export default async function documentCreator(
|
||||
lastModifiedById,
|
||||
}: Props
|
||||
): Promise<Document> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
const templateId = template ? template.id : undefined;
|
||||
const eventData = importId || apiImportId ? { source: "import" } : undefined;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
buildDocument,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import { generateUrlId } from "@server/utils/url";
|
||||
import documentDuplicator from "./documentDuplicator";
|
||||
|
||||
@@ -20,7 +20,7 @@ describe("documentDuplicator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
@@ -43,7 +43,7 @@ describe("documentDuplicator", () => {
|
||||
icon: "👋",
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
@@ -100,7 +100,7 @@ describe("documentDuplicator", () => {
|
||||
await collection.addDocumentToStructure(child2);
|
||||
await collection.addDocumentToStructure(child3);
|
||||
|
||||
await withAPIContext(user, (ctx) =>
|
||||
await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
title: "duplicate",
|
||||
document: original,
|
||||
@@ -127,7 +127,7 @@ describe("documentDuplicator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
@@ -233,7 +233,7 @@ describe("documentDuplicator", () => {
|
||||
text: `See [child 2](${child2.path}) and the [parent](/doc/${original.id}).`,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection,
|
||||
@@ -304,7 +304,7 @@ describe("documentDuplicator", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection,
|
||||
@@ -343,7 +343,7 @@ describe("documentDuplicator", () => {
|
||||
text: `See [other](${other.path}) and [elsewhere](https://example.com/doc/${other.urlId}).`,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection,
|
||||
@@ -377,7 +377,7 @@ describe("documentDuplicator", () => {
|
||||
].join("\n\n"),
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection,
|
||||
@@ -399,7 +399,7 @@ describe("documentDuplicator", () => {
|
||||
fullWidth: true,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
@@ -432,7 +432,7 @@ describe("documentDuplicator", () => {
|
||||
collectionId: collection.id,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Collection, Document } from "@server/models";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import type { DocumentReference } from "@server/models/helpers/ProsemirrorHelper";
|
||||
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { generateUrlId } from "@server/utils/url";
|
||||
import documentCreator from "./documentCreator";
|
||||
|
||||
@@ -62,12 +62,12 @@ type DuplicateItem = {
|
||||
* Duplicates a document, optionally including its child documents. Links
|
||||
* between the duplicated documents are remapped to point at the copies.
|
||||
*
|
||||
* @param ctx the API context containing the acting user and transaction.
|
||||
* @param ctx the context containing the acting user and transaction.
|
||||
* @param props the document to duplicate and optional overrides.
|
||||
* @returns the duplicated documents.
|
||||
*/
|
||||
export default async function documentDuplicator(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ document, collection, parentDocumentId, title, publish, recursive }: Props
|
||||
): Promise<Document[]> {
|
||||
return duplicateRoots(ctx, {
|
||||
@@ -82,12 +82,12 @@ export default async function documentDuplicator(
|
||||
* Duplicates several documents as one unit, so that links between them are
|
||||
* remapped to the copies no matter which of the documents they cross between.
|
||||
*
|
||||
* @param ctx the API context containing the acting user and transaction.
|
||||
* @param ctx the context containing the acting user and transaction.
|
||||
* @param props the documents to duplicate and optional overrides.
|
||||
* @returns the duplicated documents.
|
||||
*/
|
||||
export async function documentsDuplicator(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ documents, collection, publish, recursive }: ManyProps
|
||||
): Promise<Document[]> {
|
||||
return duplicateRoots(ctx, {
|
||||
@@ -99,7 +99,7 @@ export async function documentsDuplicator(
|
||||
}
|
||||
|
||||
async function duplicateRoots(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{
|
||||
roots,
|
||||
collection,
|
||||
@@ -203,7 +203,7 @@ async function duplicateRoots(
|
||||
item.original.dataValues.content !== undefined
|
||||
? item.original
|
||||
: await Document.findByPk(item.original.id, {
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { serializer } from "@server/editor";
|
||||
import { traceFunction } from "@server/logging/tracing";
|
||||
import type { User } from "@server/models";
|
||||
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { DocumentConverter } from "@server/converters/DocumentConverter";
|
||||
import { InvalidRequestError } from "../errors";
|
||||
|
||||
@@ -15,7 +15,7 @@ type Props = {
|
||||
mimeType: string;
|
||||
fileName: string;
|
||||
content: Buffer | string;
|
||||
ctx: APIContext;
|
||||
ctx: Context;
|
||||
};
|
||||
|
||||
type ImportResult = {
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import documentMover from "./documentMover";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
|
||||
describe("documentMover", () => {
|
||||
it("should move within a collection", async () => {
|
||||
@@ -24,7 +24,7 @@ describe("documentMover", () => {
|
||||
collectionId: collection.id,
|
||||
teamId: team.id,
|
||||
});
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: collection.id,
|
||||
@@ -54,7 +54,7 @@ describe("documentMover", () => {
|
||||
title: "Child document",
|
||||
text: "content",
|
||||
});
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: collection.id,
|
||||
@@ -92,7 +92,7 @@ describe("documentMover", () => {
|
||||
text: "content",
|
||||
});
|
||||
await collection.addDocumentToStructure(newDocument);
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: collection.id,
|
||||
@@ -133,7 +133,7 @@ describe("documentMover", () => {
|
||||
text: "content",
|
||||
});
|
||||
await collection.addDocumentToStructure(newDocument);
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: newCollection.id,
|
||||
@@ -182,7 +182,7 @@ describe("documentMover", () => {
|
||||
teamId: collection.teamId,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: newCollection.id,
|
||||
@@ -242,7 +242,7 @@ describe("documentMover", () => {
|
||||
teamId: team.id,
|
||||
});
|
||||
|
||||
await withAPIContext(user, (ctx) =>
|
||||
await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: newCollection.id,
|
||||
@@ -283,7 +283,7 @@ describe("documentMover", () => {
|
||||
});
|
||||
}
|
||||
|
||||
await withAPIContext(user, (ctx) =>
|
||||
await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: personal.id,
|
||||
@@ -314,7 +314,7 @@ describe("documentMover", () => {
|
||||
teamId: team.id,
|
||||
});
|
||||
|
||||
await withAPIContext(user, (ctx) =>
|
||||
await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: personal.id,
|
||||
@@ -347,7 +347,7 @@ describe("documentMover", () => {
|
||||
teamId: team.id,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
documentMover(ctx, {
|
||||
document,
|
||||
collectionId: null,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Transaction } from "sequelize";
|
||||
import { traceFunction } from "@server/logging/tracing";
|
||||
import { Document, Collection, Pin } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** Document which is being moved */
|
||||
@@ -21,7 +21,7 @@ type Result = {
|
||||
};
|
||||
|
||||
async function documentMover(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{
|
||||
document,
|
||||
collectionId,
|
||||
@@ -30,8 +30,8 @@ async function documentMover(
|
||||
index,
|
||||
}: Props
|
||||
): Promise<Result> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const collectionChanged = collectionId !== document.collectionId;
|
||||
const previousCollectionId = document.collectionId;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ParamRequiredError, ValidationError } from "@server/errors";
|
||||
import { Collection, Revision } from "@server/models";
|
||||
import type { Document } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** The document to restore. Must be loaded with `paranoid: false`. */
|
||||
@@ -20,7 +20,7 @@ type Props = {
|
||||
* are re-attached to the destination collection's structure. Authorizes the
|
||||
* acting user against the document before any other check.
|
||||
*
|
||||
* @param ctx - the API context, providing the acting user and transaction.
|
||||
* @param ctx - the context, providing the acting user and transaction.
|
||||
* @param props - the document and restore options.
|
||||
* @returns the restored document.
|
||||
* @throws AuthorizationError if the user cannot restore the document.
|
||||
@@ -28,11 +28,11 @@ type Props = {
|
||||
* @throws NotFoundError if the given revision does not exist.
|
||||
*/
|
||||
async function documentRestorer(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ document, collectionId, revisionId }: Props
|
||||
): Promise<Document> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
if (!document.deletedAt && !document.archivedAt) {
|
||||
// restore an active document to a specific revision
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
buildDocument,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import documentUpdater from "./documentUpdater";
|
||||
|
||||
describe("documentUpdater", () => {
|
||||
@@ -41,7 +41,7 @@ describe("documentUpdater", () => {
|
||||
});
|
||||
const newMention = `@[Writer](mention://user/${user.id})`;
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
document,
|
||||
text:
|
||||
@@ -83,7 +83,7 @@ describe("documentUpdater", () => {
|
||||
});
|
||||
const originalMentions = DocumentHelper.parseMentions(document);
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, { document, text: `${mention} updated` })
|
||||
);
|
||||
|
||||
@@ -97,7 +97,7 @@ describe("documentUpdater", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Changed",
|
||||
document,
|
||||
@@ -120,7 +120,7 @@ describe("documentUpdater", () => {
|
||||
userId: creator.id,
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Changed",
|
||||
publish: true,
|
||||
@@ -138,7 +138,7 @@ describe("documentUpdater", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
title: document.title,
|
||||
document,
|
||||
@@ -164,7 +164,7 @@ describe("documentUpdater", () => {
|
||||
document.state = Buffer.from(Y.encodeStateAsUpdate(ydoc));
|
||||
await document.save();
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Changed content",
|
||||
document,
|
||||
@@ -185,7 +185,7 @@ describe("documentUpdater", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
title: "New Title",
|
||||
document,
|
||||
@@ -213,7 +213,7 @@ describe("documentUpdater", () => {
|
||||
});
|
||||
const loadedCollection = document.collection;
|
||||
|
||||
const result = await withAPIContext(user, (ctx) =>
|
||||
const result = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
title: "New Title",
|
||||
document,
|
||||
@@ -234,7 +234,7 @@ describe("documentUpdater", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Changed",
|
||||
document,
|
||||
@@ -267,7 +267,7 @@ describe("documentUpdater", () => {
|
||||
text: "Initial",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Appended",
|
||||
document,
|
||||
@@ -294,7 +294,7 @@ describe("documentUpdater", () => {
|
||||
text: "**Bold**",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Appended",
|
||||
document,
|
||||
@@ -346,7 +346,7 @@ describe("documentUpdater", () => {
|
||||
};
|
||||
await document.save();
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Appended",
|
||||
document,
|
||||
@@ -382,7 +382,7 @@ describe("documentUpdater", () => {
|
||||
text: "Initial",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "\n\nAppended",
|
||||
document,
|
||||
@@ -415,7 +415,7 @@ describe("documentUpdater", () => {
|
||||
text: "Existing",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Prepended",
|
||||
document,
|
||||
@@ -442,7 +442,7 @@ describe("documentUpdater", () => {
|
||||
text: "**Bold**",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Prepended",
|
||||
document,
|
||||
@@ -478,7 +478,7 @@ describe("documentUpdater", () => {
|
||||
text: "Existing",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Prepended\n\n",
|
||||
document,
|
||||
@@ -588,7 +588,7 @@ describe("documentUpdater", () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
withAPIContext(user, (ctx) =>
|
||||
withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "replacement",
|
||||
findText: "nonexistent text",
|
||||
@@ -718,7 +718,7 @@ describe("documentUpdater", () => {
|
||||
text: "- First item\n- Second item\n- Third item",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "* Updated item",
|
||||
findText: "* Second item",
|
||||
@@ -750,7 +750,7 @@ describe("documentUpdater", () => {
|
||||
text: "1. Alpha one.\n2. Bravo two:\n\n :::info\n A note inside item two.\n :::\n3. Charlie three.",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "Amber",
|
||||
findText: "Alpha",
|
||||
@@ -803,7 +803,7 @@ describe("documentUpdater", () => {
|
||||
|
||||
const lastRow = await lineContaining(document, "gamma");
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: `${lastRow}\n\n## New\n\nbody text`,
|
||||
findText: lastRow,
|
||||
@@ -834,7 +834,7 @@ describe("documentUpdater", () => {
|
||||
|
||||
const middleRow = await lineContaining(document, "beta");
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: `${middleRow}\n\n## New`,
|
||||
findText: middleRow,
|
||||
@@ -855,7 +855,7 @@ describe("documentUpdater", () => {
|
||||
text: "* alpha\n* beta\n* gamma",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "- beta EDITED",
|
||||
findText: "* beta",
|
||||
@@ -887,7 +887,7 @@ describe("documentUpdater", () => {
|
||||
text: "> alpha\n>\n> beta\n>\n> gamma\n\n## Notes",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "beta EDITED",
|
||||
findText: "> beta",
|
||||
@@ -924,7 +924,7 @@ describe("documentUpdater", () => {
|
||||
|
||||
const lastRow = await lineContaining(document, "two");
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: `${lastRow}\n${lastRow.replace("two", "three").replace("2", "3")}`,
|
||||
findText: lastRow,
|
||||
@@ -968,7 +968,7 @@ describe("documentUpdater", () => {
|
||||
},
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "* beta EDITED\n* delta",
|
||||
findText: "* beta",
|
||||
@@ -1018,7 +1018,7 @@ describe("documentUpdater", () => {
|
||||
},
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "",
|
||||
findText: "* alpha\n",
|
||||
@@ -1046,7 +1046,7 @@ describe("documentUpdater", () => {
|
||||
text: "# Title\n\n* only item\n\nafter",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "plain text now",
|
||||
findText: "* only item",
|
||||
@@ -1073,7 +1073,7 @@ describe("documentUpdater", () => {
|
||||
text: "* alpha\n* beta\n* gamma",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "1. beta EDITED",
|
||||
findText: "* beta",
|
||||
@@ -1101,7 +1101,7 @@ describe("documentUpdater", () => {
|
||||
text: "1. one\n2. two\n3. three",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "2) two EDITED",
|
||||
findText: "2. two",
|
||||
@@ -1134,7 +1134,7 @@ describe("documentUpdater", () => {
|
||||
text: "a. alpha",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "a. alpha\n1) numeric",
|
||||
findText: "a. alpha",
|
||||
@@ -1168,7 +1168,7 @@ describe("documentUpdater", () => {
|
||||
text: "* alpha\n * one\n * two\n * three\n* beta",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: " - two EDITED",
|
||||
findText: " * two",
|
||||
@@ -1212,7 +1212,7 @@ describe("documentUpdater", () => {
|
||||
text: "> alpha\n>\n> beta",
|
||||
});
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
document = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
text: "> beta\n\n## New\n\nbody",
|
||||
findText: "> beta",
|
||||
@@ -2426,7 +2426,7 @@ describe("documentUpdater", () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({ teamId: user.teamId });
|
||||
|
||||
const result = await withAPIContext(user, (ctx) =>
|
||||
const result = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
document,
|
||||
text: "- [ ] one\n\n+++ Title\nBody\n+++",
|
||||
@@ -2450,7 +2450,7 @@ describe("documentUpdater", () => {
|
||||
content,
|
||||
});
|
||||
|
||||
const result = await withAPIContext(user, (ctx) =>
|
||||
const result = await withContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
document,
|
||||
text: replacement,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { DocumentConflictError, ValidationError } from "@server/errors";
|
||||
import { Document } from "@server/models";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import { TextHelper } from "@server/models/helpers/TextHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** The existing document */
|
||||
@@ -48,7 +48,7 @@ type Props = {
|
||||
* @returns Document The updated document
|
||||
*/
|
||||
export default async function documentUpdater(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{
|
||||
document,
|
||||
title,
|
||||
@@ -68,8 +68,8 @@ export default async function documentUpdater(
|
||||
deprecatedReason,
|
||||
}: Props
|
||||
): Promise<Document> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
const cId = collectionId || document.collectionId;
|
||||
|
||||
document.fill({
|
||||
|
||||
@@ -4,7 +4,7 @@ import Logger from "@server/logging/Logger";
|
||||
import type { AuthenticationProvider } from "@server/models";
|
||||
import { ExternalGroup, Group, GroupUser } from "@server/models";
|
||||
import type { User, Team } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import type { ExternalGroupData } from "@server/utils/GroupSyncProvider";
|
||||
|
||||
interface Props {
|
||||
@@ -32,15 +32,15 @@ interface GroupSyncResult {
|
||||
* groups. Upserts ExternalGroup records, auto-creates Group records when
|
||||
* needed, and manages GroupUser memberships.
|
||||
*
|
||||
* @param ctx - API context with transaction.
|
||||
* @param ctx - context with transaction.
|
||||
* @param props - sync parameters.
|
||||
* @returns result summary.
|
||||
*/
|
||||
async function groupsSyncer(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ user, team, authenticationProvider, externalGroups }: Props
|
||||
): Promise<GroupSyncResult> {
|
||||
const { transaction } = ctx.state;
|
||||
const { transaction } = ctx;
|
||||
const result: GroupSyncResult = {
|
||||
groupsCreated: 0,
|
||||
membershipsAdded: 0,
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
import { PersonalCollectionId } from "@shared/constants";
|
||||
import { createContext } from "@server/context";
|
||||
import { withTransaction } from "@server/context";
|
||||
import { Collection } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
/**
|
||||
* Loads the personal collection of the acting user, and creates it when the
|
||||
* user does not have one yet.
|
||||
*
|
||||
* @param ctx the API context containing the acting user.
|
||||
* @param ctx the context containing the acting user.
|
||||
* @returns the personal collection, with the memberships of the user loaded.
|
||||
* @throws AuthorizationError when the collection does not exist and the user
|
||||
* may not create it.
|
||||
*/
|
||||
export default async function personalCollectionLoader(
|
||||
ctx: APIContext
|
||||
ctx: Context
|
||||
): Promise<Collection> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const existing = await Collection.findPersonal(user, { transaction });
|
||||
if (existing) {
|
||||
@@ -33,14 +33,7 @@ export default async function personalCollectionLoader(
|
||||
|
||||
// The creation lock is only held inside a transaction.
|
||||
return sequelize.transaction((innerTransaction) =>
|
||||
Collection.findOrCreatePersonal(
|
||||
createContext({
|
||||
user,
|
||||
authType: ctx.state.auth.type,
|
||||
ip: ctx.context.ip,
|
||||
transaction: innerTransaction,
|
||||
})
|
||||
)
|
||||
Collection.findOrCreatePersonal(withTransaction(ctx, innerTransaction))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -49,7 +42,7 @@ export default async function personalCollectionLoader(
|
||||
* the acting user, which is created when it does not exist yet. Other values
|
||||
* are returned unchanged.
|
||||
*
|
||||
* @param ctx the API context containing the acting user.
|
||||
* @param ctx the context containing the acting user.
|
||||
* @param collectionId the requested collectionId.
|
||||
* @returns the resolved collectionId.
|
||||
* @throws AuthorizationError when the collection does not exist and the user
|
||||
@@ -57,7 +50,7 @@ export default async function personalCollectionLoader(
|
||||
*/
|
||||
export async function resolvePersonalCollectionId<
|
||||
T extends string | null | undefined,
|
||||
>(ctx: APIContext, collectionId: T): Promise<T | string> {
|
||||
>(ctx: Context, collectionId: T): Promise<T | string> {
|
||||
return collectionId === PersonalCollectionId
|
||||
? (await personalCollectionLoader(ctx)).id
|
||||
: collectionId;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Event } from "@server/models";
|
||||
import { buildDocument, buildUser } from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import pinCreator from "./pinCreator";
|
||||
|
||||
describe("pinCreator", () => {
|
||||
@@ -11,7 +11,7 @@ describe("pinCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const pin = await withAPIContext(user, (ctx) =>
|
||||
const pin = await withContext(user, (ctx) =>
|
||||
pinCreator({
|
||||
ctx,
|
||||
user,
|
||||
@@ -37,7 +37,7 @@ describe("pinCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const pin = await withAPIContext(user, (ctx) =>
|
||||
const pin = await withContext(user, (ctx) =>
|
||||
pinCreator({
|
||||
ctx,
|
||||
user,
|
||||
|
||||
@@ -3,11 +3,11 @@ import type { WhereOptions } from "sequelize";
|
||||
import { Sequelize, Op } from "sequelize";
|
||||
import type { User } from "@server/models";
|
||||
import { Pin } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** The request context */
|
||||
ctx: APIContext;
|
||||
ctx: Context;
|
||||
/** The user creating the pin */
|
||||
user: User;
|
||||
/** The document to pin */
|
||||
@@ -33,7 +33,7 @@ export default async function pinCreator({
|
||||
...rest
|
||||
}: Props): Promise<Pin> {
|
||||
let { index } = rest;
|
||||
const { transaction } = ctx.context;
|
||||
const { transaction } = ctx;
|
||||
const where: WhereOptions<Pin> = {
|
||||
teamId: user.teamId,
|
||||
...(collectionId ? { collectionId } : { collectionId: { [Op.is]: null } }),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Star, Event } from "@server/models";
|
||||
import { buildDocument, buildUser } from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import starCreator from "./starCreator";
|
||||
|
||||
describe("starCreator", () => {
|
||||
@@ -11,7 +11,7 @@ describe("starCreator", () => {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const star = await withAPIContext(user, (ctx) =>
|
||||
const star = await withContext(user, (ctx) =>
|
||||
starCreator({
|
||||
ctx,
|
||||
documentId: document.id,
|
||||
@@ -42,7 +42,7 @@ describe("starCreator", () => {
|
||||
index: "P",
|
||||
});
|
||||
|
||||
const star = await withAPIContext(user, (ctx) =>
|
||||
const star = await withContext(user, (ctx) =>
|
||||
starCreator({
|
||||
ctx,
|
||||
documentId: document.id,
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { WhereOptions } from "sequelize";
|
||||
import { Sequelize } from "sequelize";
|
||||
import type { User } from "@server/models";
|
||||
import { Star } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** The user creating the star */
|
||||
@@ -15,7 +15,7 @@ type Props = {
|
||||
/** The sorted index for the star in the sidebar If no index is provided then it will be at the end */
|
||||
index?: string;
|
||||
/** The request context */
|
||||
ctx: APIContext;
|
||||
ctx: Context;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -48,7 +48,7 @@ export default async function starCreator({
|
||||
Sequelize.literal('"star"."index" collate "C"'),
|
||||
["updatedAt", "DESC"],
|
||||
],
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
});
|
||||
|
||||
// create a star at the beginning of the list
|
||||
|
||||
@@ -4,11 +4,11 @@ import { createContext } from "@server/context";
|
||||
import type { Document, User } from "@server/models";
|
||||
import { Subscription, Event } from "@server/models";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import type { APIContext, DocumentEvent, RevisionEvent } from "@server/types";
|
||||
import type { Context, DocumentEvent, RevisionEvent } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** The request context, which also contains the user creating the subscription */
|
||||
ctx: APIContext;
|
||||
ctx: Context;
|
||||
/** The document to subscribe to */
|
||||
documentId?: string;
|
||||
/** The collection to subscribe to */
|
||||
@@ -34,7 +34,7 @@ export default async function subscriptionCreator({
|
||||
event,
|
||||
resubscribe = true,
|
||||
}: Props): Promise<Subscription> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
let rows: SubscriptionRow[];
|
||||
const now = new Date();
|
||||
@@ -53,7 +53,7 @@ export default async function subscriptionCreator({
|
||||
now,
|
||||
},
|
||||
type: QueryTypes.SELECT,
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
}
|
||||
);
|
||||
} else if (collectionId) {
|
||||
@@ -71,7 +71,7 @@ export default async function subscriptionCreator({
|
||||
now,
|
||||
},
|
||||
type: QueryTypes.SELECT,
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
}
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { InferCreationAttributes } from "sequelize";
|
||||
import { traceFunction } from "@server/logging/tracing";
|
||||
import { Team } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
/** The displayed name of the team */
|
||||
@@ -22,7 +22,7 @@ type Props = {
|
||||
};
|
||||
|
||||
async function teamCreator(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ name, subdomain, avatarUrl, authenticationProviders }: Props
|
||||
): Promise<Team> {
|
||||
if (!avatarUrl?.startsWith("http")) {
|
||||
@@ -30,7 +30,7 @@ async function teamCreator(
|
||||
}
|
||||
|
||||
const availableSubdomain = await Team.findAvailableSubdomain(subdomain, {
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
});
|
||||
return await Team.createWithCtx(
|
||||
ctx,
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
retryOnUniqueConstraintError,
|
||||
sequelize,
|
||||
} from "@server/storage/database";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type TeamProvisionerResult = {
|
||||
team: Team;
|
||||
@@ -45,7 +45,7 @@ type Props = {
|
||||
};
|
||||
|
||||
async function teamProvisioner(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ teamId, name, domain, subdomain, avatarUrl, authenticationProvider }: Props
|
||||
): Promise<TeamProvisionerResult> {
|
||||
const where = teamId
|
||||
|
||||
@@ -5,7 +5,7 @@ import { randomString } from "@shared/random";
|
||||
import { CommentingAccess, Plan, TeamPreference } from "@shared/types";
|
||||
import { Team } from "@server/models";
|
||||
import { buildAdmin, buildTeam, buildUser } from "@server/test/factories";
|
||||
import { setCloudHosted, withAPIContext } from "@server/test/support";
|
||||
import { setCloudHosted, withContext } from "@server/test/support";
|
||||
import teamUpdater from "./teamUpdater";
|
||||
|
||||
describe("teamUpdater", () => {
|
||||
@@ -27,7 +27,7 @@ describe("teamUpdater", () => {
|
||||
team,
|
||||
user,
|
||||
run: () =>
|
||||
withAPIContext(user, (ctx) =>
|
||||
withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: {
|
||||
preferences: { [TeamPreference.DefaultShareExpiryDays]: days },
|
||||
@@ -78,7 +78,7 @@ describe("teamUpdater", () => {
|
||||
|
||||
const newValue = CommentingAccess.None;
|
||||
|
||||
const updatedTeam = await withAPIContext(user, (ctx) =>
|
||||
const updatedTeam = await withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: {
|
||||
preferences: {
|
||||
@@ -104,7 +104,7 @@ describe("teamUpdater", () => {
|
||||
await team.save();
|
||||
|
||||
// Try to set the same value again
|
||||
const updatedTeam = await withAPIContext(user, (ctx) =>
|
||||
const updatedTeam = await withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: {
|
||||
preferences: {
|
||||
@@ -134,7 +134,7 @@ describe("teamUpdater", () => {
|
||||
await team.save();
|
||||
|
||||
// Pass an object with the same values (but different reference)
|
||||
const updatedTeam = await withAPIContext(user, (ctx) =>
|
||||
const updatedTeam = await withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: {
|
||||
preferences: {
|
||||
@@ -166,7 +166,7 @@ describe("teamUpdater", () => {
|
||||
team.setPreference(TeamPreference.ViewersCanExport, true);
|
||||
await team.save();
|
||||
|
||||
const updatedTeam = await withAPIContext(user, (ctx) =>
|
||||
const updatedTeam = await withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: {
|
||||
preferences: {
|
||||
@@ -194,7 +194,7 @@ describe("teamUpdater", () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
|
||||
const updatedTeam = await withAPIContext(user, (ctx) =>
|
||||
const updatedTeam = await withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: { name: "Updated Team Name" },
|
||||
user,
|
||||
@@ -214,7 +214,7 @@ describe("teamUpdater", () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
|
||||
const updatedTeam = await withAPIContext(user, (ctx) =>
|
||||
const updatedTeam = await withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: { subdomain },
|
||||
user,
|
||||
@@ -232,7 +232,7 @@ describe("teamUpdater", () => {
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
|
||||
await expect(
|
||||
withAPIContext(user, (ctx) =>
|
||||
withContext(user, (ctx) =>
|
||||
teamUpdater(ctx, {
|
||||
params: { subdomain },
|
||||
user,
|
||||
|
||||
@@ -5,7 +5,7 @@ import { ValidationError } from "@server/errors";
|
||||
import type { User } from "@server/models";
|
||||
import { Collection, Team, TeamDomain } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
type Props = {
|
||||
params: Partial<Omit<Team, "allowedDomains">> & { allowedDomains?: string[] };
|
||||
@@ -13,7 +13,7 @@ type Props = {
|
||||
team: Team;
|
||||
};
|
||||
|
||||
const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => {
|
||||
const teamUpdater = async (ctx: Context, { params, user, team }: Props) => {
|
||||
const { allowedDomains, preferences, subdomain, ...attributes } = params;
|
||||
team.fill(attributes);
|
||||
|
||||
@@ -25,7 +25,7 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => {
|
||||
teamId: team.id,
|
||||
ownerId: null,
|
||||
},
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
});
|
||||
|
||||
if (!collection) {
|
||||
@@ -40,7 +40,7 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => {
|
||||
const existing = await Team.findOne({
|
||||
where: { subdomain: newSubdomain },
|
||||
paranoid: false,
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
@@ -54,7 +54,7 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => {
|
||||
if (allowedDomains !== undefined) {
|
||||
const existingAllowedDomains = await TeamDomain.findAll({
|
||||
where: { teamId: team.id },
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
});
|
||||
|
||||
// Only keep existing domains if they are still in the list of allowed domains
|
||||
|
||||
@@ -2,13 +2,13 @@ import { faker } from "@faker-js/faker";
|
||||
import { UserRole } from "@shared/types";
|
||||
import { buildTeam, buildUser } from "@server/test/factories";
|
||||
import userInviter from "./userInviter";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import { TeamDomain } from "@server/models";
|
||||
|
||||
describe("userInviter", () => {
|
||||
it("should return sent invites", async () => {
|
||||
const user = await buildUser();
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
userInviter(ctx, {
|
||||
invites: [
|
||||
{
|
||||
@@ -24,7 +24,7 @@ describe("userInviter", () => {
|
||||
|
||||
it("should filter empty invites", async () => {
|
||||
const user = await buildUser();
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
userInviter(ctx, {
|
||||
invites: [
|
||||
{
|
||||
@@ -48,7 +48,7 @@ describe("userInviter", () => {
|
||||
createdById: user.id,
|
||||
});
|
||||
|
||||
await withAPIContext(user, (ctx) =>
|
||||
await withContext(user, (ctx) =>
|
||||
expect(
|
||||
userInviter(ctx, {
|
||||
invites: [
|
||||
@@ -74,7 +74,7 @@ describe("userInviter", () => {
|
||||
createdById: user.id,
|
||||
});
|
||||
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
userInviter(ctx, {
|
||||
invites: [
|
||||
{
|
||||
@@ -92,7 +92,7 @@ describe("userInviter", () => {
|
||||
|
||||
it("should filter obviously bunk emails", async () => {
|
||||
const user = await buildUser();
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
userInviter(ctx, {
|
||||
invites: [
|
||||
{
|
||||
@@ -108,7 +108,7 @@ describe("userInviter", () => {
|
||||
|
||||
it("should not send duplicates", async () => {
|
||||
const user = await buildUser();
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
userInviter(ctx, {
|
||||
invites: [
|
||||
{
|
||||
@@ -130,7 +130,7 @@ describe("userInviter", () => {
|
||||
it("should not send invites to existing team members", async () => {
|
||||
const email = faker.internet.email().toLowerCase();
|
||||
const user = await buildUser({ email });
|
||||
const response = await withAPIContext(user, (ctx) =>
|
||||
const response = await withContext(user, (ctx) =>
|
||||
userInviter(ctx, {
|
||||
invites: [
|
||||
{
|
||||
|
||||
@@ -5,7 +5,7 @@ import env from "@server/env";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { User, Team } from "@server/models";
|
||||
import { UserFlag } from "@server/models/User";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { DomainNotAllowedError } from "@server/errors";
|
||||
import { authorize, can } from "@server/policies";
|
||||
|
||||
@@ -21,14 +21,14 @@ type Props = {
|
||||
};
|
||||
|
||||
export default async function userInviter(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ invites, suppressEmail }: Props
|
||||
): Promise<{
|
||||
sent: Invite[];
|
||||
unsent: Invite[];
|
||||
users: User[];
|
||||
}> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
const team = await Team.findByPk(user.teamId, { rejectOnEmpty: true });
|
||||
|
||||
if (invites.some((invite) => invite.role === UserRole.Guest)) {
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
UserAuthentication,
|
||||
} from "@server/models";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { UserFlag } from "@server/models/User";
|
||||
import UploadUserAvatarTask from "@server/queues/tasks/UploadUserAvatarTask";
|
||||
|
||||
@@ -67,7 +67,7 @@ type Props = {
|
||||
};
|
||||
|
||||
export default async function userProvisioner(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{
|
||||
name,
|
||||
email,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import { buildUser } from "@server/test/factories";
|
||||
import { AuthenticationType } from "@server/types";
|
||||
import { createContext, withTransaction, withUser } from "./context";
|
||||
|
||||
describe("withUser", () => {
|
||||
it("should act as the given user and keep the other fields", async () => {
|
||||
const original = await buildUser();
|
||||
const user = await buildUser();
|
||||
const ctx = createContext({
|
||||
user: original,
|
||||
authType: AuthenticationType.API,
|
||||
ip: "127.0.0.1",
|
||||
});
|
||||
|
||||
const derived = withUser(ctx, user);
|
||||
expect(derived.auth.user).toBe(user);
|
||||
expect(derived.auth.type).toEqual(AuthenticationType.API);
|
||||
expect(derived.ip).toEqual("127.0.0.1");
|
||||
expect(ctx.auth.user).toBe(original);
|
||||
});
|
||||
});
|
||||
|
||||
describe("withTransaction", () => {
|
||||
it("should run in the given transaction and keep the other fields", async () => {
|
||||
const user = await buildUser();
|
||||
const ctx = createContext({ user, ip: "127.0.0.1" });
|
||||
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const derived = withTransaction(ctx, transaction);
|
||||
expect(derived.transaction).toBe(transaction);
|
||||
expect(derived.auth).toBe(ctx.auth);
|
||||
expect(derived.ip).toEqual("127.0.0.1");
|
||||
expect(ctx.transaction).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
+63
-13
@@ -1,10 +1,26 @@
|
||||
import type { Transaction } from "sequelize";
|
||||
import type { User } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { AppContext, Authentication, Context } from "@server/types";
|
||||
import { AuthenticationType } from "@server/types";
|
||||
|
||||
/** The fields of a context that model hooks read from query options. */
|
||||
export interface HookContextFields {
|
||||
/** The authentication for the actor performing the mutation. */
|
||||
auth: Authentication;
|
||||
/** The transaction the mutation runs in. */
|
||||
transaction?: Transaction;
|
||||
/** The IP address of the actor. */
|
||||
ip?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory to create a new API context.
|
||||
* Factory to create a new context.
|
||||
*
|
||||
* @param options.user the actor for the context.
|
||||
* @param options.authType the type of authentication used by the actor.
|
||||
* @param options.ip the IP address of the actor, defaults to the last active IP.
|
||||
* @param options.transaction the transaction for database mutations.
|
||||
* @returns the context.
|
||||
*/
|
||||
export function createContext({
|
||||
user,
|
||||
@@ -17,16 +33,50 @@ export function createContext({
|
||||
ip?: string | null;
|
||||
transaction?: Transaction;
|
||||
}) {
|
||||
const auth = { user, type: authType };
|
||||
return {
|
||||
state: {
|
||||
auth,
|
||||
transaction,
|
||||
},
|
||||
context: {
|
||||
auth,
|
||||
ip: ip ?? user?.lastActiveIp,
|
||||
transaction,
|
||||
},
|
||||
} as APIContext;
|
||||
auth: { user, type: authType },
|
||||
ip: ip ?? user?.lastActiveIp,
|
||||
transaction,
|
||||
} as Context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a context from an existing one that acts as the given user.
|
||||
*
|
||||
* @param ctx the context to derive from.
|
||||
* @param user the actor for the new context.
|
||||
* @returns the derived context.
|
||||
*/
|
||||
export function withUser(ctx: AppContext | Context, user?: User) {
|
||||
return createContext({
|
||||
user,
|
||||
authType: ctx.auth?.type,
|
||||
ip: ctx.ip,
|
||||
transaction: ctx.transaction,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a context from an existing one that runs in the given transaction.
|
||||
*
|
||||
* @param ctx the context to derive from.
|
||||
* @param transaction the transaction for the new context.
|
||||
* @returns the derived context.
|
||||
*/
|
||||
export function withTransaction(ctx: Context, transaction: Transaction) {
|
||||
return { auth: ctx.auth, ip: ctx.ip, transaction } as Context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the fields that model hooks read from a context, for use as query options.
|
||||
*
|
||||
* @param ctx the context to read from.
|
||||
* @returns the hook context fields.
|
||||
*/
|
||||
export function toHookContext(ctx: Context): HookContextFields {
|
||||
return {
|
||||
auth: ctx.auth,
|
||||
transaction: ctx.transaction,
|
||||
ip: ctx.ip,
|
||||
};
|
||||
}
|
||||
@@ -23,17 +23,17 @@ export function requestErrorHandler(error: any, ctx: AppContext) {
|
||||
scope.setTag("request_id", requestId as string);
|
||||
}
|
||||
|
||||
const authType = ctx.state?.auth?.type ?? undefined;
|
||||
const authType = ctx.auth?.type ?? undefined;
|
||||
if (authType) {
|
||||
scope.setTag("auth_type", authType);
|
||||
}
|
||||
|
||||
const teamId = ctx.state?.auth?.user?.teamId ?? undefined;
|
||||
const teamId = ctx.auth?.user?.teamId ?? undefined;
|
||||
if (teamId) {
|
||||
scope.setTag("team_id", teamId);
|
||||
}
|
||||
|
||||
const userId = ctx.state?.auth?.user?.id ?? undefined;
|
||||
const userId = ctx.auth?.user?.id ?? undefined;
|
||||
if (userId) {
|
||||
scope.setUser({
|
||||
id: userId,
|
||||
|
||||
@@ -60,7 +60,7 @@ export function attachmentTools(server: McpServer, scopes: string[]) {
|
||||
async ({ contentType, name, size }, extra) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(extra);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
const team = await Team.findByPk(user.teamId, {
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
|
||||
@@ -200,7 +200,7 @@ export function collectionTools(server: McpServer, scopes: string[]) {
|
||||
withTracing("create_collection", async (input, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
const team = await Team.findByPk(user.teamId, {
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
@@ -274,7 +274,7 @@ export function collectionTools(server: McpServer, scopes: string[]) {
|
||||
withTracing("update_collection", async (input, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const collection = await Collection.findByPk(input.id, {
|
||||
userId: user.id,
|
||||
@@ -360,11 +360,11 @@ export function collectionTools(server: McpServer, scopes: string[]) {
|
||||
async ({ id, archive, reason }, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
ctx.state.transaction = transaction;
|
||||
ctx.context.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
|
||||
const collection = await Collection.findByPk(id, {
|
||||
userId: user.id,
|
||||
|
||||
@@ -196,14 +196,14 @@ export function commentTools(server: McpServer, scopes: string[]) {
|
||||
) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const data = commentParser.parse(text).toJSON();
|
||||
const commentId = uuidv4();
|
||||
|
||||
const comment = await sequelize.transaction(async (transaction) => {
|
||||
ctx.state.transaction = transaction;
|
||||
ctx.context.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
|
||||
let document = await Document.findByPk(documentId, {
|
||||
userId: user.id,
|
||||
@@ -305,7 +305,7 @@ export function commentTools(server: McpServer, scopes: string[]) {
|
||||
withTracing("update_comment", async ({ id, text, status }, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const comment = await Comment.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
@@ -381,7 +381,7 @@ export function commentTools(server: McpServer, scopes: string[]) {
|
||||
withTracing("delete_comment", async ({ id }, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const comment = await Comment.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
|
||||
@@ -431,7 +431,7 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
try {
|
||||
const { collectionId, parentDocumentId, templateId } = input;
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const { collection, parentDocument } = await authorizeDocumentCreate(
|
||||
ctx,
|
||||
@@ -466,12 +466,12 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
publish: input.publish !== false,
|
||||
collectionId: collection?.id,
|
||||
parentDocumentId: parentDocument?.id,
|
||||
authType: ctx.state.auth.type,
|
||||
ip: ctx.context.ip,
|
||||
authType: ctx.auth.type,
|
||||
ip: ctx.ip,
|
||||
})
|
||||
: await sequelize.transaction(async (transaction) => {
|
||||
ctx.state.transaction = transaction;
|
||||
ctx.context.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
|
||||
return documentCreator(ctx, {
|
||||
title: input.title,
|
||||
@@ -545,11 +545,11 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
withTracing("move_document", async (input, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const document = await sequelize.transaction(async (transaction) => {
|
||||
ctx.state.transaction = transaction;
|
||||
ctx.context.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
|
||||
const document = await Document.findByPk(input.id, {
|
||||
userId: user.id,
|
||||
@@ -729,12 +729,12 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
}
|
||||
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
// Returns null when the update persisted nothing.
|
||||
const updated = await sequelize.transaction(async (transaction) => {
|
||||
ctx.state.transaction = transaction;
|
||||
ctx.context.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
|
||||
const document = await Document.findByPk(input.id, {
|
||||
userId: user.id,
|
||||
@@ -881,11 +881,11 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
async ({ id, archive, reason }, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
ctx.state.transaction = transaction;
|
||||
ctx.context.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
|
||||
const document = await Document.findByPk(id, {
|
||||
userId: user.id,
|
||||
@@ -940,11 +940,11 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
withTracing("restore_document", async ({ id, collectionId }, context) => {
|
||||
try {
|
||||
const ctx = buildAPIContext(context);
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const document = await sequelize.transaction(async (transaction) => {
|
||||
ctx.state.transaction = transaction;
|
||||
ctx.context.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
ctx.transaction = transaction;
|
||||
|
||||
const document = await Document.findByPk(id, {
|
||||
userId: user.id,
|
||||
|
||||
+6
-6
@@ -6,7 +6,7 @@ import { Collection, Share, type Team, type User } from "@server/models";
|
||||
import { addTags } from "@server/logging/tracer";
|
||||
import { traceFunction } from "@server/logging/tracing";
|
||||
import { can } from "@server/policies";
|
||||
import { type APIContext, AuthenticationType } from "@server/types";
|
||||
import { type Context, AuthenticationType } from "@server/types";
|
||||
import type { NavigationNode } from "@shared/types";
|
||||
|
||||
interface McpContext {
|
||||
@@ -24,11 +24,11 @@ export function getActorFromContext(context: McpContext) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a minimal APIContext from the MCP request context for use with
|
||||
* Constructs a minimal Context from the MCP request context for use with
|
||||
* server commands that require a Koa-style context.
|
||||
*
|
||||
* @param context - the MCP request context.
|
||||
* @returns a partial APIContext suitable for command functions.
|
||||
* @returns a partial Context suitable for command functions.
|
||||
*/
|
||||
export function buildAPIContext(context: McpContext) {
|
||||
const user = context.http?.authInfo?.extra?.user as User;
|
||||
@@ -42,11 +42,11 @@ export function buildAPIContext(context: McpContext) {
|
||||
};
|
||||
|
||||
return {
|
||||
state: { auth },
|
||||
context: { auth, ip },
|
||||
auth,
|
||||
ip,
|
||||
request: { secure: env.URL.startsWith("https://") },
|
||||
cookies: { get: () => undefined, set: () => undefined },
|
||||
} as unknown as APIContext;
|
||||
} as unknown as Context;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,7 @@ import { toError } from "@shared/utils/error";
|
||||
import { parseDomain } from "@shared/utils/domains";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { Team } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
/**
|
||||
* An authentication middleware that should be used on routes that return from external auth flows
|
||||
@@ -19,17 +19,17 @@ export default function apexAuthRedirect<T>({
|
||||
getErrorPath,
|
||||
}: {
|
||||
/** Get the team ID for the current request */
|
||||
getTeamId: (ctx: APIContext<T>) => string | null | undefined;
|
||||
getTeamId: (ctx: Context<T>) => string | null | undefined;
|
||||
/** Get the redirect URL for the given team ID */
|
||||
getRedirectPath: (ctx: APIContext<T>, team: Team) => string;
|
||||
getRedirectPath: (ctx: Context<T>, team: Team) => string;
|
||||
/** Get the error URL for the current request */
|
||||
getErrorPath: (ctx: APIContext<T>) => string;
|
||||
getErrorPath: (ctx: Context<T>) => string;
|
||||
}) {
|
||||
return async function apexAuthRedirectMiddleware(
|
||||
ctx: APIContext<T>,
|
||||
ctx: Context<T>,
|
||||
next: Next
|
||||
) {
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
if (user) {
|
||||
return next();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { Context, Next } from "koa";
|
||||
import type { Next } from "koa";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
export default function apexRedirect() {
|
||||
return async function apexRedirectMiddleware(ctx: Context, next: Next) {
|
||||
return async function apexRedirectMiddleware(ctx: AppContext, next: Next) {
|
||||
if (ctx.headers.host === "getoutline.com") {
|
||||
ctx.redirect(`https://www.${ctx.headers.host}${ctx.path}`);
|
||||
} else {
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { Next } from "koa";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
/**
|
||||
* Middleware that defines the `ctx.context` getter, which provides the current
|
||||
* request's auth, transaction, and IP to database mutation helpers like
|
||||
* `saveWithCtx` and `destroyWithCtx`.
|
||||
*
|
||||
* @returns The middleware function.
|
||||
*/
|
||||
export function apiContext() {
|
||||
return async function apiContextMiddleware(ctx: AppContext, next: Next) {
|
||||
Object.defineProperty(ctx, "context", {
|
||||
configurable: true,
|
||||
get() {
|
||||
return {
|
||||
auth: ctx.state.auth,
|
||||
transaction: ctx.state.transaction,
|
||||
ip: ctx.request.ip,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
return next();
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Context, Next } from "koa";
|
||||
import type { Next } from "koa";
|
||||
import env from "@server/env";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
/**
|
||||
* Middleware that sets the response headers that are needed when serving the
|
||||
@@ -18,7 +19,7 @@ export default function appHeaders() {
|
||||
|
||||
const timingAllowOrigin = timingOrigins.join(", ");
|
||||
|
||||
return async function appHeadersMiddleware(ctx: Context, next: Next) {
|
||||
return async function appHeadersMiddleware(ctx: AppContext, next: Next) {
|
||||
ctx.set("Timing-Allow-Origin", timingAllowOrigin);
|
||||
|
||||
// Allow the JS Self-Profiling API to be used for local performance work.
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { DefaultState } from "koa";
|
||||
import { errToString } from "@shared/utils/error";
|
||||
import { randomString } from "@shared/random";
|
||||
import { Scope } from "@shared/types";
|
||||
@@ -16,61 +15,49 @@ import auth from "./authentication";
|
||||
describe("Authentication middleware", () => {
|
||||
describe("with session JWT", () => {
|
||||
it("should authenticate with correct session token", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
expect(state.auth.user.id).toEqual(user.id);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
expect(ctx.auth?.user.id).toEqual(user.id);
|
||||
});
|
||||
|
||||
it("should return error with invalid session token", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}error`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}error`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (e) {
|
||||
expect(errToString(e)).toBe("Invalid token");
|
||||
}
|
||||
});
|
||||
|
||||
it("should return error if AuthenticationType mismatches", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth({
|
||||
type: AuthenticationType.API,
|
||||
});
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (e) {
|
||||
expect(errToString(e)).toBe("Invalid authentication type");
|
||||
}
|
||||
@@ -79,24 +66,19 @@ describe("Authentication middleware", () => {
|
||||
|
||||
describe("with API key", () => {
|
||||
it("should authenticate user with valid API key", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
const key = await buildApiKey({ userId: user.id });
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${key.value}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
expect(state.auth.user.id).toEqual(user.id);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${key.value}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
expect(ctx.auth?.user.id).toEqual(user.id);
|
||||
});
|
||||
it("should authenticate with global read scope on read endpoints", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
const key = await buildApiKey({
|
||||
@@ -104,23 +86,20 @@ describe("Authentication middleware", () => {
|
||||
scope: [Scope.Read],
|
||||
});
|
||||
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
originalUrl: "/api/auth.info",
|
||||
request: {
|
||||
url: "/auth.info",
|
||||
get: vi.fn(() => `Bearer ${key.value}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
expect(state.auth.user.id).toEqual(user.id);
|
||||
const ctx = buildMockContext({
|
||||
originalUrl: "/api/auth.info",
|
||||
request: {
|
||||
url: "/auth.info",
|
||||
get: vi.fn(() => `Bearer ${key.value}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
expect(ctx.auth?.user.id).toEqual(user.id);
|
||||
});
|
||||
|
||||
it("should return 403 authorization error when scope does not match", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
const key = await buildApiKey({
|
||||
@@ -129,18 +108,15 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
originalUrl: "/api/documents.create",
|
||||
request: {
|
||||
url: "/documents.create",
|
||||
get: vi.fn(() => `Bearer ${key.value}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
originalUrl: "/api/documents.create",
|
||||
request: {
|
||||
url: "/documents.create",
|
||||
get: vi.fn(() => `Bearer ${key.value}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
throw new Error("Expected error to be thrown");
|
||||
} catch (e) {
|
||||
expect(e).toHaveProperty("status", 403);
|
||||
@@ -152,20 +128,16 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should return error with invalid API key", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const authMiddleware = auth();
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${randomString(38)}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${randomString(38)}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (e) {
|
||||
expect(errToString(e)).toBe("Invalid API key");
|
||||
}
|
||||
@@ -174,7 +146,6 @@ describe("Authentication middleware", () => {
|
||||
|
||||
describe("with OAuth access token", () => {
|
||||
it("should authenticate user with valid OAuth access token", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
const authentication = await buildOAuthAuthentication({
|
||||
@@ -182,23 +153,20 @@ describe("Authentication middleware", () => {
|
||||
scope: [Scope.Read],
|
||||
});
|
||||
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
originalUrl: "/api/users.info",
|
||||
request: {
|
||||
url: "/users.info",
|
||||
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
expect(state.auth.user.id).toEqual(user.id);
|
||||
const ctx = buildMockContext({
|
||||
originalUrl: "/api/users.info",
|
||||
request: {
|
||||
url: "/users.info",
|
||||
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
expect(ctx.auth?.user.id).toEqual(user.id);
|
||||
});
|
||||
|
||||
it("should return error with invalid scope", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
const authentication = await buildOAuthAuthentication({
|
||||
@@ -207,18 +175,15 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
originalUrl: "/api/documents.create",
|
||||
request: {
|
||||
url: "/documents.create",
|
||||
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
originalUrl: "/api/documents.create",
|
||||
request: {
|
||||
url: "/documents.create",
|
||||
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (e) {
|
||||
expect(errToString(e)).toContain(
|
||||
"does not have access to this resource"
|
||||
@@ -227,7 +192,6 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should return error with OAuth access token in body", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
const authentication = await buildOAuthAuthentication({
|
||||
@@ -235,21 +199,18 @@ describe("Authentication middleware", () => {
|
||||
scope: [Scope.Read],
|
||||
});
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
originalUrl: "/api/users.info",
|
||||
request: {
|
||||
url: "/users.info",
|
||||
get: vi.fn(() => null),
|
||||
body: {
|
||||
token: authentication.accessToken,
|
||||
},
|
||||
const ctx = buildMockContext({
|
||||
originalUrl: "/api/users.info",
|
||||
request: {
|
||||
url: "/users.info",
|
||||
get: vi.fn(() => null),
|
||||
body: {
|
||||
token: authentication.accessToken,
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (e) {
|
||||
expect(errToString(e)).toContain(
|
||||
"must be passed in the Authorization header"
|
||||
@@ -259,20 +220,16 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should return error message if no auth token is available", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const authMiddleware = auth();
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => "error"),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => "error"),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (e) {
|
||||
expect(errToString(e)).toBe(
|
||||
'Bad Authorization header format. Format is "Authorization: Bearer <token>"'
|
||||
@@ -281,27 +238,22 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should allow passing session token in a cookie", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => null),
|
||||
},
|
||||
cookies: {
|
||||
get: vi.fn(() => user.getSessionToken()),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
expect(state.auth.user.id).toEqual(user.id);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => null),
|
||||
},
|
||||
cookies: {
|
||||
get: vi.fn(() => user.getSessionToken()),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
expect(ctx.auth?.user.id).toEqual(user.id);
|
||||
});
|
||||
|
||||
it("should return error with session token as a GET param", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
|
||||
@@ -314,7 +266,6 @@ describe("Authentication middleware", () => {
|
||||
token: user.getSessionToken(),
|
||||
},
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
@@ -325,7 +276,6 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should return error with session token in body params", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
|
||||
@@ -338,7 +288,6 @@ describe("Authentication middleware", () => {
|
||||
token: user.getSessionToken(),
|
||||
},
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
@@ -349,7 +298,6 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should not accept transfer token as a GET param", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
|
||||
@@ -362,7 +310,6 @@ describe("Authentication middleware", () => {
|
||||
token: user.getTransferToken(),
|
||||
},
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
@@ -373,7 +320,6 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should not accept transfer token in the Authorization header", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const authMiddleware = auth();
|
||||
|
||||
@@ -383,7 +329,6 @@ describe("Authentication middleware", () => {
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getTransferToken()}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
@@ -392,7 +337,6 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should return an error for suspended users", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const admin = await buildAdmin();
|
||||
const user = await buildUser({
|
||||
suspendedAt: new Date(),
|
||||
@@ -402,16 +346,13 @@ describe("Authentication middleware", () => {
|
||||
let error;
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
@@ -423,7 +364,6 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
|
||||
it("should return an error for deleted team", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
await team.destroy();
|
||||
@@ -431,16 +371,13 @@ describe("Authentication middleware", () => {
|
||||
let error;
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
vi.fn()
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, vi.fn());
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
@@ -449,7 +386,6 @@ describe("Authentication middleware", () => {
|
||||
});
|
||||
describe("with skip", () => {
|
||||
it("should ignore credentials when skip returns true", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const apiKey = await buildApiKey({
|
||||
userId: user.id,
|
||||
@@ -460,43 +396,36 @@ describe("Authentication middleware", () => {
|
||||
optional: true,
|
||||
skip: (ctx) => !!ctx.query.sig,
|
||||
});
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${apiKey.value}`),
|
||||
},
|
||||
query: { sig: "signature" },
|
||||
originalUrl: "/api/files.get?sig=signature",
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
next
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${apiKey.value}`),
|
||||
},
|
||||
query: { sig: "signature" },
|
||||
originalUrl: "/api/files.get?sig=signature",
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect(state.auth).toEqual({});
|
||||
expect(ctx.auth).toEqual({});
|
||||
});
|
||||
|
||||
it("should authenticate when skip returns false", async () => {
|
||||
const state = {} as DefaultState;
|
||||
const user = await buildUser();
|
||||
const next = vi.fn();
|
||||
const authMiddleware = auth({
|
||||
optional: true,
|
||||
skip: (ctx) => !!ctx.query.sig,
|
||||
});
|
||||
await authMiddleware(
|
||||
buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
query: {},
|
||||
state,
|
||||
cache: {},
|
||||
}),
|
||||
next
|
||||
);
|
||||
const ctx = buildMockContext({
|
||||
request: {
|
||||
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
|
||||
},
|
||||
query: {},
|
||||
cache: {},
|
||||
});
|
||||
await authMiddleware(ctx, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect(state.auth.user.id).toEqual(user.id);
|
||||
expect(ctx.auth?.user.id).toEqual(user.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -55,7 +55,7 @@ type AuthInput = {
|
||||
export default function auth(options: AuthenticationOptions = {}) {
|
||||
return async function authMiddleware(ctx: AppContext, next: Next) {
|
||||
if (options.skip?.(ctx)) {
|
||||
ctx.state.auth = {};
|
||||
ctx.auth = {};
|
||||
return next();
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ export default function auth(options: AuthenticationOptions = {}) {
|
||||
Promise.all([user.updateActiveAt(ctx), user.team?.updateActiveAt()])
|
||||
);
|
||||
|
||||
ctx.state.auth = {
|
||||
ctx.auth = {
|
||||
user,
|
||||
token,
|
||||
type,
|
||||
@@ -89,7 +89,7 @@ export default function auth(options: AuthenticationOptions = {}) {
|
||||
// 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.state.auth = {};
|
||||
ctx.auth = {};
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { Context, Next } from "koa";
|
||||
import type { Next } from "koa";
|
||||
import helmet from "koa-helmet";
|
||||
import { asyncNoop } from "es-toolkit";
|
||||
import { uniq } from "es-toolkit/compat";
|
||||
import env from "@server/env";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
const getBucketOrigins = (): string[] => {
|
||||
if (env.AWS_S3_ACCELERATE_URL) {
|
||||
@@ -59,7 +60,7 @@ interface CSPOptions {
|
||||
* @param ctx The Koa context of the current request.
|
||||
* @param sources The origins to allow.
|
||||
*/
|
||||
export function allowScriptSrc(ctx: Context, sources: string[]) {
|
||||
export function allowScriptSrc(ctx: AppContext, sources: string[]) {
|
||||
ctx.state.cspScriptSrc = [...(ctx.state.cspScriptSrc ?? []), ...sources];
|
||||
}
|
||||
|
||||
@@ -70,7 +71,7 @@ export function allowScriptSrc(ctx: Context, sources: string[]) {
|
||||
* @param ctx The Koa context of the current request.
|
||||
* @param sources The origins to allow.
|
||||
*/
|
||||
export function allowStyleSrc(ctx: Context, sources: string[]) {
|
||||
export function allowStyleSrc(ctx: AppContext, sources: string[]) {
|
||||
ctx.state.cspStyleSrc = [...(ctx.state.cspStyleSrc ?? []), ...sources];
|
||||
}
|
||||
|
||||
@@ -80,7 +81,7 @@ export function allowStyleSrc(ctx: Context, sources: string[]) {
|
||||
*
|
||||
* @param ctx The Koa context of the current request.
|
||||
*/
|
||||
export function allowFraming(ctx: Context) {
|
||||
export function allowFraming(ctx: AppContext) {
|
||||
ctx.state.cspAllowFraming = true;
|
||||
ctx.remove("X-Frame-Options");
|
||||
}
|
||||
@@ -130,7 +131,7 @@ export default function createCSPMiddleware(options?: CSPOptions) {
|
||||
objectSrc.push(cloudFrontOrigin);
|
||||
}
|
||||
|
||||
return async function cspMiddleware(ctx: Context, next: Next) {
|
||||
return async function cspMiddleware(ctx: AppContext, next: Next) {
|
||||
ctx.state.cspNonce = crypto.randomBytes(16).toString("hex");
|
||||
ctx.state.cspScriptSrc = [];
|
||||
ctx.state.cspStyleSrc = [];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Next } from "koa";
|
||||
import { CommentingAccess, TeamPreference } from "@shared/types";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
/**
|
||||
* Middleware to check if a feature is enabled for the team.
|
||||
@@ -10,8 +10,8 @@ import type { APIContext } from "@server/types";
|
||||
* @returns The middleware function
|
||||
*/
|
||||
export function feature(preference: TeamPreference) {
|
||||
return async function featureEnabledMiddleware(ctx: APIContext, next: Next) {
|
||||
if (!ctx.state.auth.user.team.getPreference(preference)) {
|
||||
return async function featureEnabledMiddleware(ctx: Context, next: Next) {
|
||||
if (!ctx.auth.user.team.getPreference(preference)) {
|
||||
throw ValidationError(`${preference} is currently disabled`);
|
||||
}
|
||||
return next();
|
||||
@@ -24,11 +24,8 @@ export function feature(preference: TeamPreference) {
|
||||
* @returns The middleware function
|
||||
*/
|
||||
export function commentingEnabled() {
|
||||
return async function commentingEnabledMiddleware(
|
||||
ctx: APIContext,
|
||||
next: Next
|
||||
) {
|
||||
const commenting = ctx.state.auth.user.team.getPreference(
|
||||
return async function commentingEnabledMiddleware(ctx: Context, next: Next) {
|
||||
const commenting = ctx.auth.user.team.getPreference(
|
||||
TeamPreference.Commenting
|
||||
);
|
||||
// A legacy boolean `false` (team not yet migrated) means disabled.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Next } from "koa";
|
||||
import { bytesToHumanReadable } from "@shared/utils/files";
|
||||
import { InvalidRequestError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { getFileFromRequest } from "@server/utils/koa";
|
||||
|
||||
export default function multipart({
|
||||
@@ -12,7 +12,7 @@ export default function multipart({
|
||||
/** When true, non-multipart requests pass through with file set to undefined. */
|
||||
optional?: boolean;
|
||||
}) {
|
||||
return async function multipartMiddleware(ctx: APIContext, next: Next) {
|
||||
return async function multipartMiddleware(ctx: Context, next: Next) {
|
||||
if (!ctx.is("multipart/form-data")) {
|
||||
if (optional) {
|
||||
return next();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import passport from "@outlinewiki/koa-passport";
|
||||
import type { Context } from "koa";
|
||||
import {
|
||||
AuthorizationError,
|
||||
InternalOAuthError,
|
||||
@@ -11,7 +10,7 @@ import env from "@server/env";
|
||||
import { AuthenticationError } from "@server/errors";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { Team } from "@server/models";
|
||||
import type { AuthenticationResult } from "@server/types";
|
||||
import type { AuthenticationResult, AppContext } from "@server/types";
|
||||
import { signIn } from "@server/utils/authentication";
|
||||
import { parseState } from "@server/utils/passport";
|
||||
|
||||
@@ -52,7 +51,7 @@ async function getValidatedHost(host: string): Promise<string> {
|
||||
}
|
||||
|
||||
export default function createMiddleware(providerName: string) {
|
||||
return function passportMiddleware(ctx: Context) {
|
||||
return function passportMiddleware(ctx: AppContext) {
|
||||
return passport.authorize(
|
||||
providerName,
|
||||
{
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { Context } from "koa";
|
||||
import { RateLimiterRes } from "rate-limiter-flexible";
|
||||
import env from "@server/env";
|
||||
import { ApiKey } from "@server/models";
|
||||
import * as jwtUtils from "@server/utils/jwt";
|
||||
import RateLimiter from "@server/utils/RateLimiter";
|
||||
import { defaultRateLimiter, rateLimiter } from "./rateLimiter";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
interface MockContextOptions {
|
||||
path?: string;
|
||||
@@ -35,7 +35,7 @@ const createContext = ({
|
||||
query: {},
|
||||
},
|
||||
cookies: { get: () => undefined },
|
||||
}) as unknown as Context;
|
||||
}) as unknown as AppContext;
|
||||
|
||||
describe("rateLimiter middleware", () => {
|
||||
const originalRateLimiterEnabled = env.RATE_LIMITER_ENABLED;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { Context, Next } from "koa";
|
||||
import type { Next } from "koa";
|
||||
import { addTags, getRootSpanFromRequestContext } from "@server/logging/tracer";
|
||||
import { RequestHelper } from "@server/utils/RequestHelper";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
export default function requestTracer() {
|
||||
return async function requestTracerMiddleware(ctx: Context, next: Next) {
|
||||
return async function requestTracerMiddleware(ctx: AppContext, next: Next) {
|
||||
const params = ctx.request.body
|
||||
? RequestHelper.getBodyObject(ctx.request)
|
||||
: ctx.request.query;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { subDays } from "date-fns";
|
||||
import type { Context } from "koa";
|
||||
import { randomString } from "@shared/random";
|
||||
import env from "@server/env";
|
||||
import { buildShare, buildTeam } from "@server/test/factories";
|
||||
import shareDomains from "./shareDomains";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
describe("shareDomains middleware", () => {
|
||||
const buildContext = (hostname: string) =>
|
||||
@@ -11,7 +11,7 @@ describe("shareDomains middleware", () => {
|
||||
host: hostname,
|
||||
hostname,
|
||||
state: {},
|
||||
}) as Context;
|
||||
}) as AppContext;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(env, "isCloudHosted", "get").mockReturnValue(true);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { Context, Next } from "koa";
|
||||
import type { Next } from "koa";
|
||||
import { Op } from "sequelize";
|
||||
import { parseDomain } from "@shared/utils/domains";
|
||||
import env from "@server/env";
|
||||
import { Share } from "@server/models";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
export default function shareDomains() {
|
||||
return async function shareDomainsMiddleware(ctx: Context, next: Next) {
|
||||
return async function shareDomainsMiddleware(ctx: AppContext, next: Next) {
|
||||
const isCustomDomain = parseDomain(ctx.host).custom;
|
||||
|
||||
if (env.isDevelopment || (isCustomDomain && env.isCloudHosted)) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { AppContext } from "@server/types";
|
||||
|
||||
/**
|
||||
* Middleware that wraps a route in a database transaction, useful for mutations
|
||||
* The transaction is available on the context as `ctx.state.transaction` and
|
||||
* The transaction is available on the context as `ctx.transaction` and
|
||||
* should be passed to all database calls within the route.
|
||||
*
|
||||
* @returns The middleware function.
|
||||
@@ -13,7 +13,7 @@ import type { AppContext } from "@server/types";
|
||||
export function transaction() {
|
||||
return async function transactionMiddleware(ctx: AppContext, next: Next) {
|
||||
await sequelize.transaction(async (t: Transaction) => {
|
||||
ctx.state.transaction = t;
|
||||
ctx.transaction = t;
|
||||
return next();
|
||||
});
|
||||
};
|
||||
|
||||
@@ -13,9 +13,9 @@ describe("userAgent middleware", () => {
|
||||
|
||||
await userAgent()(ctx, next);
|
||||
|
||||
expect(ctx.userAgent.source).toEqual(chromeOnMac);
|
||||
expect(ctx.userAgent.isDesktop).toBe(true);
|
||||
expect(ctx.userAgent.isMobile).toBe(false);
|
||||
expect(ctx.userAgent?.source).toEqual(chromeOnMac);
|
||||
expect(ctx.userAgent?.isDesktop).toBe(true);
|
||||
expect(ctx.userAgent?.isMobile).toBe(false);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -24,8 +24,8 @@ describe("userAgent middleware", () => {
|
||||
|
||||
await userAgent()(ctx, vi.fn());
|
||||
|
||||
expect(ctx.userAgent.isMobile).toBe(true);
|
||||
expect(ctx.userAgent.isDesktop).toBe(false);
|
||||
expect(ctx.userAgent?.isMobile).toBe(true);
|
||||
expect(ctx.userAgent?.isDesktop).toBe(false);
|
||||
});
|
||||
|
||||
it("should use a placeholder when the header is missing", async () => {
|
||||
@@ -33,6 +33,6 @@ describe("userAgent middleware", () => {
|
||||
|
||||
await userAgent()(ctx, vi.fn());
|
||||
|
||||
expect(ctx.userAgent.source).toEqual("unknown");
|
||||
expect(ctx.userAgent?.source).toEqual("unknown");
|
||||
});
|
||||
});
|
||||
@@ -3,12 +3,12 @@ import type { z } from "zod";
|
||||
import { ZodError } from "zod";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
export default function validate<T extends z.ZodType<Record<string, unknown>>>(
|
||||
schema: T
|
||||
) {
|
||||
return async function validateMiddleware(ctx: APIContext, next: Next) {
|
||||
return async function validateMiddleware(ctx: Context, next: Next) {
|
||||
try {
|
||||
ctx.input = {
|
||||
...ctx.input,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { Next } from "koa";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { safeEqual } from "@server/utils/crypto";
|
||||
|
||||
export default function validateWebhook({
|
||||
@@ -8,11 +8,11 @@ export default function validateWebhook({
|
||||
getSignatureFromHeader,
|
||||
hmacSign = true,
|
||||
}: {
|
||||
secretKey: string | ((ctx: APIContext) => Promise<string | undefined>);
|
||||
getSignatureFromHeader: (ctx: APIContext) => string | undefined;
|
||||
secretKey: string | ((ctx: Context) => Promise<string | undefined>);
|
||||
getSignatureFromHeader: (ctx: Context) => string | undefined;
|
||||
hmacSign?: boolean;
|
||||
}) {
|
||||
return async function validateWebhookMiddleware(ctx: APIContext, next: Next) {
|
||||
return async function validateWebhookMiddleware(ctx: Context, next: Next) {
|
||||
const { body } = ctx.request;
|
||||
const signatureFromHeader = getSignatureFromHeader(ctx);
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import Team from "./Team";
|
||||
import User from "./User";
|
||||
import IdModel from "./base/IdModel";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
export enum AccessRequestStatus {
|
||||
Pending = "pending",
|
||||
@@ -113,11 +113,11 @@ class AccessRequest extends IdModel<
|
||||
/**
|
||||
* Approve this access request, setting the status and responder, and persist.
|
||||
*
|
||||
* @param ctx the API context; the authenticated user is recorded as responder.
|
||||
* @param ctx the context; the authenticated user is recorded as responder.
|
||||
*/
|
||||
public approve(ctx: APIContext) {
|
||||
public approve(ctx: Context) {
|
||||
this.status = AccessRequestStatus.Approved;
|
||||
this.responderId = ctx.state.auth.user.id;
|
||||
this.responderId = ctx.auth.user.id;
|
||||
this.respondedAt = new Date();
|
||||
return this.saveWithCtx(ctx);
|
||||
}
|
||||
@@ -125,11 +125,11 @@ class AccessRequest extends IdModel<
|
||||
/**
|
||||
* Dismiss this access request, setting the status and responder, and persist.
|
||||
*
|
||||
* @param ctx the API context; the authenticated user is recorded as responder.
|
||||
* @param ctx the context; the authenticated user is recorded as responder.
|
||||
*/
|
||||
public dismiss(ctx: APIContext) {
|
||||
public dismiss(ctx: Context) {
|
||||
this.status = AccessRequestStatus.Dismissed;
|
||||
this.responderId = ctx.state.auth.user.id;
|
||||
this.responderId = ctx.auth.user.id;
|
||||
this.respondedAt = new Date();
|
||||
return this.saveWithCtx(ctx);
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import Team from "./Team";
|
||||
import UserAuthentication from "./UserAuthentication";
|
||||
import Length from "./validators/Length";
|
||||
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import type { DestroyOptions } from "sequelize";
|
||||
|
||||
@Scopes(() => ({
|
||||
@@ -171,14 +171,12 @@ class AuthenticationProvider extends Model<
|
||||
/**
|
||||
* Disable this authentication provider after ensuring it's allowed.
|
||||
*
|
||||
* @param ctx - API context containing the transaction.
|
||||
* @param ctx - context containing the transaction.
|
||||
* @returns The updated AuthenticationProvider instance.
|
||||
* @throws ValidationError if disabling is not allowed.
|
||||
*/
|
||||
disable: (ctx: APIContext) => Promise<AuthenticationProvider> = async (
|
||||
ctx
|
||||
) => {
|
||||
const { transaction } = ctx.state;
|
||||
disable: (ctx: Context) => Promise<AuthenticationProvider> = async (ctx) => {
|
||||
const { transaction } = ctx;
|
||||
await this.checkCanBeDisabled(transaction);
|
||||
|
||||
return this.updateWithCtx(ctx, {
|
||||
@@ -189,10 +187,10 @@ class AuthenticationProvider extends Model<
|
||||
/**
|
||||
* Enable this authentication provider.
|
||||
*
|
||||
* @param ctx - API context containing the transaction.
|
||||
* @param ctx - context containing the transaction.
|
||||
* @returns The updated AuthenticationProvider instance.
|
||||
*/
|
||||
enable: (ctx: APIContext) => Promise<AuthenticationProvider> = async (ctx) =>
|
||||
enable: (ctx: Context) => Promise<AuthenticationProvider> = async (ctx) =>
|
||||
this.updateWithCtx(ctx, {
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
buildTeam,
|
||||
buildDocument,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import Collection from "./Collection";
|
||||
import Document from "./Document";
|
||||
|
||||
@@ -32,7 +32,7 @@ describe("#updateDeprecatedReason", () => {
|
||||
);
|
||||
|
||||
await expect(
|
||||
withAPIContext(user, (ctx) =>
|
||||
withContext(user, (ctx) =>
|
||||
collection.updateDeprecatedReason(ctx, "Outdated")
|
||||
)
|
||||
).rejects.toThrow("The collection must be archived");
|
||||
@@ -685,7 +685,7 @@ describe("#archiveWithCtx", () => {
|
||||
archivedAt: new Date("2024-01-01"),
|
||||
});
|
||||
|
||||
await withAPIContext(user, (ctx) => collection.archiveWithCtx(ctx));
|
||||
await withContext(user, (ctx) => collection.archiveWithCtx(ctx));
|
||||
|
||||
await Promise.all([
|
||||
collection.reload(),
|
||||
@@ -717,7 +717,7 @@ describe("#archiveWithCtx", () => {
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
|
||||
await withAPIContext(user, (ctx) => collection.archiveWithCtx(ctx));
|
||||
await withContext(user, (ctx) => collection.archiveWithCtx(ctx));
|
||||
|
||||
await otherDocument.reload();
|
||||
expect(otherDocument.archivedAt).toBeNull();
|
||||
|
||||
+19
-18
@@ -60,7 +60,8 @@ import {
|
||||
} from "@shared/validations";
|
||||
import { parser } from "@server/editor";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { toHookContext, type HookContextFields } from "@server/context";
|
||||
import { LockHelper } from "@server/storage/LockHelper";
|
||||
import { afterCommit } from "@server/storage/transaction";
|
||||
import { CacheHelper } from "@server/utils/CacheHelper";
|
||||
@@ -427,7 +428,7 @@ class Collection extends ParanoidModel<
|
||||
}
|
||||
|
||||
@BeforeDestroy
|
||||
static async deleteDocuments(model: Collection, ctx: APIContext["context"]) {
|
||||
static async deleteDocuments(model: Collection, ctx: HookContextFields) {
|
||||
// A bulk update rather than a destroy per document, so `deletedById` is
|
||||
// written here instead of by the hook on ParanoidModel.
|
||||
await Document.update(
|
||||
@@ -535,7 +536,7 @@ class Collection extends ParanoidModel<
|
||||
@BeforeUpdate
|
||||
static async publishPermissionChangedEvent(
|
||||
model: Collection,
|
||||
ctx: APIContext["context"]
|
||||
ctx: HookContextFields
|
||||
) {
|
||||
const privacyChanged = model.previous("permission") !== model.permission;
|
||||
const sharingChanged = model.previous("sharing") !== model.sharing;
|
||||
@@ -807,9 +808,9 @@ class Collection extends ParanoidModel<
|
||||
* @param ctx The request context with the acting user and a transaction.
|
||||
* @returns the personal collection of the user.
|
||||
*/
|
||||
static async findOrCreatePersonal(ctx: APIContext): Promise<Collection> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
static async findOrCreatePersonal(ctx: Context): Promise<Collection> {
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const existing = await this.findPersonal(user, { transaction });
|
||||
if (existing) {
|
||||
@@ -937,12 +938,12 @@ class Collection extends ParanoidModel<
|
||||
* collection's `archivedAt` and `archivedBy` are set to now and the acting
|
||||
* user respectively, and child documents inherit the same `archivedAt`.
|
||||
*
|
||||
* @param ctx - the API context, including the acting user and optional transaction.
|
||||
* @param ctx - the context, including the acting user and optional transaction.
|
||||
* @returns the updated collection.
|
||||
*/
|
||||
archiveWithCtx = async (ctx: APIContext) => {
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.state.auth;
|
||||
archiveWithCtx = async (ctx: Context) => {
|
||||
const { transaction } = ctx;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
this.archivedAt = new Date();
|
||||
this.archivedById = user.id;
|
||||
@@ -971,13 +972,13 @@ class Collection extends ParanoidModel<
|
||||
/**
|
||||
* Updates the reason for archiving the collection.
|
||||
*
|
||||
* @param ctx the API context, including the acting user and transaction.
|
||||
* @param ctx the context, including the acting user and transaction.
|
||||
* @param reason the reason to save, or null to clear it.
|
||||
* @returns the updated collection.
|
||||
* @throws ValidationError if the collection is no longer archived.
|
||||
*/
|
||||
updateDeprecatedReason = async (ctx: APIContext, reason: string | null) => {
|
||||
const { transaction } = ctx.state;
|
||||
updateDeprecatedReason = async (ctx: Context, reason: string | null) => {
|
||||
const { transaction } = ctx;
|
||||
|
||||
if (transaction) {
|
||||
await Collection.unscoped().findOne({
|
||||
@@ -1005,11 +1006,11 @@ class Collection extends ParanoidModel<
|
||||
* Removes a document from this collection's structure and soft deletes it
|
||||
* along with all of its descendants.
|
||||
*
|
||||
* @param ctx the API context, which attributes the deletion to the acting user.
|
||||
* @param ctx the context, which attributes the deletion to the acting user.
|
||||
* @param document the document to delete.
|
||||
*/
|
||||
deleteDocument = async (ctx: APIContext, document: Document) => {
|
||||
const { transaction } = ctx.context;
|
||||
deleteDocument = async (ctx: Context, document: Document) => {
|
||||
const { transaction } = ctx;
|
||||
|
||||
await this.removeDocumentInStructure(document, { transaction });
|
||||
|
||||
@@ -1030,11 +1031,11 @@ class Collection extends ParanoidModel<
|
||||
|
||||
// Destroyed one at a time to ensure model hooks run for each document.
|
||||
for (const childDocumentId of childDocumentIds) {
|
||||
await childDocumentsById[childDocumentId]?.destroy(ctx.context);
|
||||
await childDocumentsById[childDocumentId]?.destroy(toHookContext(ctx));
|
||||
}
|
||||
}
|
||||
|
||||
await document.destroy(ctx.context);
|
||||
await document.destroy(toHookContext(ctx));
|
||||
};
|
||||
|
||||
removeDocumentInStructure = async (
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
buildUser,
|
||||
buildGuestUser,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import GroupMembership from "./GroupMembership";
|
||||
import GroupUser from "./GroupUser";
|
||||
@@ -47,7 +47,7 @@ describe("#restoreTo", () => {
|
||||
{ deprecatedReason: "Outdated" },
|
||||
{ where: { id: document.id }, paranoid: false }
|
||||
);
|
||||
await withAPIContext(user, (ctx) =>
|
||||
await withContext(user, (ctx) =>
|
||||
document.restoreTo(ctx, { collectionId: collection.id })
|
||||
);
|
||||
await document.reload();
|
||||
@@ -83,7 +83,7 @@ describe("#destroyWithCtx", () => {
|
||||
it("should soft delete and set last modified", async () => {
|
||||
const document = await buildDocument();
|
||||
const user = await buildUser();
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
await withContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
|
||||
const newDocument = await Document.findByPk(document.id, {
|
||||
paranoid: false,
|
||||
@@ -97,7 +97,7 @@ describe("#destroyWithCtx", () => {
|
||||
archivedAt: new Date(),
|
||||
});
|
||||
const user = await buildUser();
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
await withContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
const newDocument = await Document.findByPk(document.id, {
|
||||
paranoid: false,
|
||||
});
|
||||
@@ -120,7 +120,7 @@ describe("#destroyWithCtx", () => {
|
||||
});
|
||||
await collection.addDocumentToStructure(document, 0);
|
||||
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
await withContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
const [newDocument, newCollection] = await Promise.all([
|
||||
document.reload({ paranoid: false }),
|
||||
collection.reload(),
|
||||
@@ -134,7 +134,7 @@ describe("#destroyWithCtx", () => {
|
||||
it("should delete draft without collection", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDraftDocument();
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
await withContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
const deletedDocument = await Document.findByPk(document.id, {
|
||||
paranoid: false,
|
||||
});
|
||||
|
||||
+24
-23
@@ -81,7 +81,8 @@ import { CounterCache } from "./decorators/CounterCache";
|
||||
import { DocumentHelper } from "./helpers/DocumentHelper";
|
||||
import IsHexColor from "./validators/IsHexColor";
|
||||
import Length from "./validators/Length";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { toHookContext, type HookContextFields } from "@server/context";
|
||||
import { APIUpdateExtension } from "@server/collaboration/APIUpdateExtension";
|
||||
import { SkipChangeset } from "./decorators/Changeset";
|
||||
import type { EventOverrideOptions, HookContext } from "./base/Model";
|
||||
@@ -649,7 +650,7 @@ class Document extends ArchivableModel<
|
||||
@AfterUpdate
|
||||
static async publishTitleChangeEvent(
|
||||
model: Document,
|
||||
ctx: APIContext["context"]
|
||||
ctx: HookContextFields
|
||||
) {
|
||||
if (model.changed("title")) {
|
||||
const hookContext = {
|
||||
@@ -1285,7 +1286,7 @@ class Document extends ArchivableModel<
|
||||
};
|
||||
|
||||
publish = async (
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{
|
||||
index = 0,
|
||||
collectionId,
|
||||
@@ -1300,8 +1301,8 @@ class Document extends ArchivableModel<
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
): Promise<this> => {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
this.lastModifiedById = user.id;
|
||||
this.updatedBy = user;
|
||||
@@ -1392,19 +1393,19 @@ class Document extends ArchivableModel<
|
||||
/**
|
||||
* Unpublishes a published document, converting it back to a draft.
|
||||
*
|
||||
* @param ctx the API context.
|
||||
* @param ctx the context.
|
||||
* @param options.detach whether to detach the document from the containing collection.
|
||||
* @returns updated document.
|
||||
* @throws if the document has child documents.
|
||||
*/
|
||||
unpublishWithCtx = async (ctx: APIContext, options: { detach: boolean }) => {
|
||||
unpublishWithCtx = async (ctx: Context, options: { detach: boolean }) => {
|
||||
// If the document is already a draft then calling unpublish should act like save
|
||||
if (!this.publishedAt) {
|
||||
return this.save();
|
||||
}
|
||||
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const childDocumentIds = await this.findAllChildDocumentIds(
|
||||
{ archivedAt: { [Op.eq]: null } },
|
||||
@@ -1467,8 +1468,8 @@ class Document extends ArchivableModel<
|
||||
|
||||
// Moves a document from being visible to the team within a collection
|
||||
// to the archived area, where it can be subsequently restored.
|
||||
archiveWithCtx = async (ctx: APIContext) => {
|
||||
const { transaction } = ctx.state;
|
||||
archiveWithCtx = async (ctx: Context) => {
|
||||
const { transaction } = ctx;
|
||||
const collection = this.collectionId
|
||||
? await Collection.findByPk(this.collectionId, {
|
||||
includeDocumentStructure: true,
|
||||
@@ -1490,10 +1491,10 @@ class Document extends ArchivableModel<
|
||||
|
||||
// Restore an archived document back to being visible to the team
|
||||
restoreTo = async (
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ collectionId }: { collectionId: string }
|
||||
) => {
|
||||
const { transaction } = ctx.state;
|
||||
const { transaction } = ctx;
|
||||
const collection = collectionId
|
||||
? await Collection.findByPk(collectionId, {
|
||||
includeDocumentStructure: true,
|
||||
@@ -1544,11 +1545,11 @@ class Document extends ArchivableModel<
|
||||
|
||||
// Delete a document, archived or otherwise.
|
||||
destroyWithCtx = async (
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
eventOpts?: EventOverrideOptions
|
||||
): Promise<void> => {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
let deleted = false;
|
||||
|
||||
if (this.collectionId) {
|
||||
@@ -1566,7 +1567,7 @@ class Document extends ArchivableModel<
|
||||
}
|
||||
|
||||
if (!deleted) {
|
||||
await this.destroy(ctx.context);
|
||||
await this.destroy(toHookContext(ctx));
|
||||
}
|
||||
|
||||
this.lastModifiedById = user.id;
|
||||
@@ -1686,11 +1687,11 @@ class Document extends ArchivableModel<
|
||||
});
|
||||
|
||||
private restoreArchivedWithChildren = async (
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
{ collectionId }: { collectionId: string }
|
||||
) => {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const restoreChildren = async (parentDocumentId: string) => {
|
||||
const childDocuments = await (
|
||||
@@ -1723,9 +1724,9 @@ class Document extends ArchivableModel<
|
||||
return this.saveWithCtx(ctx, undefined, { name: "unarchive" });
|
||||
};
|
||||
|
||||
private archiveWithChildren = async (ctx: APIContext) => {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
private archiveWithChildren = async (ctx: Context) => {
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
const archivedAt = new Date();
|
||||
|
||||
// Helper to archive all child documents for a document
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
} from "sequelize-typescript";
|
||||
import { globalEventQueue } from "../queues";
|
||||
import { afterCommit } from "../storage/transaction";
|
||||
import type { APIContext } from "../types";
|
||||
import type { Context } from "../types";
|
||||
import { AuthenticationType } from "../types";
|
||||
import { normalizeIp } from "../utils/ip";
|
||||
import Collection from "./Collection";
|
||||
@@ -27,7 +27,7 @@ import Document from "./Document";
|
||||
import Team from "./Team";
|
||||
import User from "./User";
|
||||
import IdModel from "./base/IdModel";
|
||||
import type { Context } from "koa";
|
||||
import type { AppContext } from "@server/types";
|
||||
|
||||
@Table({ tableName: "events", modelName: "event", updatedAt: false })
|
||||
class Event extends IdModel<
|
||||
@@ -161,13 +161,13 @@ class Event extends IdModel<
|
||||
* @returns A promise resolving to the new event
|
||||
*/
|
||||
static createFromContext(
|
||||
ctx: Context | APIContext,
|
||||
ctx: AppContext | Context,
|
||||
attributes: Omit<Partial<Event>, "ip" | "teamId" | "actorId"> = {},
|
||||
defaultAttributes: Pick<Partial<Event>, "ip" | "teamId" | "actorId"> = {},
|
||||
options?: CreateOptions<InferAttributes<Event>>
|
||||
) {
|
||||
const user = ctx.state.auth?.user;
|
||||
const authType = ctx.state.auth?.type;
|
||||
const user = ctx.auth?.user;
|
||||
const authType = ctx.auth?.type;
|
||||
|
||||
return this.create(
|
||||
{
|
||||
@@ -178,7 +178,7 @@ class Event extends IdModel<
|
||||
authType,
|
||||
},
|
||||
{
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
...options,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
FileOperationType,
|
||||
} from "@shared/types";
|
||||
import FileStorage from "@server/storage/files";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { ValidateKey } from "@server/validation";
|
||||
import Collection from "./Collection";
|
||||
import Document from "./Document";
|
||||
@@ -155,10 +155,10 @@ class FileOperation extends ParanoidModel<
|
||||
* @returns the new file operation with its source associations set.
|
||||
*/
|
||||
static async createExport(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
options: CreateExportOptions
|
||||
): Promise<FileOperation> {
|
||||
const { user } = ctx.state.auth;
|
||||
const { user } = ctx.auth;
|
||||
const format = options.format ?? FileOperationFormat.MarkdownZip;
|
||||
|
||||
// The owner is stored on the export, as a document can move out of the
|
||||
@@ -171,7 +171,7 @@ class FileOperation extends ParanoidModel<
|
||||
? await Collection.unscoped().findOne({
|
||||
attributes: ["ownerId"],
|
||||
where: { id: sourceCollectionId },
|
||||
transaction: ctx.state.transaction,
|
||||
transaction: ctx.transaction,
|
||||
})
|
||||
: null;
|
||||
const personalOwnerId = sourceCollection?.ownerId ?? undefined;
|
||||
|
||||
@@ -26,7 +26,7 @@ import type { DocumentPermission } from "@shared/types";
|
||||
import { CollectionPermission } from "@shared/types";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import { LockHelper } from "@server/storage/LockHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { HookContextFields } from "@server/context";
|
||||
import Collection from "./Collection";
|
||||
import Document from "./Document";
|
||||
import Group from "./Group";
|
||||
@@ -252,7 +252,7 @@ class GroupMembership extends ParanoidModel<
|
||||
@AfterCreate
|
||||
static async publishAddGroupEventAfterCreate(
|
||||
model: GroupMembership,
|
||||
context: APIContext["context"]
|
||||
context: HookContextFields
|
||||
) {
|
||||
await model.insertEvent(context, "add_group", {
|
||||
membershipId: model.id,
|
||||
@@ -295,7 +295,7 @@ class GroupMembership extends ParanoidModel<
|
||||
@BeforeUpdate
|
||||
static async checkLastAdminBeforeUpdate(
|
||||
model: GroupMembership,
|
||||
ctx: APIContext["context"]
|
||||
ctx: HookContextFields
|
||||
) {
|
||||
if (
|
||||
model.permission === CollectionPermission.Admin ||
|
||||
@@ -310,7 +310,7 @@ class GroupMembership extends ParanoidModel<
|
||||
@BeforeDestroy
|
||||
static async checkLastAdminBeforeDestroy(
|
||||
model: GroupMembership,
|
||||
ctx: APIContext["context"]
|
||||
ctx: HookContextFields
|
||||
) {
|
||||
// Only check for last admin permission if this permission is admin
|
||||
if (
|
||||
@@ -325,7 +325,7 @@ class GroupMembership extends ParanoidModel<
|
||||
@AfterUpdate
|
||||
static async publishAddGroupEventAfterUpdate(
|
||||
model: GroupMembership,
|
||||
context: APIContext["context"]
|
||||
context: HookContextFields
|
||||
) {
|
||||
await model.insertEvent(context, "add_group", {
|
||||
membershipId: model.id,
|
||||
@@ -355,7 +355,7 @@ class GroupMembership extends ParanoidModel<
|
||||
@AfterDestroy
|
||||
static async publishRemoveGroupEvent(
|
||||
model: GroupMembership,
|
||||
context: APIContext["context"]
|
||||
context: HookContextFields
|
||||
) {
|
||||
await model.insertEvent(context, "remove_group", {
|
||||
membershipId: model.id,
|
||||
@@ -469,7 +469,7 @@ class GroupMembership extends ParanoidModel<
|
||||
}
|
||||
|
||||
private async insertEvent(
|
||||
ctx: APIContext["context"],
|
||||
ctx: HookContextFields,
|
||||
name: string,
|
||||
data: Record<string, unknown>
|
||||
) {
|
||||
@@ -487,7 +487,7 @@ class GroupMembership extends ParanoidModel<
|
||||
|
||||
private static async validateLastAdminPermission(
|
||||
model: GroupMembership,
|
||||
{ transaction }: APIContext["context"]
|
||||
{ transaction }: HookContextFields
|
||||
) {
|
||||
// Both models guard the same invariant, so they share one lock name,
|
||||
// otherwise the last user manager and the last group manager can be
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
Table,
|
||||
} from "sequelize-typescript";
|
||||
import { createContext } from "@server/context";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { HookContextFields } from "@server/context";
|
||||
import Comment from "./Comment";
|
||||
import User from "./User";
|
||||
import IdModel from "./base/IdModel";
|
||||
@@ -54,7 +54,7 @@ class Reaction extends IdModel<
|
||||
@AfterCreate
|
||||
public static async addReactionToCommentCache(
|
||||
model: Reaction,
|
||||
ctx: APIContext["context"] &
|
||||
ctx: HookContextFields &
|
||||
FindOrCreateOptions<Attributes<Reaction>, CreationAttributes<Reaction>>
|
||||
) {
|
||||
const { transaction } = ctx;
|
||||
@@ -86,7 +86,7 @@ class Reaction extends IdModel<
|
||||
|
||||
comment.reactions = reactions;
|
||||
|
||||
// Pass only the fields needed in APIContext; otherwise sequelize props will be overwritten.
|
||||
// Pass only the fields needed in Context; otherwise sequelize props will be overwritten.
|
||||
const context = createContext({
|
||||
user: ctx.auth.user,
|
||||
authType: ctx.auth.type,
|
||||
@@ -106,7 +106,7 @@ class Reaction extends IdModel<
|
||||
@AfterDestroy
|
||||
public static async removeReactionFromCommentCache(
|
||||
model: Reaction,
|
||||
ctx: APIContext["context"] & InstanceDestroyOptions
|
||||
ctx: HookContextFields & InstanceDestroyOptions
|
||||
) {
|
||||
const { transaction } = ctx;
|
||||
|
||||
@@ -139,7 +139,7 @@ class Reaction extends IdModel<
|
||||
|
||||
comment.reactions = reactions;
|
||||
|
||||
// Pass only the fields needed in APIContext; otherwise sequelize props will be overwritten.
|
||||
// Pass only the fields needed in Context; otherwise sequelize props will be overwritten.
|
||||
const context = createContext({
|
||||
user: ctx.auth.user,
|
||||
authType: ctx.auth.type,
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "sequelize-typescript";
|
||||
import type { ProsemirrorData, SourceMetadata } from "@shared/types";
|
||||
import { DocumentValidation, RevisionValidation } from "@shared/validations";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import Document from "./Document";
|
||||
import User from "./User";
|
||||
import ParanoidModel from "./base/ParanoidModel";
|
||||
@@ -266,12 +266,12 @@ class Revision extends ParanoidModel<
|
||||
* @returns A Promise that resolves when saved
|
||||
*/
|
||||
static createFromDocument(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
document: Document,
|
||||
collaboratorIds?: string[]
|
||||
) {
|
||||
const revision = this.buildFromDocument(document);
|
||||
const authType = ctx.context.auth?.type;
|
||||
const authType = ctx.auth?.type;
|
||||
revision.sourceMetadata = authType ? { authType } : null;
|
||||
|
||||
if (collaboratorIds) {
|
||||
|
||||
@@ -18,7 +18,7 @@ import { UrlHelper } from "@shared/utils/UrlHelper";
|
||||
import { ShareValidation } from "@shared/validations";
|
||||
import env from "@server/env";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import Collection from "./Collection";
|
||||
import Document from "./Document";
|
||||
import Team from "./Team";
|
||||
@@ -323,8 +323,8 @@ class Share extends IdModel<
|
||||
@Column(DataType.UUID)
|
||||
documentId: string | null;
|
||||
|
||||
revoke(ctx: APIContext) {
|
||||
const { user } = ctx.state.auth;
|
||||
revoke(ctx: Context) {
|
||||
const { user } = ctx.auth;
|
||||
this.revokedAt = new Date();
|
||||
this.revokedById = user.id;
|
||||
return this.saveWithCtx(ctx, undefined, { name: "revoke" });
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import crypto from "node:crypto";
|
||||
import { addHours, addMinutes, subMinutes } from "date-fns";
|
||||
import JWT from "jsonwebtoken";
|
||||
import type { Context } from "koa";
|
||||
import type {
|
||||
Transaction,
|
||||
SaveOptions,
|
||||
@@ -52,7 +51,8 @@ import env from "@server/env";
|
||||
import DeleteAttachmentTask from "@server/queues/tasks/DeleteAttachmentTask";
|
||||
import { LockHelper } from "@server/storage/LockHelper";
|
||||
import { afterCommit } from "@server/storage/transaction";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context, AppContext } from "@server/types";
|
||||
import { toHookContext } from "@server/context";
|
||||
import { VerificationCode } from "@server/utils/VerificationCode";
|
||||
import parseAttachmentIds from "@server/utils/parseAttachmentIds";
|
||||
import { CacheHelper } from "@server/utils/CacheHelper";
|
||||
@@ -582,7 +582,7 @@ class User extends ParanoidModel<
|
||||
* @param force whether to update even if the last update was recent.
|
||||
* @returns a promise that resolves with the updated user.
|
||||
*/
|
||||
updateActiveAt = async (ctx?: Context, force = false) => {
|
||||
updateActiveAt = async (ctx?: AppContext, force = false) => {
|
||||
const fiveMinutesAgo = subMinutes(new Date(), 5);
|
||||
|
||||
// ensure this is updated only every few minutes otherwise
|
||||
@@ -609,13 +609,13 @@ class User extends ParanoidModel<
|
||||
});
|
||||
};
|
||||
|
||||
updateSignedIn = (ctx: Context | APIContext) => {
|
||||
updateSignedIn = (ctx: AppContext | Context) => {
|
||||
const now = new Date();
|
||||
this.lastActiveAt = now;
|
||||
this.lastActiveIp = ctx.request.ip;
|
||||
this.lastSignedInAt = now;
|
||||
this.lastSignedInIp = ctx.request.ip;
|
||||
return this.save({ hooks: false, transaction: ctx.state.transaction });
|
||||
return this.save({ hooks: false, transaction: ctx.transaction });
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -693,7 +693,7 @@ class User extends ParanoidModel<
|
||||
* @param ctx The request context, used to get the IP address of the request
|
||||
* @returns The email signin token
|
||||
*/
|
||||
getEmailSigninToken = (ctx: Context) =>
|
||||
getEmailSigninToken = (ctx: AppContext) =>
|
||||
JWT.sign(
|
||||
{
|
||||
id: this.id,
|
||||
@@ -990,15 +990,15 @@ class User extends ParanoidModel<
|
||||
|
||||
static findByEmail = async function (
|
||||
this: typeof User,
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
email: string
|
||||
) {
|
||||
return this.findOne({
|
||||
where: {
|
||||
teamId: ctx.state.auth.user.teamId,
|
||||
teamId: ctx.auth.user.teamId,
|
||||
email: email.trim().toLowerCase(),
|
||||
},
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import Event from "./Event";
|
||||
import GroupMembership from "./GroupMembership";
|
||||
import UserMembership from "./UserMembership";
|
||||
@@ -87,14 +87,14 @@ describe("UserMembership", () => {
|
||||
});
|
||||
|
||||
// The user membership goes first, leaving the group as the only manager.
|
||||
const one = withAPIContext(user, async (ctx) => {
|
||||
const one = withContext(user, async (ctx) => {
|
||||
await userMembership.destroyWithCtx(ctx);
|
||||
removed();
|
||||
await held;
|
||||
});
|
||||
await first;
|
||||
|
||||
const two = withAPIContext(user, (ctx) =>
|
||||
const two = withContext(user, (ctx) =>
|
||||
groupMembership.destroyWithCtx(ctx)
|
||||
);
|
||||
await sleep(250);
|
||||
|
||||
@@ -29,7 +29,7 @@ import { CollectionPermission } from "@shared/types";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import { LockHelper } from "@server/storage/LockHelper";
|
||||
import { afterCommit } from "@server/storage/transaction";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { HookContextFields } from "@server/context";
|
||||
import { CacheHelper } from "@server/utils/CacheHelper";
|
||||
import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper";
|
||||
import Collection from "./Collection";
|
||||
@@ -259,7 +259,7 @@ class UserMembership extends IdModel<
|
||||
@AfterCreate
|
||||
static async publishAddUserEventAfterCreate(
|
||||
model: UserMembership,
|
||||
context: APIContext["context"]
|
||||
context: HookContextFields
|
||||
) {
|
||||
await model.insertEvent(context, "add_user", {
|
||||
isNew: true,
|
||||
@@ -311,7 +311,7 @@ class UserMembership extends IdModel<
|
||||
@BeforeUpdate
|
||||
static async checkLastAdminBeforeUpdate(
|
||||
model: UserMembership,
|
||||
ctx: APIContext["context"]
|
||||
ctx: HookContextFields
|
||||
) {
|
||||
if (
|
||||
model.permission === CollectionPermission.Admin ||
|
||||
@@ -326,7 +326,7 @@ class UserMembership extends IdModel<
|
||||
@BeforeDestroy
|
||||
static async checkLastAdminBeforeDestroy(
|
||||
model: UserMembership,
|
||||
ctx: APIContext["context"]
|
||||
ctx: HookContextFields
|
||||
) {
|
||||
// Only check for last admin permission if this permission is admin
|
||||
if (
|
||||
@@ -341,7 +341,7 @@ class UserMembership extends IdModel<
|
||||
@AfterUpdate
|
||||
static async publishAddUserEventAfterUpdate(
|
||||
model: UserMembership,
|
||||
context: APIContext["context"]
|
||||
context: HookContextFields
|
||||
) {
|
||||
await model.insertEvent(context, "add_user", {
|
||||
isNew: false,
|
||||
@@ -351,7 +351,7 @@ class UserMembership extends IdModel<
|
||||
@AfterDestroy
|
||||
static async publishRemoveUserEvent(
|
||||
model: UserMembership,
|
||||
context: APIContext["context"]
|
||||
context: HookContextFields
|
||||
) {
|
||||
await model.insertEvent(context, "remove_user");
|
||||
}
|
||||
@@ -454,7 +454,7 @@ class UserMembership extends IdModel<
|
||||
}
|
||||
|
||||
private async insertEvent(
|
||||
ctx: APIContext["context"],
|
||||
ctx: HookContextFields,
|
||||
name: string,
|
||||
data?: Record<string, unknown>
|
||||
) {
|
||||
@@ -487,7 +487,7 @@ class UserMembership extends IdModel<
|
||||
|
||||
private static async validateLastAdminPermission(
|
||||
model: UserMembership,
|
||||
{ transaction }: APIContext["context"]
|
||||
{ transaction }: HookContextFields
|
||||
) {
|
||||
// Both models guard the same invariant, so they share one lock name,
|
||||
// otherwise the last user manager and the last group manager can be
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
DataType,
|
||||
Scopes,
|
||||
} from "sequelize-typescript";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import Document from "./Document";
|
||||
import Event from "./Event";
|
||||
import User from "./User";
|
||||
@@ -61,7 +61,7 @@ class View extends IdModel<
|
||||
documentId: string;
|
||||
|
||||
static async incrementOrCreate(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
where: {
|
||||
userId: string;
|
||||
documentId: string;
|
||||
|
||||
+21
-20
@@ -23,7 +23,8 @@ import {
|
||||
Model as SequelizeModel,
|
||||
} from "sequelize-typescript";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import type { Replace, APIContext } from "@server/types";
|
||||
import type { Replace, Context } from "@server/types";
|
||||
import { toHookContext, type HookContextFields } from "@server/context";
|
||||
import { getChangesetSkipped } from "../decorators/Changeset";
|
||||
import { InternalError } from "@server/errors";
|
||||
import { afterCommit } from "@server/storage/transaction";
|
||||
@@ -46,7 +47,7 @@ type EventOptions = EventOverrideOptions & {
|
||||
publish: boolean;
|
||||
};
|
||||
|
||||
export type HookContext = APIContext["context"] & { event?: EventOptions };
|
||||
export type HookContext = HookContextFields & { event?: EventOptions };
|
||||
|
||||
class Model<
|
||||
// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- Sequelize's Attributes<M> resolves to never under object default; load-bearing for static helpers like saveWithCtx<M extends Model>.
|
||||
@@ -69,12 +70,12 @@ class Model<
|
||||
* Validates this instance, and if the validation passes, persists it to the database.
|
||||
*/
|
||||
public saveWithCtx<M extends Model>(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
options?: SaveOptions<Attributes<M>>,
|
||||
eventOpts?: EventOverrideOptions
|
||||
) {
|
||||
const hookContext: HookContext = {
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
event: {
|
||||
...eventOpts,
|
||||
publish: true,
|
||||
@@ -87,12 +88,12 @@ class Model<
|
||||
* This is the same as calling `fill` and then calling `save`.
|
||||
*/
|
||||
public updateWithCtx(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
keys: Partial<TModelAttributes>,
|
||||
eventOpts?: EventOverrideOptions
|
||||
) {
|
||||
const hookContext: HookContext = {
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
event: {
|
||||
...eventOpts,
|
||||
publish: true,
|
||||
@@ -117,9 +118,9 @@ class Model<
|
||||
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will
|
||||
* either be completely deleted, or have its deletedAt timestamp set to the current time.
|
||||
*/
|
||||
public destroyWithCtx(ctx: APIContext, eventOpts?: EventOverrideOptions) {
|
||||
public destroyWithCtx(ctx: Context, eventOpts?: EventOverrideOptions) {
|
||||
const hookContext: HookContext = {
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
event: {
|
||||
...eventOpts,
|
||||
publish: true,
|
||||
@@ -131,9 +132,9 @@ class Model<
|
||||
/**
|
||||
* Restore the row corresponding to this instance. Only available for paranoid models.
|
||||
*/
|
||||
public restoreWithCtx(ctx: APIContext, eventOpts?: EventOverrideOptions) {
|
||||
public restoreWithCtx(ctx: Context, eventOpts?: EventOverrideOptions) {
|
||||
const hookContext: HookContext = {
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
event: {
|
||||
...eventOpts,
|
||||
publish: true,
|
||||
@@ -146,25 +147,25 @@ class Model<
|
||||
* Find a row that matches the query, or build and save the row if none is found.
|
||||
* The successful result of the promise will be (instance, created) - Make sure to use `.then(([...]))`
|
||||
*
|
||||
* @param ctx The API context.
|
||||
* @param ctx The context.
|
||||
* @param options The find or create options.
|
||||
* @param eventOpts Optional event override options.
|
||||
* @returns a tuple of the instance and a boolean indicating if it was created.
|
||||
*/
|
||||
public static async findOrCreateWithCtx<M extends Model>(
|
||||
this: ModelStatic<M>,
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
options: FindOrCreateOptions<Attributes<M>, CreationAttributes<M>>,
|
||||
eventOpts?: EventOverrideOptions
|
||||
): Promise<[M, boolean]> {
|
||||
const hookContext: HookContext = {
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
event: {
|
||||
...eventOpts,
|
||||
publish: true,
|
||||
},
|
||||
};
|
||||
const transaction = ctx.context.transaction;
|
||||
const transaction = ctx.transaction;
|
||||
|
||||
// First, try to find an existing record
|
||||
const existing = await this.findOne({
|
||||
@@ -206,19 +207,19 @@ class Model<
|
||||
* each. Rows are matched when the destroy runs, so rows written after the
|
||||
* options were prepared are destroyed too.
|
||||
*
|
||||
* @param ctx The API context.
|
||||
* @param ctx The context.
|
||||
* @param options The destroy options.
|
||||
* @param eventOpts Optional event override options.
|
||||
* @returns the number of destroyed rows.
|
||||
*/
|
||||
public static destroyWithCtx<M extends Model>(
|
||||
this: ModelStatic<M>,
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
options: DestroyOptions<Attributes<M>>,
|
||||
eventOpts?: EventOverrideOptions
|
||||
) {
|
||||
const hookContext = {
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
...options,
|
||||
individualHooks: true,
|
||||
event: {
|
||||
@@ -234,13 +235,13 @@ class Model<
|
||||
*/
|
||||
public static createWithCtx<M extends Model>(
|
||||
this: ModelStatic<M>,
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
values?: CreationAttributes<M>,
|
||||
eventOpts?: EventOverrideOptions,
|
||||
createOpts?: CreateOptions<M>
|
||||
) {
|
||||
const hookContext = {
|
||||
...ctx.context,
|
||||
...toHookContext(ctx),
|
||||
...createOpts,
|
||||
event: {
|
||||
...eventOpts,
|
||||
@@ -300,7 +301,7 @@ class Model<
|
||||
*
|
||||
* @param name The name of the event.
|
||||
* @param model The model that was mutated.
|
||||
* @param context The API context.
|
||||
* @param context The context.
|
||||
*/
|
||||
protected static async insertEvent<T extends Model>(
|
||||
name: string,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createContext } from "@server/context";
|
||||
import { createContext, toHookContext } from "@server/context";
|
||||
import {
|
||||
buildCollection,
|
||||
buildDocument,
|
||||
@@ -12,7 +12,7 @@ describe("ParanoidModel", () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({ teamId: user.teamId });
|
||||
|
||||
await document.destroy(createContext({ user }).context);
|
||||
await document.destroy(toHookContext(createContext({ user })));
|
||||
await document.reload({ paranoid: false });
|
||||
|
||||
expect(document.deletedAt).toBeTruthy();
|
||||
@@ -23,7 +23,7 @@ describe("ParanoidModel", () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({ teamId: user.teamId });
|
||||
|
||||
await document.destroy(createContext({ user }).context);
|
||||
await document.destroy(toHookContext(createContext({ user })));
|
||||
await document.restore();
|
||||
await document.reload();
|
||||
|
||||
@@ -51,7 +51,7 @@ describe("ParanoidModel", () => {
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
await collection.destroy(createContext({ user }).context);
|
||||
await collection.destroy(toHookContext(createContext({ user })));
|
||||
|
||||
expect(collection.deletedAt).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -55,7 +55,7 @@ import { trace } from "@server/logging/tracing";
|
||||
import Attachment from "@server/models/Attachment";
|
||||
import User from "@server/models/User";
|
||||
import FileStorage from "@server/storage/files";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
export type HTMLOptions = {
|
||||
/** A title, if it should be included */
|
||||
@@ -1242,13 +1242,13 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper {
|
||||
* images — a PDF bundled alongside a document, for example — do not remain
|
||||
* embedded in the document as base64.
|
||||
*
|
||||
* @param ctx The API context.
|
||||
* @param ctx The context.
|
||||
* @param doc The Prosemirror node to process.
|
||||
* @param user The user context.
|
||||
* @returns A new Prosemirror node with images and embedded files replaced.
|
||||
*/
|
||||
static async replaceImagesWithAttachments(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
doc: Node,
|
||||
user: User
|
||||
): Promise<Node> {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { trace } from "@server/logging/tracing";
|
||||
import type { User } from "@server/models";
|
||||
import { Attachment } from "@server/models";
|
||||
import FileStorage from "@server/storage/files";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import parseAttachmentIds from "@server/utils/parseAttachmentIds";
|
||||
import parseImages from "@server/utils/parseImages";
|
||||
|
||||
@@ -61,13 +61,13 @@ export class TextHelper {
|
||||
* Replaces remote and base64 encoded images in the given text with attachment
|
||||
* urls and uploads the images to the storage provider.
|
||||
*
|
||||
* @param ctx The API context
|
||||
* @param ctx The context
|
||||
* @param markdown The text to replace the images in
|
||||
* @param user The user context
|
||||
* @returns The text with the images replaced
|
||||
*/
|
||||
static async replaceImagesWithAttachments(
|
||||
ctx: APIContext,
|
||||
ctx: Context,
|
||||
markdown: string,
|
||||
user: User,
|
||||
options: {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Hour } from "@shared/utils/time";
|
||||
import type Collection from "@server/models/Collection";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import presentUser from "./user";
|
||||
|
||||
type Options = {
|
||||
@@ -18,7 +18,7 @@ type Options = {
|
||||
};
|
||||
|
||||
export default async function presentCollection(
|
||||
ctx: APIContext | undefined,
|
||||
ctx: Context | undefined,
|
||||
collection: Collection,
|
||||
options: Options = {}
|
||||
) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
buildDocument,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
|
||||
describe("presentDocuments", () => {
|
||||
@@ -19,7 +19,7 @@ describe("presentDocuments", () => {
|
||||
teamId: user.teamId,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
await withContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
}
|
||||
|
||||
const documents = await Document.scope("withDrafts").findAll({
|
||||
@@ -65,8 +65,8 @@ describe("presentDocuments", () => {
|
||||
teamId: userA.teamId,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
await withAPIContext(userA, (ctx) => documentA.destroyWithCtx(ctx));
|
||||
await withAPIContext(userB, (ctx) => documentB.destroyWithCtx(ctx));
|
||||
await withContext(userA, (ctx) => documentA.destroyWithCtx(ctx));
|
||||
await withContext(userB, (ctx) => documentB.destroyWithCtx(ctx));
|
||||
|
||||
// One document arrives with the association loaded, the other without.
|
||||
const loaded = await Document.scope("withDrafts").findOne({
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Document } from "@server/models";
|
||||
import FileOperation from "@server/models/FileOperation";
|
||||
import User from "@server/models/User";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import presentUser from "./user";
|
||||
|
||||
type Options = {
|
||||
@@ -27,7 +27,7 @@ type Options = {
|
||||
};
|
||||
|
||||
async function presentDocument(
|
||||
ctx: APIContext | undefined,
|
||||
ctx: Context | undefined,
|
||||
document: Document,
|
||||
options: Options | null | undefined = {}
|
||||
) {
|
||||
@@ -159,13 +159,13 @@ export default traceFunction({
|
||||
* Batch-present multiple documents, fetching all related FileOperation and
|
||||
* deleting User records in a single query instead of one per document.
|
||||
*
|
||||
* @param ctx the API context.
|
||||
* @param ctx the context.
|
||||
* @param documents the documents to present.
|
||||
* @param options presentation options forwarded to presentDocument.
|
||||
* @returns array of presented document objects.
|
||||
*/
|
||||
export async function presentDocuments(
|
||||
ctx: APIContext | undefined,
|
||||
ctx: Context | undefined,
|
||||
documents: Document[],
|
||||
options?: Options | null
|
||||
) {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import type { Integration } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
|
||||
/**
|
||||
* Presents an integration for API responses.
|
||||
*
|
||||
* @param ctx the API context, used to find the user the integration is presented to.
|
||||
* @param ctx the context, used to find the user the integration is presented to.
|
||||
* @param integration the integration to present.
|
||||
* @returns the presented integration.
|
||||
*/
|
||||
export default function presentIntegration(
|
||||
ctx: APIContext | undefined,
|
||||
ctx: Context | undefined,
|
||||
integration: Integration
|
||||
) {
|
||||
return {
|
||||
@@ -20,7 +20,7 @@ export default function presentIntegration(
|
||||
authenticationId: integration.authenticationId,
|
||||
service: integration.service,
|
||||
events: integration.events,
|
||||
settings: integration.presentSettings(ctx?.state.auth.user),
|
||||
settings: integration.presentSettings(ctx?.auth.user),
|
||||
createdAt: integration.createdAt,
|
||||
updatedAt: integration.updatedAt,
|
||||
};
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { Notification } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import presentFileOperation from "./fileOperation";
|
||||
import presentGroup from "./group";
|
||||
import presentUser from "./user";
|
||||
import { presentComment, presentDocument } from ".";
|
||||
|
||||
export default async function presentNotification(
|
||||
ctx: APIContext | undefined,
|
||||
ctx: Context | undefined,
|
||||
notification: Notification
|
||||
) {
|
||||
return {
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
buildDocument,
|
||||
buildImport,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import MarkdownImportsProcessor from "../processors/MarkdownImportsProcessor";
|
||||
import UploadAttachmentsForImportTask from "./UploadAttachmentsForImportTask";
|
||||
import MarkdownAPIImportTask, {
|
||||
@@ -529,7 +529,7 @@ describe("MarkdownAPIImportTask document export archives", () => {
|
||||
userId: admin.id,
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
await withAPIContext(admin, (ctx) => archivable.archiveWithCtx(ctx));
|
||||
await withContext(admin, (ctx) => archivable.archiveWithCtx(ctx));
|
||||
|
||||
await new MarkdownImportsProcessor().perform({
|
||||
name: "imports.delete",
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
buildTeam,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { withContext } from "@server/test/support";
|
||||
import ShareSubscriptionNotificationsTask from "./ShareSubscriptionNotificationsTask";
|
||||
|
||||
const ip = "127.0.0.1";
|
||||
@@ -431,7 +431,7 @@ describe("ShareSubscriptionNotificationsTask", () => {
|
||||
confirmedAt: new Date(),
|
||||
});
|
||||
|
||||
await withAPIContext(user, (ctx) =>
|
||||
await withContext(user, (ctx) =>
|
||||
documentMover(ctx, { document, collectionId: other.id })
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Document, AccessRequest, UserMembership } from "@server/models";
|
||||
import { AccessRequestStatus } from "@server/models/AccessRequest";
|
||||
import { authorize, can } from "@server/policies";
|
||||
import { presentAccessRequest, presentPolicies } from "@server/presenters";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { Context } from "@server/types";
|
||||
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
|
||||
import * as T from "./schema";
|
||||
import { InvalidRequestError, NotFoundError } from "@server/errors";
|
||||
@@ -20,10 +20,10 @@ router.post(
|
||||
auth(),
|
||||
validate(T.AccessRequestsCreateSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.AccessRequestsCreateReq>) => {
|
||||
async (ctx: Context<T.AccessRequestsCreateReq>) => {
|
||||
const { documentId } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const document = await Document.findByPk(documentId, {
|
||||
userId: user.id,
|
||||
@@ -57,8 +57,8 @@ router.post(
|
||||
rateLimiter(RateLimiterStrategy.TwentyFivePerMinute),
|
||||
auth(),
|
||||
validate(T.AccessRequestsInfoSchema),
|
||||
async (ctx: APIContext<T.AccessRequestsInfoReq>) => {
|
||||
const { user } = ctx.state.auth;
|
||||
async (ctx: Context<T.AccessRequestsInfoReq>) => {
|
||||
const { user } = ctx.auth;
|
||||
const { id, documentId } = ctx.input.body;
|
||||
let accessRequest: AccessRequest | null = null;
|
||||
|
||||
@@ -91,10 +91,10 @@ router.post(
|
||||
auth(),
|
||||
validate(T.AccessRequestsApproveSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.AccessRequestsApproveReq>) => {
|
||||
async (ctx: Context<T.AccessRequestsApproveReq>) => {
|
||||
const { id, permission } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const accessRequest = await AccessRequest.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
@@ -143,10 +143,10 @@ router.post(
|
||||
auth(),
|
||||
validate(T.AccessRequestsDismissSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.AccessRequestsDismissReq>) => {
|
||||
async (ctx: Context<T.AccessRequestsDismissReq>) => {
|
||||
const { id } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const accessRequest = await AccessRequest.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
|
||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user