@softistx/janus-hono 0.0.0-stage → 0.11.34

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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,548 @@
1
- # Temporary Holding Version
1
+ # @softistx/janus-hono
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [`@softistx/janus`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus) in a
4
+ [Hono](https://hono.dev) app: the signed-in user on every request, the session
5
+ cookie set and cleared, a route guarded by a permission, the instances on the
6
+ context to grant and revoke through, and every error answered with the status
7
+ it deserves — an outage as 503, never as 401 or 403.
8
+
9
+ ```ts
10
+ import { janusErrors, sendSession, session, signOut } from '@softistx/janus-hono';
11
+ import { Hono } from 'hono';
12
+ import { auth } from './auth'; // what janus() answered
13
+
14
+ const app = new Hono()
15
+ .post('/sign-in', async (c) => {
16
+ const { email, password } = await c.req.json();
17
+ const user = sendSession(c, auth, await auth.signIn({ email, password }));
18
+ return c.json({ id: user.id }); // the token is in the cookie, not the body
19
+ })
20
+ .post('/sign-out', async (c) => {
21
+ await signOut(c, auth);
22
+ return c.body(null, 204);
23
+ })
24
+ .get('/me', session(auth, { required: true }), (c) =>
25
+ c.json({ email: c.var.user.email }), // never null here
26
+ );
27
+
28
+ app.onError(janusErrors()); // CREDENTIALS_INVALID → 401, STORE_FAILED → 503, …
29
+ ```
30
+
31
+ > **0.x.** A minor version may still change the surface; the changelog says how.
32
+
33
+ ## Install
34
+
35
+ Public on npmjs:
36
+
37
+ ```sh
38
+ bun add @softistx/janus-hono @softistx/janus hono
39
+ ```
40
+
41
+ Every peer is required: `@softistx/janus`, `hono` (4.13.4 or later) and
42
+ `typescript` (6 or 7). `@softistx/janus` is a **peer**, never a dependency: this package
43
+ defines no error class, so the `JanusError` you catch is the one you import.
44
+ Like `@softistx/janus`, it expects `"moduleResolution": "bundler"`: the
45
+ declarations import without extensions, so `nodenext` is not supported.
46
+
47
+ ## API
48
+
49
+ | Export | What it is |
50
+ | --- | --- |
51
+ | `session(auth, options?)` | Middleware. Reads who the request belongs to — `auth.authenticate(c.req.raw)` — and sets `c.var.user` and `c.var.session`, `null` for an anonymous request. `{ required: true }` answers an anonymous request 401 and types `c.var.user` as never `null`. `{ type: 'staff' }` treats a user of any other type as anonymous. `{ apiKey: true }` accepts an API key too and sets `c.var.principal` and `c.var.apiKey` (`c.var.session` is `null` for a key). Sends a renewed session's cookie again |
52
+ | `sendSession(c, auth, signedIn, options?)` | Appends the session cookie to the response — after `signUp`, `signIn`, `secondFactor.confirm`, `secondFactor.recover`, or anything that answered `{ token, session, user }` — marks the response `Cache-Control: no-store`, and answers the user. When the answer carries a `deviceToken` — the sign-in was given a `device` — it appends the device cookie too, or sets it again for another `maxAge`; `options.device` is its `DeviceCookieOptions`. With a second factor configured, narrow `signIn`'s answer on `status` first |
53
+ | `deviceOf(c, options?)` | The device token the request's device cookie holds, or `null` when there is none or it is empty: what a sign-in takes as `device` — `auth.signIn(input, { device: deviceOf(c) })`. `options` are the `DeviceCookieOptions` given to `sendSession` |
54
+ | `DeviceCookieOptions` | The device cookie: `{ name?, domain?, path?, sameSite?, secure?, maxAge? }` — `'janus-device'`, none, `'/'`, `'Lax'`, `true` and 400 days (`34560000` seconds) by default. Always `HttpOnly`. `sameSite` is Hono's capitalised `'Lax' \| 'Strict' \| 'None'`. Throws a `RangeError` for a `maxAge` outside 0 to 34560000 and a `TypeError` for a name, `__Host-`/`__Secure-` prefix or attribute a browser would refuse ([troubleshooting](docs/troubleshooting.md#rangeerror-devicecookie-maxage-must-be-a-number-of-seconds-from-0-to-34560000-400-days-got-)). |
55
+ | `DEVICE_COOKIE` | `'janus-device'`, the device cookie's default name |
56
+ | `SendSessionOptions` | `{ device? }`, the options of `sendSession` — for a wrapper of your own |
57
+ | `fresh(maxAge, { clock? })` | Middleware, after `session()`. The route runs only for a session that proved who it is less than `maxAge` ago — signed in, or confirmed since by `auth.stepUp.confirm`. An older one — and any API key — throws `STEP_UP_REQUIRED`, which `janusErrors()` answers 403; an anonymous request is 401 with no body. `clock` is the one given to `janus()`, in a spec |
58
+ | `signOut(c, auth)` | Revokes the session the request presents and clears the cookie, whatever the answer. `false` when the request presented no session, or an unknown one |
59
+ | `janusErrors({ report?, fallback? })` | An `app.onError` handler: every `JanusError` answered with `statusOf(code)` and `bodyOf(error)` — and a `Retry-After` header when it carries `retryAfter`, a throttled sign-in, a throttled e-mail request or an app's code past the user's window; anything else to `fallback`, or to Hono's own handling. `report(error, c)` sees every one answered 5xx first — `STORE_FAILED` and the like, for your logs — and cannot change the answer: one that throws or rejects is a warning, and the 503 is sent |
60
+ | `statusOf(code)` | The status a code deserves — `@softistx/janus`'s `statusOf`, typed as Hono's `ContentfulStatusCode`: `STORE_FAILED` 503, `CREDENTIALS_INVALID` and `CODE_INVALID` 401, `MAIL_THROTTLED` 429, `USER_INACTIVE`, `EMAIL_UNVERIFIED` and `STEP_UP_REQUIRED` 403, `LOGIN_TAKEN`, `SECOND_FACTOR_NOT_ENROLLED` and `SECOND_FACTOR_ACTIVE` 409, … Exhaustive over `JanusErrorCode` |
61
+ | `bodyOf(error)` | `{ code }`, plus `issues` for `USER_INVALID`, `minLength` for `PASSWORD_TOO_SHORT` and `attemptsLeft` for any `CODE_INVALID` that carries it, with `retryAfter` when the user's app-code window is spent — `secondFactor.confirm`'s, `secondFactor.recover`'s, `signInCode.confirm`'s and `stepUp.confirm`'s — `maxActive` for `API_KEY_LIMIT`, `INVITATION_LIMIT` and `PASSKEY_LIMIT`, `field` for `API_KEY_INVALID`, `INVITATION_INVALID` and `PASSKEY_INVALID`, and `retryAfter` for a `CREDENTIALS_INVALID` whose login is throttled, and for `MAIL_THROTTLED` (429): what the client can act on, and nothing else |
62
+ | `SessionOptions<Type>` | `{ type?, required?, apiKey? }`, the options of `session()` — for a wrapper of your own |
63
+ | `SessionEnv<typeof auth, Type?, Required?>` | The `Env` `session()` sets, for `new Hono<SessionEnv<typeof auth>>()` |
64
+ | `PrincipalEnv<typeof auth, Type?, Required?>` | The `Env` of `session(auth, { apiKey: true })`: `user`, `session`, `principal` and `apiKey` |
65
+ | `UserOfAuth<typeof auth>` | The users an instance knows, as a union narrowed by `user.type` |
66
+ | `permission(access, permission, type, load, options?)` | Middleware. Loads the object with `load(c)`, checks `access.can(c.var.user, permission, object)` with `type` added, and sets `c.var.object` to what `load` answered. Anonymous: 401, before loading. `load` answers `null`: 404. A denial: 403. `{ ctx: (c, object) => … }` is required exactly when the permission reaches a condition; `{ subject: (c) => … }` replaces `c.var.user`. One per route |
67
+ | `byParam(name, find)` | A `load` for `permission()`: `find(c.req.param(name))`, or `null` — a 404 — when the route has no such parameter |
68
+ | `bindJanus({ auth?, access? })` | The functions above with the instances bound: `session(options?)`, `sendSession(c, signedIn, options?)` and `signOut(c)` with `auth`; `socialRoutes(options)` when `auth` configures `social`; `passkeyRoutes(options?)` when it configures `passkeys` (with several user types, `options.type` is required and names one that does); `permission(permission, type, load, options?)` with `access`; `provide()` always |
69
+ | `socialRoutes(auth, options)` | A Hono sub-app for sign-in through an external provider: `GET /:provider` (the flow cookie and a 302 to the provider), `GET /:provider/callback` (completes the flow, sends the session cookie, 302 to the path the flow was started with), `POST /:provider/link` and `DELETE /links/:provider/:accountId` (behind `session()` and `fresh()`). `options` are `onSecondFactor` (required), `onRefusal?`, `defaultReturnTo?`, `type?`, `session?`, `device?`, `freshWithin?` and `clock?`. A refusal is a 302 with `?socialError=<code>`, never a body. See [Social sign-in](#social-sign-in) |
70
+ | `SocialRoutesOptions<typeof auth>`, `SocialAuth`, `SocialSurface`, `SecondFactorOf<typeof auth>` | The types of `socialRoutes()`: its options, the `auth` it takes, the part of `auth.social` it calls, and the challenge `onSecondFactor` receives |
71
+ | `passkeyRoutes(auth, options?)` | A Hono sub-app, all JSON, for a second factor by passkey (needs `janus({ secondFactor, passkeys })`): `GET /` (the user's passkeys), `POST /registration-options`, `POST /` (register), `POST /:credentialId/rename`, `DELETE /:credentialId`, `POST /sign-in` (answers a sign-in's second factor, sets the session cookie) and `POST /step-up` and `POST /step-up/confirm` (behind `session()`; a type with no e-mail answers 409). Every route but `/sign-in` is behind `session()`. `options` are `type?` (required with several user types: the routes then call `auth[type].passkeys`, `.secondFactor` and `.stepUp`), `session?`, `device?` and `onSignedIn?`. Refusals are thrown to `janusErrors()`. See [Passkeys](#passkeys) |
72
+ | `PasskeyRoutesOptions`, `PasskeyAuth`, `PasskeyTypeApi`, `PasskeySurface`, `PasskeyTypeNames`, `PasskeysSurface`, `StepUpPasskeySurface` | The types of `passkeyRoutes()`: its options, the `auth` it takes (`PasskeyAuth`: `authenticate` and the cookie), the surface a user type must answer (`PasskeyTypeApi`, at the top of `auth` or under `auth[type]`) and the parts of `auth.passkeys` and `auth.stepUp` it calls |
73
+ | `provide({ auth?, access? })` | Middleware. Sets `c.var.auth` and `c.var.access` to the instances given — only those — for a route that writes users or tuples |
74
+ | `ObjectData<C, Type>`, `PermissionOptions`, `Instances` | The types of `load`'s answer, of `permission()`'s options and of `provide()`'s argument |
75
+ | `FreshOptions` | `{ clock? }`, the options of `fresh()` |
76
+ | `JanusErrorsOptions` | `{ report?, fallback? }`, the options of `janusErrors()` — for a wrapper of your own |
77
+ | `Bound<I>` | What `bindJanus(instances)` answers, for `I` the type of `instances` — to pass a bound `j` to a module of routes |
78
+ | `Bindable` | What `bindJanus()` takes: `{ auth?, access? }`, the constraint on `Bound`'s `I` |
79
+ | `BoundAuth<typeof auth>` | The part of `Bound` that `auth` brings: `session`, `sendSession` and `signOut` |
80
+ | `BoundSocial<typeof auth>` | `j.socialRoutes`: `socialRoutes(auth, options)` with `auth` bound; present when `auth` configures `social` |
81
+ | `BoundSession<typeof auth>` | `j.session`: `session(auth, options?)` with `auth` bound, typed as `session()` is — `{ required: true }` types `c.var.user` as never `null` |
82
+ | `BoundPermission<C>` | `j.permission`: `permission(access, …)` with `access` bound, for `C` the model's config: `ConfigOf<typeof model>` from `@softistx/janus/permissions`, or take the whole type as `Bound<…>['permission']` |
83
+
84
+ The whole status table is in [`@softistx/janus`'s errors guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/errors.md).
85
+
86
+ ### A wrapper of your own
87
+
88
+ A wrapper around `janusErrors()` takes the same options, with your defaults:
89
+
90
+ ```ts
91
+ import { type JanusErrorsOptions, janusErrors } from '@softistx/janus-hono';
92
+ import { logger } from './logger'; // your own
93
+
94
+ export const appErrors = (options: JanusErrorsOptions = {}) =>
95
+ janusErrors({ report: (error) => logger.error(error), ...options });
96
+
97
+ app.onError(appErrors());
98
+ ```
99
+
100
+ ## Second factor
101
+
102
+ With `janus({ secondFactor })`, `signIn` answers a session or a challenge.
103
+ Narrow on `status` before `sendSession`, keep the challenge in a cookie for
104
+ the code route, and let `confirm` open the session:
105
+
106
+ ```ts
107
+ import { janusErrors, sendSession } from '@softistx/janus-hono';
108
+ import { Hono } from 'hono';
109
+ import { getCookie, setCookie } from 'hono/cookie';
110
+ import { auth } from './auth'; // janus({ …, secondFactor: { issuer, keys } })
111
+
112
+ const app = new Hono()
113
+ .post('/sign-in', async (c) => {
114
+ const result = await auth.signIn(await c.req.json());
115
+ if (result.status === 'secondFactor') {
116
+ setCookie(c, 'sign-in-challenge', result.challenge, {
117
+ path: '/sign-in', httpOnly: true, secure: true, sameSite: 'Strict', expires: result.expiresAt,
118
+ });
119
+ return c.json({ next: 'code' });
120
+ }
121
+ return c.json({ id: sendSession(c, auth, result).id });
122
+ })
123
+ .post('/sign-in/code', async (c) => {
124
+ const { code } = await c.req.json();
125
+ const challenge = getCookie(c, 'sign-in-challenge') ?? '';
126
+ const user = sendSession(c, auth, await auth.secondFactor.confirm(challenge, code));
127
+ return c.json({ id: user.id });
128
+ });
129
+
130
+ app.onError(janusErrors()); // a wrong code: 401 { code: 'CODE_INVALID', attemptsLeft: 3 }
131
+ ```
132
+
133
+ `janusErrors()` answers `CODE_INVALID` 401 with `attemptsLeft` in the body.
134
+ When the user's app-code window is spent (`regenerateRecoveryCodes`, or a
135
+ step-up confirmed with the app) the body also has `retryAfter` and the answer
136
+ a `Retry-After` header: wait that long, a new challenge does not help. With
137
+ `attemptsLeft: 0` and no `retryAfter`, only the challenge is spent: request a
138
+ new one. It answers `TOKEN_*` 400 — sign in again — and `SECOND_FACTOR_NOT_ENROLLED` and
139
+ `SECOND_FACTOR_ACTIVE` 409. The enrolment routes and a bearer client's
140
+ sign-in are in [the routes guide](docs/guide/routes.md#a-second-factor).
141
+
142
+ ## Devices
143
+
144
+ With `janus({ devices })`, a sign-in given the device token the browser
145
+ holds tells a new device from a known one. `deviceOf(c)` reads the device
146
+ cookie, and `sendSession` sets it from the answer's `deviceToken`:
147
+
148
+ ```ts
149
+ import { deviceOf, sendSession } from '@softistx/janus-hono';
150
+ import { Hono } from 'hono';
151
+ import { auth } from './auth'; // janus({ …, devices: { keys } })
152
+
153
+ const app = new Hono().post('/sign-in', async (c) => {
154
+ const { email, password } = await c.req.json();
155
+ const signedIn = await auth.signIn({ email, password }, { device: deviceOf(c) });
156
+ const user = sendSession(c, auth, signedIn); // the session cookie, and janus-device for 400 days
157
+ if (signedIn.newDevice) await tellTheUser(user, c.req.header('user-agent')); // yours — @softistx/janus-mail's newSignIn
158
+ return c.json({ id: user.id });
159
+ });
160
+ ```
161
+
162
+ The device cookie is `janus-device`, `HttpOnly`, `Secure`, `SameSite=Lax`,
163
+ `Path=/`, for 400 days; `{ device: { name, domain, path, sameSite, secure,
164
+ maxAge } }` changes it — give `deviceOf` the same options. With a second
165
+ factor, give `deviceOf(c)` again to `secondFactor.confirm` and `recover`:
166
+ the challenge carries no device. [The routes guide](docs/guide/routes.md#the-device-cookie)
167
+ has the second factor's routes and a bearer client.
168
+
169
+ ## Step-up
170
+
171
+ A sensitive route asks for a recent proof: `fresh(maxAge)` after
172
+ `session()`. An older session is answered 403 `STEP_UP_REQUIRED`; the client
173
+ asks for a step-up, confirms it, and sends the request again:
174
+
175
+ ```ts
176
+ import { fresh, janusErrors, session } from '@softistx/janus-hono';
177
+ import { getCookie, setCookie } from 'hono/cookie';
178
+
179
+ const app = new Hono()
180
+ .delete('/account', session(auth, { required: true }), fresh('10m'), deleteAccount)
181
+ .post('/step-up', session(auth, { required: true }), async (c) => {
182
+ const issued = await auth.stepUp.request(c.var.user);
183
+ if (issued.via === 'email') await sendMail(issued.email, issued.code); // yours
184
+ setCookie(c, 'step-up-challenge', issued.challenge, {
185
+ path: '/step-up', httpOnly: true, secure: true, sameSite: 'Strict', expires: issued.expiresAt,
186
+ });
187
+ return c.json({ via: issued.via }); // 'secondFactor': ask for the app's code
188
+ })
189
+ .post('/step-up/code', session(auth, { required: true }), async (c) => {
190
+ const { code } = await c.req.json();
191
+ const challenge = getCookie(c, 'step-up-challenge') ?? '';
192
+ await auth.stepUp.confirm(c.req.raw, challenge, code); // this request's session, fresh now
193
+ return c.body(null, 204);
194
+ });
195
+
196
+ app.onError(janusErrors()); // 403 { code: 'STEP_UP_REQUIRED' }, 401 { code: 'CODE_INVALID', attemptsLeft }
197
+ ```
198
+
199
+ `confirm` stamps the session the request presents and opens none: there is
200
+ no cookie to send again. The whole flow is in
201
+ [the routes guide](docs/guide/routes.md#a-step-up).
202
+
203
+ ## API keys
204
+
205
+ A route group that scripts and CI call accepts keys with
206
+ `session(auth, { apiKey: true })`; every other route still ignores them.
207
+ `fresh()` refuses a key, and a per-key rate limit keys on
208
+ `principal.apiKey.id`:
209
+
210
+ ```ts
211
+ import { type PrincipalEnv, session } from '@softistx/janus-hono';
212
+ import { Hono } from 'hono';
213
+
214
+ const api = new Hono<PrincipalEnv<typeof auth>>();
215
+ api.use(session(auth, { apiKey: true, required: true }));
216
+ api.get('/reports', (c) =>
217
+ c.json({ user: c.var.user.id, via: c.var.principal.via, key: c.var.apiKey?.id ?? null }),
218
+ );
219
+ ```
220
+
221
+ The recipe for the limiter is in [the routes guide](docs/guide/routes.md#api-keys).
222
+
223
+ ## Permissions
224
+
225
+ `permission()` guards a route: the object is loaded once, checked, and handed
226
+ to the route. `provide()` puts the instances on the context, so the route that
227
+ creates a record grants its owner through `c.var.access`:
228
+
229
+ ```ts
230
+ import { permission, provide, session } from '@softistx/janus-hono';
231
+ import { Hono } from 'hono';
232
+ import { access, recordOf } from './access'; // the guide's model, and a loader
233
+ import { auth } from './auth';
234
+ import { records } from './records'; // your own store
235
+
236
+ const app = new Hono()
237
+ .use(session(auth), provide({ auth, access }))
238
+ .get(
239
+ '/records/:id',
240
+ permission(access, 'view', 'record', recordOf),
241
+ (c) => c.json(c.var.object), // your record type, loaded once
242
+ )
243
+ .put(
244
+ '/records/:id',
245
+ permission(access, 'edit', 'record', recordOf, {
246
+ ctx: (c, record) => ({ locked: record.locked }), // `edit` reaches a when()
247
+ }),
248
+ async (c) => c.json(await records.update(c.var.object.id, await c.req.json())),
249
+ )
250
+ .post('/records', session(auth, { type: 'patient', required: true }), async (c) => {
251
+ const record = await records.create(await c.req.json());
252
+ await c.var.access.grant({ type: 'record', id: record.id }, 'owners', c.var.user);
253
+ return c.json(record, 201);
254
+ });
255
+ ```
256
+
257
+ The model — `owners`, `doctors` read from the record, `edit` under a condition
258
+ — and `recordOf` are those of the [guarded routes guide](docs/guide/permissions.md). The
259
+ permission, the object type, the fields a `fromField` reads and the `ctx`
260
+ of a condition are typed from the model, as they are for `can()`.
261
+ `janusErrors()` answers the failures of both sides alike — `can()`'s
262
+ `STORE_FAILED` is a 503, never a 403.
263
+
264
+ ### Bound once
265
+
266
+ `bindJanus({ auth, access })` answers the same functions with the instances
267
+ bound, so no route repeats them — typed exactly as the unbound ones:
268
+
269
+ ```ts
270
+ import { bindJanus, byParam } from '@softistx/janus-hono';
271
+
272
+ const j = bindJanus({ auth, access });
273
+
274
+ const app = new Hono()
275
+ .use(j.session(), j.provide())
276
+ .get('/records/:id', j.permission('view', 'record', byParam('id', (id) => records.find(id))), (c) =>
277
+ c.json(c.var.object),
278
+ )
279
+ .post('/sign-out', async (c) => {
280
+ await j.signOut(c);
281
+ return c.body(null, 204);
282
+ });
283
+ ```
284
+
285
+ Only what is given is bound: `bindJanus({ auth })` has no `permission`.
286
+
287
+ A module of routes that receives `j` types it `Bound<…>`, over the types of
288
+ the instances it was given:
289
+
290
+ ```ts
291
+ import { type Bound, bindJanus, byParam } from '@softistx/janus-hono';
292
+
293
+ export type Janus = Bound<{ auth: typeof auth; access: typeof access }>;
294
+
295
+ export const recordRoutes = (j: Janus) =>
296
+ new Hono()
297
+ .use(j.session(), j.provide())
298
+ .get('/records/:id', j.permission('view', 'record', byParam('id', (id) => records.find(id))), (c) =>
299
+ c.json(c.var.object), // typed, as with the unbound functions
300
+ );
301
+
302
+ app.route('/', recordRoutes(bindJanus({ auth, access })));
303
+ ```
304
+
305
+ Each side is usable alone. An application that signs users in some other way
306
+ passes `{ subject: (c) => … }` to `permission()`; one without permissions uses
307
+ `session()` and `janusErrors()` only.
308
+
309
+ ## Social sign-in
310
+
311
+ `socialRoutes()` mounts the four routes of a sign-in through Google, GitHub or
312
+ any `SocialProvider` (see [`@softistx/janus-social`](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-social/README.md)).
313
+ Mount it under a prefix; the callback URL you register with the provider is
314
+ `<origin>/auth/social/<provider>/callback`:
315
+
316
+ ```ts
317
+ import { Hono } from 'hono';
318
+ import { janusErrors, socialRoutes } from '@softistx/janus-hono';
319
+
320
+ const app = new Hono();
321
+ app.route(
322
+ '/auth/social',
323
+ socialRoutes(auth, {
324
+ defaultReturnTo: '/dashboard',
325
+ onSecondFactor: (c, result) => {
326
+ // keep result.challenge in a short-lived HttpOnly cookie, then ask for the code
327
+ return c.redirect('/two-factor');
328
+ },
329
+ }),
330
+ );
331
+ app.onError(janusErrors()); // an outage is a 503, never a redirect
332
+ ```
333
+
334
+ A link `<a href="/auth/social/google?returnTo=/billing">` starts it. The
335
+ callback clears the flow cookie, sends the session cookie and redirects to
336
+ `returnTo`. A refusal redirects too: `/billing?socialError=SIGN_UP_DISABLED` —
337
+ a code to show a message for, never the provider's message or cause.
338
+
339
+ The flow cookie is read from `auth.social.cookie.name` (it is
340
+ `__Host-janus-social-flow` on a secure cookie without a domain). A callback
341
+ the core refused **before** spending the flow (no cookie, a forged `state`)
342
+ leaves the cookie, so an attacker cannot burn a visitor's flow; any other
343
+ outcome clears it. The redirect path comes only from the core's answer, and is
344
+ checked again as a path of your site.
345
+
346
+ Linking is for a signed-in user whose session proved who it is within
347
+ `freshWithin` (ten minutes, as the core's `social.freshWithin`):
348
+ `POST /auth/social/github/link` answers 303 to the provider, and
349
+ `DELETE /auth/social/links/github/<accountId>` answers 204, or 404 for a link
350
+ that is not theirs. See [the routes guide](docs/guide/routes.md#social-sign-in).
351
+
352
+ ## Passkeys
353
+
354
+ `passkeyRoutes()` mounts the JSON routes of a passkey as a second factor, beside
355
+ a TOTP (see [`@softistx/janus`'s passkeys guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/passkeys.md)).
356
+ Mount it under a prefix:
357
+
358
+ ```ts
359
+ import { Hono } from 'hono';
360
+ import { janusErrors, passkeyRoutes } from '@softistx/janus-hono';
361
+
362
+ const app = new Hono();
363
+ app.route('/auth/passkeys', passkeyRoutes(auth)); // janus({ …, secondFactor, passkeys })
364
+ app.onError(janusErrors());
365
+ ```
366
+
367
+ | Route | Body | Answers |
368
+ | --- | --- | --- |
369
+ | `GET /` | | `{ passkeys }`, oldest first, without key or counter |
370
+ | `POST /registration-options` | | `{ options, challenge, expiresAt }`: `options` go to `navigator.credentials.create({ publicKey })` |
371
+ | `POST /` | `{ challenge, response, name }` | 201 with the passkey; fresh session required |
372
+ | `POST /:credentialId/rename` | `{ name }` | 204, or 404 for a passkey that is not the user's |
373
+ | `DELETE /:credentialId` | | 204, or 404; fresh session required |
374
+ | `POST /sign-in` | `{ challenge, assertion }` | Sets the session cookie, `200 { id }`. No session needed: it is the sign-in |
375
+ | `POST /step-up` | | `{ challenge, options, expiresAt }` |
376
+ | `POST /step-up/confirm` | `{ challenge, assertion }` | 204; the session the request presents is fresh now |
377
+
378
+ `signIn` already hands the page what it needs: `result.methods` and
379
+ `result.passkeyOptions` (see [A second factor](docs/guide/routes.md#a-second-factor)).
380
+ Send `result.challenge` and `result.passkeyOptions` to the page, which calls
381
+ `navigator.credentials.get({ publicKey: passkeyOptions })` and posts the
382
+ result to `/sign-in`. `CODE_INVALID` is 401 with `attemptsLeft`;
383
+ `PASSKEY_INVALID` 400 (`field: 'name'` for a bad name), `PASSKEY_TAKEN` and
384
+ `PASSKEY_LIMIT` (`maxActive`) 409, `SECOND_FACTOR_NOT_ENROLLED` 409,
385
+ `STEP_UP_REQUIRED` 403. Pass `device` when `janus({ devices })` is wired, and
386
+ `onSignedIn` to answer a bearer client the token. See [the routes
387
+ guide](docs/guide/routes.md#passkeys).
388
+
389
+ ## Traps
390
+
391
+ - **`update` of a factor holder's e-mail answers `409 {"code":"EMAIL_CHANGE_NEEDS_PROOF"}`.**
392
+ `janusErrors()` maps the core's refusal by its status; move such an e-mail
393
+ with `changeEmail`, which proves the new address.
394
+ - **`magicLink: { enabled: false }` answers `404 {"code":"MAGIC_LINK_DISABLED"}`.**
395
+ `janusErrors()` maps the core's refusal by its status; this package mounts no
396
+ magic-link route, so a route of yours that calls `auth.magicLink.*` is refused
397
+ by the core alone. Read `auth.magicLink.enabled` to hide the button.
398
+ - **A social refusal is a redirect, not a JSON body.** Read `?socialError=<code>` on
399
+ the landing page; the callback never answers `error.message` or `cause`.
400
+ - **With a second factor, `sendSession(c, auth, await auth.signIn(…))` does
401
+ not compile.** A challenge has no session to send. Narrow first:
402
+ `if (result.status === 'secondFactor') …`.
403
+ - **A 401 is not always anonymous.** `session({ required: true })` answers
404
+ 401 with no body; a wrong second-factor code is 401 with
405
+ `{ code: 'CODE_INVALID', attemptsLeft }`. Read the body before sending the
406
+ visitor to the sign-in page.
407
+ - **A `janus()` without keys signing in a user with an active factor is a
408
+ 500.** It throws a `TypeError`, not a `JanusError`, so `janusErrors()`
409
+ hands it to `fallback`. Give every instance the same `secondFactor`.
410
+ - **Without `app.onError(janusErrors())`, an outage is Hono's 500.** Not a
411
+ 401 — `session()` never turns a failure into an anonymous request — but not
412
+ the 503 that tells a client to retry either.
413
+ - **`app.use(session(auth))` on its own line does not type the routes after
414
+ it.** Hono types a chain, not statements. Chain the calls, or declare the app
415
+ as `new Hono<SessionEnv<typeof auth>>()`.
416
+ - **A renewed session is sent again only as a cookie, and only to a request
417
+ that presented one.** A client that sends `Authorization: Bearer` is renewed
418
+ too — its session token does not change — but it is never handed a cookie it did not
419
+ ask for. It reads `session.expiresAt` if it needs to.
420
+ - **`required` is typed only for a literal `true`.** A computed `boolean`
421
+ compiles, and leaves `c.var.user` nullable.
422
+ - **`required` answers 401 with no body and no `WWW-Authenticate`.** Wrap the
423
+ route yourself for another answer: `session(auth)`, then check
424
+ `c.var.user === null`.
425
+ - **The cookie is `Secure` by default.** A browser drops it over plain
426
+ `http://`, `localhost` aside in most browsers. Set `cookie: { secure: false }`
427
+ in `janus()` for a development server that is not on `localhost`, never in
428
+ production.
429
+ - **`janusErrors()` logs nothing by itself.** A `STORE_FAILED` is answered 503
430
+ without a line in your logs unless you pass `report` —
431
+ `janusErrors({ report: (error) => logger.error(error) })`.
432
+ - **`bodyOf` never carries `reason`, `login`, a challenge or a cause.** `CREDENTIALS_INVALID`
433
+ says one thing for an unknown login, a missing password and a wrong one, so a
434
+ response cannot tell which users exist. Log the error before you answer it
435
+ if you need the reason: `janusErrors` is a function of `(error, c)` you can
436
+ wrap.
437
+ - **`load` does not know the route's path.** It takes a plain `Context`:
438
+ `permission()` is built before Hono attaches it to a route, so
439
+ `c.req.param('id')` is `string | undefined` there. Answer `null` for a
440
+ missing id — that is a 404 — or let `byParam('id', find)` do it.
441
+ - **One `permission()` per route.** Both would claim `c.var.object`, so a
442
+ second throws a `TypeError`. Check a parent object through an arrow in the
443
+ model.
444
+ - **`fresh()` needs `session()` before it**, as `permission()` does: without
445
+ it, `fresh()` throws a `TypeError` at the first request. A 403
446
+ `STEP_UP_REQUIRED` is not a denial — ask for a step-up, then retry.
447
+ - **`permission()` needs `session()` before it**, or `{ subject }`. Without
448
+ either, it throws a `TypeError` at the first request — a wiring error, not
449
+ an anonymous 401.
450
+ - **Give `deviceOf` and `sendSession` the same options.** A cookie written
451
+ under one name or path and read under another is never found: every
452
+ sign-in is then a new device. Keep one `DeviceCookieOptions` and pass it
453
+ to both.
454
+ - **The device cookie's `sameSite` is Hono's, capitalised.** `'Lax'`, not
455
+ the `'lax'` of `janus({ cookie })` — a compile error, where a cast would
456
+ hand Hono a value it does not know.
457
+ - **`signOut` leaves the device cookie.** The device stays known after a
458
+ sign-out, which is the point: a user who signs out and back in is not
459
+ told of a new device.
460
+ - **With a second factor, give the device again.** `auth.secondFactor.confirm(challenge,
461
+ code, { device: deviceOf(c) })`: the challenge carries none, and a
462
+ confirmation given no device sets no device cookie and reports nothing.
463
+ - **Several user types: name the one with `type`.** `janus()` then puts
464
+ `passkeys`, `secondFactor` and `stepUp` under `auth.<type>`, and
465
+ `passkeyRoutes(auth, { type: 'staff' })` calls those (the session and the
466
+ cookie come from `auth`); one mount per type, each under its own prefix.
467
+ Without `type`, or with an unknown one, the compiler refuses, and a
468
+ JavaScript caller gets a `TypeError` at wiring. `bindJanus({ auth })
469
+ .passkeyRoutes()` is bound for every type, since the core always builds
470
+ `auth.passkeys`; only the types hide it.
471
+ - **The answers that carry a secret say `Cache-Control: no-store`**:
472
+ `POST /registration-options` and `POST /step-up` (a single-use `challenge`),
473
+ `POST /sign-in` (it sets the session cookie), the social start and link
474
+ redirects (they set the flow cookie) and the social callback once the flow is
475
+ spent (a session cookie, or `onSecondFactor` with a challenge). So does
476
+ `sendSession`, and so `session()` when it re-sends a renewed session, on that
477
+ response only, never on the others behind it. A handler that returns its own
478
+ `Response` loses the headers set on `c`. The built-in routes never put a
479
+ session token in a body; your own route that does must set the header, with
480
+ `c.header('Cache-Control', 'no-store')`, on a bearer sign-in's token and on
481
+ a second-factor `challenge` in a body. See
482
+ [the troubleshooting entry](docs/troubleshooting.md#a-response-that-answers-a-challenge-or-a-session-token-is-cached).
483
+ - **The passkey sign-in's challenge travels in the JSON body.** Unlike the
484
+ cookie the guides keep a code's challenge in, `POST /sign-in` and
485
+ `POST /step-up/confirm` read `challenge` from the body, so the page holds it.
486
+ It is a secret like a session token: never in a URL or a log. An application
487
+ that wants a cookie sets it on its own `signIn` route and calls
488
+ `auth.secondFactor.confirmPasskey` itself.
489
+ - **No CSRF token is asked.** The session cookie is `SameSite=Lax`, which keeps
490
+ a cross-site `POST` from carrying it; with `sameSite: 'None'` the routes are
491
+ exposed. Mount Hono's `csrf({ origin })` before
492
+ `app.route('/auth/passkeys', …)`: the body is read as JSON whatever its
493
+ `Content-Type`, so a `text/plain` cross-site form is parsed too.
494
+ - **Rate-limit `POST /sign-in`** per IP with `@softistx/redis` rate limits: the
495
+ challenge's five attempts bound guessing one challenge, not a flood of
496
+ requests.
497
+ - **Register and remove are refused `403 STEP_UP_REQUIRED` by the core**, not
498
+ by a `fresh()` the routes add: a session older than the core's
499
+ `passkeys.freshWithin` runs `POST /step-up` and `/step-up/confirm`, then
500
+ sends the request again. Registering spends its challenge once: ask for new
501
+ options after a response that did not verify.
502
+ - **A denial is 403, so it tells that the object exists.** Where that is a
503
+ leak, load only what the user may see and let `load` answer `null` — a 404.
504
+
505
+ ## Documentation
506
+
507
+ - [Guides](docs/README.md) — wiring the middleware, the routes of a sign-in, of a second factor, of a code or a link sent by e-mail and of the device cookie, of a passkey, guarded routes
508
+ - [Troubleshooting](docs/troubleshooting.md) — by the symptom or message you see
509
+ - [Roadmap](docs/roadmap.md) — what is next, and what is not planned
510
+
511
+ ## Type safety, counted
512
+
513
+ Thirty-nine plausible mistakes are refused by the compiler, each with a
514
+ `@ts-expect-error` case in `test/types/`:
515
+
516
+ - seven in `session.ts`: reading `c.var.user` where it may be `null` (twice,
517
+ directly and through `SessionEnv`), a field of another user type, a user type
518
+ the instance does not know (twice, in `session()` and in `SessionEnv`), and a
519
+ cookie sent without its session, and a computed `apiKey` beside
520
+ `required: true`, which leaves the user nullable;
521
+ - ten in `permission.ts`: a permission the object type does not declare, an
522
+ object type the model does not (twice: in a model of one object type and of
523
+ several, each reported on the misspelled argument), an object loaded without
524
+ a field a `fromField` reads, a condition reached with no `ctx`, a `ctx` of the
525
+ wrong shape, a `ctx` where no condition is reachable, a field the loaded
526
+ object does not have, granting a relation read from a field, and an instance
527
+ `provide()` was not given;
528
+ - nine in `bind.ts`: the same refusals through `bindJanus()` — a nullable
529
+ user, an unknown user type, a missing `ctx`, a misspelled permission — a
530
+ `permission`, `session`, `sendSession` or `signOut` it was not given the
531
+ instance for, and an `access` that is no `permissions()` instance;
532
+ - one in `fresh.ts`: a `maxAge` that is no duration — `'10 minutes'` for
533
+ `'10m'`;
534
+ - two in `device.ts`: the session cookie's lowercase `sameSite` given to the
535
+ device cookie, whose `'Lax'` is Hono's, and the device cookie's options
536
+ given to `sendSession` at the top rather than under `device`;
537
+ - two in `social.ts`: `socialRoutes` without `onSecondFactor`, and
538
+ `socialRoutes` on an instance no user type configures `social` on;
539
+ - eight in `passkeys.ts`: `passkeyRoutes` on an instance no user type configures
540
+ `passkeys` on, `passkeyRoutes` through `bindJanus()` of such an instance, the
541
+ session cookie's lowercase `sameSite` given to the device cookie, an
542
+ `onSignedIn` that answers no `Response`, and, with several user types, no
543
+ `type` and a `type` the instance does not know (each in `passkeyRoutes()` and
544
+ through `bindJanus()`).
545
+
546
+ ## Licence
547
+
548
+ MIT