Compare commits

..
Author SHA1 Message Date
Dmitry Verkhoturov d534247c5a Pin the public path #2203 fixed, which shipped without a test
The bundler used to bake a fixed public path into every entry, so an
instance mounted under a prefix, which manuals/subdomain documents,
asked the domain root for its provider icons and got nothing. #2197
derived the path from the URL the bundle was loaded from instead, and
covered it with nothing: publicPath appears only in webpack.config.js
and neither suite touched asset paths.

The check is on the assignment webpack emits for its runtime public
path, a string literal when the path is fixed and an expression when it
is derived. Asset filenames are bare in both builds, so the obvious
assertion, looking for a rooted "/web/name.svg" string, finds nothing
either way and proves nothing. I wrote that one first and it passed
against a deliberately broken build.

Every emitted bundle is checked rather than the entry the bug was
reported against: it put fifteen icons in remark.mjs and one in
last-comments.mjs, so a case reading a single entry would have gone
green with half of it still live.

Verified by rebuilding the frontend with the public path baked back in:
the assertion fails on that build and passes on master's.
2026-08-23 21:22:42 +01:00
Dmitry Verkhoturov 75e1b69342 Judge the iframe reveal by the mark, not by when the read lands
Three cases separate a reveal that came from the inited message from one that
came from the five second fallback, and two of them did it against a clock this
process holds. That is a bet on how fast an engine is, and both bets lose on a
loaded machine: TestIframe_StaysHiddenUntilTheDocumentReportsInited polled the
DOM after a loop bounded 500ms below the fallback, and an evaluate round trip
outlasts that margin, so a fallback firing exactly on time reads as an early
reveal; TestIframe_IsRevealedByTheInitedMessage capped the message path at 3s,
and webkit has reported inited 2.6s after creation here.

