From 00b124d03c1e82baea84ff032a36950be5e2189e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 23 Nov 2026 23:17:06 -0500 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf * chore: Remove deprecated APIContext alias Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf * fix: Read auth from context in OAuth provider callbacks Co-Authored-By: Claude Opus 5.5 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 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 Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf --------- Co-authored-by: Claude --- .oxlintrc.json | 5 + plugins/azure/server/auth/azure.ts | 14 +- plugins/discord/server/auth/discord.ts | 15 +- plugins/email/server/auth/email.ts | 6 +- plugins/figma/server/api/figma.ts | 8 +- plugins/gitea/server/api/gitea.ts | 14 +- plugins/github/server/api/github.ts | 10 +- plugins/gitlab/server/api/gitlab.ts | 18 +- plugins/google/server/auth/google.ts | 14 +- plugins/linear/server/api/linear.ts | 8 +- plugins/notion/server/api/notion.ts | 8 +- plugins/oidc/server/auth/oidcRouter.ts | 19 +- plugins/passkeys/server/api/passkeys.ts | 18 +- plugins/passkeys/server/auth/passkeys.test.ts | 8 +- plugins/passkeys/server/auth/passkeys.ts | 26 +- plugins/slack/server/api/hooks.ts | 8 +- plugins/slack/server/auth/slack.ts | 18 +- plugins/storage/server/api/files.ts | 12 +- .../server/api/webhookSubscriptions.ts | 22 +- server/commands/accountProvisioner.ts | 33 +- server/commands/attachmentCreator.ts | 6 +- server/commands/collectionDuplicator.ts | 12 +- server/commands/documentCreator.test.ts | 32 +- server/commands/documentCreator.ts | 24 +- server/commands/documentDuplicator.test.ts | 22 +- server/commands/documentDuplicator.ts | 14 +- server/commands/documentImporter.ts | 4 +- server/commands/documentMover.test.ts | 20 +- server/commands/documentMover.ts | 8 +- server/commands/documentRestorer.ts | 10 +- server/commands/documentUpdater.test.ts | 70 ++-- server/commands/documentUpdater.ts | 8 +- server/commands/groupsSyncer.ts | 8 +- server/commands/personalCollectionLoader.ts | 25 +- server/commands/pinCreator.test.ts | 6 +- server/commands/pinCreator.ts | 6 +- server/commands/starCreator.test.ts | 6 +- server/commands/starCreator.ts | 6 +- server/commands/subscriptionCreator.ts | 10 +- server/commands/teamCreator.ts | 6 +- server/commands/teamProvisioner.ts | 4 +- server/commands/teamUpdater.test.ts | 18 +- server/commands/teamUpdater.ts | 10 +- server/commands/userInviter.test.ts | 16 +- server/commands/userInviter.ts | 6 +- server/commands/userProvisioner.ts | 4 +- server/context.test.ts | 37 ++ server/context.ts | 76 +++- server/logging/sentry.ts | 6 +- server/mcp/tools/attachments.ts | 2 +- server/mcp/tools/collections.ts | 10 +- server/mcp/tools/comments.ts | 10 +- server/mcp/tools/documents.ts | 34 +- server/mcp/util.ts | 12 +- server/middlewares/apexAuthRedirect.ts | 12 +- server/middlewares/apexRedirect.ts | 5 +- server/middlewares/apiContext.ts | 26 -- server/middlewares/appHeaders.ts | 5 +- server/middlewares/authentication.test.ts | 349 +++++++----------- server/middlewares/authentication.ts | 6 +- server/middlewares/csp.ts | 11 +- server/middlewares/feature.ts | 13 +- server/middlewares/multipart.ts | 4 +- server/middlewares/passport.ts | 5 +- server/middlewares/rateLimiter.test.ts | 4 +- server/middlewares/requestTracer.ts | 5 +- server/middlewares/shareDomains.test.ts | 4 +- server/middlewares/shareDomains.ts | 5 +- server/middlewares/transaction.ts | 4 +- server/middlewares/userAgent.test.ts | 12 +- server/middlewares/validate.ts | 4 +- server/middlewares/validateWebhook.ts | 8 +- server/models/AccessRequest.ts | 14 +- server/models/AuthenticationProvider.ts | 14 +- server/models/Collection.test.ts | 8 +- server/models/Collection.ts | 37 +- server/models/Document.test.ts | 12 +- server/models/Document.ts | 47 +-- server/models/Event.ts | 12 +- server/models/FileOperation.ts | 8 +- server/models/GroupMembership.ts | 16 +- server/models/Reaction.ts | 10 +- server/models/Revision.ts | 6 +- server/models/Share.ts | 6 +- server/models/User.ts | 18 +- server/models/UserMembership.test.ts | 6 +- server/models/UserMembership.ts | 16 +- server/models/View.ts | 4 +- server/models/base/Model.ts | 41 +- server/models/base/ParanoidModel.test.ts | 8 +- server/models/helpers/ProsemirrorHelper.tsx | 6 +- server/models/helpers/TextHelper.ts | 6 +- server/presenters/collection.ts | 4 +- server/presenters/document.test.ts | 8 +- server/presenters/document.ts | 8 +- server/presenters/integration.ts | 8 +- server/presenters/notification.ts | 4 +- .../tasks/MarkdownAPIImportTask.test.ts | 4 +- ...ShareSubscriptionNotificationsTask.test.ts | 4 +- .../api/accessRequests/accessRequests.ts | 24 +- server/routes/api/apiKeys/apiKeys.ts | 16 +- server/routes/api/attachments/attachments.ts | 56 ++- server/routes/api/auth/auth.ts | 12 +- .../authenticationProviders.ts | 26 +- server/routes/api/batch/batch.ts | 20 +- server/routes/api/collections/collections.ts | 121 +++--- server/routes/api/comments/comments.ts | 57 +-- server/routes/api/cron/cron.ts | 4 +- server/routes/api/developer/developer.ts | 15 +- server/routes/api/documents/documents.test.ts | 88 +++-- server/routes/api/documents/documents.ts | 161 ++++---- server/routes/api/emojis/emojis.ts | 34 +- server/routes/api/events/events.ts | 6 +- .../api/fileOperations/fileOperations.ts | 20 +- .../api/groupMemberships/groupMemberships.ts | 6 +- server/routes/api/groups/groups.ts | 54 +-- server/routes/api/imports/imports.ts | 34 +- server/routes/api/index.ts | 2 - .../routes/api/installation/installation.ts | 8 +- .../routes/api/integrations/integrations.ts | 26 +- .../api/middlewares/apiErrorHandler.test.ts | 6 +- .../routes/api/middlewares/apiErrorHandler.ts | 5 +- server/routes/api/middlewares/apiResponse.ts | 5 +- server/routes/api/middlewares/editor.ts | 5 +- .../routes/api/notifications/notifications.ts | 30 +- .../oauthAuthentications.ts | 12 +- .../routes/api/oauthClients/oauthClients.ts | 36 +- server/routes/api/pins/pins.ts | 28 +- server/routes/api/reactions/reactions.ts | 6 +- .../routes/api/relationships/relationships.ts | 10 +- server/routes/api/revisions/revisions.ts | 24 +- server/routes/api/searches/searches.ts | 16 +- server/routes/api/shares/shares.test.ts | 6 +- server/routes/api/shares/shares.ts | 40 +- server/routes/api/stars/stars.ts | 24 +- .../routes/api/subscriptions/subscriptions.ts | 26 +- server/routes/api/suggestions/suggestions.ts | 6 +- server/routes/api/teams/teams.ts | 22 +- server/routes/api/templates/templates.ts | 40 +- server/routes/api/urls/urls.ts | 14 +- .../api/userMemberships/userMemberships.ts | 12 +- server/routes/api/users/users.ts | 76 ++-- server/routes/api/views/views.ts | 10 +- server/routes/app.ts | 9 +- server/routes/embeds.ts | 9 +- server/routes/mcp/index.ts | 18 +- server/routes/oauth/index.ts | 26 +- .../oauth/middlewares/oauthErrorHandler.ts | 8 +- .../oauth/middlewares/registrationAuth.ts | 12 +- server/routes/workspace.ts | 4 +- server/test/support.ts | 20 +- server/types.ts | 59 ++- server/utils/LogoutTokenStore.test.ts | 4 +- server/utils/LogoutTokenStore.ts | 8 +- server/utils/SessionsCookieHelper.ts | 14 +- server/utils/authentication.ts | 9 +- server/utils/csrf.ts | 8 +- server/utils/jwt.test.ts | 4 +- server/utils/jwt.ts | 4 +- server/utils/koa.ts | 5 +- server/utils/oauth.ts | 6 +- server/utils/oauth/OAuthHelper.ts | 4 +- server/utils/passport.ts | 33 +- server/utils/redirectOnClient.ts | 4 +- 164 files changed, 1574 insertions(+), 1592 deletions(-) create mode 100644 server/context.test.ts delete mode 100644 server/middlewares/apiContext.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index 207b36d758..2a75b9875b 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -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": [ diff --git a/plugins/azure/server/auth/azure.ts b/plugins/azure/server/auth/azure.ts index 50c89c26ea..5ac7074d2a 100644 --- a/plugins/azure/server/auth/azure.ts +++ b/plugins/azure/server/auth/azure.ts @@ -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, diff --git a/plugins/discord/server/auth/discord.ts b/plugins/discord/server/auth/discord.ts index ad7cfe208d..c8fafa41e3 100644 --- a/plugins/discord/server/auth/discord.ts +++ b/plugins/discord/server/auth/discord.ts @@ -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, diff --git a/plugins/email/server/auth/email.ts b/plugins/email/server/auth/email.ts index e9dc65c1ea..3496196a2d 100644 --- a/plugins/email/server/auth/email.ts +++ b/plugins/email/server/auth/email.ts @@ -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) => { + async (ctx: Context) => { const { email, client, preferOTP } = ctx.input.body; const domain = parseDomain(ctx.request.hostname); @@ -99,7 +99,7 @@ router.post( } ); -const emailCallback = async (ctx: APIContext) => { +const emailCallback = async (ctx: Context) => { const { query, body } = ctx.input; const token = query?.token || body?.token; const client = query?.client || body?.client || Client.Web; diff --git a/plugins/figma/server/api/figma.ts b/plugins/figma/server/api/figma.ts index 4cbb73be0f..bd71c121bb 100644 --- a/plugins/figma/server/api/figma.ts +++ b/plugins/figma/server/api/figma.ts @@ -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) => { + async (ctx: Context) => { 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. diff --git a/plugins/gitea/server/api/gitea.ts b/plugins/gitea/server/api/gitea.ts index 31ef41ddfb..86c9bac9a9 100644 --- a/plugins/gitea/server/api/gitea.ts +++ b/plugins/gitea/server/api/gitea.ts @@ -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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { 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)); diff --git a/plugins/github/server/api/github.ts b/plugins/github/server/api/github.ts index 34402faa53..c33025a3ea 100644 --- a/plugins/github/server/api/github.ts +++ b/plugins/github/server/api/github.ts @@ -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) => { + async (ctx: Context) => { 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); diff --git a/plugins/gitlab/server/api/gitlab.ts b/plugins/gitlab/server/api/gitlab.ts index bb36262043..6586902096 100644 --- a/plugins/gitlab/server/api/gitlab.ts +++ b/plugins/gitlab/server/api/gitlab.ts @@ -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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { 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 = ctx.state.webhookTeamIds ?? [null]; diff --git a/plugins/google/server/auth/google.ts b/plugins/google/server/auth/google.ts index a03b2d0929..c32e30ef03 100644 --- a/plugins/google/server/auth/google.ts +++ b/plugins/google/server/auth/google.ts @@ -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, diff --git a/plugins/linear/server/api/linear.ts b/plugins/linear/server/api/linear.ts index 27ac66a89d..5dd35af74f 100644 --- a/plugins/linear/server/api/linear.ts +++ b/plugins/linear/server/api/linear.ts @@ -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) => { + async (ctx: Context) => { 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) { diff --git a/plugins/notion/server/api/notion.ts b/plugins/notion/server/api/notion.ts index 9d4e0ee18a..c685a3694b 100644 --- a/plugins/notion/server/api/notion.ts +++ b/plugins/notion/server/api/notion.ts @@ -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) => { + async (ctx: Context) => { 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) { diff --git a/plugins/oidc/server/auth/oidcRouter.ts b/plugins/oidc/server/auth/oidcRouter.ts index 9eed7a9c85..5fdfdbd59c 100644 --- a/plugins/oidc/server/auth/oidcRouter.ts +++ b/plugins/oidc/server/auth/oidcRouter.ts @@ -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) { diff --git a/plugins/passkeys/server/api/passkeys.ts b/plugins/passkeys/server/api/passkeys.ts index afb32630e1..1801282434 100644 --- a/plugins/passkeys/server/api/passkeys.ts +++ b/plugins/passkeys/server/api/passkeys.ts @@ -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) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + 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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { 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, diff --git a/plugins/passkeys/server/auth/passkeys.test.ts b/plugins/passkeys/server/auth/passkeys.test.ts index 5bf0fc249a..0c9326bcb7 100644 --- a/plugins/passkeys/server/auth/passkeys.test.ts +++ b/plugins/passkeys/server/auth/passkeys.test.ts @@ -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({ diff --git a/plugins/passkeys/server/auth/passkeys.ts b/plugins/passkeys/server/auth/passkeys.ts index e2717cf2d7..57a627ced7 100644 --- a/plugins/passkeys/server/auth/passkeys.ts +++ b/plugins/passkeys/server/auth/passkeys.ts @@ -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) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + 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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { const body = ctx.input.body; const { challengeId, client = Client.Web } = body; diff --git a/plugins/slack/server/api/hooks.ts b/plugins/slack/server/api/hooks.ts index 7a5b8c6dda..1ad6e88d7c 100644 --- a/plugins/slack/server/api/hooks.ts +++ b/plugins/slack/server/api/hooks.ts @@ -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) => { + async (ctx: Context) => { // 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) => { + async (ctx: Context) => { const { payload } = ctx.input.body; let parsed; @@ -208,7 +208,7 @@ router.post( router.post( "hooks.slack", validate(T.HooksSlackCommandSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { token, team_id, user_id, text } = ctx.input.body; verifySlackToken(token); diff --git a/plugins/slack/server/auth/slack.ts b/plugins/slack/server/auth/slack.ts index ed54c275b9..e1709ca342 100644 --- a/plugins/slack/server/auth/slack.ts +++ b/plugins/slack/server/auth/slack.ts @@ -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) => { + async (ctx: Context) => { const { code, error, state } = ctx.input.query; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (error) { ctx.redirect(SlackUtils.errorUrl(error)); diff --git a/plugins/storage/server/api/files.ts b/plugins/storage/server/api/files.ts index 810da4ca08..e5bc1cbb64 100644 --- a/plugins/storage/server/api/files.ts +++ b/plugins/storage/server/api/files.ts @@ -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) => { - const actor = ctx.state.auth.user; + async (ctx: Context) => { + 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) => { - const actor = ctx.state.auth.user; + async (ctx: Context) => { + 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): string { +function getKeyFromContext(ctx: Context): string { const { key, sig } = ctx.input.query; if (sig) { const payload = getJWTPayload(sig); diff --git a/plugins/webhooks/server/api/webhookSubscriptions.ts b/plugins/webhooks/server/api/webhookSubscriptions.ts index 9b8024fee9..e6a28ceefa 100644 --- a/plugins/webhooks/server/api/webhookSubscriptions.ts +++ b/plugins/webhooks/server/api/webhookSubscriptions.ts @@ -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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { 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, diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts index 0161bdf2f8..9801785af5 100644 --- a/server/commands/accountProvisioner.ts +++ b/server/commands/accountProvisioner.ts @@ -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( @@ -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", diff --git a/server/commands/attachmentCreator.ts b/server/commands/attachmentCreator.ts index deb02968b6..979cea908f 100644 --- a/server/commands/attachmentCreator.ts +++ b/server/commands/attachmentCreator.ts @@ -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) { diff --git a/server/commands/collectionDuplicator.ts b/server/commands/collectionDuplicator.ts index 6fbf9e7939..f6fb147577 100644 --- a/server/commands/collectionDuplicator.ts +++ b/server/commands/collectionDuplicator.ts @@ -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 { - 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) { diff --git a/server/commands/documentCreator.test.ts b/server/commands/documentCreator.test.ts index d1013d6dfd..fd152de55a 100644 --- a/server/commands/documentCreator.test.ts +++ b/server/commands/documentCreator.test.ts @@ -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, diff --git a/server/commands/documentCreator.ts b/server/commands/documentCreator.ts index 4416b0db43..093f0c5d8e 100644 --- a/server/commands/documentCreator.ts +++ b/server/commands/documentCreator.ts @@ -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 { - 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 { - 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; diff --git a/server/commands/documentDuplicator.test.ts b/server/commands/documentDuplicator.test.ts index f04698a070..4996e19671 100644 --- a/server/commands/documentDuplicator.test.ts +++ b/server/commands/documentDuplicator.test.ts @@ -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, diff --git a/server/commands/documentDuplicator.ts b/server/commands/documentDuplicator.ts index 8543878970..35387c725a 100644 --- a/server/commands/documentDuplicator.ts +++ b/server/commands/documentDuplicator.ts @@ -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 { 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 { 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, }); diff --git a/server/commands/documentImporter.ts b/server/commands/documentImporter.ts index 2661395a26..fa6b4a22c5 100644 --- a/server/commands/documentImporter.ts +++ b/server/commands/documentImporter.ts @@ -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 = { diff --git a/server/commands/documentMover.test.ts b/server/commands/documentMover.test.ts index 67b7c06538..f78d952c91 100644 --- a/server/commands/documentMover.test.ts +++ b/server/commands/documentMover.test.ts @@ -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, diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index 0e5602f183..126386f1e7 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -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 { - 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; diff --git a/server/commands/documentRestorer.ts b/server/commands/documentRestorer.ts index d8379d7d2d..ee9f832462 100644 --- a/server/commands/documentRestorer.ts +++ b/server/commands/documentRestorer.ts @@ -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 { - 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 diff --git a/server/commands/documentUpdater.test.ts b/server/commands/documentUpdater.test.ts index b87175a6b9..bf4df5b336 100644 --- a/server/commands/documentUpdater.test.ts +++ b/server/commands/documentUpdater.test.ts @@ -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, diff --git a/server/commands/documentUpdater.ts b/server/commands/documentUpdater.ts index a7d16f22ba..8ab59a1c36 100644 --- a/server/commands/documentUpdater.ts +++ b/server/commands/documentUpdater.ts @@ -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 { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const cId = collectionId || document.collectionId; document.fill({ diff --git a/server/commands/groupsSyncer.ts b/server/commands/groupsSyncer.ts index b40014fd62..f876fcae66 100644 --- a/server/commands/groupsSyncer.ts +++ b/server/commands/groupsSyncer.ts @@ -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 { - const { transaction } = ctx.state; + const { transaction } = ctx; const result: GroupSyncResult = { groupsCreated: 0, membershipsAdded: 0, diff --git a/server/commands/personalCollectionLoader.ts b/server/commands/personalCollectionLoader.ts index 692d7b9f40..daba742c3a 100644 --- a/server/commands/personalCollectionLoader.ts +++ b/server/commands/personalCollectionLoader.ts @@ -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 { - 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 { +>(ctx: Context, collectionId: T): Promise { return collectionId === PersonalCollectionId ? (await personalCollectionLoader(ctx)).id : collectionId; diff --git a/server/commands/pinCreator.test.ts b/server/commands/pinCreator.test.ts index 79f8d0e46c..7a2d0bbf05 100644 --- a/server/commands/pinCreator.test.ts +++ b/server/commands/pinCreator.test.ts @@ -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, diff --git a/server/commands/pinCreator.ts b/server/commands/pinCreator.ts index e0ed518cf7..02b26e9e9e 100644 --- a/server/commands/pinCreator.ts +++ b/server/commands/pinCreator.ts @@ -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 { let { index } = rest; - const { transaction } = ctx.context; + const { transaction } = ctx; const where: WhereOptions = { teamId: user.teamId, ...(collectionId ? { collectionId } : { collectionId: { [Op.is]: null } }), diff --git a/server/commands/starCreator.test.ts b/server/commands/starCreator.test.ts index 31b34f8fdc..e371bd4293 100644 --- a/server/commands/starCreator.test.ts +++ b/server/commands/starCreator.test.ts @@ -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, diff --git a/server/commands/starCreator.ts b/server/commands/starCreator.ts index a969282a1b..7553fe8238 100644 --- a/server/commands/starCreator.ts +++ b/server/commands/starCreator.ts @@ -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 diff --git a/server/commands/subscriptionCreator.ts b/server/commands/subscriptionCreator.ts index dc11385c8f..3716f03e16 100644 --- a/server/commands/subscriptionCreator.ts +++ b/server/commands/subscriptionCreator.ts @@ -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 { - 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 { diff --git a/server/commands/teamCreator.ts b/server/commands/teamCreator.ts index 0b16cd201a..8c62db9cea 100644 --- a/server/commands/teamCreator.ts +++ b/server/commands/teamCreator.ts @@ -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 { 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, diff --git a/server/commands/teamProvisioner.ts b/server/commands/teamProvisioner.ts index 44d3bbb568..4a0019c6f9 100644 --- a/server/commands/teamProvisioner.ts +++ b/server/commands/teamProvisioner.ts @@ -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 { const where = teamId diff --git a/server/commands/teamUpdater.test.ts b/server/commands/teamUpdater.test.ts index 4274ff087c..aca609d3b6 100644 --- a/server/commands/teamUpdater.test.ts +++ b/server/commands/teamUpdater.test.ts @@ -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, diff --git a/server/commands/teamUpdater.ts b/server/commands/teamUpdater.ts index 155ed890ed..83e64e143e 100644 --- a/server/commands/teamUpdater.ts +++ b/server/commands/teamUpdater.ts @@ -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> & { 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 diff --git a/server/commands/userInviter.test.ts b/server/commands/userInviter.test.ts index 25f75af5e4..a00ce409a2 100644 --- a/server/commands/userInviter.test.ts +++ b/server/commands/userInviter.test.ts @@ -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: [ { diff --git a/server/commands/userInviter.ts b/server/commands/userInviter.ts index a14c404b63..908c25dee6 100644 --- a/server/commands/userInviter.ts +++ b/server/commands/userInviter.ts @@ -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)) { diff --git a/server/commands/userProvisioner.ts b/server/commands/userProvisioner.ts index dc85d013ae..8f7683aab8 100644 --- a/server/commands/userProvisioner.ts +++ b/server/commands/userProvisioner.ts @@ -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, diff --git a/server/context.test.ts b/server/context.test.ts new file mode 100644 index 0000000000..692401c485 --- /dev/null +++ b/server/context.test.ts @@ -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(); + }); + }); +}); diff --git a/server/context.ts b/server/context.ts index 910465e9e5..e0f48358da 100644 --- a/server/context.ts +++ b/server/context.ts @@ -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, + }; } diff --git a/server/logging/sentry.ts b/server/logging/sentry.ts index ec5f3e85bd..0d6e65b326 100644 --- a/server/logging/sentry.ts +++ b/server/logging/sentry.ts @@ -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, diff --git a/server/mcp/tools/attachments.ts b/server/mcp/tools/attachments.ts index 5925563bb0..5e0a83d54c 100644 --- a/server/mcp/tools/attachments.ts +++ b/server/mcp/tools/attachments.ts @@ -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, }); diff --git a/server/mcp/tools/collections.ts b/server/mcp/tools/collections.ts index e2a2766e82..cb156c4045 100644 --- a/server/mcp/tools/collections.ts +++ b/server/mcp/tools/collections.ts @@ -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, diff --git a/server/mcp/tools/comments.ts b/server/mcp/tools/comments.ts index 0dea86d6d4..808879e546 100644 --- a/server/mcp/tools/comments.ts +++ b/server/mcp/tools/comments.ts @@ -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, diff --git a/server/mcp/tools/documents.ts b/server/mcp/tools/documents.ts index bd142da4e2..f00263d699 100644 --- a/server/mcp/tools/documents.ts +++ b/server/mcp/tools/documents.ts @@ -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, diff --git a/server/mcp/util.ts b/server/mcp/util.ts index 9645fd23a3..ea6e3ce882 100644 --- a/server/mcp/util.ts +++ b/server/mcp/util.ts @@ -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; } /** diff --git a/server/middlewares/apexAuthRedirect.ts b/server/middlewares/apexAuthRedirect.ts index 466a9963f6..5409b2d69e 100644 --- a/server/middlewares/apexAuthRedirect.ts +++ b/server/middlewares/apexAuthRedirect.ts @@ -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({ getErrorPath, }: { /** Get the team ID for the current request */ - getTeamId: (ctx: APIContext) => string | null | undefined; + getTeamId: (ctx: Context) => string | null | undefined; /** Get the redirect URL for the given team ID */ - getRedirectPath: (ctx: APIContext, team: Team) => string; + getRedirectPath: (ctx: Context, team: Team) => string; /** Get the error URL for the current request */ - getErrorPath: (ctx: APIContext) => string; + getErrorPath: (ctx: Context) => string; }) { return async function apexAuthRedirectMiddleware( - ctx: APIContext, + ctx: Context, next: Next ) { - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (user) { return next(); } diff --git a/server/middlewares/apexRedirect.ts b/server/middlewares/apexRedirect.ts index 589588e172..1499af2aed 100644 --- a/server/middlewares/apexRedirect.ts +++ b/server/middlewares/apexRedirect.ts @@ -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 { diff --git a/server/middlewares/apiContext.ts b/server/middlewares/apiContext.ts deleted file mode 100644 index 5da5547442..0000000000 --- a/server/middlewares/apiContext.ts +++ /dev/null @@ -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(); - }; -} diff --git a/server/middlewares/appHeaders.ts b/server/middlewares/appHeaders.ts index 4095359882..3bd2b612ee 100644 --- a/server/middlewares/appHeaders.ts +++ b/server/middlewares/appHeaders.ts @@ -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. diff --git a/server/middlewares/authentication.test.ts b/server/middlewares/authentication.test.ts index c52c1f3ff1..49d56599a2 100644 --- a/server/middlewares/authentication.test.ts +++ b/server/middlewares/authentication.test.ts @@ -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 "' @@ -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); }); }); }); diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index 89f0ad2643..e99f971ed2 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -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; } diff --git a/server/middlewares/csp.ts b/server/middlewares/csp.ts index a00d757aba..edc23c426f 100644 --- a/server/middlewares/csp.ts +++ b/server/middlewares/csp.ts @@ -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 = []; diff --git a/server/middlewares/feature.ts b/server/middlewares/feature.ts index 120db72421..0efdcca619 100644 --- a/server/middlewares/feature.ts +++ b/server/middlewares/feature.ts @@ -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. diff --git a/server/middlewares/multipart.ts b/server/middlewares/multipart.ts index e2228211a8..fa6d0614e4 100644 --- a/server/middlewares/multipart.ts +++ b/server/middlewares/multipart.ts @@ -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(); diff --git a/server/middlewares/passport.ts b/server/middlewares/passport.ts index db09f391aa..faee69588f 100644 --- a/server/middlewares/passport.ts +++ b/server/middlewares/passport.ts @@ -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 { } export default function createMiddleware(providerName: string) { - return function passportMiddleware(ctx: Context) { + return function passportMiddleware(ctx: AppContext) { return passport.authorize( providerName, { diff --git a/server/middlewares/rateLimiter.test.ts b/server/middlewares/rateLimiter.test.ts index 770f6af3bc..def75ae532 100644 --- a/server/middlewares/rateLimiter.test.ts +++ b/server/middlewares/rateLimiter.test.ts @@ -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; diff --git a/server/middlewares/requestTracer.ts b/server/middlewares/requestTracer.ts index 81cf757e99..4ce6e3bbc1 100644 --- a/server/middlewares/requestTracer.ts +++ b/server/middlewares/requestTracer.ts @@ -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; diff --git a/server/middlewares/shareDomains.test.ts b/server/middlewares/shareDomains.test.ts index fe083e4883..ab60ffbea5 100644 --- a/server/middlewares/shareDomains.test.ts +++ b/server/middlewares/shareDomains.test.ts @@ -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); diff --git a/server/middlewares/shareDomains.ts b/server/middlewares/shareDomains.ts index 469ca78fab..b4acf9c9c1 100644 --- a/server/middlewares/shareDomains.ts +++ b/server/middlewares/shareDomains.ts @@ -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)) { diff --git a/server/middlewares/transaction.ts b/server/middlewares/transaction.ts index eaf6f196e8..664b002488 100644 --- a/server/middlewares/transaction.ts +++ b/server/middlewares/transaction.ts @@ -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(); }); }; diff --git a/server/middlewares/userAgent.test.ts b/server/middlewares/userAgent.test.ts index 83603d8bde..8a1e48bfcd 100644 --- a/server/middlewares/userAgent.test.ts +++ b/server/middlewares/userAgent.test.ts @@ -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"); }); }); diff --git a/server/middlewares/validate.ts b/server/middlewares/validate.ts index 9d7f1c1f29..7cf8926382 100644 --- a/server/middlewares/validate.ts +++ b/server/middlewares/validate.ts @@ -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>>( schema: T ) { - return async function validateMiddleware(ctx: APIContext, next: Next) { + return async function validateMiddleware(ctx: Context, next: Next) { try { ctx.input = { ...ctx.input, diff --git a/server/middlewares/validateWebhook.ts b/server/middlewares/validateWebhook.ts index b16d983e1b..f0c09577af 100644 --- a/server/middlewares/validateWebhook.ts +++ b/server/middlewares/validateWebhook.ts @@ -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); - getSignatureFromHeader: (ctx: APIContext) => string | undefined; + secretKey: string | ((ctx: Context) => Promise); + 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); diff --git a/server/models/AccessRequest.ts b/server/models/AccessRequest.ts index 4137ab10b1..27c8d7d8ff 100644 --- a/server/models/AccessRequest.ts +++ b/server/models/AccessRequest.ts @@ -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); } diff --git a/server/models/AuthenticationProvider.ts b/server/models/AuthenticationProvider.ts index 3f0425748a..c5c95478e1 100644 --- a/server/models/AuthenticationProvider.ts +++ b/server/models/AuthenticationProvider.ts @@ -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 = async ( - ctx - ) => { - const { transaction } = ctx.state; + disable: (ctx: Context) => Promise = 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 = async (ctx) => + enable: (ctx: Context) => Promise = async (ctx) => this.updateWithCtx(ctx, { enabled: true, }); diff --git a/server/models/Collection.test.ts b/server/models/Collection.test.ts index e547118bc0..f4f4c6066a 100644 --- a/server/models/Collection.test.ts +++ b/server/models/Collection.test.ts @@ -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(); diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 1625963389..3e7becad58 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -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 { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + static async findOrCreatePersonal(ctx: Context): Promise { + 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 ( diff --git a/server/models/Document.test.ts b/server/models/Document.test.ts index 5356f96830..5da5be3e50 100644 --- a/server/models/Document.test.ts +++ b/server/models/Document.test.ts @@ -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, }); diff --git a/server/models/Document.ts b/server/models/Document.ts index 943e42d7e1..28eeb412e1 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -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; } ): Promise => { - 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 => { - 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 diff --git a/server/models/Event.ts b/server/models/Event.ts index e6d70df41a..7dcf29a74b 100644 --- a/server/models/Event.ts +++ b/server/models/Event.ts @@ -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, "ip" | "teamId" | "actorId"> = {}, defaultAttributes: Pick, "ip" | "teamId" | "actorId"> = {}, options?: CreateOptions> ) { - 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, } ); diff --git a/server/models/FileOperation.ts b/server/models/FileOperation.ts index b062ab614e..b31d9d8ec9 100644 --- a/server/models/FileOperation.ts +++ b/server/models/FileOperation.ts @@ -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 { - 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; diff --git a/server/models/GroupMembership.ts b/server/models/GroupMembership.ts index df0d176bda..6fdd4b6745 100644 --- a/server/models/GroupMembership.ts +++ b/server/models/GroupMembership.ts @@ -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 ) { @@ -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 diff --git a/server/models/Reaction.ts b/server/models/Reaction.ts index f3ede25206..b9ff1bd961 100644 --- a/server/models/Reaction.ts +++ b/server/models/Reaction.ts @@ -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, CreationAttributes> ) { 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, diff --git a/server/models/Revision.ts b/server/models/Revision.ts index 395a47975c..cee2354ea7 100644 --- a/server/models/Revision.ts +++ b/server/models/Revision.ts @@ -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) { diff --git a/server/models/Share.ts b/server/models/Share.ts index cc6e45c87f..af9e28890b 100644 --- a/server/models/Share.ts +++ b/server/models/Share.ts @@ -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" }); diff --git a/server/models/User.ts b/server/models/User.ts index fb3f78c0e1..6a98df6511 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -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), }); }; diff --git a/server/models/UserMembership.test.ts b/server/models/UserMembership.test.ts index b3c5c3e50e..0c3457dccf 100644 --- a/server/models/UserMembership.test.ts +++ b/server/models/UserMembership.test.ts @@ -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); diff --git a/server/models/UserMembership.ts b/server/models/UserMembership.ts index bde81a2beb..9c5fdc1cf0 100644 --- a/server/models/UserMembership.ts +++ b/server/models/UserMembership.ts @@ -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 ) { @@ -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 diff --git a/server/models/View.ts b/server/models/View.ts index d465106284..810dad5117 100644 --- a/server/models/View.ts +++ b/server/models/View.ts @@ -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; diff --git a/server/models/base/Model.ts b/server/models/base/Model.ts index c8000325c8..c6804fac65 100644 --- a/server/models/base/Model.ts +++ b/server/models/base/Model.ts @@ -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 resolves to never under object default; load-bearing for static helpers like saveWithCtx. @@ -69,12 +70,12 @@ class Model< * Validates this instance, and if the validation passes, persists it to the database. */ public saveWithCtx( - ctx: APIContext, + ctx: Context, options?: SaveOptions>, 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, 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( this: ModelStatic, - ctx: APIContext, + ctx: Context, options: FindOrCreateOptions, CreationAttributes>, 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( this: ModelStatic, - ctx: APIContext, + ctx: Context, options: DestroyOptions>, eventOpts?: EventOverrideOptions ) { const hookContext = { - ...ctx.context, + ...toHookContext(ctx), ...options, individualHooks: true, event: { @@ -234,13 +235,13 @@ class Model< */ public static createWithCtx( this: ModelStatic, - ctx: APIContext, + ctx: Context, values?: CreationAttributes, eventOpts?: EventOverrideOptions, createOpts?: CreateOptions ) { 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( name: string, diff --git a/server/models/base/ParanoidModel.test.ts b/server/models/base/ParanoidModel.test.ts index 0d5c40ea24..abb28a8ec4 100644 --- a/server/models/base/ParanoidModel.test.ts +++ b/server/models/base/ParanoidModel.test.ts @@ -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(); }); diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index 739cfae56a..2ecc1ed4be 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -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 { diff --git a/server/models/helpers/TextHelper.ts b/server/models/helpers/TextHelper.ts index e1cea6ea76..1f736550af 100644 --- a/server/models/helpers/TextHelper.ts +++ b/server/models/helpers/TextHelper.ts @@ -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: { diff --git a/server/presenters/collection.ts b/server/presenters/collection.ts index 9b1b08bb48..b69e9d5d47 100644 --- a/server/presenters/collection.ts +++ b/server/presenters/collection.ts @@ -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 = {} ) { diff --git a/server/presenters/document.test.ts b/server/presenters/document.test.ts index 562984cea9..04f4790aec 100644 --- a/server/presenters/document.test.ts +++ b/server/presenters/document.test.ts @@ -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({ diff --git a/server/presenters/document.ts b/server/presenters/document.ts index a8d132b190..b2d6ec7f55 100644 --- a/server/presenters/document.ts +++ b/server/presenters/document.ts @@ -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 ) { diff --git a/server/presenters/integration.ts b/server/presenters/integration.ts index 523fb40c07..05cf5a812d 100644 --- a/server/presenters/integration.ts +++ b/server/presenters/integration.ts @@ -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, }; diff --git a/server/presenters/notification.ts b/server/presenters/notification.ts index 79004b0f3d..ca4970e1e8 100644 --- a/server/presenters/notification.ts +++ b/server/presenters/notification.ts @@ -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 { diff --git a/server/queues/tasks/MarkdownAPIImportTask.test.ts b/server/queues/tasks/MarkdownAPIImportTask.test.ts index 92fba4e30b..7c5fa4dffb 100644 --- a/server/queues/tasks/MarkdownAPIImportTask.test.ts +++ b/server/queues/tasks/MarkdownAPIImportTask.test.ts @@ -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", diff --git a/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts b/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts index f696dd6a5d..754af44d74 100644 --- a/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts +++ b/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts @@ -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 }) ); diff --git a/server/routes/api/accessRequests/accessRequests.ts b/server/routes/api/accessRequests/accessRequests.ts index 3ab19d5d6b..6c43fd1962 100644 --- a/server/routes/api/accessRequests/accessRequests.ts +++ b/server/routes/api/accessRequests/accessRequests.ts @@ -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) => { + async (ctx: Context) => { 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) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + 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) => { + async (ctx: Context) => { 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) => { + async (ctx: Context) => { 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, diff --git a/server/routes/api/apiKeys/apiKeys.ts b/server/routes/api/apiKeys/apiKeys.ts index 3bbbaff7d5..5b8391516a 100644 --- a/server/routes/api/apiKeys/apiKeys.ts +++ b/server/routes/api/apiKeys/apiKeys.ts @@ -7,7 +7,7 @@ import validate from "@server/middlewares/validate"; import { ApiKey, User } from "@server/models"; import { authorize, cannot } from "@server/policies"; import { presentApiKey } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { AuthenticationType } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { QueryHelper } from "@server/storage/QueryHelper"; @@ -24,9 +24,9 @@ router.post( }), validate(T.APIKeysCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { name, scope, expiresAt } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createApiKey", user.team); @@ -50,10 +50,10 @@ router.post( auth(), pagination(), validate(T.APIKeysListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { userId, query, sort, direction } = ctx.input.body; const { pagination } = ctx.state; - const actor = ctx.state.auth.user; + const actor = ctx.auth.user; let userWhere: WhereOptions = { teamId: actor.teamId, @@ -120,10 +120,10 @@ router.post( }), validate(T.APIKeysDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const key = await ApiKey.scope("withUser").findByPk(id, { lock: { diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index 18f203f77e..f9a6d9befb 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -5,7 +5,7 @@ import { AttachmentPreset } from "@shared/types"; import { bytesToHumanReadable, getFileNameFromUrl } from "@shared/utils/files"; import env from "@server/env"; import { AttachmentValidation } from "@shared/validations"; -import { createContext } from "@server/context"; +import { withTransaction } from "@server/context"; import { AuthorizationError, InvalidRequestError, @@ -25,7 +25,7 @@ import pagination from "@server/routes/api/middlewares/pagination"; import { sequelize } from "@server/storage/database"; import FileStorage from "@server/storage/files"; import BaseStorage from "@server/storage/files/BaseStorage"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { assertIn } from "@server/validation"; import * as T from "./schema"; @@ -68,9 +68,9 @@ router.post( auth(), pagination(), validate(T.AttachmentsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { documentId, userId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions = { teamId: user.teamId, @@ -115,9 +115,9 @@ router.post( auth(), validate(T.AttachmentsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name, documentId, contentType, size, preset } = ctx.input.body; - const { auth, transaction } = ctx.state; + const { auth, transaction } = ctx; const { user } = auth; if (documentId) { @@ -228,9 +228,9 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth(), validate(T.AttachmentsCreateFromUrlSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, url, documentId, preset } = ctx.input.body; - const { user, type } = ctx.state.auth; + const { user } = ctx.auth; if (preset !== AttachmentPreset.DocumentAttachment || !documentId) { throw ValidationError( @@ -252,25 +252,17 @@ router.post( // Does not use transaction middleware, as attachment must be persisted // before the job is scheduled. const attachment = await sequelize.transaction(async (transaction) => - Attachment.createWithCtx( - createContext({ - authType: type, - user, - ip: ctx.ip, - transaction, - }), - { - id: modelId, - key, - acl, - size: 0, - expiresAt: AttachmentHelper.presetToExpiry(preset), - contentType: "application/octet-stream", - documentId, - teamId: user.teamId, - userId: user.id, - } - ) + Attachment.createWithCtx(withTransaction(ctx, transaction), { + id: modelId, + key, + acl, + size: 0, + expiresAt: AttachmentHelper.presetToExpiry(preset), + contentType: "application/octet-stream", + documentId, + teamId: user.teamId, + userId: user.id, + }) ); const job = await new UploadAttachmentFromUrlTask().schedule({ @@ -296,10 +288,10 @@ router.post( auth(), validate(T.AttachmentDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const attachment = await Attachment.findByPk(id, { rejectOnEmpty: true, lock: transaction.LOCK.UPDATE, @@ -320,11 +312,11 @@ router.post( ); const handleAttachmentsRedirect = async ( - ctx: APIContext + ctx: Context ) => { const id = (ctx.input.body.id ?? ctx.input.query.id) as string; - const user = ctx.state.auth?.user; + const user = ctx.auth?.user; const attachment = await Attachment.findByPk(id, { rejectOnEmpty: true, }); diff --git a/server/routes/api/auth/auth.ts b/server/routes/api/auth/auth.ts index 16bc88f02e..3a45d527d1 100644 --- a/server/routes/api/auth/auth.ts +++ b/server/routes/api/auth/auth.ts @@ -19,7 +19,7 @@ import { presentGroupUser, } from "@server/presenters"; import ValidateSSOAccessTask from "@server/queues/tasks/ValidateSSOAccessTask"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { AuthenticationType } from "@server/types"; import { clearCSRFCookie } from "@server/utils/csrf"; import { getJWTPayload } from "@server/utils/jwt"; @@ -29,7 +29,7 @@ import type * as T from "./schema"; const router = new Router(); -router.post("auth.config", async (ctx: APIContext) => { +router.post("auth.config", async (ctx: Context) => { // If self hosted AND there is only one team then that team becomes the // brand for the knowledge base and its guest sign-in option is used for the // root login page. @@ -122,8 +122,8 @@ router.post("auth.config", async (ctx: APIContext) => { /** Authentication services that don't require SSO validation. */ const NON_SSO_SERVICES = ["email", "passkeys"]; -router.post("auth.info", auth(), async (ctx: APIContext) => { - const { user, service, type, token } = ctx.state.auth; +router.post("auth.info", auth(), async (ctx: Context) => { + const { user, service, type, token } = ctx.auth; const [team, groups, availableTeams] = await Promise.all([ Team.scope("withDomains").findByPk(user.teamId, { rejectOnEmpty: true, @@ -194,8 +194,8 @@ router.post( "auth.delete", auth(), transaction(), - async (ctx: APIContext) => { - const { auth, transaction } = ctx.state; + async (ctx: Context) => { + const { auth, transaction } = ctx; const { user, token } = auth; await user.rotateJwtSecret({ transaction }); diff --git a/server/routes/api/authenticationProviders/authenticationProviders.ts b/server/routes/api/authenticationProviders/authenticationProviders.ts index 34580ecff0..03d6876d66 100644 --- a/server/routes/api/authenticationProviders/authenticationProviders.ts +++ b/server/routes/api/authenticationProviders/authenticationProviders.ts @@ -13,7 +13,7 @@ import { presentAuthenticationProvider, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import * as T from "./schema"; const router = new Router(); @@ -22,9 +22,9 @@ router.post( "authenticationProviders.info", auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk(id); authorize(user, "read", authenticationProvider); @@ -41,10 +41,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersUpdateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, isEnabled, settings } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk(id, { transaction, @@ -102,8 +102,8 @@ router.post( "authenticationProviders.startGroupSync", auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersStartGroupSyncSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk( ctx.input.body.id ); @@ -140,10 +140,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk(id, { transaction, @@ -173,8 +173,8 @@ router.post( router.post( "authenticationProviders.list", auth({ role: UserRole.Admin }), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; authorize(user, "read", user.team); const teamAuthenticationProviders = (await user.team.$get( diff --git a/server/routes/api/batch/batch.ts b/server/routes/api/batch/batch.ts index 555f145cba..95ecb1a386 100644 --- a/server/routes/api/batch/batch.ts +++ b/server/routes/api/batch/batch.ts @@ -14,7 +14,7 @@ import { rateLimiter, } from "@server/middlewares/rateLimiter"; import validate from "@server/middlewares/validate"; -import type { APIContext, AppContext } from "@server/types"; +import type { Context, AppContext } from "@server/types"; import { AuthenticationType } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { BatchableApiMethods } from "@shared/constants"; @@ -115,9 +115,11 @@ function createSubContext( body: T.BatchRequestBody ) { const sub: AppContext = Object.create(ctx); - // A shallow copy so middleware writes (auth, transaction) don't leak between - // concurrent sub-requests or back to the parent. + // Own copies so middleware writes don't leak between concurrent sub-requests + // or back to the parent. sub.state = { ...ctx.state }; + sub.auth = ctx.auth; + sub.transaction = ctx.transaction; sub.request = Object.create(ctx.request); // The parent's credential is the actor for every sub-request, so a token in // the sub-request body must not re-authenticate it as a different one. @@ -153,16 +155,6 @@ function createSubContext( captured.status = value; }, }); - // Re-bind ctx.context to this child so mutations use the child's transaction - // rather than the parent's (the getter from apiContext closes over its ctx). - Object.defineProperty(sub, "context", { - configurable: true, - get: () => ({ - auth: sub.state.auth, - transaction: sub.state.transaction, - ip: sub.request.ip, - }), - }); return { sub, captured }; } @@ -275,7 +267,7 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth({ type: AuthenticationType.APP }), validate(T.BatchSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { requests } = ctx.input.body; // Sub-request routes would otherwise be appended to the APM route name. diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 725060b5a3..240580a155 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -46,7 +46,8 @@ import { presentGroupMembership, presentFileOperation, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext } from "@server/context"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { collectionIndexing } from "@server/utils/indexing"; import { QueryHelper } from "@server/storage/QueryHelper"; @@ -62,8 +63,8 @@ router.post( auth(), validate(T.CollectionsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { name, color, @@ -78,7 +79,7 @@ router.post( templateManagement, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createCollection", user.team); const collection = Collection.build({ @@ -119,10 +120,10 @@ router.post( auth(), validate(T.CollectionsDuplicateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, name } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -147,9 +148,9 @@ router.post( "collections.info", auth(), validate(T.CollectionsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, includeArchivedBy: true, @@ -169,9 +170,9 @@ router.post( "collections.documents", auth(), validate(T.CollectionsDocumentsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, }); @@ -192,10 +193,10 @@ router.post( auth(), validate(T.CollectionsImportSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { attachmentId, permission, format } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "importCollection", user.team); const attachment = await Attachment.findByPk(attachmentId, { @@ -237,10 +238,10 @@ router.post( auth(), validate(T.CollectionsAddGroupSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, groupId, permission } = ctx.input.body; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const [collection, group] = await Promise.all([ Collection.findByPk(id, { userId: user.id, transaction }), @@ -257,7 +258,7 @@ router.post( if (membership) { if (permission !== undefined) { membership.permission = permission; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await GroupMembership.create( @@ -267,7 +268,7 @@ router.post( permission: permission ?? CollectionPermission.ReadWrite, createdById: user.id, }, - ctx.context + toHookContext(ctx) ); } @@ -286,10 +287,10 @@ router.post( auth(), validate(T.CollectionsRemoveGroupSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, groupId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const [collection, group] = await Promise.all([ Collection.findByPk(id, { @@ -314,7 +315,7 @@ router.post( ); } - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); ctx.body = { success: true, @@ -327,9 +328,9 @@ router.post( auth(), pagination(), validate(T.CollectionsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -393,9 +394,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.CollectionsAddUserSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId, permission } = ctx.input.body; const [collection, user] = await Promise.all([ @@ -413,7 +414,7 @@ router.post( if (membership) { if (permission !== undefined) { membership.permission = permission; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await UserMembership.create( @@ -423,7 +424,7 @@ router.post( permission: permission || user.defaultCollectionPermission, createdById: actor.id, }, - ctx.context + toHookContext(ctx) ); } @@ -441,9 +442,9 @@ router.post( auth(), validate(T.CollectionsRemoveUserSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId } = ctx.input.body; const [collection, user] = await Promise.all([ @@ -461,7 +462,7 @@ router.post( ctx.throw(InvalidRequestError("User is not a collection member")); } - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); ctx.body = { success: true, @@ -474,9 +475,9 @@ router.post( auth(), pagination(), validate(T.CollectionsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -536,10 +537,10 @@ router.post( auth({ role: UserRole.Member }), validate(T.CollectionsExportSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, format, includeAttachments } = ctx.input.body; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const { team } = user; const collection = await Collection.findByPk(id, { @@ -570,10 +571,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.CollectionsExportAllSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { format, includeAttachments, includePrivate } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const team = await Team.findByPk(user.teamId, { transaction }); authorize(user, "createExport", team); @@ -598,8 +599,8 @@ router.post( auth(), validate(T.CollectionsUpdateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, name, @@ -621,7 +622,7 @@ router.post( (key) => key === "id" || key === "deprecatedReason" ); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, includeArchivedBy: updatingDeprecatedReason, @@ -723,15 +724,15 @@ router.post( validate(T.CollectionsListSchema), pagination(), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { includeListOnly, query, statusFilter, filters: rawFilters, } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const collectionIds = await user.collectionIds({ transaction }); const where: WhereOptions & { @@ -833,10 +834,10 @@ router.post( auth(), validate(T.CollectionsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, reason } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -862,10 +863,10 @@ router.post( auth(), validate(T.CollectionsArchiveSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, reason } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -893,10 +894,10 @@ router.post( auth(), validate(T.CollectionsRestoreSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let collection = await Collection.findByPk(id, { userId: user.id, @@ -943,10 +944,10 @@ router.post( auth(), validate(T.CollectionsMoveSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, index } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let collection = await Collection.findByPk(id, { transaction, diff --git a/server/routes/api/comments/comments.ts b/server/routes/api/comments/comments.ts index 84041db547..2cd446f0b0 100644 --- a/server/routes/api/comments/comments.ts +++ b/server/routes/api/comments/comments.ts @@ -16,7 +16,8 @@ import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import { TextHelper } from "@server/models/helpers/TextHelper"; import { authorize } from "@server/policies"; import { presentComment, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext } from "@server/context"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -30,7 +31,7 @@ router.post( commentingEnabled(), validate(T.CommentsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, documentId, @@ -40,8 +41,8 @@ router.post( anchorSuffix, anchorNodeId, } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const anchored = !!(anchorText || anchorNodeId); if (anchored) { @@ -109,7 +110,7 @@ router.post( // as updated by adding a comment. await document.update( { state: updated.state, content: updated.content }, - { ...ctx.context, transaction, silent: true } + { ...toHookContext(ctx), transaction, silent: true } ); } @@ -135,9 +136,9 @@ router.post( auth(), commentingEnabled(), validate(T.CommentsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, includeAnchorText } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const comment = await Comment.findByPk(id, { rejectOnEmpty: true, @@ -165,7 +166,7 @@ router.post( pagination(), commentingEnabled(), validate(T.CommentsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, @@ -175,7 +176,7 @@ router.post( collectionId, includeAnchorText, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listComments", user.team); let document: Document | null = null; @@ -221,10 +222,10 @@ router.post( commentingEnabled(), validate(T.CommentsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -297,10 +298,10 @@ router.post( commentingEnabled(), validate(T.CommentsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -331,10 +332,10 @@ router.post( commentingEnabled(), validate(T.CommentsResolveSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -367,10 +368,10 @@ router.post( commentingEnabled(), validate(T.CommentsUnresolveSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -404,10 +405,10 @@ router.post( commentingEnabled(), validate(T.CommentsReactionSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, emoji } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -460,10 +461,10 @@ router.post( commentingEnabled(), validate(T.CommentsReactionSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, emoji } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -488,7 +489,7 @@ router.post( }); authorize(user, "delete", reaction); - await reaction.destroy(ctx.context); + await reaction.destroy(toHookContext(ctx)); ctx.body = { success: true, diff --git a/server/routes/api/cron/cron.ts b/server/routes/api/cron/cron.ts index a4d56b1d91..09dc88652b 100644 --- a/server/routes/api/cron/cron.ts +++ b/server/routes/api/cron/cron.ts @@ -5,7 +5,7 @@ import Logger from "@server/logging/Logger"; import validate from "@server/middlewares/validate"; import tasks from "@server/queues/tasks"; import { CronTask, TaskInterval } from "@server/queues/tasks/base/CronTask"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { safeEqual } from "@server/utils/crypto"; import * as T from "./schema"; import { Minute } from "@shared/utils/time"; @@ -13,7 +13,7 @@ import { Minute } from "@shared/utils/time"; const router = new Router(); const receivedPeriods = new Set(); -const cronHandler = async (ctx: APIContext) => { +const cronHandler = async (ctx: Context) => { const period = Object.values(TaskInterval).includes( ctx.params.period as TaskInterval ) diff --git a/server/routes/api/developer/developer.ts b/server/routes/api/developer/developer.ts index dfa7166dce..655bc28589 100644 --- a/server/routes/api/developer/developer.ts +++ b/server/routes/api/developer/developer.ts @@ -1,4 +1,4 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import Router from "@koa/router"; import { Op } from "sequelize"; import { randomString, randomElement } from "@shared/random"; @@ -12,13 +12,16 @@ import validate from "@server/middlewares/validate"; import { Document, Notification, User } from "@server/models"; import presentNotification from "@server/presenters/notification"; import { presentUser } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context, AppContext } from "@server/types"; import * as T from "./schema"; const router = new Router(); function dev() { - return async function checkDevelopmentMiddleware(ctx: Context, next: Next) { + return async function checkDevelopmentMiddleware( + ctx: AppContext, + next: Next + ) { if (env.ENVIRONMENT !== "development") { throw new Error("Attempted to access development route in production"); } @@ -32,7 +35,7 @@ router.post( dev(), auth(), validate(T.CreateTestUsersSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { count } = ctx.input.body; const invites = Array(Math.min(count, 100)) .fill(0) @@ -69,9 +72,9 @@ router.post( dev(), auth(), validate(T.CreateTestNotificationsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { count } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const events = [ NotificationEventType.UpdateDocument, diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 4ad98e48e7..99d11e0309 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -53,7 +53,7 @@ import { import { getTestServer, readZipResponse, - withAPIContext, + withContext, } from "@server/test/support"; const server = getTestServer(); @@ -210,7 +210,7 @@ describe("#documents.info", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.info", user, { body: { id: document.id, @@ -491,7 +491,7 @@ describe("#documents.info", () => { teamId: document.teamId, userId: user.id, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.info", { body: { shareId: share.id, @@ -690,7 +690,7 @@ describe("#documents.export", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.export", user, { body: { id: document.id, @@ -1044,7 +1044,7 @@ describe("#documents.list", () => { collectionId: collection.id, }), ]); - await withAPIContext(user, (ctx) => docs[0].archiveWithCtx(ctx)); + await withContext(user, (ctx) => docs[0].archiveWithCtx(ctx)); const res = await server.post("/api/documents.list", user, { body: { statusFilter: [StatusFilter.Archived], @@ -1085,8 +1085,8 @@ describe("#documents.list", () => { }), ]); await Promise.all([ - withAPIContext(user, (ctx) => docs[0].archiveWithCtx(ctx)), - withAPIContext(user, (ctx) => docs[1].archiveWithCtx(ctx)), + withContext(user, (ctx) => docs[0].archiveWithCtx(ctx)), + withContext(user, (ctx) => docs[1].archiveWithCtx(ctx)), ]); const res = await server.post("/api/documents.list", user, { body: { @@ -3519,7 +3519,7 @@ describe("#documents.search", () => { text: "search term", teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.search", user, { body: { query: "search term", @@ -3538,7 +3538,7 @@ describe("#documents.search", () => { text: "search term", teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.search", user, { body: { query: "search term", @@ -4652,10 +4652,8 @@ describe("#documents.archived", () => { ]); await Promise.all([ - withAPIContext(user, (ctx) => - documentInFirstCollection.archiveWithCtx(ctx) - ), - withAPIContext(user, (ctx) => + withContext(user, (ctx) => documentInFirstCollection.archiveWithCtx(ctx)), + withContext(user, (ctx) => documentInSecondCollection.archiveWithCtx(ctx) ), ]); @@ -4694,10 +4692,8 @@ describe("#documents.archived", () => { ]); await Promise.all([ - withAPIContext(user, (ctx) => - documentInFirstCollection.archiveWithCtx(ctx) - ), - withAPIContext(user, (ctx) => + withContext(user, (ctx) => documentInFirstCollection.archiveWithCtx(ctx)), + withContext(user, (ctx) => documentInSecondCollection.archiveWithCtx(ctx) ), ]); @@ -4714,7 +4710,7 @@ describe("#documents.archived", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.archived", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4727,7 +4723,7 @@ describe("#documents.archived", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.archived", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4743,7 +4739,7 @@ describe("#documents.archived", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.archived", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4769,7 +4765,7 @@ describe("#documents.deleted", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4797,9 +4793,9 @@ describe("#documents.deleted", () => { collectionId: null, }); await Promise.all([ - withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)), - withAPIContext(user, (ctx) => draftDocument.destroyWithCtx(ctx)), - withAPIContext(user2, (ctx) => otherUserDraft.destroyWithCtx(ctx)), + withContext(user, (ctx) => document.destroyWithCtx(ctx)), + withContext(user, (ctx) => draftDocument.destroyWithCtx(ctx)), + withContext(user2, (ctx) => otherUserDraft.destroyWithCtx(ctx)), ]); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -4816,7 +4812,7 @@ describe("#documents.deleted", () => { userId: admin.id, teamId: admin.teamId, }); - await withAPIContext(admin, (ctx) => document.destroyWithCtx(ctx)); + await withContext(admin, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", admin); const body = await res.json(); expect(res.status).toEqual(200); @@ -4835,7 +4831,7 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4856,8 +4852,8 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); - await withAPIContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user, { body: { @@ -4896,7 +4892,7 @@ describe("#documents.deleted", () => { collectionId: collection.id, parentDocumentId: document.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await childDocument.reload({ paranoid: false }); expect(childDocument.deletedById).toEqual(user.id); @@ -4921,7 +4917,7 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.info", user, { body: { id: document.id }, @@ -4965,7 +4961,7 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await Document.update( { deletedAt: subDays(new Date(), 10) }, { @@ -5014,9 +5010,9 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => ownDraft.destroyWithCtx(ctx)); - await withAPIContext(other, (ctx) => otherDraft.destroyWithCtx(ctx)); - await withAPIContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); + await withContext(user, (ctx) => ownDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => otherDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -5043,7 +5039,7 @@ describe("#documents.deleted", () => { userId: user.id, permission: DocumentPermission.ReadWrite, }); - await withAPIContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -5071,7 +5067,7 @@ describe("#documents.deleted", () => { permission: DocumentPermission.ReadWrite, createdById: other.id, }); - await withAPIContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -5897,7 +5893,7 @@ describe("#documents.restore", () => { collectionId: collection.id, teamId: team.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await collection.destroy({ hooks: false }); const res = await server.post("/api/documents.restore", user, { @@ -5926,7 +5922,7 @@ describe("#documents.restore", () => { collectionId: collection.id, teamId: team.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await collection.destroy({ hooks: false }); const res = await server.post("/api/documents.restore", user, { @@ -5996,7 +5992,7 @@ describe("#documents.restore", () => { teamId: user.teamId, deprecatedReason: "Outdated", }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.restore", user, { body: { id: document.id, @@ -6030,7 +6026,7 @@ describe("#documents.restore", () => { parentDocumentId: child.id, deprecatedReason: "Grandchild is outdated", }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.restore", user, { body: { id: document.id }, }); @@ -6054,8 +6050,8 @@ describe("#documents.restore", () => { collectionId: document.collectionId, parentDocumentId: document.id, }); - await withAPIContext(user, (ctx) => childDocument.archiveWithCtx(ctx)); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => childDocument.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.restore", user, { body: { id: childDocument.id, @@ -7509,7 +7505,7 @@ describe("#documents.update", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.update", user, { body: { id: document.id, @@ -8195,7 +8191,7 @@ describe("#documents.unpublish", () => { teamId: user.teamId, parentDocumentId: document.id, }); - await withAPIContext(user, (ctx) => child.archiveWithCtx(ctx)); + await withContext(user, (ctx) => child.archiveWithCtx(ctx)); const res = await server.post("/api/documents.unpublish", user, { body: { id: document.id, @@ -8254,7 +8250,7 @@ describe("#documents.unpublish", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.unpublish", user, { body: { id: document.id, @@ -8269,7 +8265,7 @@ describe("#documents.unpublish", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.unpublish", user, { body: { id: document.id, diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 117f657a4a..ae10b936e1 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -97,7 +97,8 @@ import { import DocumentImportTask from "@server/queues/tasks/DocumentImportTask"; import EmptyTrashTask from "@server/queues/tasks/EmptyTrashTask"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext } from "@server/context"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { convertBareUrlsToEmbedMarkdown } from "@server/utils/embeds"; import { streamZipResponse } from "@server/utils/koa"; @@ -184,7 +185,7 @@ router.post( auth(), pagination(), validate(T.DocumentsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, @@ -198,7 +199,7 @@ router.post( const { offset, limit } = ctx.state.pagination; // always filter by the current team - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions & { [Op.and]: WhereOptions[]; } = { @@ -459,9 +460,9 @@ router.post( auth({ role: UserRole.Member }), pagination(), validate(T.DocumentsArchivedSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, collectionId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (sort === "index") { throw ValidationError( @@ -516,9 +517,9 @@ router.post( auth({ role: UserRole.Member }), pagination(), validate(T.DocumentsDeletedSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, filters: rawFilters } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collectionIds = await user.collectionIds({ paranoid: false, }); @@ -594,9 +595,9 @@ router.post( auth(), pagination(), validate(T.DocumentsViewedSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const viewIds = await View.findAccessibleIds(user, { sort, direction, @@ -642,9 +643,9 @@ router.post( auth(), pagination(), validate(T.DocumentsDraftsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId, dateFilter, direction, sort } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (collectionId) { const collection = await Collection.findByPk(collectionId, { @@ -698,9 +699,9 @@ router.post( "documents.info", auth({ optional: true }), validate(T.DocumentsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, shareId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const apiVersion = getAPIVersion(ctx); let document: Document | null; @@ -781,9 +782,9 @@ router.post( "documents.insights", auth(), validate(T.DocumentsInsightsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, startDate, endDate } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -820,9 +821,9 @@ router.post( auth(), pagination(), validate(T.DocumentsUsersSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId, query } = ctx.input.body; - const actor = ctx.state.auth.user; + const actor = ctx.auth.user; const document = await Document.findByPk(id, { userId: actor.id, includeContent: false, @@ -905,9 +906,9 @@ router.post( "documents.documents", auth(), validate(T.DocumentsChildrenSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, includeContent: false, @@ -935,9 +936,9 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth(), validate(T.DocumentsExportSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, signedUrls, includeChildDocuments } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const accept = ctx.request.headers["accept"]; const document = await documentLoader({ @@ -1141,10 +1142,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsRestoreSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, collectionId, revisionId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const document = await Document.findByPk(id, { userId: user.id, paranoid: false, @@ -1167,12 +1168,12 @@ router.post( pagination(), rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsSearchTitlesSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { query, sort, direction, filters: rawFilters } = ctx.input.body; const { collectionId, userId, documentId, statusFilter, dateFilter } = ctx.input.body; const { offset, limit } = ctx.state.pagination; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const filter = combineFilters(rawFilters) ?? legacyParamsToFilter({ @@ -1217,7 +1218,7 @@ router.post( pagination(), rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsSearchSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { query, shareId, @@ -1239,7 +1240,7 @@ router.post( dateFilter, }); const { offset, limit } = ctx.state.pagination; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let teamId; let response; @@ -1360,7 +1361,7 @@ router.post( shareId: share?.id, // auth.type values are a subset of search sources; unauthenticated share searches default to "app" source: - (ctx.state.auth.type as unknown as SearchQuerySource) || + (ctx.auth.type as unknown as SearchQuerySource) || SearchQuerySource.App, query, results: total, @@ -1383,10 +1384,10 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.DocumentsTemplatizeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, collectionId, publish } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const original = await Document.findByPk(id, { userId: user.id, @@ -1438,8 +1439,8 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsUpdateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, insightsEnabled, publish, collectionId, ...input } = ctx.input.body; const updatingDeprecatedReason = @@ -1449,7 +1450,7 @@ router.post( ); const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let collection: Collection | null | undefined; let document = await Document.findByPk(id, { @@ -1507,11 +1508,11 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.DocumentsDuplicateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, title, publish, recursive, collectionId, parentDocumentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -1585,11 +1586,11 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsMoveSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, parentDocumentId, index } = ctx.input.body; let collectionId = ctx.input.body.collectionId; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, transaction, @@ -1641,10 +1642,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsArchiveSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, reason } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const document = await Document.findByPk(id, { userId: user.id, @@ -1672,10 +1673,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, permanent, reason } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (permanent) { const document = await Document.findByPk(id, { @@ -1721,9 +1722,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsUnpublishSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, detach } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -1748,10 +1749,10 @@ router.post( optional: true, }), validate(T.DocumentsImportSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId, parentDocumentId, publish, attachmentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (!attachmentId && !ctx.input.file) { throw ValidationError("one of attachmentId or file is required"); @@ -1804,7 +1805,7 @@ router.post( collectionId: collection?.id, parentDocumentId, publish, - authType: ctx.state.auth.type, + authType: ctx.auth.type, ip: ctx.request.ip, }); @@ -1821,7 +1822,7 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.DocumentsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, title, @@ -1839,8 +1840,8 @@ router.post( } = ctx.input.body; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const { collection } = await authorizeDocumentCreate(ctx, { collectionId, @@ -1900,9 +1901,9 @@ router.post( validate(T.DocumentsAddUserSchema), rateLimiter(RateLimiterStrategy.OneHundredPerHour), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId, permission } = ctx.input.body; if (userId === actor.id) { @@ -1955,7 +1956,7 @@ router.post( membership.permission = permission; // disconnect from the source if the permission is manually updated membership.sourceId = null; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await UserMembership.create( @@ -1966,7 +1967,7 @@ router.post( permission: permission || user.defaultDocumentPermission, createdById: actor.id, }, - ctx.context + toHookContext(ctx) ); } @@ -1985,9 +1986,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.DocumentsRemoveUserSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId } = ctx.input.body; const [document, user] = await Promise.all([ @@ -2023,7 +2024,7 @@ router.post( ); } - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); ctx.body = { success: true, @@ -2037,10 +2038,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.DocumentsAddGroupSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, groupId, permission } = ctx.input.body; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const [document, group] = await Promise.all([ Document.findByPk(id, { @@ -2066,7 +2067,7 @@ router.post( membership.permission = permission; // disconnect from the source if the permission is manually updated membership.sourceId = null; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await GroupMembership.create( @@ -2076,7 +2077,7 @@ router.post( permission: permission ?? DocumentPermission.ReadWrite, createdById: user.id, }, - ctx.context + toHookContext(ctx) ); } @@ -2094,9 +2095,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.DocumentsRemoveGroupSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const { id, groupId } = ctx.input.body; const [document, group] = await Promise.all([ @@ -2123,7 +2124,7 @@ router.post( rejectOnEmpty: true, }); - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); ctx.body = { success: true, @@ -2136,9 +2137,9 @@ router.post( auth(), pagination(), validate(T.DocumentsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user: actor } = ctx.state.auth; + const { user: actor } = ctx.auth; const document = await Document.findByPk(id, { userId: actor.id }); authorize(actor, "update", document); @@ -2196,9 +2197,9 @@ router.post( auth(), pagination(), validate(T.DocumentsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id }); authorize(user, "update", document); @@ -2259,8 +2260,8 @@ router.post( "documents.empty_trash", auth({ role: UserRole.Admin }), rateLimiter(RateLimiterStrategy.TenPerHour), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const collectionIds = await user.collectionIds({ paranoid: false, @@ -2305,7 +2306,7 @@ router.post( ); // Remove this helper once apiVersion is removed (#6175) -function getAPIVersion(ctx: APIContext) { +function getAPIVersion(ctx: Context) { return Number( ctx.headers["x-api-version"] ?? (typeof ctx.input.body === "object" && diff --git a/server/routes/api/emojis/emojis.ts b/server/routes/api/emojis/emojis.ts index a91539472f..4e850ba1d8 100644 --- a/server/routes/api/emojis/emojis.ts +++ b/server/routes/api/emojis/emojis.ts @@ -9,7 +9,7 @@ import { Emoji, User, Attachment } from "@server/models"; import BaseStorage from "@server/storage/files/BaseStorage"; import { authorize } from "@server/policies"; import { presentEmoji, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -24,9 +24,9 @@ router.post( "emojis.info", auth(), validate(T.EmojisInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const include = [ { @@ -71,9 +71,9 @@ router.get( "emojis.redirect", auth({ optional: true }), validate(T.EmojisRedirectSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, shareId } = ctx.input.query; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const emoji = await Emoji.unscoped().findByPk(id, { rejectOnEmpty: true, @@ -116,8 +116,8 @@ router.post( auth(), pagination(), validate(T.EmojisListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { query } = ctx.input.body; let where: WhereOptions = { @@ -169,10 +169,10 @@ router.post( auth(), validate(T.EmojisCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { name, attachmentId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; authorize(user, "createEmoji", user.team); const attachment = await Attachment.findByPk(attachmentId, { @@ -207,10 +207,10 @@ router.post( auth(), validate(T.EmojisUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, attachmentId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const emoji = await Emoji.findByPk(id, { transaction, @@ -261,13 +261,13 @@ router.post( auth(), validate(T.EmojisDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const emoji = await Emoji.findByPk(id, { - transaction: ctx.state.transaction, + transaction: ctx.transaction, rejectOnEmpty: true, lock: transaction.LOCK.UPDATE, }); diff --git a/server/routes/api/events/events.ts b/server/routes/api/events/events.ts index 24c611fec3..d8cc1e45af 100644 --- a/server/routes/api/events/events.ts +++ b/server/routes/api/events/events.ts @@ -8,7 +8,7 @@ import validate from "@server/middlewares/validate"; import { Event, User, Collection, Document } from "@server/models"; import { authorize } from "@server/policies"; import { presentEvent } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -19,8 +19,8 @@ router.post( auth(), pagination(), validate(T.EventsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { name, events, diff --git a/server/routes/api/fileOperations/fileOperations.ts b/server/routes/api/fileOperations/fileOperations.ts index a710c609c6..8299780fcd 100644 --- a/server/routes/api/fileOperations/fileOperations.ts +++ b/server/routes/api/fileOperations/fileOperations.ts @@ -9,7 +9,7 @@ import { FileOperation, Team } from "@server/models"; import { authorize } from "@server/policies"; import { presentFileOperation, presentPolicies } from "@server/presenters"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -19,9 +19,9 @@ router.post( "fileOperations.info", auth(), validate(T.FileOperationsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const fileOperation = await FileOperation.findByPk(id, { userId: user.id, @@ -41,9 +41,9 @@ router.post( auth({ role: UserRole.Admin }), pagination(), validate(T.FileOperationsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { direction, sort, type } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions = { teamId: user.teamId, @@ -94,10 +94,10 @@ router.post( ); const handleFileOperationsRedirect = async ( - ctx: APIContext + ctx: Context ) => { const id = (ctx.input.body.id ?? ctx.input.query.id) as string; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const fileOperation = await FileOperation.findByPk(id, { userId: user.id, @@ -128,10 +128,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.FileOperationsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const fileOperation = await FileOperation.unscoped().findByPk(id, { rejectOnEmpty: true, diff --git a/server/routes/api/groupMemberships/groupMemberships.ts b/server/routes/api/groupMemberships/groupMemberships.ts index 4af2d90180..1834979ba5 100644 --- a/server/routes/api/groupMemberships/groupMemberships.ts +++ b/server/routes/api/groupMemberships/groupMemberships.ts @@ -10,7 +10,7 @@ import { presentGroupMembership, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -21,9 +21,9 @@ router.post( auth(), pagination(), validate(T.GroupMembershipsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { groupId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const userId = user.id; // Filtering on the user's groups up front lets the query use the groupId diff --git a/server/routes/api/groups/groups.ts b/server/routes/api/groups/groups.ts index de64b47e1b..8a24e1a0f4 100644 --- a/server/routes/api/groups/groups.ts +++ b/server/routes/api/groups/groups.ts @@ -22,7 +22,7 @@ import { presentPolicies, presentUser, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { QueryHelper } from "@server/storage/QueryHelper"; import pagination from "../middlewares/pagination"; @@ -49,10 +49,10 @@ router.post( auth(), pagination(), validate(T.GroupsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, query, userId, externalId, name, source } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listGroups", user.team); let where: WhereOptions = { @@ -195,9 +195,9 @@ router.post( "groups.info", auth(), validate(T.GroupsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, externalId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const include = [ { @@ -235,10 +235,10 @@ router.post( auth(), validate(T.GroupsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { name, description, icon, color, externalId, disableMentions } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createGroup", user.team); const group = await Group.createWithCtx(ctx, { @@ -267,10 +267,10 @@ router.post( auth(), validate(T.GroupsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const group = await Group.findByPk(id, { transaction, @@ -325,10 +325,10 @@ router.post( auth(), validate(T.GroupsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const group = await Group.findByPk(id, { transaction, @@ -353,10 +353,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.GroupsDeleteAllSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { authenticationProviderId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const authenticationProvider = await AuthenticationProvider.findByPk( authenticationProviderId, @@ -401,9 +401,9 @@ router.post( auth(), pagination(), validate(T.GroupsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const group = await Group.findByPk(id); authorize(user, "read", group); @@ -470,10 +470,10 @@ router.post( auth(), validate(T.GroupsAddUserSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId, permission } = ctx.input.body; - const actor = ctx.state.auth.user; - const { transaction } = ctx.state; + const actor = ctx.auth.user; + const { transaction } = ctx; const user = await User.findByPk(userId, { transaction, @@ -549,10 +549,10 @@ router.post( auth(), validate(T.GroupsRemoveUserSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId } = ctx.input.body; - const actor = ctx.state.auth.user; - const { transaction } = ctx.state; + const actor = ctx.auth.user; + const { transaction } = ctx; const group = await Group.findByPk(id, { transaction, @@ -606,10 +606,10 @@ router.post( auth(), validate(T.GroupsUpdateUserSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId, permission } = ctx.input.body; - const actor = ctx.state.auth.user; - const { transaction } = ctx.state; + const actor = ctx.auth.user; + const { transaction } = ctx; // Load group with group users for authorization const group = await Group.findByPk(id, { diff --git a/server/routes/api/imports/imports.ts b/server/routes/api/imports/imports.ts index 0d674f6481..80fecfdae0 100644 --- a/server/routes/api/imports/imports.ts +++ b/server/routes/api/imports/imports.ts @@ -13,7 +13,7 @@ import { Attachment, Collection, Document, Integration } from "@server/models"; import Import from "@server/models/Import"; import { authorize } from "@server/policies"; import { presentImport, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -25,14 +25,14 @@ const router = new Router(); * is chosen the user must be able to create documents in it; when a document * is chosen the user must be able to add children to it. * - * @param ctx The API context for the create request. + * @param ctx The context for the create request. * @returns The resolved destination ids (both null when no destination set). */ async function resolveImportDestination( - ctx: APIContext + ctx: Context ): Promise<{ collectionId: string | null; documentId: string | null }> { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const { collectionId, documentId } = ctx.input.body; if (collectionId) { @@ -65,9 +65,9 @@ router.post( auth({ role: UserRole.Admin }), validate(T.ImportsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const body = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createImport", user.team); @@ -141,9 +141,9 @@ router.post( auth({ role: UserRole.Admin }), pagination(), validate(T.ImportsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { service, sort, direction } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listImports", user.team); @@ -180,9 +180,9 @@ router.post( "imports.info", auth({ role: UserRole.Admin }), validate(T.ImportsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const importModel = await Import.findByPk(id, { rejectOnEmpty: true, @@ -201,10 +201,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.ImportsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const importModel = await Import.findByPk(id, { rejectOnEmpty: true, @@ -226,10 +226,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.ImportsCancelSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; let importModel = await Import.findByPk(id, { rejectOnEmpty: true, diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index 7ab2c17b25..04edb3e2f0 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -3,7 +3,6 @@ import bodyParser from "koa-body"; import Router from "@koa/router"; import env from "@server/env"; import { NotFoundError } from "@server/errors"; -import { apiContext } from "@server/middlewares/apiContext"; import cleanupMultipartFiles from "@server/middlewares/cleanupMultipartFiles"; import coalesceBody from "@server/middlewares/coaleseBody"; import requestContextMiddleware from "@server/middlewares/requestContext"; @@ -78,7 +77,6 @@ api.use(requestTracer()); api.use(apiResponse()); api.use(apiErrorHandler()); api.use(editor()); -api.use(apiContext()); api.use(verifyCSRFToken()); // Register plugin API routes before others to allow for overrides diff --git a/server/routes/api/installation/installation.ts b/server/routes/api/installation/installation.ts index e6c3bcaa38..9d23a64277 100644 --- a/server/routes/api/installation/installation.ts +++ b/server/routes/api/installation/installation.ts @@ -6,7 +6,7 @@ import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; import { Team, User } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { signIn } from "@server/utils/authentication"; import { getVersion, getVersionInfo } from "@server/utils/getInstallationInfo"; import * as T from "./schema"; @@ -18,9 +18,9 @@ router.post( "installation.create", validate(T.InstallationCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { teamName, userName, userEmail } = ctx.input.body; - const { transaction } = ctx.state; + const { transaction } = ctx; // Check that this can only be called when there are no existing teams const existingTeamCount = await Team.count({ transaction }); @@ -51,7 +51,7 @@ router.post( } ); -router.post("installation.info", auth(), async (ctx: APIContext) => { +router.post("installation.info", auth(), async (ctx: Context) => { const currentVersion = getVersion(); const { latestVersion, versionsBehind } = await getVersionInfo(currentVersion); diff --git a/server/routes/api/integrations/integrations.ts b/server/routes/api/integrations/integrations.ts index b31b0038a7..6a4642ef81 100644 --- a/server/routes/api/integrations/integrations.ts +++ b/server/routes/api/integrations/integrations.ts @@ -9,7 +9,7 @@ import validate from "@server/middlewares/validate"; import Integration from "@server/models/Integration"; import { authorize } from "@server/policies"; import { presentIntegration, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -21,9 +21,9 @@ router.post( auth(), pagination(), validate(T.IntegrationsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { direction, service, type, sort } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let where: WhereOptions = { teamId: user.teamId, @@ -77,9 +77,9 @@ router.post( auth({ role: UserRole.Admin }), validate(T.IntegrationsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { type, service, settings } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createIntegration", user.team); @@ -102,9 +102,9 @@ router.post( "integrations.info", auth(), validate(T.IntegrationsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const integration = await Integration.findByPk(id, { rejectOnEmpty: true, @@ -123,10 +123,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.IntegrationsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, events, settings } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const integration = await Integration.findByPk(id, { transaction, @@ -158,10 +158,10 @@ router.post( auth(), validate(T.IntegrationsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const integration = await Integration.findByPk(id, { rejectOnEmpty: true, diff --git a/server/routes/api/middlewares/apiErrorHandler.test.ts b/server/routes/api/middlewares/apiErrorHandler.test.ts index e1df1d7b16..687a4a2bf7 100644 --- a/server/routes/api/middlewares/apiErrorHandler.test.ts +++ b/server/routes/api/middlewares/apiErrorHandler.test.ts @@ -1,7 +1,7 @@ import httpErrors from "http-errors"; -import type { Context } from "koa"; import { AuthenticationError } from "@server/errors"; import apiErrorHandler from "./apiErrorHandler"; +import type { AppContext } from "@server/types"; const createContext = (challenge?: string) => { const headers: Record = {}; @@ -12,10 +12,10 @@ const createContext = (challenge?: string) => { response: { get: (field: string) => headers[field.toLowerCase()] ?? "", }, - } as unknown as Context; + } as unknown as AppContext; }; -const runWithError = async (ctx: Context) => { +const runWithError = async (ctx: AppContext) => { try { await apiErrorHandler()(ctx, () => Promise.reject(AuthenticationError())); } catch (err) { diff --git a/server/routes/api/middlewares/apiErrorHandler.ts b/server/routes/api/middlewares/apiErrorHandler.ts index 0b99206c49..1d78477dfa 100644 --- a/server/routes/api/middlewares/apiErrorHandler.ts +++ b/server/routes/api/middlewares/apiErrorHandler.ts @@ -1,5 +1,5 @@ import httpErrors from "http-errors"; -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import { ValidationError as SequelizeValidationError, EmptyResultError as SequelizeEmptyResultError, @@ -19,6 +19,7 @@ import { isDatabaseUnavailableError, isQueryCanceledError, } from "@server/storage/database"; +import type { AppContext } from "@server/types"; /** Postgres codes for a requested date the database cannot represent. */ const DATE_RANGE_ERROR_CODES = new Set(["22008", "22015"]); @@ -38,7 +39,7 @@ function sqlStateOf(err: SequelizeDatabaseError): string | undefined { } export default function apiErrorHandler() { - return async function apiErrorHandlerMiddleware(ctx: Context, next: Next) { + return async function apiErrorHandlerMiddleware(ctx: AppContext, next: Next) { try { await next(); } catch (err) { diff --git a/server/routes/api/middlewares/apiResponse.ts b/server/routes/api/middlewares/apiResponse.ts index afcc0a0c07..7d54cf4e8d 100644 --- a/server/routes/api/middlewares/apiResponse.ts +++ b/server/routes/api/middlewares/apiResponse.ts @@ -1,9 +1,10 @@ import stream from "node:stream"; -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import { Readable } from "readable-stream"; +import type { AppContext } from "@server/types"; export default function apiResponse() { - return async function apiResponseMiddleware(ctx: Context, next: Next) { + return async function apiResponseMiddleware(ctx: AppContext, next: Next) { await next(); const ok = ctx.status < 400; diff --git a/server/routes/api/middlewares/editor.ts b/server/routes/api/middlewares/editor.ts index 389817b0be..f4c07a1511 100644 --- a/server/routes/api/middlewares/editor.ts +++ b/server/routes/api/middlewares/editor.ts @@ -1,7 +1,8 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import semver from "semver"; import EDITOR_VERSION from "@shared/editor/version"; import { EditorUpdateError } from "@server/errors"; +import type { AppContext } from "@server/types"; export default function editor() { /** @@ -9,7 +10,7 @@ export default function editor() { * version. See the equivalent logic for collab server in: * /server/collaboration/EditorVersionExtension.ts */ - return async function editorMiddleware(ctx: Context, next: Next) { + return async function editorMiddleware(ctx: AppContext, next: Next) { const clientVersion = ctx.headers["x-editor-version"]; if (clientVersion) { diff --git a/server/routes/api/notifications/notifications.ts b/server/routes/api/notifications/notifications.ts index af56d48591..7ca72e5a8b 100644 --- a/server/routes/api/notifications/notifications.ts +++ b/server/routes/api/notifications/notifications.ts @@ -14,7 +14,7 @@ import NotificationSettingsHelper from "@server/models/helpers/NotificationSetti import { authorize } from "@server/policies"; import { presentPolicies } from "@server/presenters"; import presentNotification from "@server/presenters/notification"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { safeEqual } from "@server/utils/crypto"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -31,8 +31,8 @@ const pixel = Buffer.from( * @param ctx The request context. * @returns The updated user, or undefined if the token is not valid. */ -const unsubscribe = async (ctx: APIContext) => { - const { transaction } = ctx.state; +const unsubscribe = async (ctx: Context) => { + const { transaction } = ctx; const eventType = (ctx.input.body.eventType ?? ctx.input.query.eventType) as NotificationEventType; const userId = (ctx.input.body.userId ?? ctx.input.query.userId) as string; @@ -62,7 +62,7 @@ router.get( "notifications.unsubscribe", validate(T.NotificationsUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { follow } = ctx.input.query; // The link in the email does not include the follow query param, this @@ -86,7 +86,7 @@ router.post( "notifications.unsubscribe", validate(T.NotificationsUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const user = await unsubscribe(ctx); if (!user) { throw AuthenticationError("Invalid unsubscribe token"); @@ -103,9 +103,9 @@ router.post( auth(), pagination(), validate(T.NotificationsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { eventType, archived } = ctx.input.body; - const user = ctx.state.auth.user; + const user = ctx.auth.user; let where: WhereOptions = { teamId: user.teamId, userId: user.id, @@ -163,9 +163,9 @@ router.get( "notifications.pixel", validate(T.NotificationsPixelSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, token } = ctx.input.query; - const { transaction } = ctx.state; + const { transaction } = ctx; const notification = await Notification.unscoped().findByPk(id, { lock: transaction.LOCK.UPDATE, @@ -203,10 +203,10 @@ router.post( auth(), validate(T.NotificationsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, viewedAt, archivedAt } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const notification = await Notification.findByPk(id, { lock: { @@ -233,10 +233,10 @@ router.post( auth(), validate(T.NotificationsUpdateAllSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { viewedAt, archivedAt } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const values: Partial = {}; let where: WhereOptions = { diff --git a/server/routes/api/oauthAuthentications/oauthAuthentications.ts b/server/routes/api/oauthAuthentications/oauthAuthentications.ts index 56a5dfb263..f54f04ba27 100644 --- a/server/routes/api/oauthAuthentications/oauthAuthentications.ts +++ b/server/routes/api/oauthAuthentications/oauthAuthentications.ts @@ -9,7 +9,7 @@ import { authorize } from "@server/policies"; import { presentPolicies } from "@server/presenters"; import presentOAuthAuthentication from "@server/presenters/oauthAuthentication"; import { sequelize } from "@server/storage/database"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -21,8 +21,8 @@ router.post( auth(), pagination(), validate(T.OAuthAuthenticationsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const oauthAuthentications = await sequelize.query( ` @@ -64,8 +64,8 @@ router.post( auth(), validate(T.OAuthAuthenticationsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { oauthClientId, scope } = ctx.input.body; const where = { userId: user.id, @@ -75,7 +75,7 @@ router.post( const oauthAuthentications = await OAuthAuthentication.findAll({ where, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); for (const oauthAuthentication of oauthAuthentications) { diff --git a/server/routes/api/oauthClients/oauthClients.ts b/server/routes/api/oauthClients/oauthClients.ts index 1e78cf8aac..9d38f0dd48 100644 --- a/server/routes/api/oauthClients/oauthClients.ts +++ b/server/routes/api/oauthClients/oauthClients.ts @@ -14,7 +14,7 @@ import { presentOAuthClient, presentPublishedOAuthClient, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { ClientMetadataHelper } from "@server/utils/oauth/ClientMetadataHelper"; import { OAuthHelper } from "@server/utils/oauth/OAuthHelper"; @@ -31,10 +31,10 @@ const router = new Router(); * @param ctx The request context. * @returns true if the credential's scope covers managing clients. */ -function hasManageScope(ctx: APIContext) { +function hasManageScope(ctx: Context) { return AuthenticationHelper.canAccess( "/api/oauthClients.update", - ctx.state.auth.scope ?? ["*"] + ctx.auth.scope ?? ["*"] ); } @@ -43,8 +43,8 @@ router.post( auth({ role: UserRole.Admin }), pagination(), validate(T.OAuthClientsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const where = { teamId: user.teamId, createdById: { @@ -81,9 +81,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), auth(), validate(T.OAuthClientsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, clientId, redirectUri } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const oauthClient = clientId ? await ClientMetadataHelper.findOrFetchByClientId(clientId, user.team) @@ -123,9 +123,9 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const input = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createOAuthClient", user.team); @@ -147,10 +147,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, ...input } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const oauthClient = await OAuthClient.findByPk(id, { transaction, @@ -176,10 +176,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsRotateSecretSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const oauthClient = await OAuthClient.findByPk(id, { transaction, @@ -205,10 +205,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body as { id: string }; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const oauthClient = await OAuthClient.findByPk(id, { transaction, diff --git a/server/routes/api/pins/pins.ts b/server/routes/api/pins/pins.ts index 283397539c..cf8cdb02ee 100644 --- a/server/routes/api/pins/pins.ts +++ b/server/routes/api/pins/pins.ts @@ -12,7 +12,7 @@ import { presentDocuments, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -25,10 +25,10 @@ router.post( auth(), validate(T.PinsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { documentId, collectionId, index } = 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, transaction, @@ -65,8 +65,8 @@ router.post( "pins.info", auth(), validate(T.PinsInfoSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { documentId, collectionId } = ctx.input.body; const document = await Document.findByPk(documentId, { @@ -102,9 +102,9 @@ router.post( auth(), validate(T.PinsListSchema), pagination(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (collectionId) { const collection = await Collection.findByPk(collectionId, { @@ -161,10 +161,10 @@ router.post( auth(), validate(T.PinsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, index } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const pin = await Pin.findByPk(id, { transaction, lock: Transaction.LOCK.UPDATE, @@ -196,11 +196,11 @@ router.post( auth(), validate(T.PinsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { transaction } = ctx.state; + const { transaction } = ctx; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const pin = await Pin.findByPk(id, { transaction, lock: Transaction.LOCK.UPDATE, diff --git a/server/routes/api/reactions/reactions.ts b/server/routes/api/reactions/reactions.ts index 755cf08da7..891f420ccc 100644 --- a/server/routes/api/reactions/reactions.ts +++ b/server/routes/api/reactions/reactions.ts @@ -5,7 +5,7 @@ import validate from "@server/middlewares/validate"; import { Comment, Document, Reaction, User } from "@server/models"; import { authorize } from "@server/policies"; import { presentReaction } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -16,9 +16,9 @@ router.post( auth(), pagination(), validate(T.ReactionsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { commentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const comment = await Comment.findByPk(commentId, { rejectOnEmpty: true, diff --git a/server/routes/api/relationships/relationships.ts b/server/routes/api/relationships/relationships.ts index 121bb7b9f4..b1d82fd0e2 100644 --- a/server/routes/api/relationships/relationships.ts +++ b/server/routes/api/relationships/relationships.ts @@ -9,7 +9,7 @@ import { presentDocuments, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -19,9 +19,9 @@ router.post( "relationships.info", auth(), validate(T.RelationshipsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const relationship = await Relationship.findByPk(id, { rejectOnEmpty: true, @@ -58,9 +58,9 @@ router.post( auth(), pagination(), validate(T.RelationshipsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { type, documentId, reverseDocumentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; // Results are anchored to a single document, which the user must be able to // read. Documents on the opposite side of each relationship are filtered by diff --git a/server/routes/api/revisions/revisions.ts b/server/routes/api/revisions/revisions.ts index 86b6912bb6..4795ff284f 100644 --- a/server/routes/api/revisions/revisions.ts +++ b/server/routes/api/revisions/revisions.ts @@ -18,7 +18,7 @@ import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import TextBundleHelper from "@server/models/helpers/TextBundleHelper"; import { authorize } from "@server/policies"; import { presentPolicies, presentRevision } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { streamZipResponse } from "@server/utils/koa"; import pagination from "../middlewares/pagination"; @@ -30,9 +30,9 @@ router.post( "revisions.info", auth(), validate(T.RevisionsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, documentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let revision: Revision; if (id) { @@ -71,9 +71,9 @@ router.post( "revisions.update", auth(), validate(T.RevisionsUpdateSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const revision = await Revision.findByPk(id, { rejectOnEmpty: true, @@ -101,10 +101,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.RevisionsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const revision = await Revision.findByPk(id, { rejectOnEmpty: true, @@ -135,9 +135,9 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth(), validate(T.RevisionsExportSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const accept = ctx.request.headers["accept"]; const revision = await Revision.findByPk(id, { @@ -280,9 +280,9 @@ router.post( auth(), pagination(), validate(T.RevisionsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { direction, documentId, sort } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(documentId, { userId: user.id, diff --git a/server/routes/api/searches/searches.ts b/server/routes/api/searches/searches.ts index 35200caa54..dd4a2f7c0a 100644 --- a/server/routes/api/searches/searches.ts +++ b/server/routes/api/searches/searches.ts @@ -4,7 +4,7 @@ import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; import { SearchQuery } from "@server/models"; import { presentSearchQuery } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -15,8 +15,8 @@ router.post( auth(), validate(T.SearchesListSchema), pagination(), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const source = ctx.input.body?.source; const searches = await SearchQuery.findAll({ @@ -42,10 +42,10 @@ router.post( auth(), validate(T.SearchesUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, score } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const search = await SearchQuery.findOne({ where: { @@ -70,9 +70,9 @@ router.post( "searches.delete", auth(), validate(T.SearchesDeleteSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; await SearchQuery.destroy({ where: { diff --git a/server/routes/api/shares/shares.test.ts b/server/routes/api/shares/shares.test.ts index a223e655aa..6b6051bbea 100644 --- a/server/routes/api/shares/shares.test.ts +++ b/server/routes/api/shares/shares.test.ts @@ -17,7 +17,7 @@ import { buildTeam, } from "@server/test/factories"; -import { getTestServer, withAPIContext } from "@server/test/support"; +import { getTestServer, withContext } from "@server/test/support"; const server = getTestServer(); @@ -174,7 +174,7 @@ describe("#shares.list", () => { teamId: user.teamId, userId: user.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/shares.list", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -1546,7 +1546,7 @@ describe("#shares.revoke", () => { teamId: user.teamId, userId: user.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/shares.revoke", user, { body: { id: share.id, diff --git a/server/routes/api/shares/shares.ts b/server/routes/api/shares/shares.ts index ccb3bd8da3..4b5cfc43ad 100644 --- a/server/routes/api/shares/shares.ts +++ b/server/routes/api/shares/shares.ts @@ -31,7 +31,7 @@ import { presentCollection, presentDocument, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { getTeamFromContext } from "@server/utils/passport"; import { QueryHelper } from "@server/storage/QueryHelper"; @@ -52,9 +52,9 @@ router.post( "shares.info", auth({ optional: true }), validate(T.SharesInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, collectionId, documentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; // only public link loads will send "id". if (id) { @@ -160,9 +160,9 @@ router.post( auth(), pagination(), validate(T.SharesListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, query } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listShares", user.team); const collectionIds = await user.collectionIds(); @@ -261,7 +261,7 @@ router.post( auth(), validate(T.SharesCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId, documentId, @@ -274,7 +274,7 @@ router.post( showTOC, expiresAt, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createShare", user.team); const collection = collectionId @@ -350,7 +350,7 @@ router.post( auth(), validate(T.SharesUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, includeChildDocuments, @@ -365,7 +365,7 @@ router.post( iconUrl, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "share", user.team); // fetch the share with document and collection. @@ -407,9 +407,9 @@ router.post( auth(), validate(T.SharesRevokeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const share = await Share.scope({ method: ["withCollectionPermissions", user.id], }).findByPk(id); @@ -433,7 +433,7 @@ router.get( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), shareDomains(), validate(T.SharesSitemapSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.query; const team = await getTeamFromContext(ctx, { includeOAuthState: false }); @@ -461,13 +461,13 @@ router.post( rateLimiter(RateLimiterStrategy.TenPerHour), validate(T.SharesSubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { if (!env.EMAIL_ENABLED) { throw InvalidRequestError("Email is not configured"); } const { shareId, documentId, email } = ctx.input.body; - const { transaction } = ctx.state; + const { transaction } = ctx; const team = await getTeamFromContext(ctx, { includeOAuthState: false }); // Validate the share exists and is published @@ -551,9 +551,9 @@ router.get( rateLimiter(RateLimiterStrategy.TenPerMinute), validate(T.SharesConfirmSubscriptionSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, token, follow } = ctx.input.query; - const { transaction } = ctx.state; + const { transaction } = ctx; // Anti-prefetch: prevent email clients from pre-fetching the link if (!follow) { @@ -615,9 +615,9 @@ router.get( * @param ctx The request context. * @returns The updated subscription, or undefined if the token is not valid. */ -const unsubscribeShare = async (ctx: APIContext) => { +const unsubscribeShare = async (ctx: Context) => { const { id, token } = ctx.input.query; - const { transaction } = ctx.state; + const { transaction } = ctx; const subscription = await ShareSubscription.findByPk(id, { transaction, @@ -644,7 +644,7 @@ router.get( "shares.unsubscribe", validate(T.SharesUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { follow } = ctx.input.query; // Anti-prefetch: prevent email clients from pre-fetching the link @@ -669,7 +669,7 @@ router.post( "shares.unsubscribe", validate(T.SharesUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const subscription = await unsubscribeShare(ctx); if (!subscription) { throw AuthenticationError("Invalid unsubscribe token"); diff --git a/server/routes/api/stars/stars.ts b/server/routes/api/stars/stars.ts index 5b9dfcb378..96874aecf7 100644 --- a/server/routes/api/stars/stars.ts +++ b/server/routes/api/stars/stars.ts @@ -12,7 +12,7 @@ import { presentDocuments, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { starIndexing } from "@server/utils/indexing"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; @@ -26,10 +26,10 @@ router.post( auth(), validate(T.StarsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { documentId, collectionId, index } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (documentId) { const document = await Document.findByPk(documentId, { @@ -67,8 +67,8 @@ router.post( auth(), pagination(), validate(T.StarsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const [stars, collectionIds] = await Promise.all([ Star.findAll({ @@ -124,10 +124,10 @@ router.post( auth(), validate(T.StarsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, index } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const star = await Star.findByPk(id, { transaction, @@ -149,10 +149,10 @@ router.post( auth(), validate(T.StarsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const star = await Star.findByPk(id, { transaction, diff --git a/server/routes/api/subscriptions/subscriptions.ts b/server/routes/api/subscriptions/subscriptions.ts index 012191adee..2c9497b96b 100644 --- a/server/routes/api/subscriptions/subscriptions.ts +++ b/server/routes/api/subscriptions/subscriptions.ts @@ -13,7 +13,7 @@ import { Subscription, Document, User, Collection } from "@server/models"; import SubscriptionHelper from "@server/models/helpers/SubscriptionHelper"; import { authorize } from "@server/policies"; import { presentSubscription } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { safeEqual } from "@server/utils/crypto"; import pagination from "../middlewares/pagination"; @@ -26,8 +26,8 @@ router.post( auth(), pagination(), validate(T.SubscriptionsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { event, collectionId, documentId } = ctx.input.body; const where: WhereOptions = { @@ -38,7 +38,7 @@ router.post( if (collectionId) { const collection = await Collection.findByPk(collectionId, { userId: user.id, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); authorize(user, "read", collection); @@ -72,8 +72,8 @@ router.post( "subscriptions.info", auth(), validate(T.SubscriptionsInfoSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { event, collectionId, documentId } = ctx.input.body; const where: WhereOptions = { @@ -121,8 +121,8 @@ router.post( auth(), validate(T.SubscriptionsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { event, collectionId, documentId } = ctx.input.body; if (documentId) { @@ -159,8 +159,8 @@ router.get( validate(T.SubscriptionsDeleteTokenSchema), rateLimiter(RateLimiterStrategy.FivePerMinute), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { follow, userId, documentId, token } = ctx.input.query; // The link in the email does not include the follow query param, this @@ -237,9 +237,9 @@ router.post( auth(), validate(T.SubscriptionsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const { id } = ctx.input.body; const subscription = await Subscription.findByPk(id, { diff --git a/server/routes/api/suggestions/suggestions.ts b/server/routes/api/suggestions/suggestions.ts index ed674ee9ed..8d57b947da 100644 --- a/server/routes/api/suggestions/suggestions.ts +++ b/server/routes/api/suggestions/suggestions.ts @@ -19,7 +19,7 @@ import { presentGroup, presentUser, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -33,10 +33,10 @@ router.post( auth(), pagination(), validate(T.SuggestionsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { query } = ctx.input.body; const { offset, limit } = ctx.state.pagination; - const actor = ctx.state.auth.user; + const actor = ctx.auth.user; const suggestUsers = async (): Promise<{ users: User[]; diff --git a/server/routes/api/teams/teams.ts b/server/routes/api/teams/teams.ts index 6746a617ff..e4de6424c3 100644 --- a/server/routes/api/teams/teams.ts +++ b/server/routes/api/teams/teams.ts @@ -12,16 +12,16 @@ import validate from "@server/middlewares/validate"; import { Team, TeamDomain, User } from "@server/models"; import { authorize } from "@server/policies"; import { presentTeam, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { safeEqual } from "@server/utils/crypto"; import * as T from "./schema"; const router = new Router(); -const handleTeamUpdate = async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; +const handleTeamUpdate = async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const team = await Team.findByPk(user.teamId, { include: [{ model: TeamDomain, separate: true }], lock: transaction.LOCK.NO_KEY_UPDATE, @@ -63,12 +63,12 @@ router.post( "teams.requestDelete", rateLimiter(RateLimiterStrategy.FivePerHour), auth(), - async (ctx: APIContext) => { + async (ctx: Context) => { if (!env.EMAIL_ENABLED) { throw ValidationError("Email support is not set up for this instance"); } - const { user } = ctx.state.auth; + const { user } = ctx.auth; const { team } = user; authorize(user, "delete", team); @@ -90,8 +90,8 @@ router.post( auth(), validate(T.TeamsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { auth } = ctx.state; + async (ctx: Context) => { + const { auth } = ctx; const { code } = ctx.input.body; const { user } = auth; const { team } = user; @@ -120,9 +120,9 @@ router.post( auth(), validate(T.TeamsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const { name } = ctx.input.body; const existingTeam = await Team.scope( diff --git a/server/routes/api/templates/templates.ts b/server/routes/api/templates/templates.ts index 47c5619cea..dfbd191e0c 100644 --- a/server/routes/api/templates/templates.ts +++ b/server/routes/api/templates/templates.ts @@ -10,7 +10,7 @@ import validate from "@server/middlewares/validate"; import { Collection, Template } from "@server/models"; import { authorize } from "@server/policies"; import { presentPolicies, presentTemplate } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { QueryHelper } from "@server/storage/QueryHelper"; import pagination from "../middlewares/pagination"; @@ -24,13 +24,13 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.TemplatesCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, title, data, icon, color, collectionId, publish } = ctx.input.body; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; if (publish && (!data || ProsemirrorDataHelper.isEmpty(data))) { throw ValidationError("A published template must have content"); @@ -79,9 +79,9 @@ router.post( auth(), pagination(), validate(T.TemplatesListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, collectionId, query } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions