diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0681daf..365b32f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -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
diff --git a/src/accesslog.ts b/src/accesslog.ts
index 22162c3..09bddaa 100644
--- a/src/accesslog.ts
+++ b/src/accesslog.ts
@@ -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",
@@ -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";
diff --git a/src/html.ts b/src/html.ts
index bde408f..f9d94fc 100644
--- a/src/html.ts
+++ b/src/html.ts
@@ -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.
@@ -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 `
@@ -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 = ``;
const pub = lim.pub;
diff --git a/src/index.ts b/src/index.ts
index 1e97cf0..02dfc00 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -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;
@@ -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) {
@@ -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}`));
}
@@ -730,7 +730,7 @@ async function authenticate(req: Request, env: Env, ctx: ExecutionContext): Prom
async function route(req: Request, env: Env, ctx: ExecutionContext): Promise {
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 });
@@ -803,7 +803,7 @@ async function route(req: Request, env: Env, ctx: ExecutionContext): Promise {
}
})();
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]); }
diff --git a/src/util.ts b/src/util.ts
index 022ff13..e8b2cd9 100644
--- a/src/util.ts
+++ b/src/util.ts
@@ -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 `, `X-API-Key` or `?token=`. */
diff --git a/test/util.test.ts b/test/util.test.ts
index eeaa74d..1969ad7 100644
--- a/test/util.test.ts
+++ b/test/util.test.ts
@@ -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);
@@ -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);
+ });
+});