Files
gerbeur/src/components/editor/Markdown.tsx
khannurien c0d03e9aaa v4: users sign in to one gerbeur instance with their account on another — topic instances, each with its own admins, domain and data, had no way to share accounts. Sign-in is federated over a subset of OpenID Connect, the authorization code flow with PKCE: each instance is an identity provider for its own users and a client for the others', and signs what it tells them with an Ed25519 key kept in federation_keys and published at /.well-known/jwks.json, beside its metadata at /.well-known/openid-configuration. Only sign-in is federated: an account from another instance is a local users row linked to (issuer, subject) in user_identities, with no password (password_hash ''), so sessions, roles, permissions, the socket and every foreign key work as before.
A remote user is name@host here, in users.username, in paths (/@alice@music.example) and in mentions, through one handle rule in shared/validation.ts that paths, MENTION_RE and Markdown all build on; Markdown undoes GFM's email autolink of a handle. Their name, email and avatar come from their home at each sign-in and by its signed events (federation_outbox, delivered by the federation job with backoff): a rename at home leaves the old handle an alias here, and a password change or a withdrawn grant ends their sessions here. Their password, email, avatar and name can't change here (assertLocalUser), nor can they sign in elsewhere from here.

An admin keeps the trusted and blocked instances on /manage (federation:manage): a trusted instance's users sign in from a button on the login page, a blocked one's can't and are signed out at once, and any other's join with an invite from the register page. The /authorize page asks the user once per instance, and /settings lists the instances their account signs in to, each disconnectable; /login?next= brings a signed-out visitor back to /authorize. Emails stay unique among local accounts only, and migration 0024 adds the tables, makes that index partial and reserves authorize and federation as category slugs. remote/gerbeur-instance.ts is the only way to other instances: https and public addresses only, no redirects, no certificate fallback, unless GERBEUR_FEDERATION_ALLOW_PRIVATE lets two instances on one machine talk.

298 backend tests and 702 frontend tests pass, and deno check, deno fmt, deno lint, tsc, eslint, doc:lint and i18n:compile --strict are clean; checked end to end with two built instances on one machine: sign-in through the other's login and consent pages, consent skipped once granted and asked again after disconnecting, a rename and a password change at home reaching the other, and blocking; screenshots of the login, consent, profile, settings and manage pages at 1280 and 390px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 14:23:00 +00:00

259 lines
8.4 KiB
TypeScript

