diff --git a/apps/cloud/src/pages.ts b/apps/cloud/src/pages.ts index bd6cbd2..ae12fd3 100644 --- a/apps/cloud/src/pages.ts +++ b/apps/cloud/src/pages.ts @@ -1,5 +1,6 @@ // The pages the Worker itself serves on public URLs: small, self-contained -// HTML with inline CSS and no external assets. +// HTML with inline CSS and no external assets, in Localify's look: neutral +// greys, Geist when the visitor has it, a near-black button, light and dark. /** Where the password form posts, on every protected host. */ export const ACCESS_PATH = "/__localify/access"; @@ -11,25 +12,53 @@ export const ABUSE_EMAIL = "abuse@localify.dev"; export const RETRY_AFTER_SECONDS = 60; const STYLE = ` -:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--text:#1b1b18;--muted:#5d5d57;--line:#d8d8d2;--accent:#1f5eff;--error:#b42318} -@media (prefers-color-scheme:dark){:root{--bg:#121211;--card:#1c1c1a;--text:#ededea;--muted:#a3a39c;--line:#383834;--accent:#7a9dff;--error:#ff8a80}} +:root{color-scheme:light dark;--bg:#fafafa;--card:#fff;--text:#171717;--muted:#737373;--line:#e5e5e5;--soft:#f5f5f5;--button:#171717;--button-text:#fafafa;--ring:#3b82f6;--error:#dc2626;--shadow:0 1px 0 rgba(13,13,13,.03),0 24px 48px -24px rgba(13,13,13,.14)} +@media (prefers-color-scheme:dark){:root{--bg:#0a0a0a;--card:#171717;--text:#fafafa;--muted:#a3a3a3;--line:#262626;--soft:#1f1f1f;--button:#fafafa;--button-text:#171717;--error:#f87171;--shadow:0 1px 0 rgba(0,0,0,.4),0 24px 48px -24px rgba(0,0,0,.6)}} *{box-sizing:border-box} -body{margin:0;min-height:100vh;display:grid;place-items:center;padding:16px;background:var(--bg);color:var(--text);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif} -main{width:100%;max-width:380px;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:28px} -h1{font-size:1.25rem;margin:0 0 8px} -p{margin:0 0 16px;color:var(--muted)} -.host{color:var(--text);font-weight:600;word-break:break-all} -label{display:block;font-weight:600;margin-bottom:6px} -input{width:100%;font:inherit;padding:10px 12px;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--text)} -input:focus-visible,button:focus-visible{outline:3px solid var(--accent);outline-offset:2px} -button{margin-top:16px;width:100%;font:inherit;font-weight:600;padding:10px 12px;border:0;border-radius:8px;background:var(--accent);color:#fff;cursor:pointer} -.error{color:var(--error);margin:12px 0 0} -a{color:var(--accent)} -a:focus-visible{outline:3px solid var(--accent);outline-offset:2px} -footer{margin-top:20px;font-size:.85rem;color:var(--muted)} +html{-webkit-text-size-adjust:100%} +body{margin:0;min-height:100vh;min-height:100dvh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;padding:32px 16px;background:var(--bg);color:var(--text);font:15px/1.6 "Geist Variable","Geist",ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased} +.brand{display:flex;align-items:center;gap:8px;font-weight:600;font-size:15px;letter-spacing:-.01em;color:var(--text)} +.brand svg{width:20px;height:20px} +main{width:100%;max-width:400px;background:var(--card);border:1px solid var(--line);border-radius:20px;padding:28px;box-shadow:var(--shadow)} +.title{position:relative;display:flex;align-items:center;gap:6px} +h1{margin:0;font-size:20px;line-height:1.3;font-weight:600;letter-spacing:-.025em} +p{margin:12px 0 0;color:var(--muted)} +strong{color:var(--text);font-weight:600} +.host{margin:2px 0 0;color:var(--muted);font:13px/1.5 ui-monospace,"Geist Mono",SFMono-Regular,Menlo,monospace;word-break:break-all} +.help summary{display:grid;place-items:center;width:22px;height:22px;border-radius:50%;color:var(--muted);cursor:pointer;list-style:none} +.help summary::-webkit-details-marker{display:none} +.help summary svg{width:16px;height:16px} +.help summary:hover,.help[open] summary{color:var(--text)} +.tip{position:absolute;left:0;right:0;top:calc(100% + 10px);z-index:1;padding:12px 14px;border:1px solid var(--line);border-radius:12px;background:var(--card);box-shadow:var(--shadow);font-size:13px;line-height:1.55} +.tip p{margin:0} +.tip p+p{margin-top:6px} +form{margin-top:20px} +.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap} +input{width:100%;font:inherit;padding:10px 12px;border:1px solid var(--line);border-radius:10px;background:var(--card);color:var(--text)} +input::placeholder{color:var(--muted)} +input[aria-invalid="true"]{border-color:var(--error)} +button{display:block;margin-top:12px;width:100%;font:inherit;font-weight:500;padding:10px 14px;border:0;border-radius:10px;background:var(--button);color:var(--button-text);cursor:pointer;transition:opacity .15s} +button:hover{opacity:.88} +input:focus-visible,button:focus-visible,a:focus-visible,summary:focus-visible{outline:2px solid var(--ring);outline-offset:2px} +.error{color:var(--error);margin:8px 0 0;font-size:14px} +a{color:var(--text);text-decoration:underline;text-decoration-color:var(--line);text-decoration-thickness:1.5px;text-underline-offset:4px} +a:hover{text-decoration-color:currentColor} +footer{font-size:13px;color:var(--muted)} footer a{color:inherit} +.signing{display:none;align-items:center;gap:12px;color:var(--muted)} +.spinner{flex:none;width:18px;height:18px;border:2px solid var(--line);border-top-color:var(--text);border-radius:50%;animation:spin .7s linear infinite} +@keyframes spin{to{transform:rotate(360deg)}} +@media (prefers-reduced-motion:reduce){.spinner{animation:none}} +[data-signing-in] main>:not(.signing){display:none} +[data-signing-in] .signing{display:flex} `; +/** The Localify mark, drawn inline: the pages load nothing else. */ +const LOGO = ``; + +/** A question mark in a circle: the explanation of a page sits behind it. */ +const HELP_ICON = ``; + /** Every page refuses to be framed, except the framed warning (see `framedWarningPage`). */ function csp(frameAncestors = "'none'"): string { return `default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors ${frameAncestors}; base-uri 'none'`; @@ -48,28 +77,28 @@ const SECURITY_HEADERS: Record = { /** * Signs in with the password a shared link carries after `#`. The fragment * never reaches a server, so it is read here, then cleared from the address - * bar and history before the form posts it. + * bar and history before the form posts it. It runs in ``, so the page + * shows "Signing in" from its first paint instead of the form. A page brought + * back from the history cache shows the form again. */ const SUBMIT_LINK_PASSWORD = `const hash = location.hash.slice(1); if (hash) { history.replaceState(null, "", location.pathname + location.search); - try { - const form = document.forms[0]; - form.password.value = decodeURIComponent(hash); - form.submit(); - } catch {} -}`; - -/** - * The same for a browser that has not acknowledged the warning: it fills the - * password in, and the visitor's `Continue` posts it with the acknowledgement. - */ -const FILL_LINK_PASSWORD = `const hash = location.hash.slice(1); -if (hash) { - history.replaceState(null, "", location.pathname + location.search); - try { - document.forms[0].password.value = decodeURIComponent(hash); - } catch {} + const root = document.documentElement; + root.dataset.signingIn = ""; + addEventListener("pageshow", (event) => { + if (event.persisted) delete root.dataset.signingIn; + }); + addEventListener("DOMContentLoaded", () => { + try { + const form = document.forms[0]; + form.password.value = decodeURIComponent(hash); + form.from.value = "link"; + form.submit(); + } catch { + delete root.dataset.signingIn; + } + }); }`; function page( @@ -91,23 +120,47 @@ function page( ${escapeHtml(title)} - +${nonce ? `\n` : ""} +
${LOGO}Localify
${body} -
-${nonce ? `\n` : ""} + + `; return new Response(method === "HEAD" ? null : html, { status, headers }); } -/** What the warning page says (ADR 0026), also on a shared link's page. */ +/** + * The heading every page starts with. Its explanation, when it has one, sits + * behind a `?` that a click, a tap or the keyboard opens, without scripts. + */ +function heading(title: string, help?: string): string { + const tip = help + ? `
${HELP_ICON}
${help}
` + : ""; + return `

