@softistx/janus-hono 0.0.0-stage → 0.11.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +547 -2
  3. package/dist/bind.d.ts +104 -0
  4. package/dist/bind.d.ts.map +1 -0
  5. package/dist/device.d.ts +15 -0
  6. package/dist/device.d.ts.map +1 -0
  7. package/dist/errors.d.ts +60 -0
  8. package/dist/errors.d.ts.map +1 -0
  9. package/dist/fresh.d.ts +41 -0
  10. package/dist/fresh.d.ts.map +1 -0
  11. package/dist/index.d.ts +47 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +496 -0
  14. package/dist/index.js.map +22 -0
  15. package/dist/no-store.d.ts +8 -0
  16. package/dist/no-store.d.ts.map +1 -0
  17. package/dist/passkeys/body.d.ts +12 -0
  18. package/dist/passkeys/body.d.ts.map +1 -0
  19. package/dist/passkeys/index.d.ts +8 -0
  20. package/dist/passkeys/index.d.ts.map +1 -0
  21. package/dist/passkeys/routes.d.ts +32 -0
  22. package/dist/passkeys/routes.d.ts.map +1 -0
  23. package/dist/passkeys/types.d.ts +105 -0
  24. package/dist/passkeys/types.d.ts.map +1 -0
  25. package/dist/permission.d.ts +80 -0
  26. package/dist/permission.d.ts.map +1 -0
  27. package/dist/provide.d.ts +19 -0
  28. package/dist/provide.d.ts.map +1 -0
  29. package/dist/session.d.ts +156 -0
  30. package/dist/session.d.ts.map +1 -0
  31. package/dist/social/index.d.ts +9 -0
  32. package/dist/social/index.d.ts.map +1 -0
  33. package/dist/social/redirect.d.ts +9 -0
  34. package/dist/social/redirect.d.ts.map +1 -0
  35. package/dist/social/refusals.d.ts +14 -0
  36. package/dist/social/refusals.d.ts.map +1 -0
  37. package/dist/social/routes.d.ts +32 -0
  38. package/dist/social/routes.d.ts.map +1 -0
  39. package/dist/social/types.d.ts +90 -0
  40. package/dist/social/types.d.ts.map +1 -0
  41. package/docs/README.md +15 -0
  42. package/docs/guide/permissions.md +225 -0
  43. package/docs/guide/routes.md +1164 -0
  44. package/docs/roadmap.md +76 -0
  45. package/docs/troubleshooting.md +871 -0
  46. package/package.json +62 -5
