Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions CLAUDE.md

Large diffs are not rendered by default.

17 changes: 14 additions & 3 deletions api/_share-commit.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// v41 — Share links: check the manifest and the uploaded files, then publish
// the share by writing manifest.json. A share can be committed once.
import { ApiError, parseBody } from './_shared.js';
import { requireEnabled, store, checkKey, readId, pendingPath, sendError, siteOrigin } from './_share.js';
import { requireEnabled, store, checkKey, readId, pendingPath, expiryPath, sendError, siteOrigin } from './_share.js';
import { normalizeManifest, manifestAssets, sharePrefix, LIMITS, MANIFEST_NAME } from '../src/share/share-core.js';

export default async function handler(req, res) {
Expand All @@ -14,7 +14,9 @@ export default async function handler(req, res) {
if (!(await checkKey(cfg.secret, id, body.key))) throw new ApiError(403, 'Not your share');

let manifest;
try { manifest = normalizeManifest(body.manifest, { id, now: Date.now() }); } catch (e) { throw new ApiError(400, e.message); }
// v42 — `expiresIn` ('never' | '1d' | '7d' | '30d') sets the link's expiry;
// the time itself is stamped here, never taken from the client.
try { manifest = normalizeManifest(body.manifest, { id, now: Date.now(), expiresIn: body.expiresIn == null ? undefined : body.expiresIn }); } catch (e) { throw new ApiError(400, e.message); }

const st = store(cfg);
const prefix = sharePrefix(id);
Expand All @@ -37,7 +39,16 @@ export default async function handler(req, res) {
throw e;
}
await st.del([pendingPath(id)]);
res.status(201).json({ id, url: `${siteOrigin(req)}/s/${id}` });
if (manifest.expiresAt) {
// The marker only speeds up cleanup; the link stops working at its time
// either way, so a failed write is logged and the publish still stands.
try {
await st.put(expiryPath(id, Date.parse(manifest.expiresAt)), JSON.stringify({ id, expiresAt: manifest.expiresAt }), { contentType: 'application/json', cacheSeconds: 60 });
} catch (e) {
console.error('[share-commit] expiry marker', e);
}
}
res.status(201).json({ id, url: `${siteOrigin(req)}/s/${id}`, expiresAt: manifest.expiresAt || null });
} catch (e) {
sendError(res, e);
}
Expand Down
13 changes: 11 additions & 2 deletions api/_share-delete.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// v41 — Share links: delete every file of a share. Needs the owner key that
// share-create handed out (kept by the editor, or carried in a manage link).
import { ApiError, parseBody } from './_shared.js';
import { requireEnabled, store, checkKey, readId, pendingPath, sendError } from './_share.js';
import { requireEnabled, store, checkKey, readId, pendingPath, expiryPath, readManifest, sendError } from './_share.js';
import { sharePrefix } from '../src/share/share-core.js';

export default async function handler(req, res) {
Expand All @@ -15,7 +15,16 @@ export default async function handler(req, res) {
const st = store(cfg);
const files = await st.list(sharePrefix(id));
if (!files.length) throw new ApiError(404, 'This link is already gone.');
await st.del([...files.map((f) => f.pathname), pendingPath(id)]);
// v42 — a link with an expiry also has a marker for the sweep.
const extra = [pendingPath(id)];
try {
const found = await readManifest(st, id);
const t = found && typeof found.manifest.expiresAt === 'string' ? Date.parse(found.manifest.expiresAt) : NaN;
if (Number.isFinite(t)) extra.push(expiryPath(id, t));
} catch (e) {
console.error('[share-delete] expiry marker', e); // the sweep removes a stray marker
}
await st.del([...files.map((f) => f.pathname), ...extra]);
res.status(204).end();
} catch (e) {
sendError(res, e);
Expand Down
7 changes: 6 additions & 1 deletion api/_share-manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// The viewer uses this when the page was not served with the data inline.
import { ApiError } from './_shared.js';
import { requireEnabled, store, readId, readManifest, sendError } from './_share.js';
import { normalizeManifest } from '../src/share/share-core.js';
import { normalizeManifest, isExpired } from '../src/share/share-core.js';

export default async function handler(req, res) {
try {
Expand All @@ -15,6 +15,11 @@ export default async function handler(req, res) {
throw new ApiError(404, 'This link was removed, or it never existed.');
}
const manifest = normalizeManifest(found.manifest, { id });
// v42 — an expired link reads as gone, even before the sweep deletes it.
if (isExpired(manifest)) {
res.setHeader('Cache-Control', 'public, max-age=0, s-maxage=30');
throw new ApiError(404, 'This link has expired.');
}
res.setHeader('Cache-Control', 'public, max-age=30, s-maxage=60');
res.status(200).json({ manifest, base: found.base, report: cfg.reportEmail || null });
} catch (e) {
Expand Down
7 changes: 5 additions & 2 deletions api/_share-page.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { shareConfig, store, readManifest, siteOrigin } from './_share.js';
import { normalizeManifest, describeShare, isShareId } from '../src/share/share-core.js';
import { normalizeManifest, describeShare, isShareId, isExpired } from '../src/share/share-core.js';

export const SHARE_CSP = "default-src 'self'; img-src 'self' data: https://*.public.blob.vercel-storage.com; connect-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; frame-ancestors *; base-uri 'none'; form-action 'none'";

Expand Down Expand Up @@ -70,10 +70,13 @@ export default async function handler(req, res) {
const cfg = shareConfig();

let found = null;
let expired = false;
if (cfg.enabled && isShareId(id)) {
try {
const got = await readManifest(store(cfg), id);
if (got) found = { manifest: normalizeManifest(got.manifest, { id }), base: got.base };
// v42 — an expired link is served as a missing one.
if (found && isExpired(found.manifest)) { found = null; expired = true; }
} catch (e) {
console.error('[share-page]', e);
}
Expand All @@ -87,7 +90,7 @@ export default async function handler(req, res) {
return;
}

const data = found ? { manifest: found.manifest, base: found.base, report: cfg.reportEmail || null } : { missing: true };
const data = found ? { manifest: found.manifest, base: found.base, report: cfg.reportEmail || null } : { missing: true, ...(expired ? { expired: true } : {}) };
const html = fillTemplate(template, shareMeta({ ...(found || {}), origin, id: isShareId(id) ? id : null }), data);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Content-Security-Policy', SHARE_CSP);
Expand Down
23 changes: 20 additions & 3 deletions api/_share-sweep.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// v41 — Share links: daily cron. Removes uploads that were never published
// (a closed tab, a cancelled upload) once their pending marker is a day old.
// v42 — it also deletes links whose expiry has passed, found through the
// markers in shares-expiry/ (the time is in each marker's name).
import { ApiError } from './_shared.js';
import { requireEnabled, store, sendError, PENDING_PREFIX } from './_share.js';
import { requireEnabled, store, sendError, PENDING_PREFIX, EXPIRY_PREFIX } from './_share.js';
import { sharePrefix, isShareId, MANIFEST_NAME } from '../src/share/share-core.js';

const DAY_MS = 24 * 60 * 60 * 1000;
Expand All @@ -27,8 +29,23 @@ export default async function handler(req, res) {
await st.del([...files.map((f) => f.pathname), m.pathname]);
removed++;
}
console.log(`[share-sweep] removed ${removed} unpublished share(s)`);
res.status(200).json({ removed });
// Expired links, with whatever is left of this run's budget.
const now = Date.now();
let expired = 0;
const due = [];
for (const m of await st.list(EXPIRY_PREFIX)) {
const hit = /^(\d{1,16})-([A-Za-z0-9]{12})\.json$/.exec(m.pathname.slice(EXPIRY_PREFIX.length));
if (!hit) { due.push({ marker: m.pathname, id: null }); continue; }
if (Number(hit[1]) <= now) due.push({ marker: m.pathname, id: hit[2] });
}
for (const d of due.slice(0, Math.max(0, MAX_PER_RUN - markers.length))) {
if (!d.id) { await st.del([d.marker]); continue; }
const files = await st.list(sharePrefix(d.id));
await st.del([...files.map((f) => f.pathname), d.marker]);
if (files.length) expired++;
}
console.log(`[share-sweep] removed ${removed} unpublished share(s), ${expired} expired link(s)`);
res.status(200).json({ removed, expired });
} catch (e) {
sendError(res, e);
}
Expand Down
5 changes: 5 additions & 0 deletions api/_share.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import { shareKey, verifyKey, isShareId, MANIFEST_NAME, base64url } from '../src

export const PENDING_PREFIX = 'shares-pending/';
export const pendingPath = (id) => `${PENDING_PREFIX}${id}.json`;
// v42 — a link that expires leaves a marker whose NAME carries the time
// (`shares-expiry/<ms>-<id>.json`), so the daily sweep finds expired shares
// by listing one folder, without reading any manifest.
export const EXPIRY_PREFIX = 'shares-expiry/';
export const expiryPath = (id, ms) => `${EXPIRY_PREFIX}${Math.round(ms)}-${id}.json`;

// A Blob store connects in one of two ways: newer stores add BLOB_STORE_ID and
// the SDK signs in with the deployment's OIDC token; older ones add
Expand Down
Loading
Loading