${escapeHtml(title)}

${tip}
`; +} + +function hostLine(host: string): string { + return `

${escapeHtml(host)}

`; +} + +/** + * What the warning page says (ADR 0026), also on a shared link's page: who + * shared it in one line, the rest behind the `?`. + */ function noticeText(host: string, login: string): string { - return `

Before you continue

-

${escapeHtml(host)} is a development preview, served from a personal computer through Localify by GitHub user ${escapeHtml(login)}.

-

Continue only if you trust whoever sent you this link. Never enter passwords or payment details for another site here.

`; + const owner = `${escapeHtml(login)}`; + return `${heading( + "Before you continue", + `

This is a development preview, served from a personal computer through Localify by GitHub user ${owner}.

+

Never enter passwords or payment details for another site here.

`, + )} +${hostLine(host)} +

Shared by ${owner}. Continue only if you trust the sender.

`; } export type WarningPageOptions = { @@ -140,7 +193,7 @@ export function warningPage({
- +
`, method, ); @@ -185,7 +238,10 @@ export type PasswordPageOptions = { error?: string; status?: number; method?: string; - /** The page a shared link opens: it posts the password the link carries. */ + /** + * The page a shared link opens: it posts the password the link carries, + * with no click, warning or not (ADR 0036). + */ fromLink?: boolean; /** * When this browser has not acknowledged the warning yet: the owner's login @@ -205,25 +261,27 @@ export function passwordPage({ notice, }: PasswordPageOptions): Response { const errorId = error ? ` aria-describedby="password-error" aria-invalid="true"` : ""; - const intro = notice + const text = notice ? noticeText(host, notice.login) - : `

Password required

-

${escapeHtml(host)} is protected. Enter the password its owner shared with you.

`; - let script: string | undefined; - if (fromLink) script = notice ? FILL_LINK_PASSWORD : SUBMIT_LINK_PASSWORD; + : `${heading( + "Password required", + "

Its owner protected this public URL. Enter the password they shared with you, or open the link they sent.

", + )} +${hostLine(host)}`; return page( status, notice ? "Before you continue" : "Password required", - `${intro} + `${fromLink ? `
Signing in to ${escapeHtml(host)}…
\n` : ""}${text}
-${notice ? `\n` : ""} - + +${notice ? `\n` : ""} + ${error ? `` : ""}
`, method, - script, + fromLink ? SUBMIT_LINK_PASSWORD : undefined, ); } @@ -232,7 +290,7 @@ export function tooManyRequestsPage(method?: string): Response { const response = page( 429, "Too many requests", - `

Too many requests

+ `${heading("Too many requests")}

The public URLs of this owner received more requests in the last minute than Localify allows. Wait a minute, then reload this page.

`, method, ); @@ -244,7 +302,7 @@ export function notFoundPage(method?: string): Response { return page( 404, "No public URL here", - `

No public URL here

+ `${heading("No public URL here")}

Nothing is shared at this address. Check the link, or ask the person who sent it whether the URL still exists.

`, method, ); @@ -255,8 +313,8 @@ export function removedPage(method?: string): Response { return page( 410, "Removed", - `

This public URL was removed

-

It was taken offline for breaking the Localify terms. To report abuse, or if you think this is a mistake, write to abuse@localify.dev.

`, + `${heading("This public URL was removed")} +

It was taken offline for breaking the Localify terms. To report abuse, or if you think this is a mistake, write to ${ABUSE_EMAIL}.

`, method, ); } @@ -266,7 +324,7 @@ export function pausedPage(method?: string): Response { return page( 402, "Paused", - `

This public URL is paused

+ `${heading("This public URL is paused")}

Its owner's Localify Cloud plan does not cover it right now. Ask them to check their plan, then reload this page.

`, method, ); @@ -276,7 +334,7 @@ export function offlinePage(method?: string): Response { return page( 503, "Offline", - `

This public URL is offline

+ `${heading("This public URL is offline")}

The computer that serves it is not connected right now. Ask its owner to start Localify on it, then reload this page.

`, method, ); @@ -286,7 +344,7 @@ export function unreachablePage(method?: string): Response { return page( 502, "Not reachable", - `

Could not reach this public URL

+ `${heading("Could not reach this public URL")}

The computer that serves it did not answer. Reload the page in a moment. If it keeps failing, tell its owner.

`, method, ); @@ -296,7 +354,7 @@ export function unavailablePage(method?: string): Response { return page( 503, "Unavailable", - `

Public URLs are unavailable

+ `${heading("Public URLs are unavailable")}

Localify Cloud cannot serve this page right now. Try again in a few minutes.

`, method, ); diff --git a/apps/cloud/src/public.ts b/apps/cloud/src/public.ts index 1f2a36f..62d5e58 100644 --- a/apps/cloud/src/public.ts +++ b/apps/cloud/src/public.ts @@ -103,13 +103,14 @@ async function servePublic(request: Request, env: Env): Promise { } // Localify's own paths, on every URL. A link shared while the URL had a - // password still carries it after `#`, and redirecting to `/#` empties the - // fragment, which the browser would carry to the app. The access page shows - // the warning itself, so a link that carries the password takes one click. + // password still carries it after `#`, and redirecting to `#` empties + // the fragment, which the browser would carry to the app. A link that + // carries the password signs in and acknowledges the warning at once + // (ADR 0036). if (url.pathname === ACCESS_PATH) { if (site.protected) return handleAccess(request, env, site, host); await request.body?.cancel(); - return redirect("/#"); + return redirect(`${safeNext(url.searchParams.get("next"), host)}#`); } if (url.pathname === NOTICE_PATH) return handleNotice(request, env, site, host); @@ -321,11 +322,12 @@ async function hasAccess(request: Request, env: Env, site: Site, host: string): /** * `GET /__localify/access` is the page a shared link opens, with the password - * after `#`. Never a redirect: the browser would carry the fragment to the - * app's page. It posts the password by itself once the warning is - * acknowledged; before that, it shows the warning and waits for `Continue`, - * which posts the acknowledgement with the password. `POST` checks the - * password, sets the cookies, and redirects to `next`. + * after `#` and the page to land on in `?next=`. Never a redirect: the browser + * would carry the fragment to the app's page. It posts the password by + * itself, with the warning's form token when this browser has not + * acknowledged the warning yet (ADR 0036). Opened without a password, it + * shows the warning's text, or the plain password page once acknowledged. + * `POST` checks the password, sets the cookies, and redirects to `next`. */ async function handleAccess( request: Request, @@ -334,21 +336,23 @@ async function handleAccess( host: string, ): Promise { const method = request.method; + const acknowledged = + request.headers.has(SKIP_WARNING) || (await hasNoticeCookie(request, env, site, host)); + // The warning's text and a fresh form token, for a browser that has not + // acknowledged the warning. + const notice = async () => + acknowledged + ? undefined + : { login: site.ownerLogin, token: await signNoticeForm(setting(env, "COOKIE_KEY"), host) }; + if (method === "GET" || method === "HEAD") { - const acknowledged = - request.headers.has(SKIP_WARNING) || (await hasNoticeCookie(request, env, site, host)); return passwordPage({ host, - next: "/", + next: safeNext(new URL(request.url).searchParams.get("next"), host), status: 200, method, fromLink: true, - notice: acknowledged - ? undefined - : { - login: site.ownerLogin, - token: await signNoticeForm(setting(env, "COOKIE_KEY"), host), - }, + notice: await notice(), }); } if (method !== "POST") return redirect("/"); @@ -363,17 +367,12 @@ async function handleAccess( next: "/", status: 429, error: "Too many attempts. Wait a minute, then try again.", + notice: await notice(), }); } const form = await readForm(request); if (!form) return plain(413, "The form is too large."); const next = safeNext(form.get("next"), host); - // The shared link's page posts the warning's `Continue` with the password. - // The acknowledgement holds whether or not the password is right, and only - // when it comes from this exact host. - const notice = (await acknowledgedHere(request, env, host, form.get("notice"))) - ? await noticeCookie(env, site, host) - : null; const password = form.get("password") ?? ""; const valid = @@ -381,23 +380,30 @@ async function handleAccess( site.passwordSalt !== null && password !== "" && (await verifyPassword(password, { hash: site.passwordHash, salt: site.passwordSalt })); - let response: Response; - if (valid) { - const value = await signAccess(setting(env, "COOKIE_KEY"), { - host, - urlId: site.id, - version: site.passwordVersion, - }); - response = redirect(next); - response.headers.append("set-cookie", accessCookieHeader(value)); - } else { - response = passwordPage({ + if (!valid) { + // The link's page posts by itself, so a wrong password acknowledges + // nothing: the page comes back with the warning when it was not seen. + return passwordPage({ host, next, - error: "That password is not right. Check it and try again.", + error: + form.get("from") === "link" + ? "The password in this link no longer works. Ask for a new link, or enter the password." + : "That password is not right. Check it and try again.", + notice: await notice(), }); } - if (notice) response.headers.append("set-cookie", notice); + const value = await signAccess(setting(env, "COOKIE_KEY"), { + host, + urlId: site.id, + version: site.passwordVersion, + }); + const response = redirect(next); + response.headers.append("set-cookie", accessCookieHeader(value)); + // The warning's form token counts only from this exact host. + if (await acknowledgedHere(request, env, host, form.get("notice"))) { + response.headers.append("set-cookie", await noticeCookie(env, site, host)); + } return response; } diff --git a/apps/cloud/test/public.test.ts b/apps/cloud/test/public.test.ts index 8567aa9..e645a0e 100644 --- a/apps/cloud/test/public.test.ts +++ b/apps/cloud/test/public.test.ts @@ -169,6 +169,20 @@ describe("the password", () => { expect(machineCalls()).toHaveLength(0); }); + it("lands a shared link on the page in ?next=, on this host only", async () => { + const cases: [string, string][] = [ + ["/orders/42?tab=items", "/orders/42?tab=items"], + ["https://evil.example/", "/"], + ["//evil.example/", "/"], + ]; + for (const [next, expected] of cases) { + const query = new URLSearchParams({ next }).toString(); + const page = await visit(context, `https://${host()}/__localify/access?${query}`); + const html = await page.text(); + expect(html, next).toContain(`name="next" value="${expected.replaceAll("&", "&")}"`); + } + }); + it("redirects only to a path on the same host", async () => { const response = await signInWithPassword(host(), "https://evil.example/"); expect(response.headers.get("location")).toBe("/"); @@ -266,6 +280,8 @@ describe("the password", () => { expect(response.status, method).toBe(303); expect(response.headers.get("location"), method).toBe("/#"); } + const deep = await visit(context, `https://${host()}/__localify/access?next=%2Forders%2F42`); + expect(deep.headers.get("location")).toBe("/orders/42#"); expect(machineCalls()).toHaveLength(0); }); }); @@ -816,21 +832,25 @@ describe("caching of the app's responses", () => { }); describe("a shared link", () => { - it("shows the warning with the password filled in, for one click", async () => { - const page = await visit(context, `https://${host()}/__localify/access`, { + it("signs in by itself on a first visit, with the warning's token, and no click", async () => { + const page = await visit(context, `https://${host()}/__localify/access?next=%2Fdocs`, { headers: navigation, }); expect(page.status).toBe(200); const html = await page.text(); + // Without the fragment, or without scripts, the page is the warning with + // a password field. expect(html).toContain("Before you continue"); expect(html).toContain("teo-goulois"); expect(html).toContain('href="mailto:abuse@localify.dev"'); expect(html).toContain('action="/__localify/access"'); + expect(html).toContain('name="next" value="/docs"'); expect(html).toMatch(/name="notice" value="\d+\.[0-9a-f]{64}"/); expect(html).toContain('name="password"'); + expect(html).toContain("Signing in to"); expect(html).toContain("location.hash"); expect(html).toContain("history.replaceState"); - expect(html).not.toContain("submit()"); + expect(html).toContain("form.submit()"); const nonce = /