${safeTitle}
${safeDescription}
${noteHtml ? `${safeDescription}
${noteHtml ? `${safeOrg} organization on the consent screen:`,
`${safeOrg} on, then confirm.${safeOrg || "the Space"} to add you as a write member. ` +
`If you have multiple Hugging Face accounts, you can also sign out and try again with the right one.`,
buttonLabel: "Sign in with another account",
buttonHref: "/oauth/authorize?prompt=consent",
};
}
export function createApp() {
const DATA_DIR = getDataDir();
mkdirSync(DATA_DIR, { recursive: true });
const oauthEnabled = isOAuthEnabled();
let shuttingDown = false;
// Assigned right after Hocuspocus is built; hooks only run after that.
let versions!: VersionService;
// ---------- Hocuspocus (Y.js collaboration server) ----------
const hocuspocus = new Hocuspocus({
async onLoadDocument() {
if (shuttingDown) throw new Error("Server is shutting down");
},
async beforeSync() {
if (shuttingDown) throw new Error("Server is shutting down");
},
async onAuthenticate({
token,
context,
requestParameters,
}: {
token: string;
context: any;
requestParameters: URLSearchParams;
}) {
if (shuttingDown) throw new Error("Server is shutting down");
// MCP agents connect with a key issued in-process, so their edits
// are attributed to the agent rather than to the token's owner.
const agent = resolveAgentKey(requestParameters?.get("agentKey"));
if (!oauthEnabled) return agent ? { agent } : undefined;
const { resolveUser } = await import("./auth.js");
// Two-source pattern: the HocuspocusProvider client sends `token`
// via the WS sub-protocol, but our cookie is httpOnly so the
// client can't read it and sends "" instead. Fall back to the
// cookie the upgrade handler stuffed into context.token.
const authToken = token || context?.token;
// Surface enough info in the Space logs to triage "Disconnected"
// reports without leaking the token itself. We log:
// - whether each source produced a token (just truthiness)
// - the resolved user (or null) + accessIssue when present
// - the SPACE_ID owner being checked, to spot org mismatches
const tokenSource = token
? "client"
: context?.token
? "cookie"
: "none";
const tokenLen = authToken ? authToken.length : 0;
const user = await resolveUser(authToken);
const spaceOwner = (process.env.SPACE_ID || "").split("/")[0] || "(none)";
if (!user) {
console.warn(
`[ws-auth] reject: no user resolved` +
` source=${tokenSource} tokenLen=${tokenLen}` +
` spaceOwner=${spaceOwner}`,
);
throw new Error("Unauthorized: invalid or missing HF token");
}
if (!user.canEdit) {
console.warn(
`[ws-auth] reject: ${user.name} can't write to ${spaceOwner}` +
` issue=${user.accessIssue ?? "unknown"}` +
` source=${tokenSource}`,
);
throw new Error(
`Unauthorized: ${user.name} has no write access to ${spaceOwner}` +
(user.accessIssue ? ` (${user.accessIssue})` : ""),
);
}
console.log(
`[ws-auth] accept user=${user.name} spaceOwner=${spaceOwner}` +
` source=${tokenSource}`,
);
if (authToken) setUserToken(authToken);
return agent ? { user, agent } : { user };
},
extensions: [
new Database({
// Fail-closed by design: loadDocState throws when the local
// file is unreadable or the HF pull fails for any reason
// other than a definitive 404. The rejection propagates to
// Hocuspocus' onLoadDocument, which closes the connections
// and unloads the doc WITHOUT persisting it - so we never
// create an empty doc that a later debounced save would
// push over the real article in the dataset.
//
// Hocuspocus answers a failed load with permission-denied on an
// open socket, and providers never retry that: the tab would
// stay stuck until reloaded, its edits going nowhere. Closing
// the socket makes every client, however old its bundle,
// reconnect with backoff and retry the load.
fetch: async ({ documentName, context }: { documentName: string; context?: { retryLater?: () => void } }) => {
try {
return await loadDocState(documentName);
} catch (err) {
context?.retryLater?.();
throw err;
}
},
// Hocuspocus runs this at most every 10 s while editing goes on
// and right before unloading a document: the disk save must not
// lag behind either (see flushSave).
store: async ({ documentName }: { documentName: string }) => flushSave(documentName),
}),
{
async onChange({ documentName, document, context }: { documentName: string; document: any; context: any }) {
debouncedSave(documentName, document);
versions.noteChange(documentName, contributorFromContext(context));
},
async afterLoadDocument({ documentName, document }: { documentName: string; document: any }) {
console.log(`[persist] loaded "${documentName}"`);
attachRescue(document);
// A baseline per server start, so the state as found is always
// restorable. Skipped when it equals the latest version.
if (document.getXmlFragment("default").length > 0) {
versions
.checkpointDoc(documentName, document, { reason: "auto", label: "Opened" })
.catch((err) => console.error("[versions] load checkpoint failed:", (err as Error).message));
}
},
} as any,
],
});
versions = new VersionService(hocuspocus);
// ---------- Express app ----------
const app = express();
const httpServer = createServer(app);
app.use((_req, res, next) => {
if (shuttingDown) {
res.setHeader("Connection", "close");
res.status(503).json({ error: "Server is shutting down" });
return;
}
next();
});
// MCP calls can carry an embed (512 KB) and its data files (3 MB each).
app.use("/mcp", express.json({ limit: "8mb" }));
app.use(express.json({ limit: "1mb" }));
const authCtx = { oauthEnabled };
const requireEditor = createRequireEditor(authCtx);
app.use(createAuthRouter(authCtx));
app.use(createChatRouter(requireEditor));
app.use(createEmbedCheckRouter(requireEditor));
app.use(createEmbedGalleryRouter());
app.use("/api/citations", requireEditor, citationsRouter);
const publisher = createPublishService({ hocuspocus });
app.use(
createPublishRouter({
oauthEnabled,
hocuspocus,
publisher,
onPublished: async (docName, req) => {
await versions.checkpoint(docName, {
reason: "publish",
label: "Published",
createdBy: await requestContributor(req, oauthEnabled),
});
},
}),
);
app.use(createUploadRouter(requireEditor));
app.use(createStorageRouter({ oauthEnabled }));
app.use(createVersionsRouter({ oauthEnabled, requireEditor, versions, hocuspocus }));
app.use(createRescuedRouter({ hocuspocus, requireEditor }));
// Reverse proxy for private-dataset assets. Mounted before any
// static serving so `/d/*` always wins, never falls through to a
// 404 from express.static.
app.use(createDatasetProxyRouter());
// External agents (Claude Code, Cursor, ...) join as collaborators.
const mcp = createMcpRouter({ oauthEnabled, versions, requireEditor, publisher });
app.use(mcp.router);
// Machine endpoints answer misses in JSON, never with the SPA's HTML:
// MCP clients probe /.well-known/oauth-protected-resource (and friends)
// during OAuth discovery and must see a 404 to fall back to the bearer
// token; API callers get a parseable error.
app.all(/^\/(\.well-known|mcp|api)(\/|$)/, (req, res) => {
res.status(404).json({ error: "Not found", path: req.path });
});
// ---------- Collab WebSocket ----------
const wss = new WebSocketServer({ noServer: true });
/**
* Hocuspocus v4 hooks receive a web-standard Request, not Node's
* IncomingMessage. Rebuild one from the upgrade request (absolute
* URL + headers, including the session cookie our onAuthenticate
* fallback reads).
*/
function toWebRequest(req: import("http").IncomingMessage): Request {
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
const headers = new Headers();
for (const [key, value] of Object.entries(req.headers)) {
if (Array.isArray(value)) {
for (const v of value) headers.append(key, v);
} else if (value !== undefined) {
headers.set(key, value);
}
}
return new Request(url, { headers });
}
function toUint8Array(data: Buffer | ArrayBuffer | Buffer[]): Uint8Array {
if (Buffer.isBuffer(data)) {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
if (data instanceof ArrayBuffer) return new Uint8Array(data);
return new Uint8Array(Buffer.concat(data));
}
httpServer.on("upgrade", (req, socket, head) => {
if (shuttingDown) {
socket.destroy();
return;
}
const url = req.url || "";
if (url === "/collab" || url.startsWith("/collab/") || url.startsWith("/collab?")) {
console.log(`[ws] upgrade request for ${url}`);
wss.handleUpgrade(req, socket, head, (ws) => {
ws.setMaxListeners(Infinity);
ws.on("error", (error) => {
console.error("[ws] socket error:", error.message);
});
if (process.env.NODE_ENV !== "production") {
ws.on("message", (data: Buffer, isBinary: boolean) => {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data as any);
console.log(`[ws-debug] msg ${buf.length}B binary=${isBinary} first20=${buf.slice(0, 20).toString("hex")}`);
});
}
const token = extractToken(req.headers.cookie);
// Diagnostic for "Disconnected" reports: confirms whether the
// browser actually attached our session cookie to the WS
// upgrade. On HF Spaces, some gating setups occasionally
// strip cookies on WS upgrades even when they're sent for
// plain HTTP, which manifests as a working /editor route
// but a permanently-failing WS auth.
const cookieHeader = req.headers.cookie || "";
console.log(
`[ws] upgrade cookies=${cookieHeader.length}B hasToken=${Boolean(token)}`,
);
// v4 contract for custom integrations: handleConnection no
// longer attaches its own socket listeners; we must forward
// messages and the close event to the returned ClientConnection.
const clientConnection = hocuspocus.handleConnection(
ws as any,
toWebRequest(req),
{ token, retryLater: () => ws.close(1013, "document-unavailable") },
);
ws.on("message", (data: Buffer | ArrayBuffer | Buffer[]) => {
if (shuttingDown) return;
clientConnection.handleMessage(toUint8Array(data));
});
ws.on("close", (code: number, reason: Buffer) => {
clientConnection.handleClose({ code, reason: reason?.toString() ?? "" });
});
});
} else {
console.log(`[ws] rejected upgrade for ${url}`);
socket.destroy();
}
});
// ---------- Static assets ----------
app.use("/uploads", express.static(join(DATA_DIR, "uploads")));
app.use("/published", express.static(join(DATA_DIR, "published")));
const staticDir =
process.env.NODE_ENV === "production"
? join(DATA_DIR, "..", "frontend-dist")
: join(DATA_DIR, "..", "..", "frontend", "dist");
function getPublishedPath(docName: string): string {
return join(DATA_DIR, "published", docName, "index.html");
}
function getPublishedAssetPath(docName: string, filename: string): string {
return join(DATA_DIR, "published", docName, filename);
}
if (existsSync(staticDir)) {
app.use(express.static(staticDir, { index: false }));
// ---- LLM-friendly endpoints --------------------------------------
// The publisher generates a Markdown twin of the article (`llms.txt`)
// following the https://llmstxt.org/ convention. We expose it at the
// Space root so external agents/crawlers (Claude, Perplexity, ...) can
// consume the article without having to parse the heavy HTML page.
// `robots.txt` advertises this endpoint.
app.get("/llms.txt", async (_req, res) => {
const llmsPath = getPublishedAssetPath(DEFAULT_DOC_NAME, "llms.txt");
if (!existsSync(llmsPath)) {
res.status(404).type("text/plain").send("Not yet published");
return;
}
res.type("text/markdown; charset=utf-8");
res.sendFile(llmsPath);
});
app.get("/robots.txt", (_req, res) => {
res
.type("text/plain; charset=utf-8")
.send(
[
"User-agent: *",
"Allow: /",
"",
"LLMs-Txt: /llms.txt",
"",
].join("\n"),
);
});
app.get("/editor", async (req, res) => {
if (oauthEnabled) {
const { resolveUser } = await import("./auth.js");
const token = extractToken(req.headers.cookie);
const user = await resolveUser(token);
if (!user || !user.canEdit) {
res.status(200).send(renderLoginPage(buildEditorLoginPage(user)));
return;
}
}
res.sendFile(join(staticDir, "index.html"));
});
app.get("*", async (req, res) => {
if (!oauthEnabled) {
res.sendFile(join(staticDir, "index.html"));
return;
}
const visitorToken = extractToken(req.headers.cookie) ?? undefined;
await ensurePublishedRestored(visitorToken);
const publishedPath = getPublishedPath(DEFAULT_DOC_NAME);
if (existsSync(publishedPath)) {
res.sendFile(publishedPath);
return;
}
sendLoginPage(res);
});
}
/** Freeze inbound edits synchronously, before taking the final disk snapshot. */
function stopAcceptingEdits() {
if (shuttingDown) return;
shuttingDown = true;
// A sync handler may already be suspended in an async hook. Hocuspocus
// checks readOnly again before applying the update, so closing the socket
// alone would not be enough to freeze those messages.
for (const document of hocuspocus.documents.values()) {
for (const connection of document.connections.keys()) {
connection.readOnly = true;
}
}
for (const ws of wss.clients) ws.close(1012, "Server restarting");
mcp.closeAll();
versions.destroy();
}
return { app, httpServer, hocuspocus, wss, versions, stopAcceptingEdits };
}