@@ -0,0 +1,1164 @@
1
+ # The routes of an application
2
+
3
+ Every flow of `@softistx/janus` as a Hono route. What this package adds is small on
4
+ purpose — who the request belongs to, the cookie, the statuses — so each route
5
+ below is `janus()`'s own call with Hono around it.
6
+
7
+ ## Wiring
8
+
9
+ ```ts
10
+ import { janusErrors, session } from '@softistx/janus-hono';
11
+ import { Hono } from 'hono';
12
+ import { auth } from './auth';
13
+
14
+ export const app = new Hono();
15
+ app.onError(janusErrors());
16
+ ```
17
+
18
+ `janusErrors()` is what turns a `JanusError` thrown anywhere — in a route, or
19
+ in `session()` — into its status. Without it, Hono answers 500 for all of
20
+ them. To log what the server must fix — every error answered 5xx, an outage
21
+ first — pass `report`; it runs before the answer:
22
+
23
+ ```ts
24
+ app.onError(janusErrors({ report: (error) => logger.error(error) }));
25
+ ```
26
+
27
+ To log every refusal too — why a sign-in failed, say — wrap it:
28
+
29
+ ```ts
30
+ const answer = janusErrors();
31
+ app.onError((error, c) => {
32
+ // `reason`, `login`, `slot`, `operation` and `cause` are here, never in the body
33
+ logger.error(error);
34
+ return answer(error, c);
35
+ });
36
+ ```
37
+
38
+ `janusErrors({ fallback })` hands every other error to `fallback`; without one,
39
+ an `HTTPException` answers its own response and anything else is a logged
40
+ 500, as Hono does by default.
41
+
42
+ A wrapper around `janusErrors()` takes the same options, `JanusErrorsOptions`,
43
+ with your defaults:
44
+
45
+ ```ts
46
+ import { type JanusErrorsOptions, janusErrors } from '@softistx/janus-hono';
47
+
48
+ export const appErrors = (options: JanusErrorsOptions = {}) =>
49
+ janusErrors({ report: (error) => logger.error(error), ...options });
50
+ ```
51
+
52
+ ### Binding the instances once
53
+
54
+ Every function of this package takes `auth` or `access` first.
55
+ `bindJanus()` binds them once — the same functions, the same types:
56
+
57
+ ```ts
58
+ import { bindJanus } from '@softistx/janus-hono';
59
+
60
+ export const j = bindJanus({ auth, access });
61
+
62
+ app.use(j.session(), j.provide());
63
+ app.get('/me', j.session({ required: true }), (c) => c.json(c.var.user));
64
+ app.post('/sign-in', async (c) => {
65
+ const user = j.sendSession(c, await auth.signIn(await c.req.json()));
66
+ return c.json({ id: user.id });
67
+ });
68
+ ```
69
+
70
+ A module of routes that receives `j` rather than importing it types it
71
+ `Bound<…>`, over the types of the instances it was given — only what is given
72
+ is bound, so `Bound<{ auth: typeof auth }>` has no `permission`:
73
+
74
+ ```ts
75
+ import { type Bound, byParam } from '@softistx/janus-hono';
76
+
77
+ export type Janus = Bound<{ auth: typeof auth; access: typeof access }>;
78
+
79
+ export const recordRoutes = (j: Janus) =>
80
+ new Hono()
81
+ .use(j.session(), j.provide())
82
+ .get('/records/:id', j.permission('view', 'record', byParam('id', (id) => records.find(id))), (c) =>
83
+ c.json(c.var.object),
84
+ );
85
+ ```
86
+
87
+ `BoundSession`, `BoundAuth` and `BoundPermission` are its parts — `j.session`,
88
+ the three functions `auth` brings, and `j.permission` — for a helper that needs
89
+ only one of them.
90
+
91
+ The rest of this guide writes the unbound form; each call reads the same with
92
+ `j.` and without its first argument.
93
+
94
+ ## Who the request belongs to
95
+
96
+ ```ts
97
+ app.get('/', session(auth), (c) =>
98
+ c.text(c.var.user === null ? 'Hello' : `Hello ${c.var.user.name}`),
99
+ );
100
+
101
+ app.get('/account', session(auth, { required: true }), (c) =>
102
+ c.json(c.var.user), // typed: never null
103
+ );
104
+ ```
105
+
106
+ `session()` reads the session token the way `auth.authenticate` does —
107
+ `Authorization: Bearer`, then `X-Session-Token`, then the cookie, **the first
108
+ present wins** — and sets `c.var.user` and `c.var.session`.
109
+
110
+ | The request presents | `c.var.user` | With `required: true` |
111
+ | --- | --- | --- |
112
+ | Nothing | `null` | 401, no body; the route never runs |
113
+ | A lapsed, revoked or unknown session | `null` | 401 |
114
+ | A session of an inactive user, or of another type than `type` | `null` | 401 |
115
+ | A live session | the user | the user |
116
+ | A session credential, while the store cannot answer | — `STORE_FAILED` is thrown | — 503 through `janusErrors()` |
117
+
118
+ ### For a whole app
119
+
120
+ Hono types a chain, so `app.use(session(auth))` on its own line leaves the
121
+ routes after it untyped. Declare the app with the `Env` instead:
122
+
123
+ ```ts
124
+ import { type SessionEnv, session } from '@softistx/janus-hono';
125
+
126
+ const app = new Hono<SessionEnv<typeof auth>>();
127
+ app.use(session(auth));
128
+ app.get('/', (c) => c.json({ signedIn: c.var.user !== null }));
129
+ ```
130
+
131
+ An app whose every route requires a user of one type says so in both places,
132
+ and `c.var.user` is never `null` in it:
133
+
134
+ ```ts
135
+ const rota = new Hono<SessionEnv<typeof auth, 'staff', true>>();
136
+ rota.use(session(auth, { type: 'staff', required: true }));
137
+ rota.get('/', (c) => c.json(rotaOf(c.var.user.username)));
138
+ ```
139
+
140
+ ### Renewal
141
+
142
+ Every session is renewed by `authenticate` in passing once `renewAfter` has
143
+ passed — `'1d'` by default, `false` for a fixed lifespan — and its expiry
144
+ moves. `session()` sends the cookie again after the route ran, with the
145
+ new `Expires` — to a request that presented the session as a cookie. A client
146
+ using `Authorization: Bearer` is renewed too, keeps its session token, and is never
147
+ handed a cookie. A route that sets the session cookie itself — `sendSession`
148
+ after a sign-in, `signOut` — keeps its own: the renewal is not sent over it.
149
+
150
+ ## Sign-up and sign-in
151
+
152
+ ```ts
153
+ import { sendSession } from '@softistx/janus-hono';
154
+
155
+ app.post('/sign-up', async (c) => {
156
+ const { email, name, password } = await c.req.json(); // validate the shape yourself
157
+ const user = sendSession(c, auth, await auth.signUp({ email, name, password }));
158
+ return c.json({ id: user.id }, 201);
159
+ });
160
+
161
+ app.post('/sign-in', async (c) => {
162
+ const { email, password } = await c.req.json();
163
+ const user = sendSession(c, auth, await auth.signIn({ email, password }));
164
+ return c.json({ id: user.id });
165
+ });
166
+ ```
167
+
168
+ `sendSession` answers the user it signed in, so a cookie client's route never
169
+ holds the session token: it is in the `Set-Cookie`, and the body cannot leak
170
+ it.
171
+
172
+ **Password guessing is throttled per login by `@softistx/janus`**: past ten
173
+ passwords tried at one login in a 15-minute window, `signIn` refuses every
174
+ one, the right password included, until the window ends — nothing locks.
175
+ `janusErrors()` answers that refusal `401 { code: 'CREDENTIALS_INVALID',
176
+ retryAfter }` with a `Retry-After` header, the seconds until the next
177
+ window; the route needs no code of its own. `janus({ signIn: { throttle } })`
178
+ changes the limit ([passwords](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/passwords.md#password-guessing-is-throttled)).
179
+
180
+ **The requests that send an e-mail are throttled too.** Past five requests
181
+ for one address (or one user, for `verifyEmail.send`, `changeEmail.send` —
182
+ also counted per new address — and an e-mailed `stepUp.request`) in a
183
+ 10-minute window, `@softistx/janus` throws `MAIL_THROTTLED` and sends nothing; `janusErrors()` answers it
184
+ `429 { code: 'MAIL_THROTTLED', retryAfter }` with a `Retry-After` header.
185
+ **A refused request spends and rotates nothing**: the last link or code sent
186
+ still works, so tell the visitor to use the last e-mail they received, or to
187
+ wait `retryAfter` seconds. `janus({ mail: { throttle } })` changes the limit;
188
+ keep its `window` no longer than the shortest `tokens.*` lifetime you use.
189
+ `@softistx/janus` never sees IP addresses, so add a per-IP ceiling in front of
190
+ these routes with `@softistx/redis` rate limits
191
+ ([example](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/email-flows.md#requests-that-send-e-mail-are-throttled)).
192
+
193
+ What the throttle does not see is one password tried against many logins:
194
+ limit the route **per client address** as well, with the limiter you already
195
+ run, and a `changePassword` route per user — it compares the current
196
+ password too:
197
+
198
+ ```ts
199
+ app.post('/sign-in', async (c) => {
200
+ // The client address your trusted proxy sets — not a raw, spoofable X-Forwarded-For list.
201
+ const client = clientAddress(c);
202
+ if (!(await limiter.consume(`sign-in:${client}`))) {
203
+ return c.body(null, 429, { 'retry-after': '900' });
204
+ }
205
+ const { email, password } = await c.req.json();
206
+ const user = sendSession(c, auth, await auth.signIn({ email, password }));
207
+ return c.json({ id: user.id });
208
+ });
209
+ ```
210
+
211
+ With `secondFactor` configured, `signIn` may answer a challenge instead of a
212
+ session: narrow on `status` before `sendSession` — see
213
+ [A second factor](#a-second-factor).
214
+
215
+ To sign in with no password, by a code sent to the user's e-mail, see
216
+ [A code sent by e-mail](#a-code-sent-by-e-mail).
217
+
218
+ The refusals need no `try`: `janusErrors()` answers them.
219
+
220
+ | Thrown | Answered |
221
+ | --- | --- |
222
+ | `USER_INVALID` | 400 `{ code, issues }`, the fields that failed |
223
+ | `AVATAR_ID_INVALID` | 400 `{ code }` — an avatar id that is not a non-empty string of at most 512 characters that every store can keep |
224
+ | `PASSWORD_TOO_SHORT` | 400 `{ code, minLength }` |
225
+ | `LOGIN_TAKEN` | 409 `{ code }` |
226
+ | `CREDENTIALS_INVALID` | 401 `{ code }` — the same for an unknown login and a wrong password; `{ code, retryAfter }` and a `Retry-After` header once the login is throttled |
227
+ | `MAIL_THROTTLED` | 429 `{ code, retryAfter }` and a `Retry-After` header — a request that sends an e-mail, past its attempts in the window |
228
+ | `USER_INACTIVE` | 403 `{ code }` — only told to somebody who gave the right password |
229
+ | `EMAIL_UNVERIFIED` | 403 `{ code }` — the right password on an address a type with `password.requireVerifiedEmail` has not seen verified; only told to somebody who gave the right password |
230
+
231
+ A bearer client — a mobile app — keeps its session token itself and sends it
232
+ as `Authorization: Bearer`. Answer it the session token in the body, not a
233
+ cookie — keep what `signIn` answered:
234
+
235
+ ```ts
236
+ const signedIn = await auth.signIn({ email, password });
237
+ return c.json({
238
+ id: signedIn.user.id,
239
+ token: signedIn.token,
240
+ expiresAt: signedIn.session.expiresAt,
241
+ });
242
+ ```
243
+
244
+ ## A second factor
245
+
246
+ With `janus({ secondFactor })`, `signIn` answers either a session or a
247
+ **challenge** — `{ status: 'secondFactor', challenge, expiresAt, userId }` — and
248
+ `sendSession` only takes the first. **Narrow on `status` before
249
+ `sendSession`**: passing `signIn`'s answer straight in no longer compiles,
250
+ because a challenge has no `token` and no `session`.
251
+
252
+ ```ts
253
+ import { sendSession } from '@softistx/janus-hono';
254
+ import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
255
+
256
+ const CHALLENGE = 'sign-in-challenge';
257
+ const scope = { path: '/sign-in', httpOnly: true, secure: true, sameSite: 'Strict' } as const;
258
+
259
+ app.post('/sign-in', async (c) => {
260
+ const { email, password } = await c.req.json();
261
+ const result = await auth.signIn({ email, password });
262
+ if (result.status === 'secondFactor') {
263
+ // the challenge is a secret: a cookie for the code route only, never a URL or a log
264
+ setCookie(c, CHALLENGE, result.challenge, { ...scope, expires: result.expiresAt });
265
+ return c.json({ next: 'code' });
266
+ }
267
+ const user = sendSession(c, auth, result);
268
+ return c.json({ id: user.id });
269
+ });
270
+
271
+ app.post('/sign-in/code', async (c) => {
272
+ const { code } = await c.req.json();
273
+ const challenge = getCookie(c, CHALLENGE);
274
+ if (challenge === undefined) return c.json({ code: 'TOKEN_UNKNOWN' }, 400);
275
+ const user = sendSession(c, auth, await auth.secondFactor.confirm(challenge, code));
276
+ deleteCookie(c, CHALLENGE, scope);
277
+ return c.json({ id: user.id });
278
+ });
279
+ ```
280
+
281
+ With `janus({ passkeys })`, the challenge also says how it can be answered:
282
+ `result.methods` is `['totp']` or `['totp', 'passkey']`, and
283
+ `result.passkeyOptions` is present exactly when `methods` holds `'passkey'`.
284
+ Answer them to the page with the challenge (`c.json({ next: 'code', methods:
285
+ result.methods, passkeyOptions: result.passkeyOptions })`) and it picks; the
286
+ passkey answer goes to [`POST /sign-in` of `passkeyRoutes()`](#passkeys).
287
+ `passkeyOptions` names the user's credential ids: hand it only to a visitor
288
+ who just proved the first factor, which `signIn` checked.
289
+
290
+ A wrong code leaves the cookie in place, so the visitor types the next one.
291
+ `janusErrors()` answers what `confirm` throws:
292
+
293
+ | Thrown | Answered |
294
+ | --- | --- |
295
+ | `CODE_INVALID` | 401 `{ code, attemptsLeft }` — the attempts the challenge has left, `0` once the fifth wrong code spent it: sign in again. A spent user window adds `retryAfter` and a `Retry-After` header — wait, a new challenge does not help |
296
+ | `TOKEN_UNKNOWN`, `TOKEN_SPENT`, `TOKEN_EXPIRED` | 400 `{ code }` — send the visitor back to the password |
297
+ | `SECOND_FACTOR_NOT_ENROLLED` | 409 `{ code }` — the factor was disabled since `signIn`: sign in again |
298
+ | `USER_INACTIVE` | 403 `{ code }` |
299
+
300
+ `attemptsLeft` is the only thing the body adds: which cause of
301
+ `CODE_INVALID` it was — a wrong code or a reused one — is not told.
302
+
303
+ A user whose phone is gone answers the same challenge with a **recovery
304
+ code** instead, on a route of its own under the cookie's path:
305
+
306
+ ```ts
307
+ app.post('/sign-in/recovery', async (c) => {
308
+ const { code } = await c.req.json();
309
+ const challenge = getCookie(c, CHALLENGE);
310
+ if (challenge === undefined) return c.json({ code: 'TOKEN_UNKNOWN' }, 400);
311
+ const recovered = await auth.secondFactor.recover(challenge, code);
312
+ const user = sendSession(c, auth, recovered);
313
+ deleteCookie(c, CHALLENGE, scope);
314
+ return c.json({ id: user.id, recoveryCodesLeft: recovered.recoveryCodesLeft });
315
+ });
316
+ ```
317
+
318
+ It shares the challenge's five attempts with `/sign-in/code`, and
319
+ `janusErrors()` answers it as above — plus `VERSION_CONFLICT`, 409, when the
320
+ same code signed in elsewhere at the same instant: sign in again.
321
+
322
+ A bearer client gets the challenge in the body instead, and sends it back
323
+ with the code:
324
+
325
+ ```ts
326
+ app.post('/api/sign-in', async (c) => {
327
+ const result = await auth.signIn(await c.req.json());
328
+ if (result.status === 'secondFactor') {
329
+ return c.json({ challenge: result.challenge, expiresAt: result.expiresAt });
330
+ }
331
+ return c.json({ token: result.token, expiresAt: result.session.expiresAt });
332
+ });
333
+ ```
334
+
335
+ ### Enrolling, activating, recovery codes, disabling
336
+
337
+ The user is signed in for these, so `session()` names them:
338
+
339
+ ```ts
340
+ import { fresh, session } from '@softistx/janus-hono';
341
+
342
+ app.post('/account/second-factor', session(auth, { required: true }), async (c) => {
343
+ const { secret, uri } = await auth.secondFactor.enroll(c.var.user);
344
+ c.header('Cache-Control', 'no-store'); // the secret is shown once, and never cached
345
+ return c.json({ secret, uri }); // the page renders uri as a QR code
346
+ });
347
+
348
+ app.post('/account/second-factor/activate', session(auth, { required: true }), async (c) => {
349
+ const { code } = await c.req.json();
350
+ const { recoveryCodes } = await auth.secondFactor.activate(c.var.user, code);
351
+ c.header('Cache-Control', 'no-store'); // the recovery codes are shown once
352
+ return c.json({ recoveryCodes });
353
+ });
354
+
355
+ app.post('/account/second-factor/recovery-codes', session(auth, { required: true }), async (c) => {
356
+ const { code } = await c.req.json(); // a fresh code from the app
357
+ const { recoveryCodes } = await auth.secondFactor.regenerateRecoveryCodes(c.var.user, code);
358
+ c.header('Cache-Control', 'no-store');
359
+ return c.json({ recoveryCodes });
360
+ });
361
+
362
+ // Your policy: a proof in the last five minutes — a sign-in or a step-up.
363
+ app.delete('/account/second-factor', session(auth, { required: true }), fresh('5m'), async (c) => {
364
+ await auth.secondFactor.disable(c.var.user);
365
+ return c.body(null, 204);
366
+ });
367
+ ```
368
+
369
+ | Thrown | Answered |
370
+ | --- | --- |
371
+ | `SECOND_FACTOR_ACTIVE` | 409 `{ code }` — `enroll` or `activate` on a factor already active |
372
+ | `EMAIL_UNVERIFIED` | 403 `{ code }` — `enroll` or `activate` while the account's e-mail is not proved |
373
+ | `SECOND_FACTOR_NOT_ENROLLED` | 409 `{ code }` — `activate` before `enroll`, or `regenerateRecoveryCodes` without an active factor |
374
+ | `CODE_INVALID` | 401 `{ code }` from `activate`, which counts no attempts; 401 `{ code, attemptsLeft, retryAfter? }` from `regenerateRecoveryCodes` (and `stepUp.confirm` with an app's code), `retryAfter` once the user's window is spent |
375
+
376
+ **The regenerate route needs no limiter of its own.** `regenerateRecoveryCodes`
377
+ counts five attempts per user per 15-minute window in the store, so a stolen
378
+ session cannot guess the app's code there one request at a time: past the
379
+ fifth, it answers `401 {"code":"CODE_INVALID","attemptsLeft":0,"retryAfter":600}`
380
+ with a `Retry-After: 600` header, the right code included, until the window
381
+ frees. Two client reactions: with `retryAfter`, tell the user to wait that
382
+ many seconds (a new step-up challenge does not help); with `attemptsLeft: 0`
383
+ and no `retryAfter`, the challenge's own tries are spent — request a new one. A limiter in front of it — per IP, per
384
+ user — is still yours to add for load, never needed for the guesses.
385
+
386
+ The key rotation, the attempts and the replay rules are
387
+ [`@softistx/janus`'s second factor guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/second-factor.md).
388
+
389
+ ## A code sent by e-mail
390
+
391
+ A sign-in by e-mailed code is two routes, built like
392
+ [the second factor's](#a-second-factor): the first asks for a code and keeps
393
+ the **challenge** in a cookie scoped to the second, which takes the code and
394
+ opens the session. Sending the e-mail is yours.
395
+
396
+ ```ts
397
+ import { sendSession } from '@softistx/janus-hono';
398
+ import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
399
+
400
+ const CODE_CHALLENGE = 'sign-in-code';
401
+ const codeScope = { path: '/sign-in/email', httpOnly: true, secure: true, sameSite: 'Strict' } as const;
402
+
403
+ /** Runs `work` off the request, and reports what it throws: nobody else will see it. */
404
+ const offRequest = (work: () => Promise<unknown>): void => void work().catch(reportError);
405
+
406
+ app.post('/sign-in/email', async (c) => {
407
+ const { email } = await c.req.json();
408
+ // counted, nobody looked up, a challenge minted: MAIL_THROTTLED → 429 by janusErrors()
409
+ const pending = await auth.signInCode.prepare(email);
410
+ offRequest(async () => {
411
+ const issued = await pending.send(); // the lookup and the code, off the visitor's request
412
+ if (issued !== null) await mailer.send(issued.email, `Your sign-in code: ${issued.code}`); // the code only
413
+ });
414
+ // the same answer either way: a challenge for everybody, TOKEN_UNKNOWN when nobody holds the e-mail
415
+ setCookie(c, CODE_CHALLENGE, pending.challenge, { ...codeScope, maxAge: 600 });
416
+ return c.json({ next: 'code' }, 202);
417
+ });
418
+
419
+ app.post('/sign-in/email/code', async (c) => {
420
+ const { code } = await c.req.json();
421
+ const challenge = getCookie(c, CODE_CHALLENGE);
422
+ if (challenge === undefined) return c.json({ code: 'TOKEN_UNKNOWN' }, 400);
423
+ const user = sendSession(c, auth, await auth.signInCode.confirm(challenge, code));
424
+ deleteCookie(c, CODE_CHALLENGE, codeScope);
425
+ return c.json({ id: user.id });
426
+ });
427
+ ```
428
+
429
+ **The request route answers the same whoever asked** — the same status, the
430
+ same body, and a cookie either way, in the same time. `signInCode.prepare`
431
+ (`@softistx/janus` 0.20) counts the address and mints the challenge **without
432
+ looking anybody up**, so it makes the same store calls for any address;
433
+ `send()`, which looks the address up and issues the code under that
434
+ challenge, runs after the answer. For an address nobody holds `send()`
435
+ answers `null`, and the challenge confirms as `TOKEN_UNKNOWN`. `maxAge: 600`
436
+ is the default ten minutes of `tokens.signInCode`. `@softistx/janus` throttles
437
+ each address — five requests per 10 minutes, then `MAIL_THROTTLED` from
438
+ `prepare`, in the visitor's request, which `janusErrors()` answers 429 with
439
+ `Retry-After` (the last code sent still works); rate-limit the route per
440
+ client yourself, since one client can ask for many addresses. `send()` runs
441
+ once: a second call is a `TypeError`, so a retry prepares again. With
442
+ `signInCode.request(email)` instead, the route would wait for the lookup —
443
+ its time would tell — and would set a random decoy challenge for `null`.
444
+
445
+ The code route still tells a decoy apart: a wrong code against it is 400
446
+ `TOKEN_UNKNOWN`, against a real challenge 401 `CODE_INVALID` with
447
+ `attemptsLeft`. Where your users' addresses must stay secret, answer every
448
+ refusal of that route alike, before `janusErrors()` sees it:
449
+
450
+ ```ts
451
+ import { JanusError } from '@softistx/janus';
452
+
453
+ app.onError((error, c) =>
454
+ error instanceof JanusError && error.code !== 'STORE_FAILED' && c.req.path === '/sign-in/email/code'
455
+ ? c.json({ code: 'CODE_INVALID' }, 401) // no attemptsLeft: it would tell a real challenge from a decoy
456
+ : answer(error, c),
457
+ );
458
+ ```
459
+
460
+ with `answer` the `janusErrors()` of [Wiring](#wiring).
461
+
462
+ The code goes in the e-mail, **the challenge never does**: not in the
463
+ e-mail, not in a link, not in a log.
464
+
465
+ A wrong code leaves the cookie in place, so the visitor types it again.
466
+ `janusErrors()` answers what `confirm` throws, with the statuses above:
467
+
468
+ | Thrown | Answered |
469
+ | --- | --- |
470
+ | `CODE_INVALID` | 401 `{ code, attemptsLeft }` — the attempts the challenge has left, `0` once the fifth wrong code spent it |
471
+ | `TOKEN_UNKNOWN`, `TOKEN_SPENT`, `TOKEN_EXPIRED` | 400 `{ code }` — offer to send a new code |
472
+ | `TOKEN_STALE` | 400 `{ code }` — the e-mail changed since the code was sent: send a new one |
473
+ | `USER_INACTIVE` | 403 `{ code }` |
474
+
475
+ `confirm` marks the user's e-mail verified: the code reached the inbox.
476
+
477
+ ### With a second factor
478
+
479
+ With `janus({ secondFactor })`, a user whose factor is active gets a
480
+ **challenge** from `signInCode.confirm`, not a session — the code proves the
481
+ e-mail, not the factor — and passing its answer straight to `sendSession`
482
+ no longer compiles on a type with a password. Narrow on `status`, and hand
483
+ the challenge to the second factor's cookie, so
484
+ [`/sign-in/code`](#a-second-factor) takes it from there:
485
+
486
+ ```ts
487
+ app.post('/sign-in/email/code', async (c) => {
488
+ const { code } = await c.req.json();
489
+ const challenge = getCookie(c, CODE_CHALLENGE);
490
+ if (challenge === undefined) return c.json({ code: 'TOKEN_UNKNOWN' }, 400);
491
+ const result = await auth.signInCode.confirm(challenge, code);
492
+ deleteCookie(c, CODE_CHALLENGE, codeScope);
493
+ if (result.status === 'secondFactor') {
494
+ setCookie(c, CHALLENGE, result.challenge, { ...scope, expires: result.expiresAt });
495
+ return c.json({ next: 'secondFactor' });
496
+ }
497
+ const user = sendSession(c, auth, result);
498
+ return c.json({ id: user.id });
499
+ });
500
+ ```
501
+
502
+ A user type with no password has no second factor, so its `confirm` always
503
+ answers a session. The attempts, the lifetime and every refusal are
504
+ [`@softistx/janus`'s sign-in code guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/sign-in-code.md).
505
+
506
+ ## A link sent by e-mail
507
+
508
+ A sign-in by e-mailed link takes three routes. The first asks for a link.
509
+ The link then opens **a page that spends nothing**, and that page's button
510
+ posts the token back to the third route, which signs the user in.
511
+
512
+ `offRequest` is the helper of [a code sent by e-mail](#a-code-sent-by-e-mail).
513
+
514
+ Never sign in on the link's `GET`. Mail scanners open every link in an
515
+ e-mail and would spend the token before the user clicks. Sending the e-mail
516
+ is your job.
517
+
518
+ ```ts
519
+ import { JanusError, TokenError } from '@softistx/janus';
520
+ import { sendSession } from '@softistx/janus-hono';
521
+ import { csrf } from 'hono/csrf';
522
+
523
+ const ORIGIN = 'https://app.example';
524
+ const TOKEN = /^[A-Za-z0-9_-]{43}$/; // 32 bytes, base64url: the only thing echoed into the page
525
+
526
+ app.post('/sign-in/email/link', async (c) => {
527
+ const { email } = await c.req.json();
528
+ const pending = await auth.magicLink.prepare(email); // counted, nobody looked up: MAIL_THROTTLED → 429
529
+ offRequest(async () => { // offRequest: see A code sent by e-mail (#a-code-sent-by-e-mail)
530
+ // the lookup and the token, after the answer, so its time tells nothing; in production, a queue
531
+ const issued = await pending.send();
532
+ if (issued !== null) await mailer.send(issued.email, `${ORIGIN}/sign-in/link?token=${issued.token}`);
533
+ });
534
+ return c.body(null, 202); // the same answer either way: nothing of a link reaches the visitor
535
+ });
536
+
537
+ // GET: what the e-mail links to. It renders a page and does nothing else.
538
+ app.get('/sign-in/link', (c) => {
539
+ const token = c.req.query('token') ?? '';
540
+ c.header('Referrer-Policy', 'strict-origin'); // the origin only: never the token
541
+ c.header('Cache-Control', 'no-store');
542
+ if (!TOKEN.test(token)) return c.text('This link is not valid.', 400);
543
+ return c.html(`<!doctype html><meta charset="utf-8"><title>Sign in</title>
544
+ <form method="post" action="/sign-in/link">
545
+ <input type="hidden" name="token" value="${token}">
546
+ <button>Sign in</button>
547
+ </form>`);
548
+ });
549
+
550
+ // POST: the page's button. csrf() answers 403 to a form posted from another site.
551
+ app.post('/sign-in/link', csrf({ origin: ORIGIN }), async (c) => {
552
+ const token = String((await c.req.parseBody()).token ?? '');
553
+ try {
554
+ sendSession(c, auth, await auth.magicLink.confirm(token));
555
+ return c.redirect('/', 303);
556
+ } catch (error) {
557
+ if (error instanceof TokenError || (error instanceof JanusError && error.code === 'VERSION_CONFLICT')) {
558
+ return c.redirect('/sign-in?link=expired', 303); // ask for another link
559
+ }
560
+ throw error; // USER_INACTIVE 403, STORE_FAILED 503: janusErrors()
561
+ }
562
+ });
563
+ ```
564
+
565
+ - **The request route answers `202` whoever asked.** `magicLink.request`
566
+ answers `null` for an address nobody holds and for an inactive user. With
567
+ a code, the route needs a decoy challenge. Nothing of a link reaches the
568
+ visitor, so here there is no decoy to forge. Every call sends an e-mail
569
+ and cancels the link sent before it: `@softistx/janus` throttles each address
570
+ (`MAIL_THROTTLED`, 429 with `Retry-After`), and per client stays yours.
571
+ - **The page echoes only a token of the token's shape.** Anything else
572
+ written into the HTML is a cross-site scripting hole. Use a button, not a
573
+ script that submits the form by itself: a scanner that runs scripts would
574
+ submit it too.
575
+ - **Put `csrf({ origin })` on the `POST`.** The token does not identify the
576
+ browser that asked for it. Without the check, any site could post a token
577
+ for an account it controls and sign its visitor into that account.
578
+ - **Send the page with `Referrer-Policy: strict-origin`.** A `Referer` then
579
+ holds the origin only — never the path and the token in its query — so
580
+ nothing the page loads learns the token. Not `no-referrer`: with it the
581
+ browser posts the form with `Origin: null`, and wherever `csrf()` falls
582
+ back to the `Origin` — no `Sec-Fetch-Site` on plain HTTP off `localhost`,
583
+ or from an older browser — the button's own `POST` answers
584
+ [403](../troubleshooting.md#403-forbidden-on-post-sign-inlink).
585
+ - **Answer the `POST` with a `303`**, so that reloading the page does not
586
+ post the spent token again. The cookie that `sendSession` set is sent with
587
+ the redirect.
588
+
589
+ `confirm` spends the link on its first call, whether that call signs the
590
+ user in or is refused, and it marks the user's e-mail verified. To the user,
591
+ every `TOKEN_*` error means the same thing: ask for another link. The rare
592
+ `VERSION_CONFLICT` means the same too; it happens when the user record was
593
+ written while the e-mail was being proved.
594
+
595
+ ### With a second factor
596
+
597
+ With `janus({ secondFactor })`, a user whose factor is active gets a
598
+ **challenge** from `magicLink.confirm`, not a session. On a type with a
599
+ password, passing that answer straight to `sendSession` no longer compiles.
600
+ Narrow on `status`, and hand the challenge to the second factor's cookie:
601
+
602
+ ```ts
603
+ app.post('/sign-in/link', csrf({ origin: ORIGIN }), async (c) => {
604
+ const token = String((await c.req.parseBody()).token ?? '');
605
+ const result = await auth.magicLink.confirm(token);
606
+ if (result.status === 'secondFactor') {
607
+ setCookie(c, CHALLENGE, result.challenge, { ...scope, expires: result.expiresAt });
608
+ return c.redirect('/sign-in/second-factor', 303); // a page of yours whose form posts the app's code to /sign-in/code
609
+ }
610
+ sendSession(c, auth, result);
611
+ return c.redirect('/', 303);
612
+ });
613
+ ```
614
+
615
+ [`@softistx/janus-mail`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-mail) sends
616
+ this e-mail with `mail.magicLink(issued)`, building its button with
617
+ `links.magicLink(token)`. Point `links.magicLink` at the `GET` route above.
618
+ For the lifetime and every refusal, see [`@softistx/janus`'s sign-in link
619
+ guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/magic-link.md).
620
+
621
+ ## Accepting an invitation
622
+
623
+ An invitation is the application's own proof: it issued the token, and the
624
+ person followed it. `auth.signInProven(userId)` signs them in on that proof
625
+ — no e-mail, no mail-throttle count, no link spent — and answers what
626
+ `signIn` answers, so `sendSession` and the second factor work as above.
627
+ There is no route of this package for it: the proof is yours to check, and
628
+ the id must come from your invitation's record, **never from the request**.
629
+
630
+ ```ts
631
+ app.post('/invitation/accept', csrf({ origin: ORIGIN }), async (c) => {
632
+ const token = String((await c.req.parseBody()).token ?? '');
633
+ const invitation = await invitations.spend(hash(token), new Date()); // yours: once, unexpired
634
+ if (invitation === null) return c.json({ code: 'INVITATION_INVALID' }, 404);
635
+
636
+ // The invitation reached the inbox: prove it first — on an address never proved, this
637
+ // drops a password, a second factor and sessions somebody else set on it.
638
+ const user = await auth.get(invitation.userId);
639
+ if (user.email !== invitation.email) return c.json({ code: 'INVITATION_INVALID' }, 404);
640
+ await auth.verifyEmail.proveFirst(user);
641
+ // Then sign in — last, since proveFirst revokes every session.
642
+ const result = await auth.signInProven(user, { device: deviceOf(c) });
643
+ if (result.status === 'secondFactor') {
644
+ setCookie(c, CHALLENGE, result.challenge, { ...scope, expires: result.expiresAt });
645
+ return c.redirect('/sign-in/second-factor', 303);
646
+ }
647
+ sendSession(c, auth, result);
648
+ return c.redirect('/', 303);
649
+ });
650
+ ```
651
+
652
+ `verifyEmail.proveFirst` (`@softistx/janus` 0.22) comes first, and before any
653
+ `setPassword` your form makes: it drops the password and revokes every
654
+ session. The check on `email` keeps it from proving an address the user
655
+ changed since the invitation was sent.
656
+
657
+ Not `magicLink.request` then `confirm` at once: `request` counts against
658
+ the mail throttle per address, so five anonymous requests for the invitee's
659
+ address would answer this route 429. See [`@softistx/janus`'s
660
+ sessions guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/sessions.md#signing-in-on-your-own-proof--signinproven).
661
+
662
+ ## The device cookie
663
+
664
+ With `janus({ devices })`, every sign-in can tell the user it came from a
665
+ device they had not signed in from. The browser keeps a **device token** in
666
+ a long-lived cookie of its own; `deviceOf(c)` reads it for the sign-in's
667
+ `device`, and `sendSession` sets it from the answer's `deviceToken` — the
668
+ first time, and again at every sign-in, so it lasts another 400 days:
669
+
670
+ ```ts
671
+ import { deviceOf, sendSession } from '@softistx/janus-hono';
672
+
673
+ app.post('/sign-up', async (c) => {
674
+ const { email, name, password } = await c.req.json();
675
+ const signedUp = await auth.signUp({ email, name, password }, { device: deviceOf(c) });
676
+ return c.json({ id: sendSession(c, auth, signedUp).id }, 201); // the device is known from the start
677
+ });
678
+
679
+ app.post('/sign-in', async (c) => {
680
+ const { email, password } = await c.req.json();
681
+ const signedIn = await auth.signIn({ email, password }, { device: deviceOf(c) });
682
+ const user = sendSession(c, auth, signedIn);
683
+ return c.json({ id: user.id, newDevice: signedIn.newDevice });
684
+ });
685
+ ```
686
+
687
+ `deviceOf(c)` answers `null` for a browser with no device cookie, or an
688
+ empty one: the sign-in then mints its first token. A token that proves
689
+ nothing — another user's, a forged one, one whose key was removed — is a
690
+ new device, never an error. A sign-in given no `device` answers no
691
+ `deviceToken`, and `sendSession` sets no device cookie.
692
+
693
+ | Option | Type | Default | Effect |
694
+ | --- | --- | --- | --- |
695
+ | `name` | `string` | `'janus-device'` (`DEVICE_COOKIE`) | The cookie's name |
696
+ | `domain` | `string` | none | `Domain=` |
697
+ | `path` | `string` | `'/'` | `Path=`: keep it covering every sign-in route |
698
+ | `sameSite` | `'Lax' \| 'Strict' \| 'None'` | `'Lax'` | `SameSite=` — Hono's capitalised values, unlike `janus({ cookie })`'s `'lax'` |
699
+ | `secure` | `boolean` | `true` | `Secure` |
700
+ | `maxAge` | seconds | `34560000`, 400 days | `Max-Age=` — the longest a browser keeps a cookie; above `34560000`, or negative, or not finite, `sendSession` throws a `RangeError` |
701
+
702
+ The cookie is always `HttpOnly`. Give `deviceOf` and `sendSession` the same
703
+ options — one object, passed to both:
704
+
705
+ ```ts
706
+ import { type DeviceCookieOptions, bindJanus, deviceOf } from '@softistx/janus-hono';
707
+
708
+ const device: DeviceCookieOptions = { name: 'device', sameSite: 'Strict' };
709
+ const j = bindJanus({ auth });
710
+
711
+ app.post('/sign-in', async (c) => {
712
+ const signedIn = await auth.signIn(await c.req.json(), { device: deviceOf(c, device) });
713
+ j.sendSession(c, signedIn, { device });
714
+ return c.body(null, 204);
715
+ });
716
+ ```
717
+
718
+ **With a second factor, give the device again.** The challenge `signIn`
719
+ answers carries no device, and sets no device cookie: `confirm` and
720
+ `recover` decide, from what they are given. The device cookie's path is
721
+ `/`, so the code routes read it too:
722
+
723
+ ```ts
724
+ app.post('/sign-in/code', async (c) => {
725
+ const { code } = await c.req.json();
726
+ const challenge = getCookie(c, CHALLENGE);
727
+ if (challenge === undefined) return c.json({ code: 'TOKEN_UNKNOWN' }, 400);
728
+ const signedIn = await auth.secondFactor.confirm(challenge, code, { device: deviceOf(c) });
729
+ const user = sendSession(c, auth, signedIn); // and the device cookie
730
+ deleteCookie(c, CHALLENGE, scope);
731
+ return c.json({ id: user.id });
732
+ });
733
+ ```
734
+
735
+ The same holds for `/sign-in/recovery`, `signInCode.confirm` and
736
+ `magicLink.confirm`: pass `{ device: deviceOf(c) }` to each.
737
+
738
+ **A sign-out leaves the device cookie**: `signOut` clears the session
739
+ cookie only, so the device stays known. A browser two people take turns
740
+ signing in on holds one user's token at a time, so each of them is told of
741
+ a new device at every turn.
742
+
743
+ A bearer client — a mobile app — has no cookie jar to share: answer it the
744
+ `deviceToken` in the body, and take it back as `device`:
745
+
746
+ ```ts
747
+ app.post('/api/sign-in', async (c) => {
748
+ const { email, password, deviceToken } = await c.req.json();
749
+ const signedIn = await auth.signIn({ email, password }, { device: deviceToken ?? null });
750
+ return c.json({ token: signedIn.token, deviceToken: signedIn.deviceToken });
751
+ });
752
+ ```
753
+
754
+ The notice itself — which device, when — is
755
+ [`@softistx/janus-mail`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-mail)'s
756
+ `newSignIn`, sent when `signedIn.newDevice` is `true`, and everything about
757
+ the token is in [`@softistx/janus`'s devices guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/devices.md).
758
+
759
+ ## A step-up
760
+
761
+ A route a stolen session should not run alone — deleting the account,
762
+ changing the e-mail, disabling the second factor — asks for a **recent
763
+ proof** with `fresh(maxAge)`, after `session()`:
764
+
765
+ ```ts
766
+ import { fresh, session } from '@softistx/janus-hono';
767
+
768
+ app.delete('/account', session(auth, { required: true }), fresh('10m'), async (c) => {
769
+ await auth.delete(c.var.user);
770
+ return c.body(null, 204);
771
+ });
772
+ ```
773
+
774
+ A session that signed in, or was confirmed by a step-up, less than ten
775
+ minutes ago runs the route. An older one is answered
776
+ `403 {"code":"STEP_UP_REQUIRED"}` by `janusErrors()` — not a denial: the
777
+ client runs a step-up, then sends the same request again. Two routes, built
778
+ like [the code sent by e-mail](#a-code-sent-by-e-mail), except that both
779
+ need the session:
780
+
781
+ ```ts
782
+ import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
783
+
784
+ app
785
+ .post('/step-up', session(auth, { required: true }), async (c) => {
786
+ const issued = await auth.stepUp.request(c.var.user);
787
+ if (issued.via === 'email') {
788
+ await mailer.send(issued.email, `Your confirmation code: ${issued.code}`); // yours
789
+ }
790
+ setCookie(c, 'step-up-challenge', issued.challenge, {
791
+ path: '/step-up', httpOnly: true, secure: true, sameSite: 'Strict', expires: issued.expiresAt,
792
+ });
793
+ return c.json({ via: issued.via }); // 'secondFactor': the code comes from their app
794
+ })
795
+ .post('/step-up/code', session(auth, { required: true }), async (c) => {
796
+ const { code } = await c.req.json();
797
+ const challenge = getCookie(c, 'step-up-challenge') ?? '';
798
+ await auth.stepUp.confirm(c.req.raw, challenge, code);
799
+ deleteCookie(c, 'step-up-challenge', { path: '/step-up' });
800
+ return c.body(null, 204);
801
+ });
802
+ ```
803
+
804
+ - **`confirm` takes the request**: it stamps the session that request
805
+ presents — `c.req.raw`, with its cookie or its `Authorization` header —
806
+ and opens none, so there is no cookie to send again. A challenge carried
807
+ to another session is `TOKEN_UNKNOWN`, 400.
808
+ - **`via: 'secondFactor'`** — a user whose second factor is active confirms
809
+ with their app's code, and no e-mail is sent. A step-up is never weaker
810
+ than the sign-in the account asks for.
811
+ - **A wrong code** is `401 {"code":"CODE_INVALID","attemptsLeft":n}`, as on
812
+ the sign-in code form; the fifth spends the challenge.
813
+
814
+ `fresh()` reads `session.authenticatedAt` and nothing else: no store read.
815
+ In a spec, pass `janus()`'s clock — `fresh('10m', { clock })` — so
816
+ `clock.advance()` ages the session. Every refusal is in
817
+ [`@softistx/janus`'s step-up guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/step-up.md).
818
+
819
+ ## Sign-out
820
+
821
+ ```ts
822
+ import { signOut } from '@softistx/janus-hono';
823
+
824
+ app.post('/sign-out', async (c) => {
825
+ await signOut(c, auth);
826
+ return c.body(null, 204);
827
+ });
828
+
829
+ app.post('/sign-out-everywhere', session(auth, { required: true }), async (c) => {
830
+ await auth.signOutEverywhere(c.var.user, { except: c.var.session.id });
831
+ return c.body(null, 204);
832
+ });
833
+ ```
834
+
835
+ `signOut` clears the cookie whatever it revoked, so a browser holding a stale
836
+ cookie drops it too.
837
+
838
+ ## E-mail verification and password reset
839
+
840
+ Sending the e-mail is yours; the one-time token goes in a link. `offRequest`
841
+ is the helper of [a code sent by e-mail](#a-code-sent-by-e-mail).
842
+
843
+ ```ts
844
+ app.post('/verify-email', session(auth, { required: true }), async (c) => {
845
+ const { token, email } = await auth.verifyEmail.send(c.var.user);
846
+ await mailer.send(email, `https://app.test/verify?token=${token}`);
847
+ return c.body(null, 202);
848
+ });
849
+
850
+ app.post('/verify-email/confirm', async (c) => {
851
+ const { token } = await c.req.json();
852
+ await auth.verifyEmail.confirm(token, { firstProof: true }); // TOKEN_* → 400; VERSION_CONFLICT → 409 (send a new link); firstProof also drops the password of a user who signed up and has not verified yet
853
+ return c.body(null, 204);
854
+ });
855
+
856
+ app.post('/reset-password', async (c) => {
857
+ const { email } = await c.req.json();
858
+ const pending = await auth.resetPassword.prepare(email); // counted, nobody looked up: MAIL_THROTTLED → 429
859
+ offRequest(async () => { // offRequest: see A code sent by e-mail (#a-code-sent-by-e-mail)
860
+ const issued = await pending.send(); // the lookup and the link, off the visitor's request
861
+ if (issued !== null) await mailer.send(issued.email, `https://app.test/reset?token=${issued.token}`);
862
+ });
863
+ return c.body(null, 202); // the same answer, in the same time, either way: never say which e-mails exist
864
+ });
865
+
866
+ app.post('/reset-password/confirm', async (c) => {
867
+ const { token, password } = await c.req.json();
868
+ await auth.resetPassword.confirm(token, password); // signs the user out everywhere
869
+ return c.body(null, 204);
870
+ });
871
+ ```
872
+
873
+ ## API keys
874
+
875
+ A script, a CI job or a partner calls your API without a browser: it presents
876
+ an API key (`Authorization: Bearer sl_…`, made by `auth.apiKeys.create`, see
877
+ [`@softistx/janus` — API keys](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/api-keys.md))
878
+ and acts as its user. **Keys are opt-in per route group**: only a
879
+ `session(auth, { apiKey: true })` accepts one. Everywhere else a key-shaped
880
+ bearer is anonymous, and a key is accepted only from `Authorization: Bearer`:
881
+ in the session cookie or `X-Session-Token` it is anonymous on these routes too. The instance needs `janus({ apiKeys })`; without it the
882
+ first request is a `TypeError`.
883
+
884
+ ```ts
885
+ import { type PrincipalEnv, session } from '@softistx/janus-hono';
886
+
887
+ const api = new Hono<PrincipalEnv<typeof auth>>();
888
+ api.use(session(auth, { apiKey: true, required: true }));
889
+ api.get('/reports', (c) => {
890
+ // c.var.user: whoever the key (or the session) belongs to
891
+ // c.var.principal.via: 'session' | 'apiKey'
892
+ // c.var.apiKey: the key, or null for a session
893
+ return c.json(reportsOf(c.var.user.id));
894
+ });
895
+ ```
896
+
897
+ | `c.var` | A session | An API key |
898
+ | --- | --- | --- |
899
+ | `user` | the user | the key's user |
900
+ | `principal` | `{ via: 'session', … }` | `{ via: 'apiKey', apiKey, … }` |
901
+ | `apiKey` | `null` | the key (never its secret) |
902
+ | `session` | the session | `null` |
903
+
904
+ Existing routes are unchanged: without the option `c.var.principal` and
905
+ `c.var.apiKey` are not set and `c.var.session` means what it always did. On
906
+ an `apiKey: true` route, read `c.var.principal.via` before `c.var.session`.
907
+ A key is not renewed, so no cookie is sent for it.
908
+
909
+ ### A key is never fresh
910
+
911
+ `fresh()` behind such a route throws `STEP_UP_REQUIRED` with
912
+ `reason: 'apiKey'` for a key: `403 {"code":"STEP_UP_REQUIRED"}`. A step-up
913
+ cannot make a key fresh, so a sensitive route (creating keys, deleting the
914
+ account) stays a signed-in session's: keep it behind `session(auth)` without
915
+ `apiKey`, or let the client fall back to a session.
916
+
917
+ ### A rate limit per key
918
+
919
+ Key the limiter on `principal.apiKey.id`, not on the user or the IP: a user
920
+ with several keys limits each separately, and a leaked key is throttled
921
+ without locking its owner out.
922
+
923
+ ```ts
924
+ import { type PrincipalEnv, session, type UserOfAuth } from '@softistx/janus-hono';
925
+ import { createMiddleware } from 'hono/factory';
926
+
927
+ // `limiter.hit(key)` is yours (for example @softistx/redis's rate limit):
928
+ // it answers whether the key may go on.
929
+ const perKey = createMiddleware<PrincipalEnv<typeof auth, UserOfAuth<typeof auth>['type'], true>>(
930
+ async (c, next) => {
931
+ const { principal } = c.var;
932
+ if (principal.via === 'apiKey' && !(await limiter.hit(principal.apiKey.id))) {
933
+ return c.body(null, 429, { 'Retry-After': '60' });
934
+ }
935
+ await next();
936
+ return undefined;
937
+ },
938
+ );
939
+
940
+ api.use(session(auth, { apiKey: true, required: true }), perKey);
941
+ ```
942
+
943
+ Sessions pass through untouched; give them their own limit if you want one.
944
+
945
+ ### Errors
946
+
947
+ Creating a key can refuse with `API_KEY_LIMIT` (409,
948
+ `{ "code": "API_KEY_LIMIT", "maxActive": 10 }`) and `API_KEY_INVALID` (400,
949
+ `{ "code": "API_KEY_INVALID", "field": "name" }`, `field` being `name` or
950
+ `lifetime`). `janusErrors()` and `bodyOf` carry `maxActive` and `field`.
951
+
952
+ ## Social sign-in
953
+
954
+ `socialRoutes(auth, options)` is a Hono sub-app with the routes of
955
+ [`@softistx/janus`'s social sign-in](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/social.md):
956
+
957
+ | Route | What it does |
958
+ | --- | --- |
959
+ | `GET /:provider?returnTo=/path` | `auth.social.start`: appends the flow cookie, 302 to the provider. A bad `returnTo` is `RETURN_TO_INVALID` (400), an unknown provider `SOCIAL_PROVIDER_UNKNOWN` (404), an unreachable one `PROVIDER_ERROR` (502) |
960
+ | `GET /:provider/callback` | `auth.social.complete`: see below. Its success answers (the session cookie, or `onSecondFactor` with a challenge) carry `Cache-Control: no-store`, as the start and the link redirects do (they set the flow cookie) |
961
+ | `POST /:provider/link?returnTo=/path` | Behind `session({ required: true })` and `fresh()`: `auth.social.link`, 303 to the provider. Anonymous 401, a stale session `STEP_UP_REQUIRED` |
962
+ | `DELETE /links/:provider/:accountId` | Behind the same: `auth.social.unlink`. 204, 404 for a link that is not the user's, `LAST_SIGN_IN_METHOD` (409) for their last way in |
963
+
964
+ ```ts
965
+ import { bindJanus } from '@softistx/janus-hono';
966
+
967
+ const j = bindJanus({ auth });
968
+ app.route(
969
+ '/auth/social',
970
+ j.socialRoutes({
971
+ type: 'patient', // only when several user types configure social
972
+ defaultReturnTo: '/dashboard',
973
+ onSecondFactor: (c, result) => {
974
+ setCookie(c, 'sf', result.challenge, { httpOnly: true, sameSite: 'Lax', maxAge: 300 });
975
+ return c.redirect('/two-factor');
976
+ },
977
+ }),
978
+ );
979
+ ```
980
+
981
+ ### The callback
982
+
983
+ 1. It reads the flow from the cookie named `auth.social.cookie.name` and calls
984
+ `complete` (with the device cookie as the sign-in's `device` when you gave
985
+ `device`, and the signed-in user as `current`, which a link flow needs).
986
+ 2. **Signed in**: the session cookie (and the device cookie) are appended with
987
+ `sendSession`, then 302 to the flow's `returnTo`, or `defaultReturnTo`
988
+ (`/` by default). **Linked** (a link flow): 302 likewise, no session.
989
+ **Second factor**: your `onSecondFactor(c, result)` answers.
990
+ 3. **Refused** with one of the visitor's refusals (the ten social codes,
991
+ `USER_INACTIVE`, `EMAIL_UNVERIFIED`, `STEP_UP_REQUIRED`): 302 to the same path with
992
+ `?socialError=<code>` added before any fragment, or your
993
+ `onRefusal(c, error, location)`, which gets that location. Any other
994
+ error is thrown to `app.onError`: `STORE_FAILED` is a 503 with
995
+ `janusErrors()`, a bug is Hono's 500.
996
+
997
+ **The flow cookie** is cleared on every outcome except one: an error whose
998
+ `flowSpent === false` (the cookie missing, or a `state` that is not the
999
+ flow's) keeps it, because a forged callback must not burn the visitor's real
1000
+ flow, which may still arrive. A refused `FLOW_MISMATCH` carries no `returnTo`,
1001
+ so it lands on `defaultReturnTo`.
1002
+
1003
+ **`returnTo` is never taken from the request.** It comes from the error's or
1004
+ the result's `returnTo`, which the core fills from the flow it checked and
1005
+ bound; the route does not unpack the cookie. It is checked once more with the
1006
+ core's `isReturnTo` (a path of your site; see the social guide) and replaced by `defaultReturnTo` if it fails.
1007
+
1008
+ ### Options
1009
+
1010
+ | Option | Default | Effect |
1011
+ | --- | --- | --- |
1012
+ | `onSecondFactor(c, result)` | required | Answers when the user has a second factor; `result.challenge` goes to `secondFactor.confirm` |
1013
+ | `onRefusal(c, error, location)` | 302 to `location` | Answers a refusal. Do not put `error.message` or `error.cause` in a response |
1014
+ | `defaultReturnTo` | `'/'` | Where the visitor lands without a valid `returnTo`; a path of your site, else a `TypeError` |
1015
+ | `type` | none | The user type, when several configure `social` |
1016
+ | `session` | `session(auth, { required: true, type })` | Another middleware for the link and unlink routes; it must answer 401 to an anonymous request |
1017
+ | `device` | none | `DeviceCookieOptions`: pass it when `janus({ devices })` is wired, so the callback reads and sets the device cookie like [the sign-in routes](#the-device-cookie). Without `devices` in `janus()`, leave it out |
1018
+ | `freshWithin` | `'10m'` | The `fresh()` window; set it to the core's `social.freshWithin` |
1019
+ | `clock` | the system's | The clock given to `janus()`, in a spec |
1020
+
1021
+ The routes ask for no CSRF token: the flow cookie is `SameSite=Lax` and the
1022
+ callback is a `GET` the provider redirects to. `POST` and `DELETE` are
1023
+ the application's to protect (Hono's `csrf()`), as for any cookie-authenticated
1024
+ route.
1025
+
1026
+ **Rate-limit the start route.** `GET /:provider` is anonymous and writes a token
1027
+ per request, so anyone can fill the token store. Put a rate limit in front of
1028
+ it, for example with `@softistx/redis`.
1029
+
1030
+ ## Passkeys
1031
+
1032
+ `passkeyRoutes(auth, options?)` is the one set of routes this package mounts
1033
+ for you besides the social ones: the bodies are the browser's WebAuthn JSON,
1034
+ which an application has no reason to reshape. It needs `janus({ secondFactor,
1035
+ passkeys })` (a passkey stands beside an active TOTP) and a verifier; the
1036
+ core's [passkeys guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/passkeys.md)
1037
+ has the wiring.
1038
+
1039
+ ```ts
1040
+ import { janusErrors, passkeyRoutes } from '@softistx/janus-hono';
1041
+
1042
+ app.route('/auth/passkeys', passkeyRoutes(auth, { device: {} })); // device: only with janus({ devices })
1043
+ app.onError(janusErrors());
1044
+ ```
1045
+
1046
+ With several user types, name the one that holds passkeys: `janus()` puts
1047
+ `passkeys`, `secondFactor` and `stepUp` under `auth.<type>`, and the routes call
1048
+ those (the session and the cookie come from `auth`). Mount one set per type;
1049
+ a session of another type is answered 401:
1050
+
1051
+ ```ts
1052
+ app.route('/staff/passkeys', passkeyRoutes(auth, { type: 'staff' }));
1053
+ app.route('/patient/passkeys', passkeyRoutes(auth, { type: 'patient' }));
1054
+ ```
1055
+
1056
+ Leaving `type` out, or naming one the instance does not have, is a compile
1057
+ error (a `TypeError` at wiring in JavaScript).
1058
+
1059
+ A page registers a passkey in two requests, the second after the browser's
1060
+ prompt:
1061
+
1062
+ ```ts
1063
+ const issued = await (await fetch('/auth/passkeys/registration-options', { method: 'POST' })).json();
1064
+ const credential = await navigator.credentials.create({ publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(issued.options) });
1065
+ await fetch('/auth/passkeys', {
1066
+ method: 'POST',
1067
+ headers: { 'content-type': 'application/json' },
1068
+ body: JSON.stringify({ challenge: issued.challenge, response: credential.toJSON(), name: 'Laptop' }),
1069
+ }); // 201 { credentialId, name, … }
1070
+ ```
1071
+
1072
+ Signing in is `signIn` (your route), then a second request to
1073
+ `POST /sign-in` with the `challenge` it answered and the browser's
1074
+ assertion; the session cookie is set and the answer is `{ id }`:
1075
+
1076
+ ```ts
1077
+ const assertion = await navigator.credentials.get({ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(passkeyOptions) });
1078
+ await fetch('/auth/passkeys/sign-in', {
1079
+ method: 'POST',
1080
+ headers: { 'content-type': 'application/json' },
1081
+ body: JSON.stringify({ challenge, assertion: assertion.toJSON() }),
1082
+ });
1083
+ ```
1084
+
1085
+ `onSignedIn: (c, signedIn) => c.json({ token: signedIn.token })` answers a
1086
+ bearer client the token instead (the cookie is set all the same). With
1087
+ `device`, the route reads the device cookie as the sign-in's `device` and sets
1088
+ it again, as [the device cookie](#the-device-cookie) describes.
1089
+
1090
+ `POST /registration-options` and `POST /step-up` answer a single-use `challenge`,
1091
+ and `POST /sign-in` sets the session cookie: their responses carry
1092
+ `Cache-Control: no-store`.
1093
+
1094
+ A step-up is `POST /step-up` (`{ challenge, options, expiresAt }`) and
1095
+ `POST /step-up/confirm` with `{ challenge, assertion }`; always mounted; a user
1096
+ without a passkey, or a type without an e-mail, is answered 409. It stamps the session the
1097
+ request presents, like `stepUp.confirm`.
1098
+
1099
+ | Thrown | Answered |
1100
+ | --- | --- |
1101
+ | `CODE_INVALID` | 401 `{ code, attemptsLeft }` — a wrong, foreign or replayed assertion; the fifth spends the challenge |
1102
+ | `TOKEN_UNKNOWN`, `TOKEN_SPENT`, `TOKEN_EXPIRED` | 400 `{ code }` — a missing, spent or lapsed challenge |
1103
+ | `PASSKEY_INVALID` | 400 `{ code }`, plus `field: 'name'` for a bad name (nothing is spent); a response that did not verify spends its challenge, `reason` stays in your logs |
1104
+ | `PASSKEY_TAKEN`, `PASSKEY_LIMIT` | 409 `{ code }`; `maxActive` is the cap |
1105
+ | `EMAIL_UNVERIFIED` | 403 `{ code }` — options or register while the account's e-mail is not proved |
1106
+ | `SECOND_FACTOR_NOT_ENROLLED` | 409 `{ code }` — no active TOTP, or no passkey for a step-up |
1107
+ | `STEP_UP_REQUIRED` | 403 `{ code }` — register or remove with a session older than `passkeys.freshWithin`: step up, then retry |
1108
+
1109
+ A body that is not JSON, or not an object, reads as `{}`: the core then
1110
+ refuses the absent field with its own code (`PASSKEY_INVALID` for the name,
1111
+ `TOKEN_UNKNOWN` for the challenge), never a 500. A missing session on the
1112
+ routes that need one is 401 with no body.
1113
+
1114
+ The routes ask for no CSRF token: the session cookie is `SameSite=Lax`, so a
1115
+ cross-site `POST` does not carry it. With `sameSite: 'None'` they are exposed,
1116
+ and the body is read as JSON whatever its `Content-Type`, so a `text/plain`
1117
+ cross-site form is parsed too. Mount Hono's `csrf({ origin })` before the
1118
+ sub-app, as for any cookie-authenticated `POST`:
1119
+
1120
+ ```ts
1121
+ import { csrf } from 'hono/csrf';
1122
+
1123
+ app.use('/auth/passkeys/*', csrf({ origin: ORIGIN }));
1124
+ app.route('/auth/passkeys', passkeyRoutes(auth));
1125
+ ```
1126
+
1127
+ **Rate-limit `POST /sign-in`** per IP with `@softistx/redis` rate limits, like
1128
+ any anonymous route: the challenge's five attempts bound guessing one
1129
+ challenge, not a flood of requests.
1130
+
1131
+ ## Several user types
1132
+
1133
+ With `janus({ users: { patient, staff } })`, each type's flows are under its
1134
+ name, and `session()` takes the type a route admits:
1135
+
1136
+ ```ts
1137
+ app.post('/staff/sign-in', async (c) => {
1138
+ const { username, password } = await c.req.json();
1139
+ sendSession(c, auth, await auth.staff.signIn({ username, password }));
1140
+ return c.body(null, 204);
1141
+ });
1142
+
1143
+ app.get('/staff/rota', session(auth, { type: 'staff', required: true }), (c) =>
1144
+ c.json(rotaOf(c.var.user.username)), // a staff user: the compiler knows
1145
+ );
1146
+ ```
1147
+
1148
+ A patient's session on `/staff/rota` is anonymous there, and answered 401. The
1149
+ session stands, and still authenticates the patient on the routes that admit them.
1150
+ One cookie holds one session: a browser signed in as a patient that signs in
1151
+ as staff replaces the patient's cookie.
1152
+
1153
+ ## See also
1154
+
1155
+ - [`@softistx/janus` — sessions](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/sessions.md) — lifespans, renewal, the cookie's attributes
1156
+ - [`@softistx/janus` — API keys](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/api-keys.md) — creating, listing, revoking, lifetimes
1157
+ - [`@softistx/janus` — errors](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/errors.md) — every code
1158
+ - [`@softistx/janus` — the second factor](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/second-factor.md) — keys, states, attempts
1159
+ - [`@softistx/janus` — devices](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/devices.md) — the device token, the event, rotating the keys
1160
+ - [`@softistx/janus` — sign-in codes](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/sign-in-code.md) — requesting, the challenge, attempts, passwordless types
1161
+ - [`@softistx/janus` — passkeys](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/passkeys.md) — wiring, registering, the counter rule, the events
1162
+ - [`@softistx/janus` — social sign-in](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/social.md) — the flow, every case `complete` decides, writing a provider
1163
+ - [Guarded routes and writing tuples](permissions.md) — `permission()`, `provide()`
1164
+ - [Troubleshooting](../troubleshooting.md)