Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

API: a profile can hold more than one passkey, and a signed-in device can hand another one a one-time code to add its own (#95)

Duarte Santos30978bb2f26e
diff --git a/api/Dockerfile b/api/Dockerfile
index 51c1f8f2a..69b8c5198 100644
--- a/api/Dockerfile
+++ b/api/Dockerfile
@@ -53,7 +53,7 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force
# Every module server.js imports from the api root has to be named here: the image carries nothing
# else, and one that is missing only shows at boot, as ERR_MODULE_NOT_FOUND.
-COPY server.js push-messages.js verify-error.js password.js rate-limit.js ./
+COPY server.js push-messages.js verify-error.js password.js rate-limit.js passkeys-store.js device-link.js ./
COPY coach ./coach
ENV NODE_ENV=production
ENV PORT=3000
diff --git a/api/device-link.js b/api/device-link.js
index a2fe73bcc..dc66a769b 100644
--- a/api/device-link.js
+++ b/api/device-link.js
@@ -1,34 +1,68 @@
+/* One-time device links (#95).
+ *
+ * A signed-in device shows a code, and a QR code of a link that carries it. Another device of the
+ * same person redeems it by creating a passkey of its own, and that passkey is what signs it in.
+ * For those few minutes the code is the whole credential, so:
+ *
+ * - 12 characters from the pairing alphabet (no 0/O/1/I), 60 bits, typed as XXXX-XXXX-XXXX when
+ * the other device cannot scan;
+ * - stored only as a SHA-256, like an admin's reset code: a copy of db.json holds no code that
+ * works. The code is random, so a slow hash would add nothing;
+ * - one per profile — a new one replaces the one before — good for DEVICE_LINK_TTL_MS, and gone
+ * with the first passkey made with it. An expired one is dropped the next time links are read.
+ *
+ * Pure bookkeeping on `db.deviceLinks`; the routes, the throttle and the audit are server.js's. */
import crypto from 'node:crypto';
-export const DEVICE_LINK_TTL_MS = 15 * 60 * 1000;
+// Long enough to walk to the other device, find the camera and sign in; short enough that a code
+// photographed off a screen is dead by the time anyone could use it.
+export const DEVICE_LINK_TTL_MS = 10 * 60 * 1000;
+const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
+const LENGTH = 12;
-function prune(db, now, keepUserId) {
- db.deviceLinks = (db.deviceLinks || []).filter(l => l.exp > now && l.userId !== keepUserId);
+export function makeLinkCode() {
+ // 256 is a multiple of 32, so the modulo is unbiased.
+ const raw = Array.from(crypto.randomBytes(LENGTH), b => ALPHABET[b % ALPHABET.length]).join('');
+ return raw.slice(0, 4) + '-' + raw.slice(4, 8) + '-' + raw.slice(8);
}
+// Dashes, spaces and case are how a person types it, not part of it.
+const clean = code => (typeof code === 'string' ? code : '').toUpperCase().replace(/[^A-Z0-9]/g, '');
+export const hashLinkCode = code => crypto.createHash('sha256').update('opengym-link:' + clean(code)).digest('hex');
+function prune(db, now) {
+ db.deviceLinks = (db.deviceLinks || []).filter(l => l && typeof l.h === 'string' && l.exp > now);
+}
+
+// → { code, link }. The code is returned once and never stored.
export function createDeviceLink(db, userId, now = Date.now(), ttlMs = DEVICE_LINK_TTL_MS) {
- prune(db, now, userId);
- const link = {
- token: crypto.randomBytes(18).toString('base64url'),
- userId,
- exp: now + ttlMs,
- created: now
- };
+ prune(db, now);
+ db.deviceLinks = db.deviceLinks.filter(l => l.userId !== userId);
+ const code = makeLinkCode();
+ const link = { h: hashLinkCode(code), userId, exp: now + ttlMs, created: now };
db.deviceLinks.push(link);
- return link;
+ return { code, link };
+}
+
+// The live link a code belongs to, or null — a wrong code, a used one and an expired one all look
+// the same from outside. Finding a link does not use it up; burnDeviceLink does.
+export function findDeviceLink(db, code, now = Date.now()) {
+ prune(db, now);
+ if (clean(code).length !== LENGTH) return null;
+ const h = Buffer.from(hashLinkCode(code), 'hex');
+ return db.deviceLinks.find(l => {
+ const stored = Buffer.from(l.h, 'hex');
+ return stored.length === h.length && crypto.timingSafeEqual(stored, h);
+ }) || null;
}
-export function claimDeviceLink(db, token, now = Date.now()) {
- db.deviceLinks = db.deviceLinks || [];
- const i = db.deviceLinks.findIndex(l => l.token === token);
- if (i < 0) return { error: 'unknown or already used' };
- const link = db.deviceLinks[i];
- db.deviceLinks.splice(i, 1);
- if (link.exp < now) return { error: 'link expired' };
- return { userId: link.userId };
+export function burnDeviceLink(db, link) {
+ db.deviceLinks = (db.deviceLinks || []).filter(l => l !== link);
}
-export function deviceLinkUrl(origin, token) {
- const base = String(origin || '').replace(/\/+$/, '');
- return base + '/?link=' + encodeURIComponent(token);
+// Every unused link of a profile, for the moments its sessions end: an unused link is a way in
+// waiting to be taken, like a pairing code. Says whether anything went, so a caller can skip a save.
+export function dropDeviceLinks(db, userId) {
+ const before = (db.deviceLinks || []).length;
+ db.deviceLinks = (db.deviceLinks || []).filter(l => l.userId !== userId);
+ return db.deviceLinks.length !== before;
}
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 950177455..c20bb4bd9 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -34,6 +34,9 @@ info:
starts, so checks sent at once get no more tries than checks sent one by one. A
paused caller gets `429 {"error": …, "code": "locked", "retryAfter": <s>}` with a
`Retry-After` header. The passkey and pairing routes are not throttled.
+ The two routes that redeem a one-time device link (tag `passkeys`) share the
+ per-address budget, and wrong codes pause the address for link redemption only,
+ after 20, the way wrong reset codes do.
The address is the socket's, or with `TRUST_PROXY=1` the one a trusted proxy put in
`CF-Connecting-IP` / the last `X-Forwarded-For` entry / `X-Real-IP`; IPv6 clients are
counted by /64. Counters live in memory and reset on restart.
@@ -53,6 +56,8 @@ info:
one-shot credential in the body) and any request authenticated with a Bearer token.
The password routes are **not** exempt: a hostile page knows a valid name and
password of its own, and could otherwise sign a visitor into it (login CSRF).
+ Neither are the device-link routes: a link is redeemed on the app's own origin,
+ the only one a passkey can be created for.
### Environment-dependent behavior
- `INVITE_ONLY=1` — registration requires a valid invite code (minted by an admin).
@@ -106,6 +111,10 @@ tags:
description: >-
Optional name-and-password sign-in (`PASSWORD_LOGIN=1`). Every route here is a 404
while the flag is off.
+ - name: passkeys
+ description: >-
+ More than one passkey on a profile: list, add, rename, remove — and one-time device
+ links, which let another device of the same person add a passkey of its own.
- name: data
description: Per-user state sync (the whole app state as one JSON blob)
- name: push
@@ -865,6 +874,313 @@ paths:
example: { error: "no such user" }
'409': { $ref: '#/components/responses/NameTaken' }
+ /api/account/passkeys:
+ get:
+ tags: [passkeys]
+ operationId: listPasskeys
+ summary: This profile's passkeys
+ description: >-
+ Every passkey that signs this profile in, without key material. `created` and
+ `lastUsed` are null for a passkey made before they were recorded.
+ responses:
+ '200':
+ description: The list, and what it allows.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/PasskeyList' }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ delete:
+ tags: [passkeys]
+ operationId: removePasskey
+ summary: Remove one passkey
+ description: |
+ Refused while it is the profile's last way in: its only passkey, and no password
+ that can sign in (a password counts only while `PASSWORD_LOGIN` is on). No proof is
+ asked — removing takes a way in away. Audited as `auth.passkey.remove`.
+
+ Sessions are not tied to the passkey that opened them, so a session it already
+ opened carries on; `POST /api/logout/all` ends those.
+ parameters:
+ - name: id
+ in: query
+ required: true
+ description: The passkey's `id` from the list (its WebAuthn credential id).
+ schema: { type: string }
+ responses:
+ '200':
+ description: Removed. The list as it is now.
+ content:
+ application/json:
+ schema:
+ allOf:
+ - $ref: '#/components/schemas/PasskeyList'
+ - type: object
+ properties:
+ ok: { type: boolean, const: true }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '404':
+ description: No passkey of this profile has that id.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "passkey not found", code: "not-found" }
+ '409':
+ description: It is the profile's last way in.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "this passkey is the only way into this profile", code: "last-way-in" }
+
+ /api/account/passkeys/options:
+ post:
+ tags: [passkeys]
+ operationId: addPasskeyOptions
+ summary: 'Add a passkey (step 1): prove it is you, get creation options'
+ description: |
+ A session alone is never enough to add a way in that outlives "sign out
+ everywhere". The body carries the same proof `POST /api/account/password` takes:
+ a passkey assertion made for this request (`cid` from `POST /api/login/options`,
+ `credential` signed by one of *this* profile's passkeys), or `current`, the
+ profile's password — accepted even on an instance that has since switched password
+ sign-in off, so a password-only profile can move onto a passkey. Wrong passwords
+ count toward the sign-in pause.
+
+ The options use the profile's own user handle and list its passkeys in
+ `excludeCredentials`, so an authenticator that already holds one refuses. The
+ challenge is good for 5 minutes, for this profile, and only while the session
+ version is unchanged.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/OwnerProof' }
+ responses:
+ '200':
+ description: Ceremony options.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ cid: { type: string, description: 'One-shot challenge id for /api/account/passkeys/verify.' }
+ options: { $ref: '#/components/schemas/WebAuthnRegistrationOptions' }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '403': { $ref: '#/components/responses/ProofRefused' }
+ '409': { $ref: '#/components/responses/PasskeyLimit' }
+ '429': { $ref: '#/components/responses/TooManyRequests' }
+ '503': { $ref: '#/components/responses/Busy' }
+
+ /api/account/passkeys/verify:
+ post:
+ tags: [passkeys]
+ operationId: addPasskeyVerify
+ summary: 'Add a passkey (step 2): store the new one'
+ description: >-
+ Verifies the attestation against the challenge from step 1 and stores the passkey
+ on this profile. Audited as `auth.passkey.add`, with the proof that allowed it.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [cid, credential]
+ properties:
+ cid: { type: string }
+ credential: { $ref: '#/components/schemas/WebAuthnRegistrationCredential' }
+ name: { type: string, maxLength: 40, description: 'A label of the owner''s choosing ("Work laptop").' }
+ responses:
+ '200':
+ description: Added. The list as it is now.
+ content:
+ application/json:
+ schema:
+ allOf:
+ - $ref: '#/components/schemas/PasskeyList'
+ - type: object
+ properties:
+ ok: { type: boolean, const: true }
+ '400':
+ description: Challenge expired, replayed or made for another profile, or the attestation did not verify.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "challenge expired — try again" }
+ '401':
+ description: >-
+ Not signed in — including a session that was ended ("sign out everywhere", a
+ new password) after step 1.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "not signed in" }
+ '409':
+ description: '`credential-exists` (that passkey is already registered) or `passkey-limit`.'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "credential already registered", code: "credential-exists" }
+
+ /api/account/passkeys/rename:
+ post:
+ tags: [passkeys]
+ operationId: renamePasskey
+ summary: Name one passkey
+ description: An empty name clears it; the app then shows a numbered "Passkey n".
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [id]
+ properties:
+ id: { type: string }
+ name: { type: string, maxLength: 40 }
+ responses:
+ '200':
+ description: Renamed. The list as it is now.
+ content:
+ application/json:
+ schema:
+ allOf:
+ - $ref: '#/components/schemas/PasskeyList'
+ - type: object
+ properties:
+ ok: { type: boolean, const: true }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '404':
+ description: No passkey of this profile has that id.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "passkey not found", code: "not-found" }
+
+ /api/account/device-link:
+ post:
+ tags: [passkeys]
+ operationId: createDeviceLink
+ summary: Make a one-time device link
+ description: |
+ For adding another device of the same person: returns a code of 12 characters from
+ the pairing alphabet (60 bits), which the app also shows as a QR code of
+ `<app>?link=<code>`. The other device redeems it with `/api/device-link/*` by
+ creating a passkey of its own. The code is shown once, stored only as a SHA-256,
+ good for 10 minutes and for one passkey; a newer one replaces it, and signing out
+ everywhere, a new password, an admin reset or a disable drop it. Same proof as
+ adding a passkey. Audited as `auth.link.create`.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/OwnerProof' }
+ responses:
+ '200':
+ description: The code, once.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ code: { type: string }
+ expires: { type: number, description: Expiry (ms). }
+ example: { code: "K7WQ-2MZP-4HXA", expires: 1790000000000 }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '403': { $ref: '#/components/responses/ProofRefused' }
+ '409': { $ref: '#/components/responses/PasskeyLimit' }
+ '429': { $ref: '#/components/responses/TooManyRequests' }
+ '503': { $ref: '#/components/responses/Busy' }
+
+ /api/device-link/options:
+ post:
+ tags: [passkeys]
+ operationId: deviceLinkOptions
+ summary: 'Redeem a device link (step 1): check the code, get creation options'
+ description: |
+ Called on the other device, which has no session: the code is the credential.
+ Returns creation options for the profile the code belongs to, and that profile's
+ name. Does not use the code up, so a dismissed passkey prompt can be tried again.
+ Wrong codes count toward a per-address pause of link redemption (see
+ *Throttling*). **Not** CSRF-exempt.
+ security: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [code]
+ properties:
+ code: { type: string, description: 'Case, spaces and dashes are ignored.' }
+ example: { code: "K7WQ-2MZP-4HXA" }
+ responses:
+ '200':
+ description: Ceremony options.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ cid: { type: string }
+ options: { $ref: '#/components/schemas/WebAuthnRegistrationOptions' }
+ name: { type: string, description: The profile this device is being added to. }
+ '400': { $ref: '#/components/responses/LinkInvalid' }
+ '409': { $ref: '#/components/responses/PasskeyLimit' }
+ '429': { $ref: '#/components/responses/TooManyRequests' }
+
+ /api/device-link/verify:
+ post:
+ tags: [passkeys]
+ operationId: deviceLinkVerify
+ summary: 'Redeem a device link (step 2): store the passkey and sign this device in'
+ description: |
+ Verifies the attestation against the challenge from step 1 (which must have been
+ made for this very code), stores the passkey on the code's profile, burns the code
+ and sets the session cookie — the passkey just made is what signs the device in.
+ Of two requests racing with one code, one wins. Audited as `auth.link.ok`, and every
+ refusal as `auth.link.fail`. **Not** CSRF-exempt.
+ security: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [code, cid, credential]
+ properties:
+ code: { type: string }
+ cid: { type: string }
+ credential: { $ref: '#/components/schemas/WebAuthnRegistrationCredential' }
+ name: { type: string, maxLength: 40 }
+ responses:
+ '200':
+ description: Added and signed in.
+ headers:
+ Set-Cookie:
+ description: Session cookie (see /api/register/verify).
+ schema: { type: string }
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user: { $ref: '#/components/schemas/SessionUser' }
+ '400':
+ description: >-
+ `link-invalid` (see below), a challenge that expired or was made for another
+ code, or an attestation that did not verify.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "that code is wrong, used or expired", code: "link-invalid" }
+ '409':
+ description: '`credential-exists` or `passkey-limit`.'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "credential already registered", code: "credential-exists" }
+ '429': { $ref: '#/components/responses/TooManyRequests' }
+
/api/data:
get:
tags: [data]
@@ -2171,6 +2487,30 @@ components:
schema: { $ref: '#/components/schemas/Error' }
example: { error: "another profile already signs in with this name", code: "name-taken" }
+ ProofRefused:
+ description: >-
+ No acceptable proof that the owner is here: `passkey-required` (no password, so a
+ passkey has to confirm), `passkey` (the assertion did not verify or belongs to
+ another profile), `current-required` or `current-wrong`.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "confirm with your passkey first", code: "passkey-required" }
+ PasskeyLimit:
+ description: The profile already has the most passkeys it can have (20).
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "a profile can have at most 20 passkeys", code: "passkey-limit" }
+ LinkInvalid:
+ description: >-
+ The code is wrong, used, replaced or expired, or its profile is gone or disabled —
+ one answer for all of them.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "that code is wrong, used or expired", code: "link-invalid" }
+
schemas:
Error:
type: object
@@ -2193,6 +2533,40 @@ components:
properties:
ok: { type: boolean, const: true }
+ PasskeyList:
+ type: object
+ properties:
+ passkeys:
+ type: array
+ items:
+ type: object
+ properties:
+ id: { type: string, description: WebAuthn credential id (base64url). }
+ name: { oneOf: [{ type: string }, { type: 'null' }] }
+ created: { oneOf: [{ type: string }, { type: 'null' }], description: ISO timestamp. }
+ lastUsed: { oneOf: [{ type: string }, { type: 'null' }], description: 'ISO timestamp of the last sign-in or confirmation with it.' }
+ transports: { type: array, items: { type: string } }
+ password:
+ type: boolean
+ description: The profile has a password, so `current` can prove an addition.
+ lastWayIn:
+ type: boolean
+ description: Removing any one passkey would be refused (409 `last-way-in`).
+ example:
+ passkeys: [{ id: "g3Xq…", name: "Laptop", created: "2026-09-23T10:00:00.000Z", lastUsed: "2026-09-23T10:00:00.000Z", transports: [internal] }]
+ password: false
+ lastWayIn: true
+
+ OwnerProof:
+ type: object
+ description: >-
+ Either a passkey assertion made for this request (`cid` + `credential`), or the
+ profile's current password (`current`).
+ properties:
+ cid: { type: string, description: 'From POST /api/login/options.' }
+ credential: { $ref: '#/components/schemas/WebAuthnAuthenticationCredential' }
+ current: { type: string }
+
SessionUser:
type: object
description: The caller's identity, as returned by /api/me and the sign-in routes.
diff --git a/api/passkeys-store.js b/api/passkeys-store.js
index a2f346347..479859877 100644
--- a/api/passkeys-store.js
+++ b/api/passkeys-store.js
@@ -1,33 +1,79 @@
+/* More than one passkey on a profile (#95).
+ *
+ * A passkey lives where it was made — Windows Hello on one PC, one phone's keychain, one security
+ * key — so a profile that only ever had the passkey it was created with could not be reached from
+ * a second device, and "Create profile" there made a new, empty one. These are the bookkeeping
+ * rules for more than one, kept out of server.js so they can be tested without a WebAuthn
+ * ceremony: which rows belong to whom, what a list may show of them, and the rule that matters
+ * most — a profile never loses its last way in.
+ *
+ * `otherWays` is how many ways besides its passkeys can still sign the profile in (a password, on
+ * an instance with password sign-in on). server.js decides that; this only counts. */
+
+// Far above anyone's real use — a phone, a laptop, a security key or two. What it bounds is a
+// signed-in session adding rows to db.json, which is rewritten whole on every save.
+export const MAX_PASSKEYS = 20;
+export const NAME_MAX = 40;
+
+// A label someone typed: control characters out, runs of whitespace folded, capped. Empty means
+// no name, and the app shows a numbered "Passkey n" instead.
+export const passkeyName = v => (typeof v === 'string' ? v : '')
+ .replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, NAME_MAX);
+
+// `transports` comes from the browser that made the passkey, which is to say from the request. It
+// is handed back to browsers as a hint, so only a short list of short words is kept.
+const transportsOf = v => (Array.isArray(v) ? v.filter(x => typeof x === 'string' && x.length <= 16).slice(0, 8) : []);
+
+// What the owner sees of their passkeys: never the public key, which nothing on screen needs.
export function listPasskeys(db, userId) {
return (db.creds || [])
.filter(c => c.userId === userId)
.map(c => ({
id: c.id,
+ name: c.name || null,
+ // Passkeys made before these fields existed have neither; the list leaves the line out.
created: c.created || null,
- transports: c.transports || []
+ lastUsed: c.lastUsed || null,
+ transports: transportsOf(c.transports)
}));
}
export function addPasskeyRecord(db, userId, cred) {
db.creds = db.creds || [];
- if (db.creds.some(c => c.id === cred.id)) return { error: 'credential already registered' };
- db.creds.push({
+ if (db.creds.some(c => c.id === cred.id)) return { error: 'credential already registered', code: 'credential-exists' };
+ if (db.creds.filter(c => c.userId === userId).length >= MAX_PASSKEYS) {
+ return { error: `a profile can have at most ${MAX_PASSKEYS} passkeys`, code: 'passkey-limit' };
+ }
+ const row = {
id: cred.id,
userId,
publicKey: cred.publicKey,
counter: cred.counter || 0,
- transports: cred.transports || [],
+ transports: transportsOf(cred.transports),
created: cred.created || new Date().toISOString()
- });
- return { ok: true };
+ };
+ const name = passkeyName(cred.name);
+ if (name) row.name = name;
+ db.creds.push(row);
+ return { ok: true, row };
+}
+
+export function renamePasskeyRecord(db, userId, credId, name) {
+ const row = (db.creds || []).find(c => c.id === credId && c.userId === userId);
+ if (!row) return { error: 'passkey not found', code: 'not-found' };
+ const clean = passkeyName(name);
+ if (clean) row.name = clean; else delete row.name;
+ return { ok: true, row };
}
-export function removePasskeyRecord(db, userId, credId) {
+// Refused when it would leave the profile with no way in at all: its last passkey goes only while
+// something else (`otherWays`) can still sign it in.
+export function removePasskeyRecord(db, userId, credId, otherWays = 0) {
db.creds = db.creds || [];
const i = db.creds.findIndex(c => c.id === credId && c.userId === userId);
- if (i < 0) return { error: 'passkey not found' };
- const mine = db.creds.filter(c => c.userId === userId);
- if (mine.length <= 1) return { error: 'keep at least one passkey' };
- db.creds.splice(i, 1);
- return { ok: true };
+ if (i < 0) return { error: 'passkey not found', code: 'not-found' };
+ const mine = db.creds.filter(c => c.userId === userId).length;
+ if (mine - 1 + otherWays < 1) return { error: 'this passkey is the only way into this profile', code: 'last-way-in' };
+ const [row] = db.creds.splice(i, 1);
+ return { ok: true, row };
}
diff --git a/api/server.js b/api/server.js
index 9457e366a..cdcfde306 100644
--- a/api/server.js
+++ b/api/server.js
@@ -24,6 +24,10 @@ import {
MIN_LENGTH, MAX_LENGTH, makeResetCode, hashResetCode, resetCodeMatches, RESET_TTL_MS, warmUp
} from './password.js';
import { createBackoff, createWindow } from './rate-limit.js';
+import {
+ listPasskeys, addPasskeyRecord, renamePasskeyRecord, removePasskeyRecord, MAX_PASSKEYS
+} from './passkeys-store.js';
+import { createDeviceLink, findDeviceLink, burnDeviceLink, dropDeviceLinks } from './device-link.js';
const PORT = +(process.env.PORT || 3000);
const DATA = process.env.DATA_DIR || '/data';
@@ -81,6 +85,7 @@ let db = { users: [], creds: [], subs: [], invites: [] };
try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
db.subs = db.subs || [];
db.invites = db.invites || [];
+db.deviceLinks = db.deviceLinks || []; // unused one-time device links, hashed (device-link.js)
const isAdmin = user => !!user && (user.admin === true || ADMIN_UIDS.includes(user.id));
// 0600: db.json holds passkey credential material. It used to be covered by a blanket 0700 on
// the whole directory; now that the directory stays traversable, the file carries its own mode.
@@ -732,19 +737,23 @@ if (AUDIT_ON) {
}
/* ---------- sign-in throttle ---------- */
-// The password routes are counted (rate-limit.js), and only those — so only on an instance with
-// PASSWORD_LOGIN on, since none of them exists otherwise. Passkey sign-in, passkey registration
-// and phone pairing stay out of it, as they always were: nothing there is worth guessing (an
-// assertion is a signature, an invite code 64 random bits, a pairing code lives five minutes),
-// and behind a proxy that hands the API one address for every visitor a per-address count on
-// them would let one stranger pause everybody's way in. Three counts:
+// The password routes are counted (rate-limit.js) — only on an instance with PASSWORD_LOGIN on,
+// since none of them exists otherwise — and so are the two that redeem a device link (#95).
+// Passkey sign-in, passkey registration and phone pairing stay out of it, as they always were:
+// nothing there is worth guessing (an assertion is a signature, an invite code 64 random bits, a
+// pairing code lives five minutes), and behind a proxy that hands the API one address for every
+// visitor a per-address count on them would let one stranger pause everybody's way in. A
+// device-link code is 60 bits that live ten minutes, no more worth guessing than a pairing code,
+// but it is counted the way a reset code is: every wrong one is a guess at a way into somebody's
+// profile, and the pause it can start only ever stops link redemption, never a sign-in.
+// Three counts:
//
-// AUTH_BURST every request to a password route, 60 a minute per address. Enough for a
+// AUTH_BURST every request to a counted route, 60 a minute per address. Enough for a
// household behind one proxy; not enough to run scrypt as fast as one client
// can ask.
// ADDR_FAILS wrong answers per address and per kind (a password or reset code, an invite
-// code on password signup): 20 free, then a pause of 30 s that doubles up to
-// 15 min.
+// code on password signup, a device-link code): 20 free, then a pause of 30 s
+// that doubles up to 15 min.
// ACCOUNT_FAILS wrong passwords per *name*, whoever sends them: 5 free, then 1 min doubling
// up to 1 h, forgotten after a day without one or on the next success. This is
// the one that protects a password — an address is cheap to change, a name is
@@ -774,7 +783,11 @@ setInterval(() => { AUTH_BURST.sweep(); ADDR_FAILS.sweep(); ACCOUNT_FAILS.sweep(
const THROTTLED = {
'POST /api/login/password': 'password', 'POST /api/login/password-reset': 'password',
'POST /api/register/password': 'signup',
- 'POST /api/account/password': 'password', 'DELETE /api/account/password': null
+ 'POST /api/account/password': 'password', 'DELETE /api/account/password': null,
+ // Redeeming a device link (#95). Adding a passkey and making a link only spend the budget: the
+ // password that may prove them counts its own failures (passwordAttempt).
+ 'POST /api/device-link/options': 'link', 'POST /api/device-link/verify': 'link',
+ 'POST /api/account/passkeys/options': null, 'POST /api/account/device-link': null
};
// Which address the throttle counts against. Unlike clientIp() above, which only labels a log
@@ -851,14 +864,15 @@ const policyError = (res, problem) => json(res, 400, { error: POLICY_ERRORS[prob
const WRONG = { error: 'wrong name or password', code: 'bad-credentials' };
// A new password ends every other session of the account, the way "sign out everywhere" does,
-// pending pairing codes included; the caller's own is re-issued by the route. Always a new
-// record, never an edit of the old one: a check still running against the old one tells the two
-// apart by that (see POST /api/login/password).
+// pending pairing codes and device links included; the caller's own is re-issued by the route.
+// Always a new record, never an edit of the old one: a check still running against the old one
+// tells the two apart by that (see POST /api/login/password).
function setPassword(user, h) {
user.pw = { h, set: new Date().toISOString() };
delete user.pwReset;
user.sv = sessionVersion(user) + 1;
for (const [k, v] of pairings) if (v.uid === user.id) pairings.delete(k);
+ dropDeviceLinks(db, user.id);
}
// A passkey assertion made just now by the signed-in account itself — how someone who has no
@@ -878,6 +892,7 @@ async function passkeyStepUp(user, body) {
});
if (!v.verified) return false;
cred.counter = v.authenticationInfo.newCounter;
+ cred.lastUsed = new Date().toISOString();
return true;
} catch { return false; }
}
@@ -915,6 +930,45 @@ function passwordAttempt(req, res, k) {
};
}
+// Proof that whoever holds this session is the account's owner right now, for the changes that
+// add a lasting way in — a password, another passkey, a device link. A session on its own is not
+// enough for those: it may be a cookie someone walked off with, and each of them would outlive
+// "sign out everywhere". Either a passkey assertion made for this request (`cid` from
+// /api/login/options, `credential` signed by one of this account's passkeys), or the current
+// password when there is one. The password counts here even on an instance that has since
+// switched password sign-in off: it is still the owner's secret, and it is how a profile that only
+// ever had a password gets onto a passkey. Answers the refusal itself and returns null, or says
+// which proof it was ('passkey' | 'password'). Wrong passwords count toward the sign-in pause.
+async function proveOwner(req, res, user, body, failEv) {
+ if (body.credential) {
+ if (await passkeyStepUp(user, body)) return 'passkey';
+ audit(req, failEv, { ok: false, user, msg: 'step-up-failed' });
+ json(res, 403, { error: 'the passkey could not be verified', code: 'passkey' });
+ return null;
+ }
+ if (!hasPassword(user)) {
+ json(res, 403, { error: 'confirm with your passkey first', code: 'passkey-required' });
+ return null;
+ }
+ const current = typeof body.current === 'string' ? body.current : '';
+ const wrongCurrent = () => { json(res, 403, { error: 'your current password is not right', code: 'current-wrong' }); return null; };
+ if (!current) {
+ json(res, 403, { error: 'enter your current password', code: 'current-required' });
+ return null;
+ }
+ const check = passwordAttempt(req, res, nameKey(user.name));
+ if (!check) return null;
+ const rec = user.pw;
+ if (!(await check.verify(current, rec.h))) {
+ check.failed(user, 'bad-current');
+ return wrongCurrent();
+ }
+ // Changed or removed while it was being checked: it is no longer the current password.
+ if (user.pw !== rec) { check.void(); return wrongCurrent(); }
+ check.ok();
+ return 'password';
+}
+
if (PASSWORD_LOGIN) warmUp();
const passwordRoutes = {
@@ -1019,31 +1073,8 @@ const passwordRoutes = {
const taken = () => json(res, 409, { error: 'another profile already signs in with this name', code: 'name-taken' });
if (nameTaken(user.name, user.id)) return taken();
const k = nameKey(user.name);
- let proof;
- if (body.credential) {
- if (!(await passkeyStepUp(user, body))) {
- audit(req, 'auth.password.fail', { ok: false, user, msg: 'step-up-failed' });
- return json(res, 403, { error: 'the passkey could not be verified', code: 'passkey' });
- }
- proof = 'passkey';
- } else if (hasPassword(user)) {
- const current = typeof body.current === 'string' ? body.current : '';
- const wrongCurrent = () => json(res, 403, { error: 'your current password is not right', code: 'current-wrong' });
- if (!current) return json(res, 403, { error: 'enter your current password', code: 'current-required' });
- const check = passwordAttempt(req, res, k);
- if (!check) return;
- const rec = user.pw;
- if (!(await check.verify(current, rec.h))) {
- check.failed(user, 'bad-current');
- return wrongCurrent();
- }
- // Changed or removed while it was being checked: it is no longer the current password.
- if (user.pw !== rec) { check.void(); return wrongCurrent(); }
- check.ok();
- proof = 'password';
- } else {
- return json(res, 403, { error: 'confirm with your passkey first', code: 'passkey-required' });
- }
+ const proof = await proveOwner(req, res, user, body, 'auth.password.fail');
+ if (!proof) return;
const h = await hashPassword(body.next);
// Everything above awaited: an admin reset, a disable or "sign out everywhere" may have ended
// this session in the meantime, and a password set now would outlive that.
@@ -1091,6 +1122,7 @@ const passwordRoutes = {
u.pwReset = { h: hashResetCode(code), exp: Date.now() + RESET_TTL_MS, by: admin.id };
u.sv = sessionVersion(u) + 1;
for (const [k, v] of pairings) if (v.uid === u.id) pairings.delete(k);
+ dropDeviceLinks(db, u.id);
presence.delete(u.id);
saveDb();
audit(req, 'admin.password.reset', { user: admin, target: u });
@@ -1135,6 +1167,233 @@ const passwordRoutes = {
}
};
+/* ---------- more than one passkey, and one-time device links (#95) ---------- */
+// A passkey lives where it was made — Windows Hello on one PC, one phone's keychain, one security
+// key — so a profile that only had the passkey it was created with could not be reached from a
+// second device, and "Create profile" there made a new, empty one. Two ways to add another:
+//
+// Settings → Passkeys → Add: a registration ceremony in the signed-in browser, for any other
+// authenticator it can reach — a security key, a password manager, a phone through the
+// browser's own QR prompt.
+//
+// A device link: the signed-in device shows a one-time code (device-link.js), and the other
+// device redeems it by creating a passkey of its own, which is what then signs it in. The code
+// never opens a session by itself: whoever redeems it leaves a passkey on the profile, listed
+// in Settings where the owner sees it and can remove it.
+//
+// Either way the new passkey is a way into the profile that outlives "sign out everywhere", so
+// both ask for the proof a first password does (proveOwner). Removing one never leaves a profile
+// without a way in: its last passkey stays unless a password can sign in instead.
+//
+// Sessions are not tied to the passkey that opened them — a session is `uid:expiry:version`,
+// nothing more — so removing a passkey stops it signing in again but does not end a session it
+// already opened. "Sign out everywhere" does that, and Settings says so where a passkey is removed.
+const passwordWayIn = u => PASSWORD_LOGIN && hasPassword(u);
+const passkeyState = u => {
+ const passkeys = listPasskeys(db, u.id);
+ // `password`: whether a password can confirm an addition (proveOwner). `lastWayIn`: whether
+ // removing any one passkey would be refused.
+ return { passkeys, password: hasPassword(u), lastWayIn: passkeys.length + (passwordWayIn(u) ? 1 : 0) <= 1 };
+};
+const LIMIT = { error: `a profile can have at most ${MAX_PASSKEYS} passkeys`, code: 'passkey-limit' };
+const LINK_INVALID = { error: 'that code is wrong, used or expired', code: 'link-invalid' };
+const notSignedIn = res => json(res, 401, { error: 'not signed in' });
+
+// Creation options for another passkey of `user`. The user handle is the profile's id, exactly as
+// at sign-up, so an authenticator files the new passkey under the same account; the passkeys the
+// profile has already are excluded, so an authenticator that holds one of them says so instead of
+// making a second.
+const moreOptions = user => generateRegistrationOptions({
+ rpName: RP_NAME, rpID: RP_ID,
+ userID: Buffer.from(user.id), userName: user.name, userDisplayName: user.name,
+ attestationType: 'none',
+ authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
+ excludeCredentials: db.creds.filter(c => c.userId === user.id).map(c => ({ id: c.id, transports: c.transports || [] }))
+});
+
+// The second half of either ceremony: the new passkey as a db.creds row, or null once the
+// refusal has been answered and audited as `ev`.
+async function newPasskey(req, res, c, body, ev, user) {
+ let verification;
+ try {
+ verification = await verifyRegistrationResponse({
+ response: body.credential, expectedChallenge: c.challenge, expectedOrigin: ORIGIN, expectedRPID: RP_ID,
+ requireUserVerification: false
+ });
+ } catch (e) {
+ // e.message can echo attacker-supplied response fields, so only the reason code is kept.
+ audit(req, ev, { ok: false, user, msg: 'verify-error' });
+ json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });
+ return null;
+ }
+ if (!verification.verified) {
+ audit(req, ev, { ok: false, user, msg: 'not-verified' });
+ json(res, 400, { error: 'not verified' });
+ return null;
+ }
+ const { credential } = verification.registrationInfo;
+ return {
+ id: credential.id,
+ publicKey: Buffer.from(credential.publicKey).toString('base64url'),
+ counter: credential.counter || 0,
+ transports: body.credential?.response?.transports,
+ name: body.name
+ };
+}
+
+const passkeyRoutes = {
+ 'GET /api/account/passkeys': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return notSignedIn(res);
+ json(res, 200, passkeyState(user));
+ },
+
+ // Adding one from Settings, step one: the proof, then the options. The proof is spent here; the
+ // challenge that comes back is good for five minutes, for this profile, under this session
+ // version — "sign out everywhere" in between ends the ceremony with everything else.
+ 'POST /api/account/passkeys/options': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return notSignedIn(res);
+ const body = await readBody(req);
+ if (passkeyCount(user) >= MAX_PASSKEYS) return json(res, 409, LIMIT);
+ const proof = await proveOwner(req, res, user, body, 'auth.passkey.fail');
+ if (!proof) return;
+ // Awaited: a sign-out everywhere, a disable or an admin reset may have ended this session.
+ if (readSession(req) !== user) return notSignedIn(res);
+ if (proof === 'passkey') saveDb(); // the confirming passkey's counter and last use
+ const options = await moreOptions(user);
+ const cid = putChallenge({ challenge: options.challenge, uid: user.id, kind: 'add', sv: sessionVersion(user), proof });
+ json(res, 200, { cid, options });
+ },
+
+ 'POST /api/account/passkeys/verify': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return notSignedIn(res);
+ const body = await readBody(req);
+ const c = takeChallenge(text(body.cid));
+ if (!c || c.kind !== 'add' || c.uid !== user.id) {
+ audit(req, 'auth.passkey.fail', { ok: false, user, msg: 'challenge-expired' });
+ return json(res, 400, { error: 'challenge expired — try again' });
+ }
+ const cred = await newPasskey(req, res, c, body, 'auth.passkey.fail', user);
+ if (!cred) return;
+ if (readSession(req) !== user || sessionVersion(user) !== c.sv) return notSignedIn(res);
+ const added = addPasskeyRecord(db, user.id, cred);
+ if (added.error) {
+ audit(req, 'auth.passkey.fail', { ok: false, user, msg: added.code });
+ return json(res, 409, { error: added.error, code: added.code });
+ }
+ saveDb();
+ audit(req, 'auth.passkey.add', { user, msg: c.proof });
+ json(res, 200, { ok: true, ...passkeyState(user) });
+ },
+
+ 'POST /api/account/passkeys/rename': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return notSignedIn(res);
+ const body = await readBody(req);
+ const r = renamePasskeyRecord(db, user.id, text(body.id), body.name);
+ if (r.error) return json(res, 404, { error: r.error, code: r.code });
+ saveDb();
+ json(res, 200, { ok: true, ...passkeyState(user) });
+ },
+
+ // `?id=` — the credential id from the list. No proof: removing takes a way in away rather than
+ // adding one, and the last one is never removed (removePasskeyRecord).
+ 'DELETE /api/account/passkeys': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return notSignedIn(res);
+ const id = new URL(req.url, 'http://x').searchParams.get('id') || '';
+ const r = removePasskeyRecord(db, user.id, id, passwordWayIn(user) ? 1 : 0);
+ if (r.error) return json(res, r.code === 'last-way-in' ? 409 : 404, { error: r.error, code: r.code });
+ saveDb();
+ audit(req, 'auth.passkey.remove', { user, msg: r.row.name || null });
+ json(res, 200, { ok: true, ...passkeyState(user) });
+ },
+
+ // Makes the code another device redeems below. Same proof as adding a passkey here, because the
+ // code is how a passkey gets added there.
+ 'POST /api/account/device-link': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return notSignedIn(res);
+ const body = await readBody(req);
+ if (passkeyCount(user) >= MAX_PASSKEYS) return json(res, 409, LIMIT);
+ const proof = await proveOwner(req, res, user, body, 'auth.link.fail');
+ if (!proof) return;
+ if (readSession(req) !== user) return notSignedIn(res);
+ const { code, link } = createDeviceLink(db, user.id);
+ saveDb();
+ audit(req, 'auth.link.create', { user, msg: proof });
+ json(res, 200, { code, expires: link.exp });
+ },
+
+ // Redeeming, from the other device, which has no session: the code is the credential. Step one
+ // checks it and hands back creation options for the profile it belongs to, and that profile's
+ // name, so the screen can say where this device is being added. It does not use the code up —
+ // a passkey prompt dismissed by mistake can be tried again — and wrong codes pause the address.
+ // Not CSRF-exempt: only the app's own origin can create a passkey for it anyway, and a code
+ // redeemed from anywhere else is not one the owner meant to hand over.
+ 'POST /api/device-link/options': async (req, res) => {
+ const body = await readBody(req);
+ if (addressPaused(req, res, 'link')) return;
+ const link = findDeviceLink(db, text(body.code));
+ if (!link) {
+ strikeAddress(req, 'link');
+ audit(req, 'auth.link.fail', { ok: false, msg: 'link-invalid' });
+ return json(res, 400, LINK_INVALID);
+ }
+ const user = db.users.find(u => u.id === link.userId);
+ if (!user || user.disabled) {
+ audit(req, 'auth.link.fail', { ok: false, uid: link.userId, msg: 'user-unavailable' });
+ return json(res, 400, LINK_INVALID);
+ }
+ if (passkeyCount(user) >= MAX_PASSKEYS) return json(res, 409, LIMIT);
+ const options = await moreOptions(user);
+ const cid = putChallenge({ challenge: options.challenge, uid: user.id, kind: 'link', lh: link.h });
+ json(res, 200, { cid, options, name: user.name });
+ },
+
+ // Step two: the new passkey is stored, the code is burned, and this device is signed in by the
+ // passkey it just made — the same cookie a passkey sign-in sets. Of two requests racing with one
+ // code, the first to finish wins and the other finds it gone.
+ 'POST /api/device-link/verify': async (req, res) => {
+ const body = await readBody(req);
+ if (addressPaused(req, res, 'link')) return;
+ const code = text(body.code);
+ const c = takeChallenge(text(body.cid));
+ const link = findDeviceLink(db, code);
+ if (!link) {
+ strikeAddress(req, 'link');
+ audit(req, 'auth.link.fail', { ok: false, msg: 'link-invalid' });
+ return json(res, 400, LINK_INVALID);
+ }
+ if (!c || c.kind !== 'link' || c.lh !== link.h || c.uid !== link.userId) {
+ audit(req, 'auth.link.fail', { ok: false, uid: link.userId, msg: 'challenge-expired' });
+ return json(res, 400, { error: 'challenge expired — try again' });
+ }
+ const owner = db.users.find(u => u.id === link.userId);
+ const cred = await newPasskey(req, res, c, body, 'auth.link.fail', owner || { id: link.userId });
+ if (!cred) return;
+ // Everything above awaited: the code may have been used, replaced or dropped since (a sign-out
+ // everywhere, a new password, a disable), and the profile may be gone or locked.
+ const user = db.users.find(u => u.id === link.userId);
+ if (findDeviceLink(db, code) !== link || !user || user.disabled) {
+ audit(req, 'auth.link.fail', { ok: false, uid: link.userId, msg: 'link-invalid' });
+ return json(res, 400, LINK_INVALID);
+ }
+ const added = addPasskeyRecord(db, user.id, cred);
+ if (added.error) {
+ audit(req, 'auth.link.fail', { ok: false, user, msg: added.code });
+ return json(res, 409, { error: added.error, code: added.code });
+ }
+ added.row.lastUsed = added.row.created;
+ burnDeviceLink(db, link);
+ saveDb();
+ audit(req, 'auth.link.ok', { user, msg: added.row.name || null });
+ json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });
+ }
+};
+
/* ---------- routes ---------- */
const routes = {
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
@@ -1249,7 +1508,9 @@ const routes = {
id: credential.id, userId: user.id,
publicKey: Buffer.from(credential.publicKey).toString('base64url'),
counter: credential.counter || 0,
- transports: body.credential?.response?.transports || []
+ transports: body.credential?.response?.transports || [],
+ // What Settings → Passkeys shows (#95); a passkey from before then has neither.
+ created: user.created, lastUsed: user.created
});
saveDb();
audit(req, 'auth.register.ok', { user, msg: invite ? invite.code : null });
@@ -1303,6 +1564,7 @@ const routes = {
return json(res, 400, { error: 'not verified' });
}
cred.counter = verification.authenticationInfo.newCounter;
+ cred.lastUsed = new Date().toISOString();
saveDb();
const user = db.users.find(u => u.id === cred.userId);
if (!user) {
@@ -1333,8 +1595,10 @@ const routes = {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
user.sv = sessionVersion(user) + 1;
- // An unredeemed pairing code is a session-in-waiting for this account; it goes too.
+ // An unredeemed pairing code is a session-in-waiting for this account; it goes too, and so
+ // does an unused device link.
for (const [k, v] of pairings) if (v.uid === user.id) pairings.delete(k);
+ dropDeviceLinks(db, user.id);
saveDb();
audit(req, 'auth.logout.all', { user });
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
@@ -1374,6 +1638,9 @@ const routes = {
// Absent entirely while PASSWORD_LOGIN is off, so each of them is a plain 404.
...(PASSWORD_LOGIN ? passwordRoutes : {}),
+ // Always there: more passkeys and device links need nothing an instance has to switch on.
+ ...passkeyRoutes,
+
// `rev` is the server's own count of writes to this profile (also stored inside the document as
// `_rev`, so every other reader of the file — reminder tick, admin, Coach, MCP — is unaffected).
// A client pushes it back as `baseRev`, and a write over a document it never saw is refused.
@@ -1598,6 +1865,8 @@ const routes = {
if (isAdmin(u)) return json(res, 400, { error: 'cannot disable an admin' });
u.disabled = !!body.disabled;
if (u.disabled) presence.delete(u.id); // drop them off "training now" at once
+ // A device link made before the lock would otherwise still be waiting when it is lifted.
+ if (u.disabled) dropDeviceLinks(db, u.id);
saveDb();
audit(req, u.disabled ? 'admin.user.disable' : 'admin.user.enable', { user: admin, target: u });
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
@@ -1620,6 +1889,7 @@ const routes = {
db.users = db.users.filter(x => x.id !== u.id);
db.creds = (db.creds || []).filter(c => c.userId !== u.id);
db.subs = (db.subs || []).filter(x => x.userId !== u.id);
+ dropDeviceLinks(db, u.id);
presence.delete(u.id);
// The training history and any Coach credential of theirs, both outside db.json.
try { fs.unlinkSync(stateFile(u.id)); } catch { /* already gone */ }
diff --git a/api/test/device-link.test.js b/api/test/device-link.test.js
index 68697f663..bb097ac1a 100644
--- a/api/test/device-link.test.js
+++ b/api/test/device-link.test.js
@@ -1,18 +1,31 @@
+/* The device-link bookkeeping (#95): one code per profile, hashed at rest, good once and for a few
+ minutes. The routes around it are in server-passkeys.test.js. */
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
-import { createDeviceLink, claimDeviceLink, deviceLinkUrl } from '../device-link.js';
+import {
+ createDeviceLink, findDeviceLink, burnDeviceLink, dropDeviceLinks, hashLinkCode, makeLinkCode, DEVICE_LINK_TTL_MS
+} from '../device-link.js';
describe('createDeviceLink', () => {
- it('issues a one-time token bound to the user, with an expiry', () => {
+ it('issues a code bound to the user, with an expiry, and keeps only its hash', () => {
const db = { deviceLinks: [] };
const now = 1_700_000_000_000;
- const link = createDeviceLink(db, 'user-a', now, 15 * 60 * 1000);
+ const { code, link } = createDeviceLink(db, 'user-a', now, 10 * 60 * 1000);
assert.equal(link.userId, 'user-a');
- assert.equal(link.exp, now + 15 * 60 * 1000);
- assert.equal(typeof link.token, 'string');
- assert.ok(link.token.length >= 20);
+ assert.equal(link.exp, now + 10 * 60 * 1000);
+ assert.match(code, /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/);
assert.equal(db.deviceLinks.length, 1);
- assert.equal(db.deviceLinks[0].token, link.token);
+ assert.equal(db.deviceLinks[0].h, hashLinkCode(code));
+ // Nowhere in what is stored does the code itself appear.
+ assert.doesNotMatch(JSON.stringify(db), new RegExp(code.replace(/-/g, '')));
+ assert.doesNotMatch(JSON.stringify(db), new RegExp(code));
+ });
+
+ it('lasts ten minutes unless told otherwise', () => {
+ const db = {};
+ const { link } = createDeviceLink(db, 'user-a', 1000);
+ assert.equal(link.exp, 1000 + DEVICE_LINK_TTL_MS);
+ assert.equal(DEVICE_LINK_TTL_MS, 10 * 60 * 1000);
});
it('replaces any unused link for the same user', () => {
@@ -20,8 +33,8 @@ describe('createDeviceLink', () => {
const first = createDeviceLink(db, 'user-a', 1000, 60_000);
const second = createDeviceLink(db, 'user-a', 2000, 60_000);
assert.equal(db.deviceLinks.length, 1);
- assert.equal(db.deviceLinks[0].token, second.token);
- assert.notEqual(first.token, second.token);
+ assert.equal(findDeviceLink(db, first.code, 2500), null);
+ assert.equal(findDeviceLink(db, second.code, 2500), second.link);
});
it('leaves another user’s unused link alone', () => {
@@ -30,46 +43,55 @@ describe('createDeviceLink', () => {
createDeviceLink(db, 'user-b', 1000, 60_000);
assert.equal(db.deviceLinks.length, 2);
});
+
+ it('makes codes that differ', () => {
+ const seen = new Set(Array.from({ length: 200 }, makeLinkCode));
+ assert.equal(seen.size, 200);
+ });
});
-describe('claimDeviceLink', () => {
- it('returns the user and burns the token', () => {
+describe('findDeviceLink', () => {
+ it('finds the link however the code is typed, without using it up', () => {
const db = { deviceLinks: [] };
- const link = createDeviceLink(db, 'user-a', 1000, 60_000);
- const claimed = claimDeviceLink(db, link.token, 2000);
- assert.deepEqual(claimed, { userId: 'user-a' });
- assert.equal(db.deviceLinks.length, 0);
- assert.deepEqual(claimDeviceLink(db, link.token, 3000), { error: 'unknown or already used' });
+ const { code, link } = createDeviceLink(db, 'user-a', 1000, 60_000);
+ assert.equal(findDeviceLink(db, code, 2000), link);
+ assert.equal(findDeviceLink(db, ' ' + code.toLowerCase().replace(/-/g, ' ') + ' ', 2000), link);
+ assert.equal(db.deviceLinks.length, 1);
});
- it('refuses an expired link and removes it', () => {
+ it('is single use once burned', () => {
const db = { deviceLinks: [] };
- const link = createDeviceLink(db, 'user-a', 1000, 60_000);
- const claimed = claimDeviceLink(db, link.token, 1000 + 60_000 + 1);
- assert.deepEqual(claimed, { error: 'link expired' });
+ const { code, link } = createDeviceLink(db, 'user-a', 1000, 60_000);
+ burnDeviceLink(db, link);
+ assert.equal(findDeviceLink(db, code, 2000), null);
assert.equal(db.deviceLinks.length, 0);
});
- it('refuses a missing token without touching other links', () => {
+ it('refuses an expired link and drops it', () => {
const db = { deviceLinks: [] };
+ const { code } = createDeviceLink(db, 'user-a', 1000, 60_000);
+ assert.equal(findDeviceLink(db, code, 1000 + 60_000 + 1), null);
+ assert.equal(db.deviceLinks.length, 0);
+ });
+
+ it('refuses a wrong code without touching other links, and ignores rows that are not links', () => {
+ const db = { deviceLinks: [null, { userId: 'x', exp: Infinity }] };
createDeviceLink(db, 'user-a', 1000, 60_000);
- assert.deepEqual(claimDeviceLink(db, 'nope', 1000), { error: 'unknown or already used' });
+ assert.equal(findDeviceLink(db, 'nope', 1000), null);
+ assert.equal(findDeviceLink(db, 'AAAA-AAAA-AAAA', 1000), null);
+ assert.equal(findDeviceLink(db, { toString: 1 }, 1000), null);
assert.equal(db.deviceLinks.length, 1);
});
});
-describe('deviceLinkUrl', () => {
- it('puts the token on the origin as ?link=', () => {
- assert.equal(
- deviceLinkUrl('https://gym.avott.duckdns.org', 'abc+1'),
- 'https://gym.avott.duckdns.org/?link=abc%2B1'
- );
- });
-
- it('does not double the slash when the origin already has one', () => {
- assert.equal(
- deviceLinkUrl('https://gym.example.com/', 'tok'),
- 'https://gym.example.com/?link=tok'
- );
+describe('dropDeviceLinks', () => {
+ it('drops only that user’s links and says whether any went', () => {
+ const db = { deviceLinks: [] };
+ const a = createDeviceLink(db, 'user-a', 1000, 60_000);
+ const b = createDeviceLink(db, 'user-b', 1000, 60_000);
+ assert.equal(dropDeviceLinks(db, 'user-a'), true);
+ assert.equal(dropDeviceLinks(db, 'user-a'), false);
+ assert.equal(findDeviceLink(db, a.code, 2000), null);
+ assert.equal(findDeviceLink(db, b.code, 2000), b.link);
});
});
diff --git a/api/test/passkeys-store.test.js b/api/test/passkeys-store.test.js
index c07190428..47d2bb7e2 100644
--- a/api/test/passkeys-store.test.js
+++ b/api/test/passkeys-store.test.js
@@ -1,6 +1,10 @@
+/* Bookkeeping for more than one passkey on a profile (#95). The routes are in
+ server-passkeys.test.js; this is the part that decides without a WebAuthn ceremony. */
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
-import { addPasskeyRecord, listPasskeys, removePasskeyRecord } from '../passkeys-store.js';
+import {
+ addPasskeyRecord, listPasskeys, removePasskeyRecord, renamePasskeyRecord, passkeyName, MAX_PASSKEYS
+} from '../passkeys-store.js';
const cred = (id, userId = 'u1') => ({
id, userId, publicKey: 'pk-' + id, counter: 0, transports: ['internal']
@@ -9,28 +13,70 @@ const cred = (id, userId = 'u1') => ({
describe('addPasskeyRecord', () => {
it('attaches a credential to the existing user', () => {
const db = { creds: [cred('hello', 'u1')] };
- const r = addPasskeyRecord(db, 'u1', cred('phone', 'u1'));
- assert.deepEqual(r, { ok: true });
+ const r = addPasskeyRecord(db, 'u1', { ...cred('phone', 'u1'), name: ' Work phone ' });
+ assert.equal(r.ok, true);
assert.equal(db.creds.length, 2);
assert.equal(db.creds[1].id, 'phone');
assert.equal(db.creds[1].userId, 'u1');
+ assert.equal(db.creds[1].name, 'Work phone');
assert.ok(db.creds[1].created);
});
it('refuses a credential id that already exists', () => {
const db = { creds: [cred('hello', 'u1')] };
const r = addPasskeyRecord(db, 'u2', cred('hello', 'u2'));
- assert.deepEqual(r, { error: 'credential already registered' });
+ assert.deepEqual(r, { error: 'credential already registered', code: 'credential-exists' });
assert.equal(db.creds.length, 1);
});
+
+ it('keeps only a short list of short transport words', () => {
+ const db = { creds: [] };
+ addPasskeyRecord(db, 'u1', { ...cred('a'), transports: ['usb', 42, 'x'.repeat(100), ...Array(20).fill('nfc')] });
+ assert.deepEqual(db.creds[0].transports, ['usb', ...Array(7).fill('nfc')]);
+ addPasskeyRecord(db, 'u1', { ...cred('b'), transports: 'internal' });
+ assert.deepEqual(db.creds[1].transports, []);
+ });
+
+ it(`stops at ${MAX_PASSKEYS} passkeys per profile`, () => {
+ const db = { creds: Array.from({ length: MAX_PASSKEYS }, (_, i) => cred('k' + i)) };
+ assert.equal(addPasskeyRecord(db, 'u1', cred('one-more')).code, 'passkey-limit');
+ assert.equal(addPasskeyRecord(db, 'u2', cred('theirs', 'u2')).ok, true);
+ });
});
describe('listPasskeys', () => {
it('returns only this user’s credentials, without the public key', () => {
- const db = { creds: [cred('a', 'u1'), cred('b', 'u2'), cred('c', 'u1')] };
+ const db = { creds: [cred('a', 'u1'), cred('b', 'u2'), { ...cred('c', 'u1'), name: 'Laptop', created: 'x', lastUsed: 'y' }] };
const list = listPasskeys(db, 'u1');
assert.deepEqual(list.map(c => c.id), ['a', 'c']);
for (const c of list) assert.equal(c.publicKey, undefined);
+ assert.deepEqual(list[0], { id: 'a', name: null, created: null, lastUsed: null, transports: ['internal'] });
+ assert.deepEqual(list[1], { id: 'c', name: 'Laptop', created: 'x', lastUsed: 'y', transports: ['internal'] });
+ });
+});
+
+describe('renamePasskeyRecord', () => {
+ it('names one of the user’s passkeys, and an empty name clears it', () => {
+ const db = { creds: [cred('a', 'u1')] };
+ assert.equal(renamePasskeyRecord(db, 'u1', 'a', 'Security key\n').ok, true);
+ assert.equal(db.creds[0].name, 'Security key');
+ renamePasskeyRecord(db, 'u1', 'a', ' ');
+ assert.equal('name' in db.creds[0], false);
+ });
+
+ it('does not touch another user’s passkey', () => {
+ const db = { creds: [cred('a', 'u1')] };
+ assert.equal(renamePasskeyRecord(db, 'u2', 'a', 'mine now').code, 'not-found');
+ assert.equal(db.creds[0].name, undefined);
+ });
+});
+
+describe('passkeyName', () => {
+ it('folds whitespace and control characters, and caps the length', () => {
+ assert.equal(passkeyName('a\u0000b\tc'), 'a b c');
+ assert.equal(passkeyName('x'.repeat(100)).length, 40);
+ assert.equal(passkeyName(42), '');
+ assert.equal(passkeyName({ toString: () => 'x' }), '');
});
});
@@ -38,21 +84,28 @@ describe('removePasskeyRecord', () => {
it('removes one of several passkeys', () => {
const db = { creds: [cred('hello', 'u1'), cred('phone', 'u1')] };
const r = removePasskeyRecord(db, 'u1', 'hello');
- assert.deepEqual(r, { ok: true });
+ assert.equal(r.ok, true);
+ assert.equal(r.row.id, 'hello');
assert.deepEqual(db.creds.map(c => c.id), ['phone']);
});
- it('refuses to remove the last passkey', () => {
- const db = { creds: [cred('hello', 'u1')] };
+ it('refuses to remove the last passkey when nothing else signs the profile in', () => {
+ const db = { creds: [cred('hello', 'u1'), cred('other', 'u2')] };
const r = removePasskeyRecord(db, 'u1', 'hello');
- assert.deepEqual(r, { error: 'keep at least one passkey' });
- assert.equal(db.creds.length, 1);
+ assert.deepEqual(r, { error: 'this passkey is the only way into this profile', code: 'last-way-in' });
+ assert.equal(db.creds.length, 2);
+ });
+
+ it('lets the last passkey go while a password still signs the profile in', () => {
+ const db = { creds: [cred('hello', 'u1')] };
+ assert.equal(removePasskeyRecord(db, 'u1', 'hello', 1).ok, true);
+ assert.equal(db.creds.length, 0);
});
it('does not let one user delete another’s passkey', () => {
const db = { creds: [cred('hello', 'u1'), cred('other', 'u2')] };
const r = removePasskeyRecord(db, 'u2', 'hello');
- assert.deepEqual(r, { error: 'passkey not found' });
+ assert.deepEqual(r, { error: 'passkey not found', code: 'not-found' });
assert.equal(db.creds.length, 2);
});
});
diff --git a/api/test/server-passkeys.test.js b/api/test/server-passkeys.test.js
new file mode 100644
index 000000000..7cacec876
--- /dev/null
+++ b/api/test/server-passkeys.test.js
@@ -0,0 +1,514 @@
+/* More than one passkey per profile, and one-time device links (#95): the routes, the proof they
+ ask for, the last-way-in rule, the throttle in front of link redemption and the audit trail.
+ Real server.js in a child, the same harness as server-password.test.js; every test talks from
+ its own X-Forwarded-For address (TRUST_PROXY=1), so one test's failures never pause another's.
+ The authenticator is software: a P-256 key that makes attestations ("none") and assertions the
+ way a browser's would. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { hashPassword } from '../password.js';
+import { hashLinkCode } from '../device-link.js';
+import { MAX_PASSKEYS } from '../passkeys-store.js';
+import { boundPort } from './helpers.mjs';
+
+const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SECRET = crypto.randomBytes(32).toString('hex');
+const ORIGIN = 'http://localhost:8080';
+const b64u = b => Buffer.from(b).toString('base64url');
+const sha = b => crypto.createHash('sha256').update(b).digest();
+
+const mintSession = (uid, sv = 0) => {
+ const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
+ return 'gymsid=' + payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
+};
+
+// Just enough CBOR for an attestation object: a map of text keys to text, bytes or an empty map.
+const cborHead = (major, n) => n < 24 ? Buffer.from([(major << 5) | n])
+ : n < 256 ? Buffer.from([(major << 5) | 24, n]) : Buffer.from([(major << 5) | 25, n >> 8, n & 255]);
+const cborText = s => Buffer.concat([cborHead(3, Buffer.byteLength(s)), Buffer.from(s)]);
+const cborBytes = b => Buffer.concat([cborHead(2, b.length), b]);
+
+function softPasskey() {
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
+ const jwk = publicKey.export({ format: 'jwk' });
+ const cose = Buffer.concat([
+ Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]), Buffer.from(jwk.x, 'base64url'),
+ Buffer.from([0x22, 0x58, 0x20]), Buffer.from(jwk.y, 'base64url')
+ ]);
+ const raw = crypto.randomBytes(16);
+ const id = b64u(raw);
+ let counter = 0;
+ return {
+ id,
+ row: (userId, extra = {}) => ({ id, userId, publicKey: cose.toString('base64url'), counter: 0, transports: ['internal'], ...extra }),
+ // What navigator.credentials.create() hands back, serialised the way lib/api.js does.
+ attestation(challenge, { origin = ORIGIN } = {}) {
+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.create', challenge, origin, crossOrigin: false }));
+ const len = Buffer.from([raw.length >> 8, raw.length & 255]);
+ const authData = Buffer.concat([sha('localhost'), Buffer.from([0x45]), Buffer.alloc(4), Buffer.alloc(16), len, raw, cose]);
+ const attestationObject = Buffer.concat([
+ Buffer.from([0xa3]), cborText('fmt'), cborText('none'), cborText('attStmt'), Buffer.from([0xa0]),
+ cborText('authData'), cborBytes(authData)
+ ]);
+ return {
+ id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',
+ response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ['internal', 'hybrid'] }
+ };
+ },
+ assertion(challenge) {
+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin: ORIGIN, crossOrigin: false }));
+ const c = Buffer.alloc(4); c.writeUInt32BE(++counter);
+ const authData = Buffer.concat([sha('localhost'), Buffer.from([0x05]), c]);
+ const signature = crypto.sign('sha256', Buffer.concat([authData, sha(clientDataJSON)]), privateKey);
+ return {
+ id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',
+ response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: null }
+ };
+ }
+ };
+}
+
+const GOOD = 'correct horse battery staple';
+let pwHash;
+
+async function startServer(t, { env = {}, users = [], creds = [], deviceLinks } = {}) {
+ pwHash ??= await hashPassword(GOOD);
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pk-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users, creds, subs: [], invites: [], ...(deviceLinks ? { deviceLinks } : {}) }));
+ const child = spawn(process.execPath, ['server.js'], {
+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
+ env: {
+ ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN, RP_ID: 'localhost',
+ PASSWORD_LOGIN: '1', TRUST_PROXY: '1', INVITE_ONLY: '', ADMIN_UIDS: '', AUDIT_LOG: '1', ...env
+ }
+ });
+ const h = { api: '', log: '', dataDir };
+ child.stdout.on('data', d => h.log += d);
+ child.stderr.on('data', d => h.log += d);
+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
+ h.api = `http://127.0.0.1:${await boundPort(child, () => h.log)}`;
+ h.req = async (method, p, { body, cookie, ip = '198.51.100.1', headers = {} } = {}) => {
+ const r = await fetch(`${h.api}${p}`, {
+ method,
+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin', 'X-Forwarded-For': ip, ...(cookie ? { Cookie: cookie } : {}), ...headers },
+ body: body === undefined ? undefined : JSON.stringify(body)
+ });
+ const setCookie = r.headers.getSetCookie().find(c => c.startsWith('gymsid=') && !c.startsWith('gymsid=;'));
+ return { status: r.status, body: await r.json(), headers: r.headers, cookie: setCookie ? setCookie.split(';')[0] : null };
+ };
+ h.db = () => JSON.parse(fs.readFileSync(path.join(dataDir, 'db.json'), 'utf8'));
+ h.audit = () => { try { return fs.readFileSync(path.join(dataDir, 'audit.log'), 'utf8').trim().split('\n').map(l => JSON.parse(l)); } catch { return []; } };
+ // A passkey assertion made for this request, the way Settings confirms before adding.
+ h.stepUp = async (key, ip) => {
+ const { cid, options } = (await h.req('POST', '/api/login/options', { body: {}, ip })).body;
+ return { cid, credential: key.assertion(options.challenge) };
+ };
+ return h;
+}
+const user = (id, name, extra = {}) => ({ id, name, created: new Date().toISOString(), ...extra });
+const withPassword = (id, name) => user(id, name, { pw: { h: pwHash, set: new Date().toISOString() } });
+
+test('the list is the caller’s own passkeys, without key material, and says when one is the last way in', async t => {
+ const a = softPasskey(), b = softPasskey(), c = softPasskey();
+ const h = await startServer(t, {
+ users: [user('u1', 'Ana'), user('u2', 'Bea')],
+ creds: [a.row('u1', { name: 'Laptop', created: '2026-09-01T00:00:00.000Z' }), b.row('u2'), c.row('u1')]
+ });
+ assert.equal((await h.req('GET', '/api/account/passkeys')).status, 401);
+ const r = await h.req('GET', '/api/account/passkeys', { cookie: mintSession('u1') });
+ assert.equal(r.status, 200);
+ assert.deepEqual(r.body.passkeys.map(p => p.id), [a.id, c.id]);
+ assert.deepEqual(r.body.passkeys[0], { id: a.id, name: 'Laptop', created: '2026-09-01T00:00:00.000Z', lastUsed: null, transports: ['internal'] });
+ assert.ok(r.body.passkeys.every(p => !('publicKey' in p) && !('userId' in p) && !('counter' in p)));
+ assert.equal(r.body.lastWayIn, false);
+ assert.equal(r.body.password, false);
+ const bea = await h.req('GET', '/api/account/passkeys', { cookie: mintSession('u2') });
+ assert.equal(bea.body.lastWayIn, true);
+});
+
+test('adding a passkey needs proof, excludes the ones the profile has, and the new one signs in', async t => {
+ const key = softPasskey(), fresh = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana')], creds: [key.row('u1')] });
+ const ip = '198.51.100.20', cookie = mintSession('u1');
+ // A session on its own is not enough.
+ const bare = await h.req('POST', '/api/account/passkeys/options', { body: {}, cookie, ip });
+ assert.equal(bare.status, 403);
+ assert.equal(bare.body.code, 'passkey-required');
+
+ const opt = await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(key, ip), cookie, ip });
+ assert.equal(opt.status, 200);
+ assert.deepEqual(opt.body.options.excludeCredentials.map(c => c.id), [key.id]);
+ assert.equal(opt.body.options.user.id, b64u('u1')); // the profile's own user handle, as at sign-up
+ const ver = await h.req('POST', '/api/account/passkeys/verify', {
+ body: { cid: opt.body.cid, credential: fresh.attestation(opt.body.options.challenge), name: ' Phone\n' }, cookie, ip
+ });
+ assert.equal(ver.status, 200, JSON.stringify(ver.body));
+ assert.deepEqual(ver.body.passkeys.map(p => p.id), [key.id, fresh.id]);
+ const row = h.db().creds.find(c => c.id === fresh.id);
+ assert.equal(row.userId, 'u1');
+ assert.equal(row.name, 'Phone');
+ assert.ok(row.created);
+ // The confirming passkey was used just now.
+ assert.ok(h.db().creds.find(c => c.id === key.id).lastUsed);
+ assert.ok(h.audit().some(e => e.ev === 'auth.passkey.add' && e.uid === 'u1' && e.msg === 'passkey'));
+
+ // The new passkey is a way in of its own.
+ const lo = (await h.req('POST', '/api/login/options', { body: {}, ip })).body;
+ const signedIn = await h.req('POST', '/api/login/verify', { body: { cid: lo.cid, credential: fresh.assertion(lo.options.challenge) }, ip });
+ assert.equal(signedIn.status, 200);
+ assert.equal(signedIn.body.user.id, 'u1');
+ assert.ok(h.db().creds.find(c => c.id === fresh.id).lastUsed);
+
+ // The same authenticator again is refused, not stored twice.
+ const again = await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(key, ip), cookie, ip });
+ const dup = await h.req('POST', '/api/account/passkeys/verify', { body: { cid: again.body.cid, credential: fresh.attestation(again.body.options.challenge) }, cookie, ip });
+ assert.equal(dup.status, 409);
+ assert.equal(dup.body.code, 'credential-exists');
+ assert.equal(h.db().creds.length, 2);
+});
+
+test('another profile’s passkey, or a challenge minted for another profile, adds nothing', async t => {
+ const ana = softPasskey(), bea = softPasskey(), fresh = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana'), user('u2', 'Bea')], creds: [ana.row('u1'), bea.row('u2')] });
+ const ip = '198.51.100.21';
+ // Bea's session confirmed with Ana's passkey.
+ const wrong = await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(ana, ip), cookie: mintSession('u2'), ip });
+ assert.equal(wrong.status, 403);
+ assert.equal(wrong.body.code, 'passkey');
+ assert.ok(h.audit().some(e => e.ev === 'auth.passkey.fail' && e.uid === 'u2' && e.msg === 'step-up-failed'));
+ // Ana's ceremony finished under Bea's session.
+ const opt = await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(ana, ip), cookie: mintSession('u1'), ip });
+ const hijack = await h.req('POST', '/api/account/passkeys/verify', {
+ body: { cid: opt.body.cid, credential: fresh.attestation(opt.body.options.challenge) }, cookie: mintSession('u2'), ip
+ });
+ assert.equal(hijack.status, 400);
+ assert.equal(h.db().creds.length, 2);
+ // A registration made for another origin does not verify.
+ const opt2 = await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(ana, ip), cookie: mintSession('u1'), ip });
+ const phish = await h.req('POST', '/api/account/passkeys/verify', {
+ body: { cid: opt2.body.cid, credential: fresh.attestation(opt2.body.options.challenge, { origin: 'https://evil.example' }) }, cookie: mintSession('u1'), ip
+ });
+ assert.equal(phish.status, 400);
+ assert.equal(h.db().creds.length, 2);
+});
+
+test('signing out everywhere between the proof and the new passkey ends the ceremony', async t => {
+ const key = softPasskey(), fresh = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana')], creds: [key.row('u1')] });
+ const ip = '198.51.100.22', cookie = mintSession('u1');
+ const opt = await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(key, ip), cookie, ip });
+ assert.equal((await h.req('POST', '/api/logout/all', { body: {}, cookie, ip })).status, 200);
+ // Even a session signed in afterwards cannot finish a ceremony begun under the old version.
+ const late = await h.req('POST', '/api/account/passkeys/verify', {
+ body: { cid: opt.body.cid, credential: fresh.attestation(opt.body.options.challenge) }, cookie: mintSession('u1', 1), ip
+ });
+ assert.equal(late.status, 401);
+ assert.equal(h.db().creds.length, 1);
+});
+
+test('the current password proves an addition too — also after the instance switched password sign-in off', async t => {
+ for (const flag of ['1', '']) {
+ const fresh = softPasskey();
+ const h = await startServer(t, { env: { PASSWORD_LOGIN: flag }, users: [withPassword('u1', 'Ana')] });
+ const ip = flag ? '198.51.100.23' : '198.51.100.24', cookie = mintSession('u1');
+ const missing = await h.req('POST', '/api/account/passkeys/options', { body: {}, cookie, ip });
+ assert.equal(missing.body.code, 'current-required');
+ const wrong = await h.req('POST', '/api/account/passkeys/options', { body: { current: 'not it at all' }, cookie, ip });
+ assert.equal(wrong.status, 403);
+ assert.equal(wrong.body.code, 'current-wrong');
+ assert.ok(h.audit().some(e => e.ev === 'auth.password.fail' && e.msg === 'bad-current'));
+ const opt = await h.req('POST', '/api/account/passkeys/options', { body: { current: GOOD }, cookie, ip });
+ assert.equal(opt.status, 200, flag);
+ assert.deepEqual(opt.body.options.excludeCredentials, []);
+ const ver = await h.req('POST', '/api/account/passkeys/verify', { body: { cid: opt.body.cid, credential: fresh.attestation(opt.body.options.challenge) }, cookie, ip });
+ assert.equal(ver.status, 200);
+ assert.ok(h.audit().some(e => e.ev === 'auth.passkey.add' && e.msg === 'password'));
+ }
+});
+
+test('wrong current passwords on the way to a passkey count toward the sign-in pause', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });
+ const ip = '198.51.100.25', cookie = mintSession('u1');
+ const answers = [];
+ for (let i = 0; i < 7; i++) answers.push(await h.req('POST', '/api/account/passkeys/options', { body: { current: 'wrong password ' + i }, cookie, ip }));
+ assert.deepEqual(answers.map(r => r.status), [403, 403, 403, 403, 403, 403, 429]);
+ assert.ok(+answers[6].headers.get('retry-after') > 0);
+ // The name is paused, so the right password waits too, from any address.
+ assert.equal((await h.req('POST', '/api/account/passkeys/options', { body: { current: GOOD }, cookie, ip: '198.51.100.26' })).status, 429);
+});
+
+test('a profile has at most MAX_PASSKEYS passkeys', async t => {
+ const keys = Array.from({ length: MAX_PASSKEYS }, softPasskey);
+ const h = await startServer(t, { users: [user('u1', 'Ana')], creds: keys.map(k => k.row('u1')) });
+ const ip = '198.51.100.27', cookie = mintSession('u1');
+ const r = await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(keys[0], ip), cookie, ip });
+ assert.equal(r.status, 409);
+ assert.equal(r.body.code, 'passkey-limit');
+ assert.equal((await h.req('POST', '/api/account/device-link', { body: await h.stepUp(keys[0], ip), cookie, ip })).body.code, 'passkey-limit');
+});
+
+test('renaming touches only the caller’s own passkey', async t => {
+ const a = softPasskey(), b = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana'), user('u2', 'Bea')], creds: [a.row('u1'), b.row('u2')] });
+ const r = await h.req('POST', '/api/account/passkeys/rename', { body: { id: a.id, name: ' Work\tlaptop ' }, cookie: mintSession('u1') });
+ assert.equal(r.status, 200);
+ assert.equal(r.body.passkeys[0].name, 'Work laptop');
+ const theirs = await h.req('POST', '/api/account/passkeys/rename', { body: { id: b.id, name: 'mine' }, cookie: mintSession('u1') });
+ assert.equal(theirs.status, 404);
+ assert.equal(h.db().creds.find(c => c.id === b.id).name, undefined);
+ assert.equal((await h.req('POST', '/api/account/passkeys/rename', { body: { id: a.id, name: 'x' } })).status, 401);
+});
+
+test('removing: never the last way in, never someone else’s, audited, and it stops that passkey signing in', async t => {
+ const a = softPasskey(), b = softPasskey(), bea = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana'), user('u2', 'Bea')], creds: [a.row('u1', { name: 'Old phone' }), b.row('u1'), bea.row('u2')] });
+ const cookie = mintSession('u1');
+ const del = id => h.req('DELETE', '/api/account/passkeys?id=' + encodeURIComponent(id), { cookie });
+ assert.equal((await del(bea.id)).status, 404);
+ const first = await del(a.id);
+ assert.equal(first.status, 200);
+ assert.deepEqual(first.body.passkeys.map(p => p.id), [b.id]);
+ assert.equal(first.body.lastWayIn, true);
+ assert.ok(h.audit().some(e => e.ev === 'auth.passkey.remove' && e.uid === 'u1' && e.msg === 'Old phone'));
+ const last = await del(b.id);
+ assert.equal(last.status, 409);
+ assert.equal(last.body.code, 'last-way-in');
+ assert.equal(h.db().creds.filter(c => c.userId === 'u1').length, 1);
+ // The removed passkey is unknown from now on…
+ const lo = (await h.req('POST', '/api/login/options', { body: {} })).body;
+ assert.equal((await h.req('POST', '/api/login/verify', { body: { cid: lo.cid, credential: a.assertion(lo.options.challenge) } })).status, 404);
+ // …but sessions are not tied to a passkey, so one it opened lasts until "sign out everywhere".
+ assert.equal((await h.req('GET', '/api/me', { cookie })).status, 200);
+});
+
+test('a password is a way in only while the instance offers password sign-in', async t => {
+ for (const [flag, status] of [['1', 200], ['', 409]]) {
+ const key = softPasskey();
+ const h = await startServer(t, { env: { PASSWORD_LOGIN: flag }, users: [withPassword('u1', 'Ana')], creds: [key.row('u1')] });
+ const list = await h.req('GET', '/api/account/passkeys', { cookie: mintSession('u1') });
+ assert.equal(list.body.lastWayIn, !flag);
+ const r = await h.req('DELETE', '/api/account/passkeys?id=' + key.id, { cookie: mintSession('u1') });
+ assert.equal(r.status, status, `PASSWORD_LOGIN=${flag}`);
+ }
+});
+
+test('a password-only profile keeps its password until a passkey is added, and then may drop it', async t => {
+ const fresh = softPasskey();
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });
+ const ip = '198.51.100.28', cookie = mintSession('u1');
+ assert.equal((await h.req('DELETE', '/api/account/password', { cookie, ip })).body.code, 'last-way-in');
+ const opt = await h.req('POST', '/api/account/passkeys/options', { body: { current: GOOD }, cookie, ip });
+ await h.req('POST', '/api/account/passkeys/verify', { body: { cid: opt.body.cid, credential: fresh.attestation(opt.body.options.challenge) }, cookie, ip });
+ assert.equal((await h.req('DELETE', '/api/account/password', { cookie, ip })).status, 200);
+ // And now the passkey is the last way in.
+ assert.equal((await h.req('DELETE', '/api/account/passkeys?id=' + fresh.id, { cookie, ip })).body.code, 'last-way-in');
+});
+
+/* ------------------------------------------------------------------ device links ---------- */
+
+// Makes a link as Ana would in Settings: confirmed with her passkey.
+async function makeLink(h, key, uid, ip) {
+ return h.req('POST', '/api/account/device-link', { body: await h.stepUp(key, ip), cookie: mintSession(uid), ip });
+}
+// Redeems it as the other device would: options, then the new passkey.
+async function redeem(h, code, fresh, ip, name) {
+ const opt = await h.req('POST', '/api/device-link/options', { body: { code }, ip });
+ if (opt.status !== 200) return opt;
+ return h.req('POST', '/api/device-link/verify', { body: { code, cid: opt.body.cid, credential: fresh.attestation(opt.body.options.challenge), name }, ip });
+}
+
+test('a device link: made with proof, kept only as a hash, redeemed once by a new passkey that signs the device in', async t => {
+ const key = softPasskey(), phone = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana'), user('u2', 'Bea')], creds: [key.row('u1')] });
+ const ip = '198.51.100.40';
+ assert.equal((await h.req('POST', '/api/account/device-link', { body: {} })).status, 401);
+ assert.equal((await h.req('POST', '/api/account/device-link', { body: {}, cookie: mintSession('u1'), ip })).body.code, 'passkey-required');
+
+ const made = await makeLink(h, key, 'u1', ip);
+ assert.equal(made.status, 200);
+ const { code, expires } = made.body;
+ assert.match(code, /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/);
+ assert.ok(expires > Date.now() + 9 * 60000 && expires <= Date.now() + 10 * 60000);
+ const stored = fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8');
+ assert.doesNotMatch(stored, new RegExp(code));
+ assert.doesNotMatch(stored, new RegExp(code.replace(/-/g, '')));
+ assert.deepEqual(h.db().deviceLinks.map(l => [l.userId, l.h]), [['u1', hashLinkCode(code)]]);
+ assert.ok(h.audit().some(e => e.ev === 'auth.link.create' && e.uid === 'u1' && e.msg === 'passkey'));
+
+ // The other device, signed in as nobody.
+ const opt = await h.req('POST', '/api/device-link/options', { body: { code: code.toLowerCase() }, ip: '198.51.100.41' });
+ assert.equal(opt.status, 200);
+ assert.equal(opt.body.name, 'Ana');
+ assert.deepEqual(opt.body.options.excludeCredentials.map(c => c.id), [key.id]);
+ const done = await h.req('POST', '/api/device-link/verify', {
+ body: { code, cid: opt.body.cid, credential: phone.attestation(opt.body.options.challenge), name: 'Phone' }, ip: '198.51.100.41'
+ });
+ assert.equal(done.status, 200, JSON.stringify(done.body));
+ assert.deepEqual(done.body.user, { id: 'u1', name: 'Ana', admin: false });
+ assert.ok(done.cookie);
+ assert.equal((await h.req('GET', '/api/me', { cookie: done.cookie })).body.user.id, 'u1');
+ const row = h.db().creds.find(c => c.id === phone.id);
+ assert.equal(row.userId, 'u1');
+ assert.equal(row.name, 'Phone');
+ assert.deepEqual(h.db().deviceLinks, []);
+ assert.ok(h.audit().some(e => e.ev === 'auth.link.ok' && e.uid === 'u1'));
+
+ // Used: gone for good, whichever step tries it.
+ const again = await redeem(h, code, softPasskey(), '198.51.100.42');
+ assert.equal(again.status, 400);
+ assert.equal(again.body.code, 'link-invalid');
+ assert.equal(h.db().creds.length, 2);
+});
+
+test('a password-only profile can make a link with its password, and the phone gets a passkey', async t => {
+ const phone = softPasskey();
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });
+ const ip = '198.51.100.43';
+ const made = await h.req('POST', '/api/account/device-link', { body: { current: GOOD }, cookie: mintSession('u1'), ip });
+ assert.equal(made.status, 200);
+ assert.ok(h.audit().some(e => e.ev === 'auth.link.create' && e.msg === 'password'));
+ assert.equal((await redeem(h, made.body.code, phone, ip)).status, 200);
+ assert.equal(h.db().creds[0].userId, 'u1');
+});
+
+test('an expired link, a replaced link and a link of a disabled profile are all just wrong', async t => {
+ const code = 'ABCD-EFGH-JKLM', old = 'ZZZZ-YYYY-XXXX', locked = 'QQQQ-RRRR-SSSS';
+ const h = await startServer(t, {
+ users: [user('u1', 'Ana'), user('u2', 'Bea', { disabled: true })],
+ deviceLinks: [
+ { h: hashLinkCode(code), userId: 'u1', exp: Date.now() - 1000, created: Date.now() - 601000 },
+ { h: hashLinkCode(locked), userId: 'u2', exp: Date.now() + 60000, created: Date.now() }
+ ]
+ });
+ const ip = '198.51.100.44';
+ for (const c of [code, old, locked, '', 'x'.repeat(5000)]) {
+ const r = await h.req('POST', '/api/device-link/options', { body: { code: c }, ip });
+ assert.equal(r.status, 400, c.slice(0, 20));
+ assert.equal(r.body.code, 'link-invalid');
+ }
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code: { toString: 1 } }, ip })).status, 400);
+ assert.ok(h.audit().some(e => e.ev === 'auth.link.fail' && e.msg === 'user-unavailable' && e.uid === 'u2'));
+});
+
+test('a newer link replaces the older one, and signing out everywhere or a new password drops it', async t => {
+ const key = softPasskey();
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')], creds: [key.row('u1')] });
+ const ip = '198.51.100.45', cookie = mintSession('u1');
+ const first = (await makeLink(h, key, 'u1', ip)).body.code;
+ const second = (await makeLink(h, key, 'u1', ip)).body.code;
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code: first }, ip })).status, 400);
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code: second }, ip })).status, 200);
+ await h.req('POST', '/api/logout/all', { body: {}, cookie, ip });
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code: second }, ip })).status, 400);
+
+ // A new one, under the session version after that sign-out — and then a new password.
+ const after = mintSession('u1', 1);
+ const third = (await h.req('POST', '/api/account/device-link', { body: await h.stepUp(key, ip), cookie: after, ip })).body.code;
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code: third }, ip })).status, 200);
+ const set = await h.req('POST', '/api/account/password', { body: { current: GOOD, next: 'another good long passphrase' }, cookie: after, ip });
+ assert.equal(set.status, 200);
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code: third }, ip })).status, 400);
+});
+
+test('a link redeemed after the owner signed out everywhere mid-ceremony makes no passkey', async t => {
+ const key = softPasskey(), thief = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana')], creds: [key.row('u1')] });
+ const ip = '198.51.100.46';
+ const { code } = (await makeLink(h, key, 'u1', ip)).body;
+ const opt = await h.req('POST', '/api/device-link/options', { body: { code }, ip });
+ await h.req('POST', '/api/logout/all', { body: {}, cookie: mintSession('u1'), ip });
+ const r = await h.req('POST', '/api/device-link/verify', { body: { code, cid: opt.body.cid, credential: thief.attestation(opt.body.options.challenge) }, ip });
+ assert.equal(r.status, 400);
+ assert.equal(r.cookie, null);
+ assert.equal(h.db().creds.length, 1);
+});
+
+test('two devices racing with one code: exactly one gets the passkey and the session', async t => {
+ const key = softPasskey(), one = softPasskey(), two = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana')], creds: [key.row('u1')] });
+ const ip = '198.51.100.47';
+ const { code } = (await makeLink(h, key, 'u1', ip)).body;
+ const o1 = (await h.req('POST', '/api/device-link/options', { body: { code }, ip })).body;
+ const o2 = (await h.req('POST', '/api/device-link/options', { body: { code }, ip })).body;
+ const results = await Promise.all([
+ h.req('POST', '/api/device-link/verify', { body: { code, cid: o1.cid, credential: one.attestation(o1.options.challenge) }, ip }),
+ h.req('POST', '/api/device-link/verify', { body: { code, cid: o2.cid, credential: two.attestation(o2.options.challenge) }, ip })
+ ]);
+ assert.deepEqual(results.map(r => r.status).sort(), [200, 400]);
+ assert.equal(results.filter(r => r.cookie).length, 1);
+ assert.equal(h.db().creds.length, 2);
+});
+
+test('a challenge from one ceremony does not finish the other, nor a link of another profile', async t => {
+ const ana = softPasskey(), bea = softPasskey(), fresh = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana'), user('u2', 'Bea')], creds: [ana.row('u1'), bea.row('u2')] });
+ const ip = '198.51.100.48';
+ const anaCode = (await makeLink(h, ana, 'u1', ip)).body.code;
+ const beaCode = (await makeLink(h, bea, 'u2', ip)).body.code;
+ // Bea's options, Ana's code: the challenge belongs to the other link.
+ const beaOpt = (await h.req('POST', '/api/device-link/options', { body: { code: beaCode }, ip })).body;
+ const cross = await h.req('POST', '/api/device-link/verify', { body: { code: anaCode, cid: beaOpt.cid, credential: fresh.attestation(beaOpt.options.challenge) }, ip });
+ assert.equal(cross.status, 400);
+ // A Settings ceremony's challenge presented as a link's.
+ const add = (await h.req('POST', '/api/account/passkeys/options', { body: await h.stepUp(ana, ip), cookie: mintSession('u1'), ip })).body;
+ const mixed = await h.req('POST', '/api/device-link/verify', { body: { code: anaCode, cid: add.cid, credential: fresh.attestation(add.options.challenge) }, ip });
+ assert.equal(mixed.status, 400);
+ // …and a link's challenge presented to Settings.
+ const linkOpt = (await h.req('POST', '/api/device-link/options', { body: { code: anaCode }, ip })).body;
+ const mixed2 = await h.req('POST', '/api/account/passkeys/verify', { body: { cid: linkOpt.cid, credential: fresh.attestation(linkOpt.options.challenge) }, cookie: mintSession('u1'), ip });
+ assert.equal(mixed2.status, 400);
+ assert.equal(h.db().creds.length, 2);
+ // Both codes still work for their own profiles.
+ assert.equal((await redeem(h, beaCode, fresh, ip)).body.user.id, 'u2');
+});
+
+test('wrong codes pause link redemption for the address, and only that', async t => {
+ const key = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana')], creds: [key.row('u1')] });
+ const ip = '198.51.100.49';
+ const { code } = (await makeLink(h, key, 'u1', '198.51.100.50')).body;
+ // 20 wrong codes are free; the 21st is still answered, and starts the pause.
+ for (let i = 0; i < 21; i++) {
+ const r = await h.req('POST', '/api/device-link/options', { body: { code: 'WRONG' + i }, ip });
+ assert.equal(r.status, 400, `attempt ${i}`);
+ }
+ const paused = await h.req('POST', '/api/device-link/options', { body: { code: 'ZZZZ-ZZZZ-ZZZZ' }, ip });
+ assert.equal(paused.status, 429);
+ assert.equal(paused.body.code, 'locked');
+ assert.ok(+paused.headers.get('retry-after') > 0);
+ // Even the right code waits at that address…
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code }, ip })).status, 429);
+ assert.equal((await h.req('POST', '/api/device-link/verify', { body: { code }, ip })).status, 429);
+ assert.ok(h.audit().some(e => e.ev === 'auth.throttled' && e.msg === 'link'));
+ // …while another address redeems it, and sign-in at the paused one is untouched.
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code }, ip: '198.51.100.51' })).status, 200);
+ assert.equal((await h.req('POST', '/api/login/options', { body: {}, ip })).status, 200);
+ const lo = (await h.req('POST', '/api/login/options', { body: {}, ip })).body;
+ assert.equal((await h.req('POST', '/api/login/verify', { body: { cid: lo.cid, credential: key.assertion(lo.options.challenge) }, ip })).status, 200);
+});
+
+test('link redemption keeps the origin check; the account routes do too', async t => {
+ const key = softPasskey();
+ const h = await startServer(t, { users: [user('u1', 'Ana')], creds: [key.row('u1')] });
+ const ip = '198.51.100.52';
+ const { code } = (await makeLink(h, key, 'u1', ip)).body;
+ const crossSite = { 'Sec-Fetch-Site': 'cross-site' };
+ const sibling = { 'Sec-Fetch-Site': 'same-site' };
+ const noFetchMeta = { 'Sec-Fetch-Site': '', Origin: 'https://evil.example' };
+ for (const headers of [crossSite, sibling, noFetchMeta]) {
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code }, ip, headers })).status, 403);
+ assert.equal((await h.req('POST', '/api/device-link/verify', { body: { code }, ip, headers })).status, 403);
+ assert.equal((await h.req('POST', '/api/account/device-link', { body: {}, cookie: mintSession('u1'), ip, headers })).status, 403);
+ assert.equal((await h.req('POST', '/api/account/passkeys/options', { body: {}, cookie: mintSession('u1'), ip, headers })).status, 403);
+ assert.equal((await h.req('DELETE', '/api/account/passkeys?id=' + key.id, { cookie: mintSession('u1'), ip, headers })).status, 403);
+ }
+ // The refused requests used nothing up.
+ assert.equal((await h.req('POST', '/api/device-link/options', { body: { code }, ip })).status, 200);
+});
diff --git a/scripts/build-api-docs.mjs b/scripts/build-api-docs.mjs
index 81a02f05b..6c11a2734 100644
--- a/scripts/build-api-docs.mjs
+++ b/scripts/build-api-docs.mjs
@@ -124,6 +124,7 @@ const TAGS = {
auth: { title: 'Auth', side: 'Passkeys &amp; sessions' },
pairing: { title: 'Pairing', side: 'Connect the mobile app' },
password: { title: 'Password', side: 'Optional name &amp; password (PASSWORD_LOGIN)' },
+ passkeys: { title: 'Passkeys', side: 'More passkeys &amp; device links' },
data: { title: 'Data', side: 'State sync' },
push: { title: 'Push', side: 'Notifications &amp; rest timer' },
activity: { title: 'Activity', side: 'Live presence' },