mirror of
https://github.com/outline/outline.git
synced 2026-11-21 05:24:03 +03:00
* feat: Personal collections backend Adds an owner to collections. A personal collection is private, one per user per team, created lazily through collections.personal, and only its owner can see or manage it. Admin bypasses in policies, lists, exports, events, webhooks and file operations exclude the personal collections of other users. Turning off the PersonalDocs preference makes the collection read-only. * test: Access matrix for personal collections Checks that collection and document endpoints, list and search results, MCP tools, collaboration and websocket rooms agree with the read policy for the owner, collaborators, members, admins, guests and other teams. * feat: Personal collection in the sidebar Adds a Personal sidebar section that renders the personal collection with the collection document tree, creates the collection on the first new document, and keeps it out of the Collections section. Adds the workspace setting, the personal sidebar context, and hides collection sharing and membership UI for personal collections. * fix: Drag and drop in shared with me trees Anchors the reorder drop cursor inside the row, and prefetches documents on hover so that nested rows that were never opened can be dragged. * feat: Personal collection owner for collaborators, no collection page Presents the owner of the personal collection on documents, so that collaborators see the owner in the share popover. Root rows in the Personal section show the default document icon. A personal collection has no page: the scene shows not found, and the breadcrumb, command bar and delete redirect no longer link to it. * fix: Personal sidebar indent and breadcrumb items without a link Children of rows at depth 0 skip a level so that they start beyond the row icon. Breadcrumb items without a destination, such as the personal and deleted collection, are shown as plain text. * test: Reduce personal collection tests to list paths Endpoints that authorize a single model are already covered by the policy tests. Keeps the lists and searches, which filter in queries, and the presenter. * test: Move personal collection list tests into collections tests * feat: Create documents in the personal collection by alias documents.create, documents.import and the MCP create_document tool accept the collectionId "personal", which refers to the personal collection of the user and creates it when it does not exist yet. * refactor: Remove collections.personal route The sidebar creates its first personal document with the personal collectionId alias, so documents.create is the only path that creates the personal collection. * feat: Personal collection name, starring, templates and default Personal collections cannot be starred, renamed or hold templates, and the PersonalDocs preference is on by default. The app shows collections through a displayName getter, which is the translated "Personal" for a personal collection. * fix: Use the same policy for starring and unstarring collections * fix: No pins or viewer insights for personal documents * revert: Show personal collection events in the audit log Admins with audit access should see events in personal collections, even when they cannot open the documents. * fix: Load collection owner in share scopes * fix: Keep personal collections out of workspace exports and webhooks Workspace exports skip all personal collections, while an explicit export of a personal collection stays available to its owner. Events in personal collections, including attachments and documents moved after queueing, are never delivered to workspace webhooks. Personal collections cannot be renamed or made public through any path, cannot hold pins, and are not offered as mentions. * Change icon to avatar * fix: Personal documents cannot be unpublished * feat: Personal collection context for MCP Collections are presented with an isPersonal flag, the server instructions explain the personal collection, and move_document and update_document accept the personal collectionId alias. * fix: Keep moved personal exports private and remove pins on move Document exports record the owner of the personal collection they came from, so they stay private after the document moves. Moving documents into a personal collection removes their pins, including pins to home. * fix: Only create the personal collection in MCP when it is used
230 lines
6.7 KiB
TypeScript
230 lines
6.7 KiB
TypeScript
import querystring from "node:querystring";
|
|
import { addMonths } from "date-fns";
|
|
import type { Context } from "koa";
|
|
import { isPlainObject, pick } from "es-toolkit/compat";
|
|
import isUUID from "validator/lib/isUUID";
|
|
import { toError } from "@shared/utils/error";
|
|
import { Client } from "@shared/types";
|
|
import { getCookieDomain } from "@shared/utils/domains";
|
|
import env from "@server/env";
|
|
import Logger from "@server/logging/Logger";
|
|
import { Event, Collection, Team, View } from "@server/models";
|
|
import type { APIContext, AuthenticationResult } from "@server/types";
|
|
import { AuthenticationType } from "@server/types";
|
|
|
|
/**
|
|
* Parse and return the details from the "sessions" cookie in the request, if
|
|
* any. The cookie is on the apex domain and includes session details for
|
|
* other subdomains.
|
|
*
|
|
* @param ctx The Koa context
|
|
* @returns The session details
|
|
*/
|
|
export function getSessionsInCookie(ctx: Context) {
|
|
try {
|
|
const sessionCookie = ctx.cookies.get("sessions") || "";
|
|
const decodedSessionCookie = decodeURIComponent(sessionCookie);
|
|
const sessions = decodedSessionCookie
|
|
? JSON.parse(decodedSessionCookie)
|
|
: {};
|
|
return isPlainObject(sessions) ? sessions : {};
|
|
} catch (_err) {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Finds the workspace to send a request for the app root domain to, using the
|
|
* first usable workspace in the "sessions" cookie. Entries that are malformed,
|
|
* deleted, suspended, or already the current host are ignored.
|
|
*
|
|
* @param ctx The Koa context
|
|
* @returns The workspace url for the requested path, if there is one.
|
|
*/
|
|
export async function getSessionRedirectUrl(
|
|
ctx: Context
|
|
): Promise<string | undefined> {
|
|
const teamIds = Object.keys(getSessionsInCookie(ctx)).filter((id) =>
|
|
isUUID(id)
|
|
);
|
|
if (teamIds.length === 0) {
|
|
return;
|
|
}
|
|
|
|
// Preserve cookie order so the earliest sign-in wins.
|
|
const teams = await Team.findAll({ where: { id: teamIds } });
|
|
const team = teamIds
|
|
.map((id) => teams.find((t) => t.id === id))
|
|
.find((t) => t && !t.isSuspended && !t.isTeamUrl(ctx.href));
|
|
if (!team) {
|
|
return;
|
|
}
|
|
|
|
const url = new URL(team.url);
|
|
url.pathname = ctx.path;
|
|
url.search = ctx.search;
|
|
return url.toString();
|
|
}
|
|
|
|
/**
|
|
* Signs in a user by setting authentication cookies and recording the sign-in
|
|
* event, then redirects to the appropriate destination.
|
|
*
|
|
* @param ctx the Koa context.
|
|
* @param service the name of the authentication service used to sign in.
|
|
* @param result the authentication result containing user and team details.
|
|
*/
|
|
export async function signIn(
|
|
ctx: Context | APIContext,
|
|
service: string,
|
|
{ user, team, client, isNewTeam }: AuthenticationResult
|
|
) {
|
|
const { transaction } = ctx.state;
|
|
|
|
if (team.isSuspended) {
|
|
return ctx.redirect("/?notice=team-suspended");
|
|
}
|
|
if (user.isSuspended) {
|
|
return ctx.redirect("/?notice=user-suspended");
|
|
}
|
|
|
|
if (isNewTeam) {
|
|
// see: scenes/Login/index.js for where this cookie is written when
|
|
// viewing the /login or /create pages. It is a URI encoded JSON string.
|
|
const cookie = ctx.cookies.get("signupQueryParams");
|
|
|
|
if (cookie) {
|
|
try {
|
|
const signupQueryParams = pick(
|
|
JSON.parse(querystring.unescape(cookie)),
|
|
["ref", "utm_content", "utm_medium", "utm_source", "utm_campaign"]
|
|
);
|
|
await team.update(
|
|
{
|
|
signupQueryParams,
|
|
},
|
|
{
|
|
transaction,
|
|
}
|
|
);
|
|
} catch (error) {
|
|
Logger.error(`Error persisting signup query params`, toError(error));
|
|
}
|
|
}
|
|
}
|
|
|
|
// update the database when the user last signed in
|
|
await user.updateSignedIn(ctx);
|
|
|
|
await Event.createFromContext(
|
|
ctx,
|
|
{
|
|
name: "users.signin",
|
|
userId: user.id,
|
|
authType: AuthenticationType.APP,
|
|
data: {
|
|
name: user.name,
|
|
service,
|
|
},
|
|
},
|
|
{
|
|
actorId: user.id,
|
|
teamId: team.id,
|
|
}
|
|
);
|
|
|
|
const domain = getCookieDomain(ctx.request.hostname, env.isCloudHosted);
|
|
const expires = addMonths(new Date(), 3);
|
|
|
|
// set a cookie for which service we last signed in with. This is
|
|
// only used to display a UI hint for the user for next time
|
|
ctx.cookies.set("lastSignedIn", service, {
|
|
httpOnly: false,
|
|
sameSite: true,
|
|
expires: new Date("2100"),
|
|
domain,
|
|
});
|
|
|
|
// On cloud hosted multi-team deployments, record the signed-in team in the
|
|
// sessions cookie so the web team switcher stays in sync. This applies to
|
|
// both web and desktop clients.
|
|
if (env.isCloudHosted && team.subdomain) {
|
|
// get any existing sessions (teams signed in) and add this team
|
|
const existing = getSessionsInCookie(ctx);
|
|
const sessions = encodeURIComponent(
|
|
JSON.stringify({
|
|
...existing,
|
|
[team.id]: {
|
|
name: team.name,
|
|
logoUrl: team.avatarUrl,
|
|
url: team.url,
|
|
},
|
|
})
|
|
);
|
|
ctx.cookies.set("sessions", sessions, {
|
|
httpOnly: false,
|
|
expires,
|
|
domain,
|
|
});
|
|
}
|
|
|
|
// If the authentication request originally came from the desktop app then we send the user
|
|
// back to a screen in the web app that will immediately redirect to the desktop. The reason
|
|
// to do this from the client is that if you redirect from the server then the browser ends up
|
|
// stuck on the SSO screen.
|
|
if (client === Client.Desktop) {
|
|
const token = encodeURIComponent(user.getTransferToken(service));
|
|
ctx.redirect(`${team.url}/desktop-redirect?token=${token}`);
|
|
return;
|
|
}
|
|
|
|
// Redirect to the team subdomain with a short-lived transfer token that the
|
|
// /auth/redirect handler exchanges for the actual session cookie.
|
|
if (env.isCloudHosted && team.subdomain) {
|
|
const token = encodeURIComponent(user.getTransferToken(service));
|
|
ctx.redirect(`${team.url}/auth/redirect?token=${token}`);
|
|
} else {
|
|
ctx.cookies.set("accessToken", user.getSessionToken(expires, service), {
|
|
sameSite: "lax",
|
|
expires,
|
|
});
|
|
|
|
const defaultCollectionId = team.defaultCollectionId;
|
|
|
|
if (defaultCollectionId) {
|
|
const collection = await Collection.findOne({
|
|
where: {
|
|
id: defaultCollectionId,
|
|
teamId: team.id,
|
|
ownerId: null,
|
|
},
|
|
transaction,
|
|
});
|
|
|
|
if (collection) {
|
|
ctx.redirect(`${team.url}${collection.path}`);
|
|
return;
|
|
}
|
|
}
|
|
|
|
const [collection, view] = await Promise.all([
|
|
Collection.findFirstCollectionForUser(user, {
|
|
transaction,
|
|
}),
|
|
View.findOne({
|
|
where: {
|
|
userId: user.id,
|
|
},
|
|
transaction,
|
|
}),
|
|
]);
|
|
const hasViewedDocuments = !!view;
|
|
|
|
ctx.redirect(
|
|
!hasViewedDocuments && collection
|
|
? `${team.url}${collection.path}/recent`
|
|
: `${team.url}/home`
|
|
);
|
|
}
|
|
}
|