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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
with:
node-version: 26
cache: npm
- run: npm ci --prefer-offline --no-audit --no-fund
- run: npm ci --ignore-scripts --prefer-offline --no-audit --no-fund
- run: npm run typecheck
- run: npm test
- run: npm run build
Expand Down
4 changes: 3 additions & 1 deletion src/accesslog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// ("invocation_logs": false) and rely on this line instead: no query string, file/text/link ids,
// deletion codes and claim codes are masked, and only a few harmless headers are kept.

import { trimTrailingSlashes } from "./util";

const KEEP = new Set([
"/", "/robots.txt", "/sitemap.xml", "/og.png", "/og-card", "/llms.txt", "/health", "/request",
"/privacy", "/datenschutz", "/imprint", "/impressum", "/terms", "/nutzungsbedingungen", "/content-policy", "/inhaltsrichtlinie",
Expand All @@ -11,7 +13,7 @@ const KEEP = new Set([

/** The request path with everything that could open, delete or claim something replaced by a placeholder. */
export function logPath(pathname: string): string {
const p = pathname.replace(/\/+$/, "") || "/";
const p = trimTrailingSlashes(pathname) || "/";
if (KEEP.has(p) || /^\/(assets\/[\w./-]+|favicon[\w.-]*)$/.test(p)) return p;
if (p.startsWith("/api/items/")) return "/api/items/:id";
if (p.startsWith("/api/")) return "/api/:other";
Expand Down
7 changes: 5 additions & 2 deletions src/html.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { bloomSvg, faviconSvg } from "./bloom";
import { brandFrom, type Brand } from "./brand";
import type { Item } from "./index";
import { trimTrailingSlashes } from "./util";

/* drop - UI following the shiftbloom studio brand book v2.
* Paper & ink with one loud flower: Bloom Red for actions and seeds, gradients only inside the mark.
Expand Down Expand Up @@ -119,7 +120,7 @@ function landingMeta(origin: string) {
isAccessibleForFree: true,
license: "https://www.gnu.org/licenses/agpl-3.0.html",
offers: { "@type": "Offer", price: "0", priceCurrency: "EUR" },
...(o ? { publisher: { "@type": "Organization", ...(o.url ? { "@id": `${o.url.replace(/\/+$/, "")}/#org` } : {}), name: o.name, ...(o.url ? { url: o.url } : {}) } } : {}),
...(o ? { publisher: { "@type": "Organization", ...(o.url ? { "@id": `${trimTrailingSlashes(o.url)}/#org` } : {}), name: o.name, ...(o.url ? { url: o.url } : {}) } } : {}),
sameAs: [sourceUrl()],
};
return `<meta name="description" content="${esc(SITE_DESC)}"><link rel="canonical" href="${esc(origin)}/">
Expand All @@ -133,7 +134,9 @@ function landingMeta(origin: string) {
/** `pub` is set when visitors without a token may upload (see public.ts). */
export type Limits = { multiMb: number; maxMb: number; pub?: { siteKey: string; maxMb: number; pasteKb: number } };

export function landingPage(host: string, lim: Limits = { multiMb: 95, maxMb: 500 }, origin = `https://${host}`) {
const DEFAULT_LIMITS: Limits = { multiMb: 95, maxMb: 500 };

export function landingPage(host: string, lim: Limits = DEFAULT_LIMITS, origin = `https://${host}`) {
// the token check runs before first paint, so visitors never see the tool flash
const early = `<script>try{if(localStorage.getItem('drop_token'))document.documentElement.classList.add('authed')}catch(e){}</script>`;
const pub = lim.pub;
Expand Down
16 changes: 8 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { sniff, blockReason, effectiveType, INLINE_TYPES, stripJpegLocation, str
import { brandFrom, type BrandEnv } from "./brand";
import { CHECKING, NOT_CHECKED, limitKey, PUBLIC_ACTION, PUBLIC_ID_LENGTH, PUBLIC_OWNER, PUBLIC_PREFIX, publicEnabled, publicExpiry, publicLimits, publicTypeAllowed, publicNameMatches, PUBLIC_TYPES, PUBLIC_GIF_MAX_FRAMES, PUBLIC_GIF_MAX_PIXELS, PUBLIC_GIF_MAX_WORK, usageKey, utcDay, withinDailyCap, type PublicEnv, type PublicLimits } from "./public";
import { mandatePrincipal, type MandateEnv } from "./mandate";
import { randomString, timingSafeEqual, parseExpiry, extOf, isAuthed, isNamedToken, requestToken, sha256Hex, tokenUsable, sanitizeName, robotsTxt, ownerFilter, canManage, MASTER_OWNER, type Principal } from "./util";
import { randomString, timingSafeEqual, parseExpiry, extOf, isAuthed, isNamedToken, requestToken, sha256Hex, tokenUsable, sanitizeName, robotsTxt, trimTrailingSlashes, ownerFilter, canManage, MASTER_OWNER, type Principal } from "./util";

export interface Env extends BrandEnv, PublicEnv, MandateEnv, PostHogEnv {
FILES: R2Bucket;
Expand Down Expand Up @@ -135,7 +135,7 @@ const viaOf = (p: Principal) => (p.owner === PUBLIC_OWNER ? "public" : p.check ?

/** item_created: kind, rough size, general type and where it came from. Never the name, id or content. */
function trackItem(env: Env, ctx: ExecutionContext | undefined, req: Request, it: Item, p: Principal) {
phCapture(env, ctx, "item_created", { kind: it.kind, size_bucket: it.kind === "link" ? null : sizeBucket(it.size), type_group: it.kind === "file" ? typeGroup(it.mime) : it.kind, source: sourceOf(req), via: viaOf(p), expires: it.expires_at ? "set" : "never" });
void phCapture(env, ctx, "item_created", { kind: it.kind, size_bucket: it.kind === "link" ? null : sizeBucket(it.size), type_group: it.kind === "file" ? typeGroup(it.mime) : it.kind, source: sourceOf(req), via: viaOf(p), expires: it.expires_at ? "set" : "never" });
}

async function cacheItem(env: Env, it: Item) {
Expand Down Expand Up @@ -473,7 +473,7 @@ async function handleTokenRequest(req: Request, env: Env, url: URL, ctx?: Execut
const code = newClaimCode();
await env.DB.prepare("INSERT INTO token_requests (id, name, reason, claim_hash, status, created_at) VALUES (?, ?, ?, ?, 'pending', ?)")
.bind(randomString(12), v.name, v.reason, await sha256Hex(code), now).run();
phCapture(env, ctx, "token_requested", {});
void phCapture(env, ctx, "token_requested", {});
return reqHtml(requestSentPage(`${url.origin}/request/${code}`));
}

Expand Down Expand Up @@ -730,7 +730,7 @@ async function authenticate(req: Request, env: Env, ctx: ExecutionContext): Prom

async function route(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname.replace(/\/+$/, "") || "/";
const path = trimTrailingSlashes(url.pathname) || "/";
const m = req.method;

const ph = await phProxy(req, env, { app: "drop", keep: PH_KEEP });
Expand Down Expand Up @@ -803,7 +803,7 @@ async function route(req: Request, env: Env, ctx: ExecutionContext): Promise<Res
// another token's item looks exactly like a missing one
if (!it || !canManage(who, it.owner)) return err(404, "not found");
if (who.check) { const no = await who.check({ action: m === "DELETE" ? "delete" : "list", path: it.name ?? "" }); if (no) return no; }
if (m === "DELETE") { await deleteItem(env, it); phCapture(env, ctx, "item_deleted", { kind: it.kind, by: "api", via: viaOf(who) }); return json({ deleted: it.id }); }
if (m === "DELETE") { await deleteItem(env, it); void phCapture(env, ctx, "item_deleted", { kind: it.kind, by: "api", via: viaOf(who) }); return json({ deleted: it.id }); }
if (m === "GET") return json({ ...it, ...links(req, it) });
if (m === "POST" && url.searchParams.get("reanalyze") !== null) { await env.JOBS.send({ type: "scan", id: it.id }); return json({ queued: it.id }); }
if (m === "POST" && url.searchParams.get("release") !== null) {
Expand All @@ -825,7 +825,7 @@ async function route(req: Request, env: Env, ctx: ExecutionContext): Promise<Res
// GET only asks: link previews and crawlers that open a deletion URL must not delete anything
if (m === "GET") return new Response(deletePage(it.name || it.id, false), { headers: htmlHeaders("no-store") });
await deleteItem(env, it);
phCapture(env, ctx, "item_deleted", { kind: it.kind, by: "deletion_link" });
void phCapture(env, ctx, "item_deleted", { kind: it.kind, by: "deletion_link" });
if (m === "DELETE") return new Response(`deleted ${it.id}\n`, { headers: { "content-type": "text/plain" } });
return new Response(deletePage(it.name || it.id, true), { headers: htmlHeaders("no-store") });
}
Expand Down Expand Up @@ -874,7 +874,7 @@ async function handle(req: Request, env: Env, ctx: ExecutionContext): Promise<Re
return r;
} catch (e) {
console.error("unhandled", String(e), (e as Error)?.stack);
phException(env, ctx, e, { where: "fetch" });
void phException(env, ctx, e, { where: "fetch" });
return err(500, "internal error");
}
}
Expand All @@ -895,7 +895,7 @@ export default {
msg.ack();
} catch (e) {
console.error("job failed", msg.body, String(e));
phException(env, ctx, e, { where: "queue", job: msg.body.type });
void phException(env, ctx, e, { where: "queue", job: msg.body.type });
msg.retry({ delaySeconds: 30 });
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/node/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ export class LocalQueue<T> {
}
})();
this.pending.add(run);
run.finally(() => this.pending.delete(run));
void run.finally(() => this.pending.delete(run));
}
/** Waits for running jobs; drops scheduled retries. */
async drain() { this.closed = true; for (const t of this.timers) clearTimeout(t); await Promise.allSettled([...this.pending]); }
Expand Down
7 changes: 7 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ export function timingSafeEqual(a: string, b: string) {
}

/** Prefix of named API tokens (issued from an admin hub and stored hashed in D1). */
/** `s` without trailing slashes; a linear scan instead of /\/+$/, which backtracks on long runs of slashes. */
export function trimTrailingSlashes(s: string) {
let end = s.length;
while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
return end === s.length ? s : s.slice(0, end);
}

export const TOKEN_PREFIX = "drop_";

/** The token a request carries: `Authorization: Bearer <token>`, `X-API-Key` or `?token=`. */
Expand Down
18 changes: 17 additions & 1 deletion test/util.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { extOf, isAuthed, isNamedToken, requestToken, sha256Hex, tokenUsable, parseExpiry, randomString, sanitizeName, timingSafeEqual, ID_ALPHABET, ownerFilter, canManage } from "../src/util";
import { extOf, isAuthed, isNamedToken, requestToken, sha256Hex, tokenUsable, parseExpiry, randomString, sanitizeName, timingSafeEqual, ID_ALPHABET, ownerFilter, canManage, trimTrailingSlashes } from "../src/util";

const now = () => Math.floor(Date.now() / 1000);

Expand Down Expand Up @@ -100,3 +100,19 @@ describe("history is private per token", () => {
expect(canManage(master, "other")).toBe(true);
});
});

describe("trimTrailingSlashes", () => {
it("strips only trailing slashes", () => {
expect(trimTrailingSlashes("/api/items///")).toBe("/api/items");
expect(trimTrailingSlashes("/a//b")).toBe("/a//b");
expect(trimTrailingSlashes("///")).toBe("");
expect(trimTrailingSlashes("")).toBe("");
expect(trimTrailingSlashes("https://example.com/")).toBe("https://example.com");
});
it("stays fast on long runs of slashes", () => {
const s = "/".repeat(200_000) + "x";
const t = performance.now();
expect(trimTrailingSlashes(s)).toBe(s);
expect(performance.now() - t).toBeLessThan(50);
});
});