All three now judge the recorded reveal against one cutoff, half a second under
the fallback. A timer cannot fire early, so below it the reveal can only be the
message and above it only the fallback, and the mark carries the moment itself,
so a slow read cannot move it. The hidden case drops its polled visibility
assertion for the same mark, which is what the observer records in the first
place.
2026-08-23 21:22:42 +01:00
8 changed files with 128 additions and 356 deletions
+1 -1
View File
@@ -102,7 +102,7 @@ type ServerCommand struct {
Cookie time.Duration `long:"cookie" env:"COOKIE" default:"200h" description:"auth cookie TTL"`
} `group:"ttl" namespace:"ttl" env-namespace:"TTL"`
SendJWTHeader bool `long:"send-jwt-header" env:"SEND_JWT_HEADER" description:"also send JWT as a header, so the frontend can store it in a client-side cookie that survives third-party cookie blocking; server-set cookies are still sent (note: increases vulnerability to XSS attacks)"`
SendJWTHeader bool `long:"send-jwt-header" env:"SEND_JWT_HEADER" description:"send JWT as a header instead of server-set cookie; with this enabled, frontend stores the JWT in a client-side cookie (note: increases vulnerability to XSS attacks)"`
SameSite string `long:"same-site" env:"SAME_SITE" description:"set same site policy for cookies" choice:"default" choice:"none" choice:"lax" choice:"strict" default:"default"` // nolint
Apple AppleGroup `group:"apple" namespace:"apple" env-namespace:"APPLE" description:"Apple OAuth"`
+1 -4
View File
@@ -271,14 +271,11 @@ func TestRest_securityHeaders(t *testing.T) {
client := http.Client{}
resp, err := client.Get(ts.URL + "/web/index.html")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Contains(t, resp.Header.Get("Content-Security-Policy"), "img-src *;")
assert.Equal(t, "nosniff", resp.Header.Get("X-Content-Type-Options"))
assert.Equal(t, "strict-origin-when-cross-origin", resp.Header.Get("Referrer-Policy"))
// httptest.Server.Close waits on connections still in use, and a deferred close does not run
// until the test ends, so the body has to be released before the server is torn down here
require.NoError(t, resp.Body.Close())
client.CloseIdleConnections()
teardown()
// check CSP with proxy enabled
+1 -4
View File
@@ -573,12 +573,9 @@ func TestRest_frameAncestors(t *testing.T) {
client := http.Client{}
resp, err := client.Get(ts.URL + "/web/index.html")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Contains(t, resp.Header.Get("Content-Security-Policy"), "frame-ancestors 'self' https://example.com;")
// httptest.Server.Close waits on connections still in use, and a deferred close does not run
// until the test ends, so the body has to be released before the server is torn down here
require.NoError(t, resp.Body.Close())
client.CloseIdleConnections()
teardown()
// test case without frame-ancestors
+57 -254
View File
@@ -1,9 +1,9 @@
# Frontend direction: two viable paths, and what has to be true for either
Written 2026-08-19, revised 2026-08-24. Every file reference below was re-checked against master
`7de51ad2`. The frontend work merged since 2026-08-22 is treated here as landed: it changes the e2e
net, the manifest layout, the fallback page, the asset path and the instance URL, and costing either
direction against the state before it would be costing a world that no longer exists.
Written 2026-08-19, revised 2026-08-22. Every file reference below was re-checked against master
`a82dc8d3` plus #2196, #2197 and #2198, which are treated here as landed: they change the e2e net,
the manifest layout, the fallback page, the asset path and the instance URL, and costing either
direction against the state before them would be costing a world that no longer exists.
## Overview
@@ -33,170 +33,23 @@ users report against most. The target arrangement is remark42 serving from its o
documented in `site/content/docs/manuals/separate-domain/index.md`, so operators follow it and then
find that authentication behaves differently from the same-domain case.
**Acceptance criteria.** A reader on `food.com` signs in through email, Telegram or anonymous,
posts, reloads the page, and is still signed in, on a browser that blocks unpartitioned third-party
cookies. Nothing short of the reload proves it: the widget holds a token in memory for the life of a
page, so a test that signs in and posts without reloading passes while the persistence is entirely
broken.
**Acceptance criteria.** A reader on `food.com` can sign in with any configured provider, post,
reload the page, and still be signed in, on a browser that blocks unpartitioned third-party cookies.
Nothing short of the reload proves it: the widget holds a token in memory for the life of a page, so
a test that signs in and posts without reloading passes while the persistence is entirely broken.
**Two things about this criterion are decisions, not findings, and they belong to the
maintainer.** They are marked so neither is settled by implication.
**Where that stands.** The e2e suite covers the rendering half through
`TestCrossOrigin_WidgetRendersOnAnotherOrigin`, which proves the document loads on another origin
and reports itself through postMessage across the boundary, and `ALLOWED_HOSTS` refusal through
`TestCrossOrigin_DisallowedHostNeverReportsInited`. The authentication half is not covered and
cannot be until the e2e stack speaks https, because an embedded cookie needs `SameSite=None`, which
browsers accept only with `Secure`.
The first is that it excludes OAuth, where the requirement as originally written said any configured
provider. That is a narrowing of product scope, not a correction of fact. OAuth off-domain fails for
the flow as built on any browser that blocks or partitions third-party cookies, which is Safari's
default; under the recommended recipe, which drops `AUTH_SAME_SITE=none`, it fails on the remaining
browsers too. The routes priced below would change that, and the narrowing sits awkwardly beside
`fixing #1139 must not get harder` in the Path B constraints, which is the same subject. Either the
requirement excludes OAuth and #1139 is a separate goal carrying its own timeline, or the
requirement keeps OAuth and is not met today. This document assumes the first and is not entitled to
assume it.
The second is what counts as evidence, and the criterion is not met end to end by any single run.
The criterion asks for sign-in, a post and a reload. The permanent suite covers sign-in, post and
reload for anonymous and email, but on Chromium's default policy and against a stack running
`AUTH_SAME_SITE=none` alongside the header, which is not the recommended recipe; the blocking case
adds the control and the reload but does not post. The cross-browser campaign covered sign-in,
reload and the controls on the recommended recipe, and did not post. So persistence is measured and
posting-after-reload is not, on the same run. Taking those together, the criterion is met for
anonymous and email by measurement,
and for Telegram by inference from the client writer keying off `X-JWT` and not off the provider. A
standing requirement is meant to be a test a proposal passes, so either inference is acceptable
evidence here and the section should say so, or Telegram leaves the criterion partly pending until
#2208 and `go-pkgz/auth` #316 make it measurable.
OAuth sits outside that criterion as the flow is built today. The provider callback is a top-level
navigation in a popup, so `Service.Set` writes its
cookie there as an ordinary first-party cookie for the auth host, carrying no `Partitioned` and so
having no partition key at all. The frame on `food.com` sees it only as an unpartitioned third-party
cookie, which is exactly what a blocking browser refuses. The cookie is `HttpOnly` besides, so the
popup cannot read it and hand it over in script. `SameSite` is not what obstructs this: the
separate-domain manual has operators set `AUTH_SAME_SITE=none`, and the callback navigation is
top-level regardless.
Two routes could bring OAuth inside the criterion, and both need costing before either is called
mandatory.
The first is the Storage Access API, which exists for exactly this shape: an embedded frame asks
the browser, on a user gesture, for permission to send its own unpartitioned first-party cookies,
and Safari, Chrome and Firefox all implement it. Note what the grant is and is not. It lets the
frame's
requests carry that cookie; it does not make the cookie script-readable, and the JWT cookie is
`HttpOnly` in any case, which is the same point the OAuth paragraph above makes.
It is also not available to remark42 as the flow stands, which is the part worth pricing. That much
is read off documented browser policy and the code, not measured: nothing in the campaign called
`requestStorageAccess`. A browser
denies the request outright when the embedded origin has no recent first-party interaction to
grant against, and remark42 never acquires one: the reader interacts on the provider's origin, and
the callback returns to the remark42 origin at a document whose first statement is `window.close()`
under `?selfClose` in `iframe.ejs`. Nothing happens there that a browser counts as interaction.
So the cost is not a permission prompt bolted onto the existing flow. Either the callback stops
closing itself and collects a click first, or something else establishes first-party interaction on
the instance's own origin before the frame ever asks. That is a change to the first-party
experience, which is a different order of cost from either handoff shape and has to be weighed as
one.
The second is a server-mediated handoff, where the popup posts a one-time code to its opener and
the frame redeems it over XHR. Two shapes exist there and they cost differently. If the redemption
answers with `Set-Cookie`, that cookie has to carry `Partitioned` to
be stored at all, which is the upstream library work described below. If it answers with `X-JWT`
instead, `fetcher.ts` writes the partitioned pair itself and nothing upstream has to change, which
makes it the cheaper of the two. Both handoff shapes are backend features and out of scope here; the
Storage Access
route is not, and is the one worth pricing first for that reason. Until something lands, an
operator who needs OAuth off-domain serves remark42 from the same registrable domain as the site,
or accepts that OAuth readers sign in on the instance's own origin.
**Where that stands.** Master satisfies the criterion today on every browser measured except one,
provided `AUTH_SEND_JWT_HEADER` is on. The exception is Firefox with "block all third-party cookies"
chosen, which discards partitioned cookies too and which no configuration survives.
The server returns the token in `X-JWT` and `fetcher.ts` writes the `JWT` and `XSRF-TOKEN` cookies
itself through `authCookieOptions`, which marks them `SameSite=None; Secure; Partitioned` in a
third-party context. The attribute is what carries the reload, not the fact that the write happened
in the frame: `activeJwtToken` in `fetcher.ts` is a module-level variable filled only from the
response header, nothing ever reads the `JWT` cookie back, and `getCookie` is called once in the
whole app for `XSRF-TOKEN`. So the first request after a reload sends no header and the token
arrives as an ambient cookie, third-party by definition inside the frame, and survives only because
it is partitioned. #2214's control cookie encodes exactly that: an unpartitioned `SameSite=None`
cookie written by the same script in the same frame has to be dropped, or the case declares itself
vacuous.
**Measured across three engines and four browser targets, and the mechanism is not uniform.** The
above was reasoned from the code and verified on Chromium. Driving the real thing on two genuinely
different registrable domains with real certificates, across Chromium, Firefox, WebKit and Safari
27, shows the recommended arrangement working everywhere except one case, and working for two
different reasons.
On Chromium, WebKit and Safari the server's own pair does not reach the frame, and the widget's
partitioned pair is what the session runs on. The reason the server pair is absent differs by
engine: on Chromium `AUTH_SAME_SITE` defaults to emitting no `SameSite` at all and Chromium treats
a missing attribute as `Lax`, so the cookie is not sent cross-site; on WebKit and Safari it is
third-party blocking, which applies whatever the attribute says. Only the outcome was measured; the
causes are read off documented browser behaviour.
The two pairs are not in competition. CHIPS makes the partition key part of a cookie's identity, so
a partitioned cookie and an unpartitioned one of the same name are different cookies and coexist:
#2218 measured all four at once on Chromium with both settings on. Firefox is the exception
precisely because Total Cookie Protection files the server's cookie under the embedder's partition,
which makes the keys match, and a script may not replace an `HttpOnly` cookie whose key it collides
with.
On Firefox the server's pair is accepted, and since the `JWT` it sets is `HttpOnly`, the browser
then forbids the widget's script from replacing a cookie of that name. So Firefox never holds a
partitioned copy of its own, and the session rides on the server's cookie instead. Under Firefox's
default, Total Cookie Protection, that cookie carries no `Partitioned` attribute but the browser
stores it in a per-site partition anyway, which is why it survives. Its opt-in "block all
third-party cookies" discards partitioned cookies as well, so nothing survives it and nothing in
remark42 can change that.
Safari is the sharp end: it blocks third-party cookies with nothing configured, so
`AUTH_SAME_SITE=none`
on its own has already stopped working there for every reader. The old recipe is not deprecated, it
is broken, which is the strongest argument for treating R1 as live work and not a documented
limitation.
**That changes what the upstream `Partitioned` work is worth.** Building `go-pkgz/auth` with a
`PartitionedCookies` option and running the same matrix gives the same persistence with the server's
`JWT` still `HttpOnly`: on Safari, `document.cookie` inside the frame returns the token under the
header flag and does not under the partitioned build, while both keep the reader signed in. So the
two routes are not equivalent, and the header path's token exposure is avoidable, not inherent.
`go-pkgz/auth` #318 carries that change with the measurements behind it.
The documentation gap this section named is closed by #2218. The separate-domain manual now
recommends `AUTH_SEND_JWT_HEADER=true` and carries the XSS trade-off in the same breath, and the
parameter page no longer promises `SameSite=Strict` cookies and a `__Host-` prefix that
`authCookieOptions` stopped emitting in a third-party context at #2197. That PR also measured
`AUTH_SAME_SITE=none` out of the recommended recipe: on Chromium, where that jar was read, the
header flag leaves it adding an unpartitioned `HttpOnly` JWT to third-party delivery and
contributing nothing to persistence. Safari drops that pair outright and Firefox delivers it either
way, so the setting is dead weight on all three for different reasons.
The e2e suite covers the rendering half through `TestCrossOrigin_WidgetRendersOnAnotherOrigin`,
which proves the document loads on another origin and reports itself through postMessage across the
boundary, and `ALLOWED_HOSTS` refusal through `TestCrossOrigin_DisallowedHostNeverReportsInited`.
#2214 added the authentication half over TLS, the reload included, and runs it once more
against a browser configured to block third-party cookies. That second case needs
`IgnoreDefaultArgs`, because Playwright's own `--disable-features` list switches partitioning off
and beats the flags passed through `Args`, which would leave the case asserting nothing.
`TestHTTPS_CrossOriginSignInSurvivesAReload` and `TestHTTPS_SessionSurvivesThirdPartyCookieBlocking`
are table-driven over two flows, so anonymous and email are each measured in a third-party frame
with the reload, and each again under enforced partitioning, the blocking case giving every subtest
its own control cookie and its own partitioned-JWT guard in a fresh context so neither can pass
vacuously. `TestHTTPS_AuthCookiesCarryTheThirdPartyForm` is the third and reads the attributes out
of the browser store directly. Telegram is the one of the three still resting on inference. It is
exercised nowhere and cannot be until #2208 makes the Telegram API base URL configurable, because
without that the stack cannot answer as Telegram; `go-pkgz/auth` #316 is the change that would let
the suite measure it. The inference itself is that the client-side writer keys off `X-JWT` on any
auth response and not off the provider, so nothing in it distinguishes one flow from another. The
distinction is worth keeping visible, because a criterion resting on flows the suite cannot reach
asserts more than the evidence holds, which is the defect this section exists to avoid.
`ALLOWED_HOSTS` sets the CSP `frame-ancestors` and `AUTH_SAME_SITE=none` lets the server's auth
cookies be set from any embedding domain. Those server-set cookies carry no `Partitioned`, so they
are the ones Chromium, WebKit and Safari drop; Firefox keeps them, which is why it never holds a
partitioned copy of its own. What survives the drop is the header fallback above.
`ALLOWED_HOSTS` sets the CSP `frame-ancestors` and `AUTH_SAME_SITE=none` lets auth cookies be set
from any embedding domain. OAuth is what visibly fails off-domain (discussion #1139). Telegram,
email and anonymous work where third-party cookies are still permitted, and stop working where they
are not: the server's cookies carry no `Partitioned`, and the header fallback is off by default, so
nothing saves them once the browser blocks unpartitioned third-party cookies.
There is a second mechanism aimed squarely at this, `AUTH_SEND_JWT_HEADER`, which returns the token
in a response header so the client can present it without relying on an ambient cookie. #1877 was
@@ -205,11 +58,8 @@ first half. Its persistence never worked on https: the client wrote its copy und
prefix that neither the backend nor the widget's own reader ever asks for, and marked it
`SameSite=Strict`, which is never sent from a third-party frame. Both are corrected here, and the
frontend now marks its cookies `SameSite=None; Secure; Partitioned` when it detects a third-party
context. The server-set cookies are untouched and still carry no `Partitioned`. That is what makes
the upstream work matter, not what excuses it: `AUTH_SEND_JWT_HEADER` defaults to false, so in the
configuration remark42 actually ships nothing writes a partitioned cookie anywhere, and partitioning
the server's pair is what would carry email, anonymous and Telegram off-domain without asking
operators for a flag that exposes the token to script.
context. The server-set cookies still need the same treatment, and that is upstream work in
`go-pkgz/auth`.
Constraints on any frontend design:
@@ -220,28 +70,19 @@ Constraints on any frontend design:
outright and honours only cookies explicitly marked `Partitioned`; its CHIPS support has been
switched on, off and on again across releases, so pin the current state before relying on a
version number. A design depending on `SameSite=None` surviving has an expiry date
- the endpoint is CHIPS (`SameSite=None; Secure; Partitioned`) either way, and the only question is
who writes the cookie. The header path is not a token free of ambient cookies: it holds the token
in memory for one page, and after a reload the browser sends the partitioned cookie the frontend
wrote. Both routes stand on the same attribute and differ only in whether the server or the
frontend sets it, plus the token-theft exposure the frontend writer carries.
Neither is a flag flip, and the first cost falls upstream, not here:
- the endpoint is CHIPS (`SameSite=None; Secure; Partitioned`) or a token not relying on ambient
cookies. Neither is a flag flip, and the first cost is upstream rather than here:
`go-pkgz/auth/v2@v2.2.0` cannot emit `Partitioned` at all. Both cookies are hand-built in
`Service.Set` with only `HttpOnly`, `Path`, `Domain`, `MaxAge`, `Secure` and `SameSite`, and
`AUTH_SAME_SITE` in `cmd/server.go` offers `default`/`none`/`lax`/`strict` with no partitioned
axis, since `Partitioned` is a separate attribute. The first option therefore starts with a PR to
the library. The second needs nothing upstream and already works, which is why R1 leans on it, but
it is gated behind a flag that ships off and exposes the token to script, so it answers the
requirement
without being the answer an operator gets by default
axis, since `Partitioned` is a separate attribute. That is a PR to the library before anything in
this repo changes
- the popup-to-iframe handoff cannot be done in JS. The JWT cookie is `HttpOnly: true`, set in
`Service.Set`, so the top-level popup cannot read it to hand over. The receiving end is no longer
the obstacle it was: since #2197 `authCookieOptions` in `cookies.ts` returns
`SameSite=None; Secure; Partitioned` in a third-party https context and adds no `__Host-` prefix.
What remains missing is any route from the popup's storage bucket to the frame's, so the handoff
has to be server-mediated, a one-time code redeemed either for a `Set-Cookie … Partitioned` or,
more cheaply, for an `X-JWT` the frame's own writer turns into the partitioned pair. Email and
anonymous authenticate over XHR from inside the iframe, which keeps
`Service.Set`, so the top-level popup cannot read it to hand over, and the receiving end would not
work either: `setAuthCookie` in `cookies.ts` writes `SameSite: 'Strict'` under a `__Host-` prefix
with no `Partitioned`, and Strict is never sent from a third-party frame. The handoff has to be
server-mediated, a one-time code redeemed for a `Set-Cookie … Partitioned` issued from the
embedded context. Email and anonymous authenticate over XHR from inside the iframe, which keeps
them working while third-party cookies are permitted, but XHR does not create a partition by
itself, so they need `Partitioned` for the same reason OAuth does
- the failure mode is silent rather than an error, which is why #1139 reads as a hang. OAuth
@@ -330,17 +171,11 @@ exposes on `Opts` and threads into the JWT service. remark42 leaves it unset, so
list applies and the short circuit in `Service.Get` never fires for any method. Setting it would
make an authenticated document render possible.
Do not reach for it globally, though, and note that the obvious example does not carry the argument.
`GET /deleteme` deletes every comment a user has written and is a GET deliberately, so that the
link in the confirmation email works when clicked, but XSRF is only one of three gates on it: the
route sits under `radmin`, which applies `Auth`, `AdminOnly` and `matchSiteID`, and
`deleteMeRequestCtrl` then requires a separately signed token carrying a `delete_me` attribute it
cannot forge. Exempting GET wholesale removes one defence there, not the only one.
The caution still stands, but it has to be earned by an audit instead of by that example: scope any
exemption to the document route, establish that route is side-effect free, and check every other
authenticated GET before deciding how much route-scoped work the library needs. Cost that audit,
without assuming either that the door is shut or that it is open.
Do not reach for it globally, though. `GET /deleteme` deletes every comment a user has written, and
is a GET deliberately, so that the link in the confirmation email works when clicked. Exempting GET
from XSRF wholesale removes that protection from a destructive endpoint. Anything built on this has
to scope the exemption to the document route alone, and that route has to be provably side-effect
free. Cost that work rather than assuming either that the door is shut or that it is open.
There is also a query-parameter path, and it is worse than the constraint: `Service.Get` accepts the
token from a query parameter, `?jwt=` rather than the library default `?token=` because remark42
@@ -349,15 +184,15 @@ skipped entirely. That would put a live JWT into `Referer`, into history, and in
the route is one that logs bodies. It is unreachable in any case, since the JWT cookie is `HttpOnly:
true`, set in `Service.Set`, and no JS can read it to build the URL.
So anonymous-first is what the current configuration gives, and the defensible Path B position is
that making the document authenticated is a scoped piece of security work with its own cost. Until
that is costed, budget for anonymous-first: render anonymous, then hydrate the user state over XHR,
which does carry the header. Anonymous-first is also what a shared cache wants, though see the
hydration item in Path B for how much that is worth.
So anonymous-first is what the current configuration gives, and the honest Path B position is that
making the document authenticated is a scoped piece of security work with its own cost. Until that
is costed, budget for anonymous-first: render anonymous, then hydrate the user state over XHR, which
does carry the header. Anonymous-first is also what a shared cache wants, though see the hydration
item in Path B for how much that is worth.
## Verified facts
Checked against the code at `7de51ad2` and by independent reviewers.
Checked against the code at `a82dc8d3` and by independent reviewers.
- 9 runtime dependencies against 61 devDependencies, and **68** override entries, all in the single
`frontend/apps/remark42/package.json` since #2197 removed the workspace root. Before this effort
@@ -377,11 +212,11 @@ Checked against the code at `7de51ad2` and by independent reviewers.
- The e2e suite is Go and playwright-go since #2180, and passed 60 tests while this was being
written, up from 7. Treat the exact figure as stale on sight; it is the only coverage that
survives a rewrite
- The unit suite is 48 files, 27 `*.test.*` plus 21 `*.spec.*`, and **426 cases**, as jest
enumerates them. Counting only `*.test.*` understates it by twenty-one files, which is the trap
- The unit suite is 46 files, 25 `*.test.*` plus 21 `*.spec.*`, and **426 cases**, as jest
enumerates them. Counting only `*.test.*` understates it by twenty files, which is the trap
- `en.json` is 180 keys with no ICU plural or select forms
- 143 non-test source files under `app/` excluding typings, mocks and stubs; 158 counting them,
which is the figure the bundler section uses
- 136 non-test source files under `app/` excluding typings, mocks and stubs, 8,498 lines; 152 files
and 8,715 lines counting them
- `profile.ts` (139 lines) is only the iframe host; the view is `profile.tsx` (235) reusing
`Comment` (638) in `view="user"` mode
- `last-comments` renders into the **host page**, not an iframe, and side-loads its own stylesheet
@@ -410,7 +245,7 @@ Checked against the code at `7de51ad2` and by independent reviewers.
The concrete "what is left" list, and what any no-npm proposal has to answer for.
- transpiles TS and JSX for 158 source files, typed by `tsconfig.json`, compiled by the
- transpiles TS and JSX for 136 to 152 source files, typed by `tsconfig.json`, compiled by the
preset list in `.babelrc.js`
- CSS modules for 29 `*.module.css` files, 2,219 lines, including 177 nested `&`, 4 `composes` and
10 `:global` occurrences across 6 files, all handled by the CSS-modules rule in
@@ -487,33 +322,21 @@ widget *code* through npm breaks OAuth, but it adds a publish step and a version
- [ ] Document `__colors__` from `window.name` (`templates/iframe.ejs`), which works today and is
undocumented
- [ ] Fix the Astro and Gatsby manuals, which declare `REMARK42: any` and `remark_config: any`
- [ ] Correct the published locale list. `site/content/docs/configuration/frontend/_index.md` names
17 languages under `Locales`, and `app/locales/` ships 24 catalogs, so seven are documented
nowhere and a reader cannot discover them
### Task 2: Extend the e2e suite
**Done.** #2180 moved the suite to Go and playwright-go and took it from 7 tests to 22; #2196 took
it to 63, and master now carries 70 runnable top-level tests. Every item this task originally listed
is covered: vote and its failure path (`vote_test.go`), edit inside and outside the deadline, delete
and reply (`comment_test.go`), sort change and collapse persistence (`thread_test.go`), anonymous
and email auth (`auth_test.go`), the profile iframe and last-comments (`widgets_test.go`).
it to 48. Every item this task originally listed is covered: vote and its failure path
(`vote_test.go`), edit inside and outside the deadline, delete and reply (`comment_test.go`), sort
change and collapse persistence (`thread_test.go`), anonymous and email auth (`auth_test.go`), the
profile iframe and last-comments (`widgets_test.go`).
Most of what this task once listed as the remaining contract surface has since been covered too,
and the list is kept short here because an out-of-date backlog sends someone to write tests that
exist. Now covered: the cross-origin host page (`crossorigin_test.go` and `https_test.go`), the
`comments.html` fallback and its injection case
(`TestWidgets_CommentsPageOpensAThreadOnItsOwnOrigin`
and `TestWidgets_CommentsPageRefusesInjectedMarkup`), and the `remark_config` fields `url`,
`page_title`, `__colors__`, the subscription flags, timezone rendering and the unknown-locale
fallback, all as `TestConfig_*` cases in `config_test.go`. The composer is substantially covered by
`comment_test.go`, including drafts and a failed post. Repeated `createInstance` is covered at unit
level in `embed.test.ts`, though not end to end.
What is genuinely still uncovered: hash deep links, `max_shown_comments`, Telegram auth and its
subscription flag, and the storage-denied fallback trigger, which `e2e/README.md` explains needs
WebKit. Telegram is blocked on #2208 and `go-pkgz/auth` #316. #2219 adds one more: a deployment
under a path prefix, verifying chunks and assets for every entry including `deleteme`.
What remains uncovered is a different list, and it is the contract surface rather than the
behaviour: a cross-origin host page (every host page in the suite is served from the widget origin,
so R1 has no coverage at all), the `comments.html` fallback, `remark_config` fields (`url`,
`page_title`, hash deep links, `max_shown_comments`, the three `show_*_subscription` flags,
`__colors__`), the listener leak on a repeated `createInstance`, timezone-local date rendering, the
unknown-locale fallback, and the composer.
### Task 3: Stable class names and a documented override stylesheet
@@ -606,10 +429,6 @@ compiled, it is what verifies it.
(`URLKeyWithUser`, used by `findCommentsCtrl`), one entry per user with a separate `admin!!` key.
An HTML cache fragments the same way, so the shared-cache benefit only pays for logged-out readers
- [ ] Attach the existing auth via `htmx:configRequest` on fragment requests
- [ ] Preserve the explicit height report on panel close. `useDropdown` in `auth.hooks.ts` calls
`updateIframeHeight()` when the sign-in panel closes, added by #2213, because the panel is
absolutely positioned and neither ResizeObserver sees it disappear. A server-rendered replacement
loses the widget's height entirely if it drops that call
- [ ] Keep client-side: embed script, auth popups, composer, collapse and hidden-user state,
optimistic votes, and the **three subscription flows**. Email, Telegram and RSS
(`comment-form/__subscribe-by-email/`, `__subscribe-by-telegram/`, `__subscribe-by-rss/`) are each
@@ -641,23 +460,7 @@ compiled, it is what verifies it.
**Cost**: months to an opt-in parallel UI reads as a floor derived from the optimistic architecture,
and the optimistic architecture does not hold. Anonymous-first is forced rather than chosen, so the
fragment layer reproduces the entire authenticated tree rather than a delta; add the three
subscription flows. R1 costs Path B little: the task list above retains the existing auth through
`htmx:configRequest`, and `request` in `fetcher.ts` already turns `X-JWT` into the partitioned pair,
so Path B can keep that writer or attach the same handling to a response hook.
The upstream `Partitioned` work is the better answer for the flows that can use it. With
`PartitionedCookies` the server sets the pair itself and the `JWT` stays `HttpOnly`, so the session
survives third-party blocking without the token ever becoming readable from script, where the header
route buys the same persistence by giving that readability away.
Two limits keep that from being a free win. The option is global, so `Service.Set` applies it to the
OAuth callback too, and a cookie partitioned to the popup's own top-level context is one the frame
cannot see: turning it on regresses OAuth on the permissive browsers where an unpartitioned
`SameSite=None` cookie works today, so it wants flow scoping or a separate OAuth answer. And the
security gain is narrower than "no XSS exposure": `HttpOnly` stops a script extracting and replaying
the bearer token, but the XSRF value stays readable by design, and script on the widget origin can
still make authenticated requests that the browser attaches the `HttpOnly` cookie to. What it
removes is token theft, not authenticated action during an XSS.
subscription flows and, if R1 is to be honoured, the upstream `Partitioned` work in `go-pkgz/auth`.
On one contributor the realistic figure is long enough that the plan's own warning applies to the
schedule and not only to the design. Deletes the entire npm toolchain. **Against it**: 2,400 lines
of the most stateful code get rewritten; a second HTML-fragment API surface becomes permanent
+19 -21
View File
@@ -96,9 +96,12 @@ const (
// be satisfied by the fallback alone and says nothing about the message path. bound the
// message-path assertions well under it
revealTimeout = 5 * time.Second
// generous enough for a cold navigation on a loaded runner, and still well under the
// fallback, which is the point of the assertion
messageRevealBudget = 3 * time.Second
// the line the three reveal cases are judged against, measured from the element's creation
// and not from anything this process can time. a timer cannot fire early, so below this the
// reveal can only have come from the message, and above it only from the fallback. a budget
// chosen for how long an engine takes instead would be a bet on the slowest one: webkit has
// reported inited 2.6s after creation on a loaded machine
revealCutoff = revealTimeout - 500*time.Millisecond
)
// openWithBlockedIframeDoc loads the demo page with the widget document aborted, so the
@@ -242,21 +245,19 @@ func TestIframe_StaysHiddenUntilTheDocumentReportsInited(t *testing.T) {
forEachEngine(t, func(t *testing.T, page playwright.Page) {
openWithBlockedIframeDoc(t, page)
// unconditional: the loop below is bounded by the frame's own age, and on a slow
// enough load that bound can already be spent, which would leave the test asserting
// nothing at all about visibility
require.Equal(t, "hidden", iframeVisibility(t, page))
// then hold it for almost the whole fallback window. stopping halfway would only prove
// the fallback is not shorter than that, and a widget that revealed on anything other
// than `inited` would still pass. measured from the element's creation, since that is
// when the fallback it must not have used starts counting
for iframeAge(t, page) < revealTimeout-500*time.Millisecond {
require.Equal(t, "hidden", iframeVisibility(t, page))
// hold for almost the whole fallback window. stopping halfway would only prove the
// fallback is not shorter than that, and a widget that revealed on anything other than
// `inited` would still pass
for iframeAge(t, page) < revealCutoff {
time.Sleep(100 * time.Millisecond)
}
_, revealed := revealDelay(t, page)
assert.False(t, revealed, "the frame was revealed before its document reported inited")
// the mark and not what is visible when the read lands: the two are separated by the
// margin above, and an evaluate round trip on a loaded engine outlasts it, which reads
// a fallback that fired exactly on time as an early reveal
delay, revealed := revealDelay(t, page)
assert.False(t, revealed && delay < revealCutoff,
"the frame was revealed %v after it was created, before its document reported inited", delay)
})
}
@@ -290,7 +291,7 @@ func TestIframe_IsRevealedByTheInitedMessage(t *testing.T) {
// whole 5s window without the widget being at fault
delay, ok := revealDelay(t, page)
require.True(t, ok, "the frame reported no reveal at all")
assert.Less(t, delay, messageRevealBudget,
assert.Less(t, delay, revealCutoff,
"the reveal was slow enough to have come from the fallback and not the message")
waitVisible(t, page.Locator("#remark42 iframe"))
})
@@ -310,12 +311,9 @@ func TestIframe_IsRevealedByTheTimeoutWhenInitedNeverArrives(t *testing.T) {
// and not before it: without a lower bound, shortening the fallback to a value that
// defeats its purpose would still pass. against the frame's own clock, so that a slow
// navigation cannot be mistaken for the timer having run
// close to the fallback and not three quarters of it: measured in the page there is
// no navigation to make room for, and a wider floor tolerates a fallback shortened
// enough to defeat its purpose
delay, ok := revealDelay(t, page)
require.True(t, ok, "the frame reported no reveal at all")
assert.Greater(t, delay, revealTimeout-500*time.Millisecond,
assert.Greater(t, delay, revealCutoff,
"the reveal came too early to have been the fallback timer")
})
}
+37
View File
@@ -11,6 +11,7 @@ import (
"net/http"
"os"
"os/exec"
"regexp"
"slices"
"strings"
"sync"
@@ -264,3 +265,39 @@ func pauseForWebLimit() {
}
lastWebGet = time.Now()
}
// TestWeb_NoBundleHardcodesTheWebRoot pins the fix for #2203, which shipped with no test at any
// level. The bundler used to bake a fixed public path into every entry, so an instance mounted
// under a prefix, which manuals/subdomain documents, asked the domain root for its provider icons
// and got nothing. The path is derived from the URL the bundle was loaded from now, which is
// correct for both arrangements.
//
// What separates the two builds is the assignment webpack emits for its runtime public path: a
// literal when the path is fixed, and a computed value when it is derived. Asset filenames appear
// bare either way, so a case looking for a rooted "/web/name.svg" string finds nothing in either
// build and proves nothing; this asserts the assignment instead.
//
// Every emitted bundle is checked rather than the obvious one: the original defect put fifteen
// icons in remark.mjs and one in last-comments.mjs, so a case reading a single entry would have
// gone green with half of it still live.
func TestWeb_NoBundleHardcodesTheWebRoot(t *testing.T) {
names := emittedBundles(t)
require.Contains(t, names, "remark.mjs", "listing is not the served web root: %v", names)
require.Contains(t, names, "last-comments.mjs",
"the entry carrying the second half of #2203 is missing from the listing: %v", names)
// webpack writes its public path to the `p` property of the runtime object. A baked-in path
// is a string literal there; a derived one is an expression
baked := regexp.MustCompile("\\.p\\s*=\\s*[\"'`]/web/[\"'`]")
for _, name := range names {
t.Run(name, func(t *testing.T) {
body := getWeb(t, "/web/"+name).body
require.NotEmpty(t, body, "%s serves nothing, so this asserts nothing", name)
assert.NotRegexp(t, baked, body,
"%s bakes the public path in rather than deriving it, so an instance mounted under "+
"a prefix fetches its assets from the domain root", name)
})
}
}
@@ -78,9 +78,9 @@ services:
| image.resize-width | IMAGE_RESIZE_WIDTH | `2400` | width of a resized image |
| image.resize-height | IMAGE_RESIZE_HEIGHT | `900` | height of a resized image |
| auth.ttl.jwt | AUTH_TTL_JWT | `5m` | JWT TTL |
| auth.ttl.cookie | AUTH_TTL_COOKIE | `200h` | TTL of the server-set auth cookie. Note it does not govern the cookie the frontend writes under `auth.send-jwt-header`, which is fixed at 200h |
| auth.send-jwt-header | AUTH_SEND_JWT_HEADER | `false` | also send JWT as a header, so the frontend can store it in a client-side cookie that survives third-party cookie blocking; the server-set cookies are still sent. [See security considerations](#security-considerations-for-authsend-jwt-header). |
| auth.same-site | AUTH_SAME_SITE | `default` | SameSite attribute for the server-set auth cookies (`default`, `none`, `lax` or `strict`). `default` emits no attribute at all and leaves the choice to the browser, which is not the same as `lax` |
| auth.ttl.cookie | AUTH_TTL_COOKIE | `200h` | cookie TTL |
| auth.send-jwt-header | AUTH_SEND_JWT_HEADER | `false` | send JWT as a header instead of a server-set cookie; with this enabled, frontend stores the JWT in a client-side cookie. [See security considerations](#security-considerations-for-authsend-jwt-header). |
| auth.same-site | AUTH_SAME_SITE | `default` | set same site policy for cookies (`default`, `none`, `lax` or `strict`) |
| auth.apple.cid | AUTH_APPLE_CID | | Apple client ID (App ID or Services ID) |
| auth.apple.tid | AUTH_APPLE_TID | | Apple service ID |
| auth.apple.kid | AUTH_APPLE_KID | | Apple Private key ID |
@@ -194,14 +194,9 @@ When `auth.send-jwt-header=true` is enabled:
- **Security Impact**: JWT tokens are stored in client-accessible cookies that can be accessed by JavaScript
- **Vulnerability**: This increases vulnerability to XSS attacks compared to server-set HttpOnly cookies
- **Implementation Mitigations**:
- `SameSite=Strict` when the widget and the page share an origin, which is what prevents the
cookie being sent from another site
- `SameSite=None; Secure; Partitioned` when the widget is embedded on another domain, where
`Strict` would never be sent at all. `Partitioned` keys the cookie to the embedding top-level
site, so a different site gets a separate cookie and cannot reach this one. Pages and
subdomains under that same site do share it, since the partition key is the site rather than
the page
- SameSite=Strict cookies to prevent CSRF attacks
- Secure flag automatically added on HTTPS connections
- __Host- prefix added on HTTPS to prevent subdomain attacks
- Double Submit Cookie pattern with XSRF token matching the JWT ID
This configuration should only be used when:
@@ -6,78 +6,23 @@ title: Configure Instance on a different domain
### What doesn't work so far?
Unless discussion [#1139](https://github.com/umputun/remark42/discussions/1139) has a marked answer, authorisation using oAuth like GitHub or Google is impossible on domains other than the original one. Telegram, Email and anonymous auth work on allowed HTTPS embedding domains when `AUTH_SEND_JWT_HEADER=true`.
Unless discussion [#1139](https://github.com/umputun/remark42/discussions/1139) has a marked answer, authorisation using oAuth like GitHub or Google is impossible on domains other than the original one. Telegram, Email and anonymous auth would work everywhere.
### Setup
Set `ALLOWED_HOSTS="'self',https://example1.org,https://example2.org"` with your domain names, and `AUTH_SEND_JWT_HEADER=true`.
`AUTH_SEND_JWT_HEADER` is what keeps a reader signed in across a page reload on Safari, in Chrome Incognito, and in any browser configured to block third-party cookies. Read [its security considerations](../../configuration/parameters/#security-considerations-for-authsend-jwt-header) before enabling it: it puts the token in a cookie JavaScript can read, which costs XSS exposure that a server-set `HttpOnly` cookie does not.
**`AUTH_SAME_SITE=none` is not needed alongside it**, which reverses what this page recommended for years, so it is worth showing the measurement instead of asserting it. Signing in anonymously from an embedded widget over https and dumping the browser's cookie jar gives, with the setting:
| name | httpOnly | partition key | written by |
| --- | --- | --- | --- |
| `JWT` | yes | none | the server |
| `XSRF-TOKEN` | no | none | the server |
| `JWT` | no | the embedding site | the widget |
| `XSRF-TOKEN` | no | the embedding site | the widget |
and without it, only the widget's own partitioned pair. Sign-in, posting and the reload all work either way, in a permissive browser and in one blocking third-party cookies. What the setting adds is the unpartitioned `HttpOnly` `JWT` in the first row, delivered as a third-party cookie to every listed domain wherever the browser still permits that. Nothing needs it, so leaving it at the default is the smaller exposure.
Keep `AUTH_SAME_SITE=none` if you are *not* setting `AUTH_SEND_JWT_HEADER`. Then the server's cookies are the only ones there are, and this is what allows them to be set off-domain at all, for as long as the reader's browser still accepts unpartitioned third-party cookies.
Set `ALLOWED_HOSTS="'self',https://example1.org,https://example2.org"` with your domain names and `AUTH_SAME_SITE=none`.
The `'self'` in `ALLOWED_HOSTS` value means "domain where Remark42 is installed on" and needed if you want `remark42.example.com/web/` to work in case you want to test something with it.
### Technical details
`ALLOWED_HOSTS` sets CSP [frame-ancestors](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors), which, once enabled, limits the domains where Remark42 would work. The default value is `*` so that it would work on any domain.
`ALLOWED_HOSTS` sets CSP [frame-ancestors](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors), which, once enabled, limits the domains where Remark42 would work. The default value is `*` so that it would work on any domain`.
`AUTH_SAME_SITE` sets the [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) attribute on the cookies the server sets. `none` lets those cookies be set on any domain where Remark42 is shown.
The `default` setting does not mean `Lax`. It means Remark42 emits no `SameSite` attribute at all and leaves the choice to the browser, and browsers differ: Chromium treats a missing attribute as `Lax` and so refuses the cookie cross-site, while Firefox accepts it. That difference is not a detail, because it decides which of the two cookie pairs below a reader actually ends up with.
`SameSite=None` is not sufficient on its own, and with `AUTH_SEND_JWT_HEADER` it is not necessary either. A browser that blocks third-party cookies drops a cookie set by Remark42 for a reader on another domain no matter what its `SameSite` value is, unless the cookie is explicitly marked [`Partitioned`](https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies), and the server-set cookies are not. `AUTH_SEND_JWT_HEADER=true` is what closes that: the token comes back in an `X-JWT` response header and the widget stores it in its own cookie, written from inside the embedded frame and marked `SameSite=None; Secure; Partitioned`, so the browser keeps it for that embedding site and sends it back after a reload. That cookie is the widget's own doing and owes nothing to `AUTH_SAME_SITE`, which reaches only the pair the server sets.
A browser that refuses a cross-site `Set-Cookie` lacking `SameSite=None` refuses it outright, so with the setting left at its default the server's pair is absent from the jar, not present with a stricter attribute.
Note that this applies to Email, Telegram and anonymous authorisation, which the widget performs from inside the frame. It does not rescue oAuth, which completes in a popup that is a top-level page of its own, so the cookie set there belongs to the Remark42 domain and the embedded frame never sees it.
### What each browser actually does
Measured on real domains over real certificates, with Remark42 on one registrable domain and the
host page on another, signing in and then reloading. Every "blocked" column below was verified with
a control cookie: an ordinary third-party cookie written from inside the widget frame has to be
dropped, or the run is not blocking anything and proves nothing.
| configuration | Chrome, default | Chrome, third-party cookies blocked | Firefox, default | Firefox, "block all third-party" | Safari |
| --- | --- | --- | --- | --- | --- |
| `AUTH_SEND_JWT_HEADER` only | works | works | works | fails | works |
| `AUTH_SAME_SITE=none` only | works | fails | works | fails | fails |
| both | works | works | works | fails | works |
Three things in that table are worth spelling out.
**Safari needs no configuring to break the old recipe.** It blocks third-party cookies out of the
box, so `AUTH_SAME_SITE=none` on its own has already stopped working there for every reader. This
is not a future deprecation to plan for.
**Firefox reaches "works" by a different route, and a weaker one.** Chrome and Safari refuse the
server's cookie when it carries no `SameSite` attribute, which leaves the field clear for the
widget to write its own partitioned pair. Firefox accepts that cookie, and because the server's
`JWT` is `HttpOnly`, the browser then refuses to let the widget's script overwrite it: a cookie set
by JavaScript may not replace an `HttpOnly` one of the same name. So on Firefox the session rides
on an ordinary unpartitioned third-party cookie even with the header flag on, and it disappears the
moment the reader blocks those.
**No configuration survives Firefox's "block all third-party cookies" setting.** That mode discards
partitioned cookies too, so the `Partitioned` escape hatch does not apply. A reader who has turned
it on cannot stay signed in on an embedded widget, and nothing in Remark42 can change that.
`AUTH_SAME_SITE` sets the [SAME_SITE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) attribute for authorisation cookies, allowing Remark42 either on the original domain and subdomains there (default value, which equals to `Lax`) or allows setting authorisation cookies on any domain where remark42 is shown (`None` setting).
Here are all possible combinations of these two:
- Default setup with unaltered variables: comments are shown on any domain, but the authorisation wouldn't work anywhere, except on the same domain Remark42 is installed on and subdomains of it.
- `ALLOWED_HOSTS` set to a set of domains: comments are shown only on listed domains, and authorisation wouldn't work anywhere, except on the same domain Remark42 is installed on and subdomains of it.
- `AUTH_SAME_SITE` set to `None`: comments are shown on any domain. Authorisation works on browsers that still permit third-party cookies, and stops working on the ones that block them.
- `ALLOWED_HOSTS` set to a set of domains and `AUTH_SAME_SITE` set to `None`: comments are shown on listed domains, with the same authorisation caveat.
- `ALLOWED_HOSTS` and `AUTH_SEND_JWT_HEADER=true`, with `AUTH_SAME_SITE` left alone: comments are shown on listed domains, and Email, Telegram and anonymous authorisation survives a reload whatever the browser's third-party cookie policy. This is the recommended arrangement. Adding `AUTH_SAME_SITE=none` on top changes nothing about whether a reader stays signed in; it only adds the server's unpartitioned cookies where the browser still takes them.
- `ALLOWED_HOSTS` set to a set of domains: comments are shown only on listed domains, and authorisation wouldn't work anywhere, expect on the same domain Remark42 is installed on and subdomains of it.
- `AUTH_SAME_SITE` set to `None`: comments are shown on any domain. The authorisation would work anywhere.
- `ALLOWED_HOSTS` set to a set of domains and `AUTH_SAME_SITE` set to `None`: comments are shown on listed domains. The authorisation would work on all of them.