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

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

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

* chore: Remove deprecated APIContext alias

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

* fix: Read auth from context in OAuth provider callbacks

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

* chore: Add withUser and withTransaction context helpers

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

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

* chore: Remove arbitrary property access from Koa context types

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

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

---------

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

283 lines
7.5 KiB
TypeScript

import Router from "@koa/router";
import { isEmpty, isNil, isNull, isUndefined } from "es-toolkit/compat";
import type { WhereOptions } from "sequelize";
import { Op } from "sequelize";
import type { NotificationEventType } from "@shared/types";
import { createContext } from "@server/context";
import env from "@server/env";
import { AuthenticationError } from "@server/errors";
import auth from "@server/middlewares/authentication";
import { transaction } from "@server/middlewares/transaction";
import validate from "@server/middlewares/validate";
import { Notification, User } from "@server/models";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import { authorize } from "@server/policies";
import { presentPolicies } from "@server/presenters";
import presentNotification from "@server/presenters/notification";
import type { Context } from "@server/types";
import { safeEqual } from "@server/utils/crypto";
import pagination from "../middlewares/pagination";
import * as T from "./schema";
const router = new Router();
const pixel = Buffer.from(
"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
"base64"
);
/**
* Turns off the event type for the user in the request, if the token is valid.
*
* @param ctx The request context.
* @returns The updated user, or undefined if the token is not valid.
*/
const unsubscribe = async (ctx: Context<T.NotificationsUnsubscribeReq>) => {
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;
const token = (ctx.input.body.token ?? ctx.input.query.token) as string;
const unsubscribeToken = NotificationSettingsHelper.unsubscribeToken(
userId,
eventType
);
if (!safeEqual(unsubscribeToken, token)) {
return;
}
const user = await User.scope("withTeam").findByPk(userId, {
rejectOnEmpty: true,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: User },
transaction,
});
user.setNotificationEventType(eventType, false);
await user.save({ transaction });
return user;
};
router.get(
"notifications.unsubscribe",
validate(T.NotificationsUnsubscribeSchema),
transaction(),
async (ctx: Context<T.NotificationsUnsubscribeReq>) => {
const { follow } = ctx.input.query;
// The link in the email does not include the follow query param, this
// is to help prevent anti-virus, and email clients from pre-fetching the link
if (!follow) {
return ctx.redirectOnClient(ctx.request.href + "&follow=true");
}
const user = await unsubscribe(ctx);
if (!user) {
ctx.redirect(`${env.URL}?notice=invalid-auth`);
return;
}
ctx.redirect(`${user.team.url}/settings/notifications?success`);
}
);
// Supports RFC 8058 one-click unsubscribe from the List-Unsubscribe header.
router.post(
"notifications.unsubscribe",
validate(T.NotificationsUnsubscribeSchema),
transaction(),
async (ctx: Context<T.NotificationsUnsubscribeReq>) => {
const user = await unsubscribe(ctx);
if (!user) {
throw AuthenticationError("Invalid unsubscribe token");
}
ctx.body = {
success: true,
};
}
);
router.post(
"notifications.list",
auth(),
pagination(),
validate(T.NotificationsListSchema),
async (ctx: Context<T.NotificationsListReq>) => {
const { eventType, archived } = ctx.input.body;
const user = ctx.auth.user;
let where: WhereOptions<Notification> = {
teamId: user.teamId,
userId: user.id,
};
if (eventType) {
where = { ...where, event: eventType };
}
if (!isNil(archived)) {
where = {
...where,
archivedAt: archived
? {
[Op.ne]: null,
}
: {
[Op.eq]: null,
},
};
}
const [notifications, total, unseen] = await Promise.all([
Notification.findAll({
where,
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
Notification.unscoped().count({
where,
}),
Notification.unscoped().count({
where: {
...where,
viewedAt: {
[Op.is]: null,
},
},
}),
]);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: {
notifications: await Promise.all(
notifications.map((notification) =>
presentNotification(ctx, notification)
)
),
unseen,
},
};
}
);
router.get(
"notifications.pixel",
validate(T.NotificationsPixelSchema),
transaction(),
async (ctx: Context<T.NotificationsPixelReq>) => {
const { id, token } = ctx.input.query;
const { transaction } = ctx;
const notification = await Notification.unscoped().findByPk(id, {
lock: transaction.LOCK.UPDATE,
transaction,
rejectOnEmpty: true,
});
if (!safeEqual(token, notification.pixelToken)) {
throw AuthenticationError();
}
if (!notification.viewedAt) {
const user = await notification.$get("user");
if (user) {
await notification.updateWithCtx(
createContext({
ip: ctx.request.ip,
transaction,
user,
}),
{
viewedAt: new Date(),
}
);
}
}
ctx.response.set("Content-Type", "image/gif");
ctx.body = pixel;
}
);
router.post(
"notifications.update",
auth(),
validate(T.NotificationsUpdateSchema),
transaction(),
async (ctx: Context<T.NotificationsUpdateReq>) => {
const { id, viewedAt, archivedAt } = ctx.input.body;
const { user } = ctx.auth;
const { transaction } = ctx;
const notification = await Notification.findByPk(id, {
lock: {
level: transaction.LOCK.UPDATE,
of: Notification,
},
rejectOnEmpty: true,
transaction,
});
authorize(user, "update", notification);
notification.fill({ viewedAt, archivedAt });
await notification.saveWithCtx(ctx);
ctx.body = {
data: await presentNotification(ctx, notification),
policies: presentPolicies(user, [notification]),
};
}
);
router.post(
"notifications.update_all",
auth(),
validate(T.NotificationsUpdateAllSchema),
transaction(),
async (ctx: Context<T.NotificationsUpdateAllReq>) => {
const { viewedAt, archivedAt } = ctx.input.body;
const { user } = ctx.auth;
const { transaction } = ctx;
const values: Partial<Notification> = {};
let where: WhereOptions<Notification> = {
teamId: user.teamId,
userId: user.id,
};
if (!isUndefined(viewedAt)) {
values.viewedAt = viewedAt;
where = {
...where,
viewedAt: !isNull(viewedAt) ? { [Op.is]: null } : { [Op.ne]: null },
};
}
if (!isUndefined(archivedAt)) {
values.archivedAt = archivedAt;
where = {
...where,
archivedAt: !isNull(archivedAt) ? { [Op.is]: null } : { [Op.ne]: null },
};
}
let total = 0;
if (!isEmpty(values)) {
total = await Notification.unscoped().findAllInBatches(
{ where, transaction, lock: transaction.LOCK.UPDATE },
async (results) => {
await Promise.all(
results.map((notification) =>
notification.updateWithCtx(ctx, values)
)
);
}
);
}
ctx.body = {
success: true,
data: { total },
};
}
);
export default router;