/**
* Renders the Markdown that `TextEditor` writes, wherever a dump's note, a
* comment, a chat message or a description is shown.
*
* @module
*/
import { memo } from "react";
import { Link } from "react-router";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { useAuth } from "../../hooks/auth/useAuth.ts";
import { userPath } from "../../../shared/paths.ts";
import { EVERYONE } from "../../../shared/mention.ts";
import { HANDLE_SOURCE } from "../../../shared/validation.ts";
import { isAttachmentUrl } from "../../../shared/attachment.ts";
/** Passed to {@link Markdown} by any component that shows a user's text. */
export interface MarkdownProps {
children: string;
className?: string;
/**
* Drops the images, for a line-clamped teaser in a card, where an image
* would break the layout. The full text is one click away.
*/
inline?: boolean;
/**
* Shows `@everyone` as a mention, from a chat message's
* `mentionsEveryone`. Without it, `@everyone` is plain text: anyone may type
* it, and it reaches no one.
*/
everyone?: boolean;
}
/**
* The rule of shared/mention.ts, which the server notifies by, applied to
* parsed text: link syntax is already parsed away here, so only a preceding
* word character (an email address) rules a mention out.
*/
const MENTION_RE = new RegExp(`(?<!\\w)@(${HANDLE_SOURCE})`, "g");
/** The part of a Markdown syntax tree node that the plugins below read. */
interface MdNode {
type: string;
value?: string;
url?: string;
children?: MdNode[];
/** Read by mdast-util-to-hast: the element and attributes to render. */
data?: { hName: string; hProperties: Record<string, string> };
}
/**
* Returns `children` with each `@name@host` that GFM took for an email address
* (text ending in `@`, then a `mailto:` link of `name@host`) back in one text
* node, which {@link remarkMentions} then reads as a remote user's handle.
*/
function unlinkHandles(children: MdNode[]): MdNode[] {
const out: MdNode[] = [];
for (const child of children) {
const prev = out.at(-1);
const only = child.children?.length === 1 ? child.children[0] : undefined;
const address = child.type === "link" && only?.type === "text"
? only.value
: undefined;
if (
prev?.type === "text" &&
((address && child.url === `mailto:${address}` &&
/(?<!\w)@$/.test(prev.value ?? "")) ||
child.type === "text")
) {
prev.value = `${prev.value}${address ?? child.value}`;
continue;
}
out.push(child);
}
return out;
}
/**
* Turns a bare `@username`, or a remote user's `@name@host`, into a link to
* that user's profile. It works on the parsed tree rather than the source, so
* code keeps its `@`s and a URL that contains one
* (`https://mastodon.social/@bob`) isn't split in two.
* `@everyone` names no profile: it is left as text, or with `everyone` set,
* becomes a `span.md-everyone`.
*/
function remarkMentions({ everyone = false }: { everyone?: boolean } = {}) {
const walk = (node: MdNode) => {
if (!node.children) return;
// Link text is already a link, whatever it says.
if (node.type === "link" || node.type === "linkReference") return;
node.children = unlinkHandles(node.children).flatMap((child) => {
if (child.type !== "text" || !child.value?.includes("@")) {
walk(child);
return [child];
}
const out: MdNode[] = [];
let last = 0;
for (const m of child.value.matchAll(MENTION_RE)) {
const isEveryone = m[1].toLowerCase() === EVERYONE;
if (isEveryone && !everyone) continue;
if (m.index > last) {
out.push({ type: "text", value: child.value.slice(last, m.index) });
}
out.push(
isEveryone
? {
type: "emphasis",
data: {
hName: "span",
hProperties: { className: "md-everyone" },
},
children: [{ type: "text", value: m[0] }],
}
: {
type: "link",
url: userPath(m[1]),
children: [{ type: "text", value: m[0] }],
},
);
last = m.index + m[0].length;
}
if (last === 0) return [child];
if (last < child.value.length) {
out.push({ type: "text", value: child.value.slice(last) });
}
return out;
});
};
return (tree: MdNode) => walk(tree);
}
/**
* Turns a single newline into a line break, as chat apps do. Markdown folds it
* into a space, so a message typed on three lines with Shift+Enter would show
* as one. Code keeps its newlines, since it has no text nodes.
*/
function remarkBreaks() {
const walk = (node: MdNode) => {
if (!node.children) return;
node.children = node.children.flatMap((child) => {
if (child.type !== "text" || !child.value?.includes("\n")) {
walk(child);
return [child];
}
return child.value.split("\n").flatMap((part, i) =>
i === 0
? [{ type: "text", value: part }]
: [{ type: "break" }, { type: "text", value: part }]
);
});
};
return (tree: MdNode) => walk(tree);
}
const REMARK_PLUGINS = [remarkGfm, remarkMentions, remarkBreaks];
/** {@link REMARK_PLUGINS} for a text whose `@everyone` is a mention. */
const REMARK_PLUGINS_EVERYONE = [
remarkGfm,
[remarkMentions, { everyone: true }],
remarkBreaks,
] as React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"];
/**
* Returns the path of a link into this app, relative or absolute to this
* origin, or null for anywhere else. The API's files and attachments count as
* elsewhere, since they aren't routes of the app.
*/
function internalPath(href: string | undefined): string | null {
if (!href) return null;
if (href.startsWith("/") && !href.startsWith("//")) {
return href.startsWith("/api/") ? null : href;
}
try {
const url = new URL(href);
if (url.origin !== globalThis.location.origin) return null;
if (url.pathname.startsWith("/api/")) return null;
return url.pathname + url.search + url.hash;
} catch {
return null;
}
}
type Components = React.ComponentProps<typeof ReactMarkdown>["components"];
/**
* Renders an image of the text. An attachment gets the viewer's media token,
* which the server asks for when the text linking it is private; any other
* image is left as written.
*/
function MarkdownImage(
{ src, alt }: { src?: string | Blob; alt?: string },
): React.JSX.Element {
const { mediaToken } = useAuth();
let url = typeof src === "string" ? src : undefined;
if (url && mediaToken && isAttachmentUrl(url)) {
url = `${url}?token=${encodeURIComponent(mediaToken)}`;
}
return <img src={url} alt={alt ?? ""} loading="lazy" decoding="async" />;
}
/**
* Overrides react-markdown's elements. It is built once, since a new object on
* each render would re-render every element.
*/
const MARKDOWN_COMPONENTS: Components = {
// Mentions and links to the app navigate in place, without a reload. The
// rest open in a new tab.
a: ({ href, children: linkChildren }) => {
const path = internalPath(href);
if (path) return <Link to={path}>{linkChildren}</Link>;
return (
<a href={href} target="_blank" rel="noopener noreferrer">
{linkChildren}
</a>
);
},
img: ({ src, alt }) => <MarkdownImage src={src} alt={alt} />,
// A wide GFM table scrolls inside its own box instead of the page.
table: ({ children: tableChildren }) => (
<div className="md-table-wrap">
<table>{tableChildren}</table>
</div>
),
};
/** Overrides react-markdown's elements for an `inline` rendering. */
const INLINE_MARKDOWN_COMPONENTS: Components = {
...MARKDOWN_COMPONENTS,
img: () => null,
};
/**
* Renders GFM with `@mentions` as profile links and single newlines kept. It
* is memoized because parsing runs the whole remark pipeline, and the text
* rarely changes when its parent re-renders.
*/
export const Markdown: React.MemoExoticComponent<
(props: MarkdownProps) => React.JSX.Element
> = memo(function Markdown(
{ children, className, inline = false, everyone = false }: MarkdownProps,
) {
return (
<div
className={`md${className ? ` ${className}` : ""}${
inline ? " md--inline" : ""
}`}
>
<ReactMarkdown
remarkPlugins={everyone ? REMARK_PLUGINS_EVERYONE : REMARK_PLUGINS}
components={inline ? INLINE_MARKDOWN_COMPONENTS : MARKDOWN_COMPONENTS}
>
{children}
</ReactMarkdown>
</div>
);
});