fix(auth): move the BankID flow into a signed, user-gated, single-use cookie (#1625)

* fix(auth): move the BankID flow into a signed, single-use, confirm-on-resume cookie

A user's BankID signup identified successfully four times and created no
account. His screenshots show four tabs, one on the finished "Verifierad med
BankID, ange e-post" step, and the tab he was looking at showing the idle
button. Prod agreed: no bankid_identities row, no auth.users row.

On iOS outside plain Safari the BankID return URL is handed to the OS, which
opens a NEW tab. The session lived in per-tab sessionStorage, so that tab
started empty and rendered the start button while the completed flow sat
stranded. Login hid it (self-finishing, cookie-backed session); signup waits
for a human to type an e-mail into the stranded tab, so it dies there.

The session id is no longer handed to the browser. It lives in a signed
__Host- HttpOnly cookie set at /start; /poll, /complete, /link and /cancel
read it. Cookies are shared by every tab of the origin, which is what the
handoff needed. The id had to leave the client because it is an
unauthenticated bearer credential: /poll was skipAuth and returned
user.personalNumber, and /complete with mode 'login' returns a tokenHash that
verifyOtp turns into a session, MFA skipped for bankid_linked accounts.

A completed identification must never be consumed by whoever merely opens the
page. A shared cookie plus a shared machine means the tab that finds a
completed flow cannot prove the person at it is the one who made it, and no
client-side token can prove otherwise: nothing survives an iOS same-tab reload
yet dies on reopen-closed-tab / session restore / tab duplication. So a resume
is never automatic. The mount probe routes any found live flow to a confirm
card ("Fortsätt bara om det var du") that reveals no name, and only that click
polls and consumes. Auto-consume happens only inside the live component
instance that called startSession (desktop QR; the pre-navigation mobile
launch), which by construction is the originator. Cost: one tap after
returning from the BankID app on iOS, exactly where the reported bug lives;
desktop and Android never hit the resume path.

The rest is defence the four review rounds proved load-bearing:
- __Host- with Path=/ and unconditional Secure, so a script cannot plant the
  same name at a longer path; readBankIdFlow fails closed on duplicates and on
  a malformed percent-escape.
- Single-use is a unique index (bankid_consumed_sessions), claimed before
  generateLink, not a Set-Cookie. Fail-closed on any non-23505 error, so the
  migration MUST be applied before the code.
- A link flow requires auth at /start and pins userId; /link rejects a flow
  owned by anyone else, before any TIC call. mode is pinned and /poll rejects a
  body mode that does not match, so a login session cannot finish through the
  signup panel. /poll withholds the holder name from a probe. The 900s
  verified-step window is capped by MAX_TOTAL_LIFE from a signed startedAt.
  /poll never clears the cookie (an untargeted Set-Cookie would delete a newer
  flow); only /cancel and terminal /complete + /link exits clear. Avbryt holds
  a 'cancelling' state until /cancel resolves so a new /start cannot race the
  clear. Session id is logged only as an 8-char prefix.

The launch is untouched: iOS keeps its return URL, Android keeps redirect=null
(#194 closed that path deliberately).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): bind BankID actions to the resumed flow

* docs: record BankID staging migration drift

* fix(auth): address BankID PR review

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-15 23:07:29 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 2deea05d42
commit edfdbe2d2a
13 changed files with 2294 additions and 227 deletions
+51 -14
View File
@@ -62,11 +62,12 @@ function RegisterPageContent() {
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [isCancelling, setIsCancelling] = useState(false)
const [isRegistered, setIsRegistered] = useState(false)
const [duplicateEmail, setDuplicateEmail] = useState<string | null>(null)
const [inviteEmail, setInviteEmail] = useState<string | null>(null)
const [bankIdUser, setBankIdUser] = useState<{ givenName?: string; surname?: string } | null>(null)
const [bankIdSessionId, setBankIdSessionId] = useState<string | null>(null)
const [bankIdFlowId, setBankIdFlowId] = useState<string | null>(null)
const [bankIdEmail, setBankIdEmail] = useState('')
// Signup failures render inline next to the form (see AuthFormError), never
// as a toast. Field-level problems attach to their field; everything else
@@ -166,29 +167,37 @@ function RegisterPageContent() {
setFormError({ kind: 'bankid', message: t('bankid_failed_description') })
return
}
// BankID verified: store sessionId and show email form
// BankID verified: show the email form. The session itself stays in the
// server's HttpOnly flow cookie, so there is nothing to hold on to here.
setFormError(null)
setBankIdUser({ givenName: result.givenName, surname: result.surname })
if (result.sessionId) setBankIdSessionId(result.sessionId)
setBankIdFlowId(result.flowId ?? null)
}
const handleBankIdSignup = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
setFormError(null)
setIsLoading(true)
const formData = new FormData(e.currentTarget)
const emailValue = (formData.get('bankid_email') as string) || bankIdEmail
if (!bankIdFlowId) {
setFormError({ kind: 'bankid', message: t('bankid_failed_description') })
return
}
setIsLoading(true)
try {
// Only the e-mail travels: the session and the fact that this is a
// signup are both pinned in the server's flow cookie.
const res = await fetch('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: bankIdSessionId,
mode: 'signup',
email: emailValue,
}),
headers: {
'Content-Type': 'application/json',
'x-bankid-flow-id': bankIdFlowId,
},
body: JSON.stringify({ email: emailValue }),
})
const json = await res.json()
@@ -546,7 +555,9 @@ function RegisterPageContent() {
{inviteEmail ? t('invite_email_hint') : t('bankid_email_hint')}
</p>
</div>
<Button type="submit" className="w-full h-11" disabled={isLoading}>
{/* Also disabled while Back's /cancel is in flight: submitting
then would race the cookie clear (recoverable, but pointless). */}
<Button type="submit" className="w-full h-11" disabled={isLoading || isCancelling}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -560,9 +571,35 @@ function RegisterPageContent() {
type="button"
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => {
setBankIdUser(null)
setBankIdSessionId(null)
disabled={isLoading || isCancelling}
onClick={async () => {
// AWAIT the cancel before remounting BankIdAuth. The flow
// cookie outlives this component and BankIdAuth probes for a
// live flow on mount, so clearing the form first would let it
// find the still-completed session. Its own isCancelling
// state, not isLoading: isLoading drives the submit button's
// "Skapar konto...", and pressing Back should not claim an
// account is being created.
setIsCancelling(true)
try {
const res = await fetch('/api/extensions/ext/tic/bankid/cancel', {
method: 'POST',
headers: bankIdFlowId
? { 'x-bankid-flow-id': bankIdFlowId }
: undefined,
})
if (!res.ok) throw new Error(`cancel failed: ${res.status}`)
// Flow cleared server-side; the remounted BankIdAuth will
// probe, find nothing, and show the start button.
setBankIdUser(null)
setBankIdFlowId(null)
} catch {
// The flow is still live, so resetting the form would just
// bounce the user back here. Say so instead of looping.
setFormError({ kind: 'bankid', message: t('bankid_cancel_failed') })
} finally {
setIsCancelling(false)
}
}}
>
<ArrowLeft className="mr-2 h-4 w-4" />