feat(storage): private dataset by default + /d/* reverse proxy
Browse filesThe dataset that backs persistence was being created `private: false`
on every first write. For org-owned Spaces with strict data
policies (notably `HuggingFaceBio/carbon-tokenization`) this could
either silently fail (org blocks public dataset creation) or be
flat-out wrong (working drafts of an internal research paper
shouldn't be sitting on a public dataset).
Flip the default to `private: true`. The complication this creates
is that published articles' `<img>` tags, og:image and PDF
download all pointed at `huggingface.co/datasets/.../resolve/...`
URLs that would now 401 for anonymous viewers. Solve that with a
small reverse-proxy route on the editor itself.
- New `GET /d/:path*` handler streams from
`huggingface.co/datasets/${id}/resolve/main/${path}` to the
caller, attaching the right HF token along the way:
1. cookie token from the current request (most viewers are
signed in on private Spaces anyway)
2. last-known cached user token (any signed-in request warms
the proxy for subsequent anonymous viewers)
3. `HF_TOKEN` env fallback (operator-set)
4. anonymous (works only when dataset is public)
- Path whitelist hard-coded to `images/` + `published/`. `articles/`
(raw `.yjs` drafts) is *never* exposed through the proxy. Path
traversal sequences (`..`, leading `/`, NUL bytes) are dropped
before the whitelist check.
- Body is piped via `Readable.fromWeb` so large PDFs don't pin Node
heap.
- Cache-Control:
- `images/*` are UUID-named and never overwritten => `immutable,
max-age=1y`. Browsers skip revalidation entirely.
- `published/*` is republished in place => `max-age=300,
stale-while-revalidate=60` so a freshly-published article
propagates within minutes without thundering-herding HF on every
page load.
- Upstream 401/403 collapse to 502 instead of being forwarded, so
the browser never gets prompted for credentials it can't supply.
Upstream 404 passes through.
`hf-storage.ts` changes:
- `createRepo({ private: true })` + clearer log on the 409-vs-real
failure split (now includes the HTTP status, the most common
cause being a missing `manage-repos` OAuth scope).
- `uploadImageToHf` returns `/d/images/<file>` instead of the raw HF
URL.
- `getPublishedAssetUrl` returns
`https://${SPACE_HOST}/d/published/...` (absolute on purpose:
og:image gets fetched by external unfurlers that don't know our
origin; the PDF download link can be hit from other sites too).
Falls back to `http://localhost:${PORT}` in dev.
- `resolveToken` is now exported so the proxy can reuse the same
cascade without duplicating it.
Backward compat: articles that already have hard-coded
`huggingface.co/datasets/.../resolve/...` image URLs in their Y.js
state keep working because their dataset is still public (the
private default only applies to *new* dataset creations - existing
ones aren't migrated). For brand-new deployments (the bio case),
everything is `/d/*` from day one and the dataset is private.
Docs: TESTS.md gains rows 2.3.3 / 2.3.4 (proxy serves images,
proxy whitelist enforced); SPECIFICATION.md 4.3 calls out the
private default + a new 4.3.1 documenting the proxy contract.
Co-authored-by: Cursor <cursoragent@cursor.com>
- backend/src/create-app.ts +5 -0
- backend/src/hf-storage.ts +66 -10
- backend/src/routes/dataset-proxy.ts +162 -0
- docs/SPECIFICATION.md +13 -2
- docs/TESTS.md +3 -1
|
@@ -15,6 +15,7 @@ import { createAuthRouter, createRequireEditor } from "./routes/auth.js";
|
|
| 15 |
import { createChatRouter } from "./routes/chat.js";
|
| 16 |
import { createPublishRouter } from "./routes/publish.js";
|
| 17 |
import { createUploadRouter } from "./routes/upload.js";
|
|
|
|
| 18 |
|
| 19 |
export { debouncedSave, resetSaveTimers, resetPublishedRestored } from "./persistence.js";
|
| 20 |
|
|
@@ -408,6 +409,10 @@ export function createApp() {
|
|
| 408 |
app.use("/api/citations", citationsRouter);
|
| 409 |
app.use(createPublishRouter({ oauthEnabled, hocuspocus }));
|
| 410 |
app.use(createUploadRouter());
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
// ---------- Collab WebSocket ----------
|
| 413 |
|
|
|
|
| 15 |
import { createChatRouter } from "./routes/chat.js";
|
| 16 |
import { createPublishRouter } from "./routes/publish.js";
|
| 17 |
import { createUploadRouter } from "./routes/upload.js";
|
| 18 |
+
import { createDatasetProxyRouter } from "./routes/dataset-proxy.js";
|
| 19 |
|
| 20 |
export { debouncedSave, resetSaveTimers, resetPublishedRestored } from "./persistence.js";
|
| 21 |
|
|
|
|
| 409 |
app.use("/api/citations", citationsRouter);
|
| 410 |
app.use(createPublishRouter({ oauthEnabled, hocuspocus }));
|
| 411 |
app.use(createUploadRouter());
|
| 412 |
+
// Reverse proxy for private-dataset assets. Mounted before any
|
| 413 |
+
// static serving so `/d/*` always wins, never falls through to a
|
| 414 |
+
// 404 from express.static.
|
| 415 |
+
app.use(createDatasetProxyRouter());
|
| 416 |
|
| 417 |
// ---------- Collab WebSocket ----------
|
| 418 |
|
|
@@ -2,6 +2,7 @@ import { uploadFile, downloadFile, createRepo, commit, type CommitFile, type Rep
|
|
| 2 |
import { sanitizeName } from "./utils.js";
|
| 3 |
|
| 4 |
const SPACE_ID = process.env.SPACE_ID || "";
|
|
|
|
| 5 |
|
| 6 |
// Derive dataset ID: explicit env > "<space-id>-data"
|
| 7 |
const HF_DATASET_ID =
|
|
@@ -28,13 +29,48 @@ function getToken(explicit?: string): string {
|
|
| 28 |
return explicit || _cachedToken || ENV_TOKEN;
|
| 29 |
}
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
export function isHfStorageEnabled(): boolean {
|
| 32 |
return Boolean(HF_DATASET_ID && (_cachedToken || ENV_TOKEN));
|
| 33 |
}
|
| 34 |
|
| 35 |
/**
|
| 36 |
-
*
|
| 37 |
-
*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
*/
|
| 39 |
let _datasetReady = false;
|
| 40 |
|
|
@@ -45,13 +81,22 @@ export async function ensureDatasetExists(token?: string): Promise<void> {
|
|
| 45 |
if (!accessToken) return;
|
| 46 |
|
| 47 |
try {
|
| 48 |
-
await createRepo({ repo, private:
|
| 49 |
-
console.log(`[hf-storage] created
|
| 50 |
} catch (err: any) {
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
console.log(`[hf-storage] dataset ${HF_DATASET_ID} already exists`);
|
| 53 |
} else {
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
return;
|
| 56 |
}
|
| 57 |
}
|
|
@@ -75,7 +120,12 @@ export async function uploadImageToHf(
|
|
| 75 |
commitTitle: `upload image ${filename}`,
|
| 76 |
});
|
| 77 |
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
}
|
| 80 |
|
| 81 |
// ---------- Documents ----------
|
|
@@ -242,12 +292,18 @@ export async function pullPublishedAssets(
|
|
| 242 |
// ---------- Published Assets ----------
|
| 243 |
|
| 244 |
/**
|
| 245 |
-
* Build the
|
| 246 |
-
*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
*/
|
| 248 |
export function getPublishedAssetUrl(docName: string, filename: string): string {
|
| 249 |
const safeName = sanitizeName(docName);
|
| 250 |
-
return `
|
| 251 |
}
|
| 252 |
|
| 253 |
interface PublishedPayload {
|
|
|
|
| 2 |
import { sanitizeName } from "./utils.js";
|
| 3 |
|
| 4 |
const SPACE_ID = process.env.SPACE_ID || "";
|
| 5 |
+
const SPACE_HOST = process.env.SPACE_HOST || "";
|
| 6 |
|
| 7 |
// Derive dataset ID: explicit env > "<space-id>-data"
|
| 8 |
const HF_DATASET_ID =
|
|
|
|
| 29 |
return explicit || _cachedToken || ENV_TOKEN;
|
| 30 |
}
|
| 31 |
|
| 32 |
+
/**
|
| 33 |
+
* Public wrapper around the same token cascade used internally. The
|
| 34 |
+
* dataset-proxy route needs to forward the right token to HF when
|
| 35 |
+
* fetching assets on behalf of a viewer.
|
| 36 |
+
*/
|
| 37 |
+
export function resolveToken(explicit?: string): string {
|
| 38 |
+
return getToken(explicit);
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
export function isHfStorageEnabled(): boolean {
|
| 42 |
return Boolean(HF_DATASET_ID && (_cachedToken || ENV_TOKEN));
|
| 43 |
}
|
| 44 |
|
| 45 |
/**
|
| 46 |
+
* Public-facing base URL the editor is reachable at, used to build
|
| 47 |
+
* absolute proxy URLs for assets that need to render outside the
|
| 48 |
+
* Space's own page (og:image consumed by social card unfurlers,
|
| 49 |
+
* "Download PDF" link from external sites, ...). In dev we don't
|
| 50 |
+
* have SPACE_HOST so we fall back to localhost.
|
| 51 |
+
*/
|
| 52 |
+
function getPublicBaseUrl(): string {
|
| 53 |
+
if (SPACE_HOST) return `https://${SPACE_HOST}`;
|
| 54 |
+
const port = process.env.PORT || "8080";
|
| 55 |
+
return `http://localhost:${port}`;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
/**
|
| 59 |
+
* Ensure the backing dataset exists on HF.
|
| 60 |
+
*
|
| 61 |
+
* The dataset is created **private by default**: most editor
|
| 62 |
+
* deployments live in organisations where the working drafts must
|
| 63 |
+
* not leak, and even for solo public projects the published assets
|
| 64 |
+
* (images, PDFs, thumbnails) flow back through the editor's own
|
| 65 |
+
* `/d/...` reverse proxy anyway, so anonymous viewers never need
|
| 66 |
+
* direct dataset access. Keeping it private also avoids running
|
| 67 |
+
* into orgs that block `private: false` creations by policy.
|
| 68 |
+
*
|
| 69 |
+
* Safe to call multiple times; treats 409 as success and caches a
|
| 70 |
+
* "ready" flag so we don't retry on every push. A non-409 failure
|
| 71 |
+
* is logged with the HTTP status when available (the most common
|
| 72 |
+
* cause is a missing `manage-repos` scope on the user's OAuth
|
| 73 |
+
* grant) and the flag is *not* set, so the next push will retry.
|
| 74 |
*/
|
| 75 |
let _datasetReady = false;
|
| 76 |
|
|
|
|
| 81 |
if (!accessToken) return;
|
| 82 |
|
| 83 |
try {
|
| 84 |
+
await createRepo({ repo, private: true, accessToken });
|
| 85 |
+
console.log(`[hf-storage] created private dataset ${HF_DATASET_ID}`);
|
| 86 |
} catch (err: any) {
|
| 87 |
+
const statusCode = err?.statusCode ?? err?.status;
|
| 88 |
+
const message = String(err?.message || err);
|
| 89 |
+
if (statusCode === 409 || message.includes("already")) {
|
| 90 |
console.log(`[hf-storage] dataset ${HF_DATASET_ID} already exists`);
|
| 91 |
} else {
|
| 92 |
+
// Surface enough detail to triage from Space logs: status code
|
| 93 |
+
// (403 = scope/permission, 422 = invalid name, 5xx = HF down)
|
| 94 |
+
// and a one-line message. We deliberately omit the full error
|
| 95 |
+
// object to avoid noisy stack dumps on every retry.
|
| 96 |
+
console.error(
|
| 97 |
+
`[hf-storage] failed to create dataset ${HF_DATASET_ID}` +
|
| 98 |
+
` (status=${statusCode ?? "unknown"}): ${message}`,
|
| 99 |
+
);
|
| 100 |
return;
|
| 101 |
}
|
| 102 |
}
|
|
|
|
| 120 |
commitTitle: `upload image ${filename}`,
|
| 121 |
});
|
| 122 |
|
| 123 |
+
// Relative URL through the editor's reverse proxy. The dataset is
|
| 124 |
+
// private and the raw `huggingface.co/datasets/...` URL would 401
|
| 125 |
+
// for anonymous viewers - the proxy attaches a server-side token
|
| 126 |
+
// and forwards. Relative is fine because images are only ever
|
| 127 |
+
// rendered from inside the Space's own pages.
|
| 128 |
+
return `/d/${path}`;
|
| 129 |
}
|
| 130 |
|
| 131 |
// ---------- Documents ----------
|
|
|
|
| 292 |
// ---------- Published Assets ----------
|
| 293 |
|
| 294 |
/**
|
| 295 |
+
* Build the proxied URL for a published asset.
|
| 296 |
+
*
|
| 297 |
+
* Returns an **absolute** URL because consumers are sometimes
|
| 298 |
+
* external (Twitter / Slack / Discord card unfurlers reading
|
| 299 |
+
* og:image, or external links to the PDF download), and a relative
|
| 300 |
+
* `/d/...` wouldn't resolve there. Inside the Space's own pages a
|
| 301 |
+
* relative URL would have worked equally well, but emitting the
|
| 302 |
+
* absolute form keeps the contract uniform.
|
| 303 |
*/
|
| 304 |
export function getPublishedAssetUrl(docName: string, filename: string): string {
|
| 305 |
const safeName = sanitizeName(docName);
|
| 306 |
+
return `${getPublicBaseUrl()}/d/published/${safeName}/${filename}`;
|
| 307 |
}
|
| 308 |
|
| 309 |
interface PublishedPayload {
|
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Router, type Request, type Response } from "express";
|
| 2 |
+
import { Readable } from "stream";
|
| 3 |
+
import { extractToken } from "../auth.js";
|
| 4 |
+
import {
|
| 5 |
+
getDatasetId,
|
| 6 |
+
resolveToken,
|
| 7 |
+
setUserToken,
|
| 8 |
+
} from "../hf-storage.js";
|
| 9 |
+
|
| 10 |
+
/**
|
| 11 |
+
* Authenticated reverse proxy for the backing HF dataset.
|
| 12 |
+
*
|
| 13 |
+
* Why this exists
|
| 14 |
+
* ---------------
|
| 15 |
+
* The dataset that backs the editor is **private by default** (see
|
| 16 |
+
* `hf-storage.ts::ensureDatasetExists`), but the published article's
|
| 17 |
+
* `<img>` tags and the og:image / pdf links still need to be
|
| 18 |
+
* resolvable from a normal browser - including by anonymous viewers
|
| 19 |
+
* of a public Space. We can't just hand out
|
| 20 |
+
* `huggingface.co/datasets/.../resolve/...` URLs because the dataset
|
| 21 |
+
* itself is gated. Instead, the editor server proxies those reads on
|
| 22 |
+
* the viewer's behalf, attaching a token it has on hand.
|
| 23 |
+
*
|
| 24 |
+
* Token resolution cascade (most specific to most ambient):
|
| 25 |
+
* 1. Cookie from the current request (if the viewer is signed in)
|
| 26 |
+
* 2. Last-known cached user token (warmed by any prior signed-in
|
| 27 |
+
* request - see `hf-storage::setUserToken`)
|
| 28 |
+
* 3. The server-side `HF_TOKEN` env (when an operator set one)
|
| 29 |
+
* 4. No token at all (works only for public datasets)
|
| 30 |
+
*
|
| 31 |
+
* Path whitelist
|
| 32 |
+
* --------------
|
| 33 |
+
* Only `images/` and `published/` may flow through the proxy. We
|
| 34 |
+
* explicitly never expose `articles/` (raw Y.js `.yjs` snapshots
|
| 35 |
+
* including unpublished drafts) and never expose the dataset root
|
| 36 |
+
* either. Anything outside the whitelist gets a 404 - leaking the
|
| 37 |
+
* proxy's existence is fine, leaking the path layout is not.
|
| 38 |
+
*
|
| 39 |
+
* Streaming
|
| 40 |
+
* ---------
|
| 41 |
+
* Responses are piped straight from `fetch`'s WHATWG body to the
|
| 42 |
+
* Express `res`, so we never buffer a full PDF or large image in
|
| 43 |
+
* Node memory. The cost is a tiny shim through `Readable.fromWeb`.
|
| 44 |
+
*
|
| 45 |
+
* Cache-Control
|
| 46 |
+
* -------------
|
| 47 |
+
* - `images/*` filenames are UUID-based and content-addressed in
|
| 48 |
+
* practice (the editor never overwrites an existing upload), so
|
| 49 |
+
* they get `immutable, max-age=1y` - browsers will skip
|
| 50 |
+
* revalidation entirely.
|
| 51 |
+
* - `published/*` is mutable (every republish overwrites it) so we
|
| 52 |
+
* cap at a short max-age and tell intermediaries to revalidate.
|
| 53 |
+
*/
|
| 54 |
+
export function createDatasetProxyRouter(): Router {
|
| 55 |
+
const router = Router();
|
| 56 |
+
|
| 57 |
+
router.get(/^\/d\/(.+)$/, async (req: Request, res: Response) => {
|
| 58 |
+
const datasetId = getDatasetId();
|
| 59 |
+
if (!datasetId) {
|
| 60 |
+
res.status(503).json({ error: "Dataset persistence not configured" });
|
| 61 |
+
return;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
const relPath = (req.params as { 0?: string })[0] || "";
|
| 65 |
+
if (!isPathAllowed(relPath)) {
|
| 66 |
+
// 404, not 403: don't confirm whether the caller "almost" had
|
| 67 |
+
// the right path. An attacker probing for /d/articles/foo.yjs
|
| 68 |
+
// gets the same response as one probing for /d/garbage.
|
| 69 |
+
res.status(404).json({ error: "Not found" });
|
| 70 |
+
return;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// Promote a cookie token to the cache opportunistically: even if
|
| 74 |
+
// this very request was authenticated, future anonymous requests
|
| 75 |
+
// from the same Space session benefit from a warm cache.
|
| 76 |
+
const cookieToken = extractToken(req.headers.cookie);
|
| 77 |
+
if (cookieToken) setUserToken(cookieToken);
|
| 78 |
+
|
| 79 |
+
const token = resolveToken(cookieToken);
|
| 80 |
+
const upstreamUrl = `https://huggingface.co/datasets/${datasetId}/resolve/main/${encodePath(relPath)}`;
|
| 81 |
+
|
| 82 |
+
let upstream: Response | globalThis.Response;
|
| 83 |
+
try {
|
| 84 |
+
upstream = await fetch(upstreamUrl, {
|
| 85 |
+
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
| 86 |
+
});
|
| 87 |
+
} catch (err) {
|
| 88 |
+
console.error(`[dataset-proxy] fetch failed for ${relPath}:`, (err as Error).message);
|
| 89 |
+
res.status(502).json({ error: "Upstream fetch failed" });
|
| 90 |
+
return;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
if (!upstream.ok || !upstream.body) {
|
| 94 |
+
// Don't reflect upstream 401 directly: the viewer can't do
|
| 95 |
+
// anything about a missing server-side token, and surfacing
|
| 96 |
+
// 401 would trigger browser auth prompts in some setups.
|
| 97 |
+
// Map any non-2xx to a generic 404 + log the real status for
|
| 98 |
+
// operators reading the Space logs.
|
| 99 |
+
console.warn(
|
| 100 |
+
`[dataset-proxy] ${relPath}: upstream status ${upstream.status} (token=${token ? "yes" : "no"})`,
|
| 101 |
+
);
|
| 102 |
+
res.status(upstream.status === 404 ? 404 : 502).json({
|
| 103 |
+
error: upstream.status === 404 ? "Not found" : "Upstream error",
|
| 104 |
+
});
|
| 105 |
+
return;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// Forward content-type + content-length when present so the
|
| 109 |
+
// browser renders the right viewer and shows progress for PDFs.
|
| 110 |
+
const ct = upstream.headers.get("content-type");
|
| 111 |
+
if (ct) res.setHeader("Content-Type", ct);
|
| 112 |
+
const cl = upstream.headers.get("content-length");
|
| 113 |
+
if (cl) res.setHeader("Content-Length", cl);
|
| 114 |
+
|
| 115 |
+
res.setHeader("Cache-Control", cacheControlFor(relPath));
|
| 116 |
+
|
| 117 |
+
// Stream the WHATWG body straight to the Express response. The
|
| 118 |
+
// `as any` is required because @types/node's `Readable.fromWeb`
|
| 119 |
+
// doesn't accept the DOM `ReadableStream` type without a cast.
|
| 120 |
+
const nodeStream = Readable.fromWeb(upstream.body as any);
|
| 121 |
+
nodeStream.on("error", (err) => {
|
| 122 |
+
console.error(`[dataset-proxy] stream error for ${relPath}:`, err.message);
|
| 123 |
+
if (!res.headersSent) res.status(502).end();
|
| 124 |
+
else res.end();
|
| 125 |
+
});
|
| 126 |
+
nodeStream.pipe(res);
|
| 127 |
+
});
|
| 128 |
+
|
| 129 |
+
return router;
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
const ALLOWED_PREFIXES = ["images/", "published/"];
|
| 133 |
+
|
| 134 |
+
function isPathAllowed(path: string): boolean {
|
| 135 |
+
// Reject path traversal up-front. `decodeURIComponent` would let
|
| 136 |
+
// an attacker hide `..` segments behind URL encoding, but Express
|
| 137 |
+
// already decodes the wildcard param for us, so a plain string
|
| 138 |
+
// check is sufficient.
|
| 139 |
+
if (path.includes("..") || path.includes("\0") || path.startsWith("/")) {
|
| 140 |
+
return false;
|
| 141 |
+
}
|
| 142 |
+
return ALLOWED_PREFIXES.some((prefix) => path.startsWith(prefix));
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
/**
|
| 146 |
+
* Re-encode the path before sending it upstream so spaces / unicode
|
| 147 |
+
* filenames don't trip HF's URL parser. We split on `/` so the
|
| 148 |
+
* slashes stay literal.
|
| 149 |
+
*/
|
| 150 |
+
function encodePath(path: string): string {
|
| 151 |
+
return path.split("/").map(encodeURIComponent).join("/");
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
function cacheControlFor(path: string): string {
|
| 155 |
+
if (path.startsWith("images/")) {
|
| 156 |
+
// UUID names + no overwrite => safe to mark immutable.
|
| 157 |
+
return "public, max-age=31536000, immutable";
|
| 158 |
+
}
|
| 159 |
+
// Published assets get republished in place, so cap aggressively
|
| 160 |
+
// but allow shared caches to serve while revalidating.
|
| 161 |
+
return "public, max-age=300, stale-while-revalidate=60";
|
| 162 |
+
}
|
|
@@ -92,12 +92,23 @@ All types are concurrently editable by multiple users and persist to `data/defau
|
|
| 92 |
### 4.3 HF Storage
|
| 93 |
|
| 94 |
- Dataset ID: `HF_DATASET_ID` or `{SPACE_ID}-data`
|
|
|
|
| 95 |
- Token: `HF_TOKEN` (env) or cached OAuth token from last authenticated user
|
| 96 |
- **Documents**: `articles/<name>.yjs` - debounced push on every Hocuspocus store
|
| 97 |
-
- **Published assets**: `published/<name>/{index.html, article.pdf, thumb.jpg, meta.json}`
|
| 98 |
-
- **Images**: `images/<uuid-filename>`
|
| 99 |
- `flushAll()` on `SIGTERM`/`SIGINT` to push pending changes
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
### 4.4 Publisher Pipeline
|
| 102 |
|
| 103 |
```mermaid
|
|
|
|
| 92 |
### 4.3 HF Storage
|
| 93 |
|
| 94 |
- Dataset ID: `HF_DATASET_ID` or `{SPACE_ID}-data`
|
| 95 |
+
- Dataset is created **private by default** (`createRepo({ private: true })`). The OAuth grant needs `manage-repos` on the user's first write; subsequent containers reuse the cached token.
|
| 96 |
- Token: `HF_TOKEN` (env) or cached OAuth token from last authenticated user
|
| 97 |
- **Documents**: `articles/<name>.yjs` - debounced push on every Hocuspocus store
|
| 98 |
+
- **Published assets**: `published/<name>/{index.html, article.pdf, thumb.jpg, meta.json, llms.txt}`
|
| 99 |
+
- **Images**: `images/<uuid-filename>` referenced from articles via `/d/images/...` proxy URLs
|
| 100 |
- `flushAll()` on `SIGTERM`/`SIGINT` to push pending changes
|
| 101 |
|
| 102 |
+
### 4.3.1 Dataset Reverse Proxy (`/d/*`)
|
| 103 |
+
|
| 104 |
+
Since the dataset is private, anonymous viewers of a published article can't fetch its images / PDF / og:image directly from `huggingface.co/datasets/...`. The editor server exposes `GET /d/:path*` as an authenticated forward-proxy:
|
| 105 |
+
|
| 106 |
+
- **Whitelist**: only `images/` and `published/` are reachable; `articles/` (raw `.yjs` drafts) is **always 404** regardless of caller.
|
| 107 |
+
- **Token cascade**: request cookie → cached user token → `HF_TOKEN` env → anonymous fetch. The cookie token is also promoted into the cache opportunistically, so the first signed-in viewer warms the proxy for subsequent anonymous viewers within the same container lifetime.
|
| 108 |
+
- **Streaming**: WHATWG body piped straight to the Express response - no buffering of full PDFs in Node memory.
|
| 109 |
+
- **Caching**: `images/*` is served as `immutable, max-age=1y` (UUID names, never overwritten); `published/*` as `max-age=300, stale-while-revalidate=60` (re-published in place).
|
| 110 |
+
- **Error mapping**: upstream 401/403 collapse to 502 so the browser never gets prompted for credentials it can't supply; upstream 404 passes through.
|
| 111 |
+
|
| 112 |
### 4.4 Publisher Pipeline
|
| 113 |
|
| 114 |
```mermaid
|
|
@@ -85,8 +85,10 @@ Data loss is game over for a collaborative editor.
|
|
| 85 |
|
| 86 |
| # | Test | Given / When / Then | Priority |
|
| 87 |
|---|------|---------------------|----------|
|
| 88 |
-
| 2.3.1 | Upload returns
|
| 89 |
| 2.3.2 | Reject oversized file | Given a file > 10MB / When POST /api/upload / Then response is 413 or 400 with error message | P1 |
|
|
|
|
|
|
|
| 90 |
|
| 91 |
---
|
| 92 |
|
|
|
|
| 85 |
|
| 86 |
| # | Test | Given / When / Then | Priority |
|
| 87 |
|---|------|---------------------|----------|
|
| 88 |
+
| 2.3.1 | Upload returns proxy URL | Given a valid image file / When POST /api/upload / Then response contains a `/d/images/...` URL routed through the editor's dataset proxy (the underlying HF dataset is private) | P1 |
|
| 89 |
| 2.3.2 | Reject oversized file | Given a file > 10MB / When POST /api/upload / Then response is 413 or 400 with error message | P1 |
|
| 90 |
+
| 2.3.3 | Proxy serves images | Given an uploaded image / When GET `/d/images/<file>` / Then 200 + image bytes (proxy attaches a server-side token to fetch the private HF dataset) | P1 |
|
| 91 |
+
| 2.3.4 | Proxy whitelist | Given any path under `/d/articles/...` (raw Y.js drafts) / When GET / Then 404 - never expose drafts via the proxy | P0 |
|
| 92 |
|
| 93 |
---
|
| 94 |
|