@tylix/auth 1.4.0 → 1.5.0
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.
- package/README.md +284 -14
- package/package.json +95 -9
- package/src/client/client.d.ts +14 -0
- package/src/client/client.js +83 -0
- package/src/cookies/authCookies.d.ts +8 -6
- package/src/cookies/authCookies.js +43 -28
- package/src/core/crypto.js +143 -0
- package/src/core/keys.js +83 -0
- package/src/core/seal.js +43 -0
- package/src/generators/AuthGenerator.d.ts +9 -3
- package/src/generators/AuthGenerator.js +16 -4
- package/src/generators/templates/auth-controller-ts.tyx +401 -98
- package/src/generators/templates/auth-controller.tyx +384 -96
- package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
- package/src/generators/templates/auth-session-migration.tyx +32 -0
- package/src/generators/templates/auth-session-model-ts.tyx +53 -0
- package/src/generators/templates/auth-session-model.tyx +34 -0
- package/src/generators/templates/auth-validator-ts.tyx +17 -0
- package/src/generators/templates/auth-validator.tyx +17 -0
- package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
- package/src/generators/templates/oauth-account-migration.tyx +27 -0
- package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
- package/src/generators/templates/oauth-account-model.tyx +45 -0
- package/src/generators/templates/password-reset-model-ts.tyx +26 -4
- package/src/generators/templates/password-reset-model.tyx +26 -4
- package/src/generators/templates/reset-password-view.html +30 -3
- package/src/generators/templates/verify-email-view.html +30 -3
- package/src/http/cookies.js +91 -0
- package/src/http/origin.js +68 -0
- package/src/http/request.js +179 -0
- package/src/index.d.ts +9 -1
- package/src/index.js +5 -0
- package/src/integrations/h3.d.ts +6 -0
- package/src/integrations/h3.js +70 -0
- package/src/integrations/hono.d.ts +6 -0
- package/src/integrations/hono.js +36 -0
- package/src/integrations/next.d.ts +16 -0
- package/src/integrations/next.js +36 -0
- package/src/integrations/node.d.ts +7 -0
- package/src/integrations/node.js +87 -0
- package/src/integrations/routes.js +92 -0
- package/src/integrations/sveltekit.d.ts +5 -0
- package/src/integrations/sveltekit.js +52 -0
- package/src/integrations/web.js +69 -0
- package/src/mfa/totp.js +150 -0
- package/src/oauth/oauth.js +142 -0
- package/src/oauth/providers.js +112 -0
- package/src/password/hashPassword.d.ts +5 -1
- package/src/password/hashPassword.js +96 -30
- package/src/password/index.d.ts +2 -0
- package/src/password/index.js +2 -0
- package/src/password/policy.js +108 -0
- package/src/rateLimiter/loginRateLimiter.js +16 -6
- package/src/ratelimit/limiter.js +129 -0
- package/src/session/adapters/keyValue.js +87 -0
- package/src/session/adapters/memory.js +38 -0
- package/src/session/adapters/model.js +97 -0
- package/src/session/adapters/prisma.js +67 -0
- package/src/session/adapters/sql.js +128 -0
- package/src/session/createAuth.js +420 -0
- package/src/token/jwt.js +144 -0
- package/src/token/signToken.js +41 -22
- package/src/tylix/accessTokens.js +61 -0
- package/src/web.d.ts +359 -0
- package/src/web.js +47 -0
package/README.md
CHANGED
|
@@ -1,23 +1,293 @@
|
|
|
1
1
|
# @tylix/auth
|
|
2
2
|
|
|
3
|
-
Authentication
|
|
4
|
-
|
|
3
|
+
Authentication for **any JavaScript framework**: Next.js, Nuxt, SvelteKit,
|
|
4
|
+
Remix, Astro, Hono, Express, Fastify, Koa and Tylix. It runs on Node, Bun,
|
|
5
|
+
Deno, Cloudflare Workers and the edge, and has no runtime dependencies.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
```sh
|
|
8
|
+
npm install @tylix/auth
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
- **Sessions you can revoke.** Short-lived JWT access tokens and rotating
|
|
12
|
+
refresh tokens, stored server-side as HMACs, with idle and absolute
|
|
13
|
+
timeouts and a device list. Logout, "sign out everywhere" and password
|
|
14
|
+
resets take effect immediately.
|
|
15
|
+
- **Token theft detection.** Every refresh rotates the refresh token. If an
|
|
16
|
+
old one is replayed (someone holds a copy), the whole session ends. A
|
|
17
|
+
short grace period keeps parallel tabs from tripping it.
|
|
18
|
+
- **CSRF protection without tokens.** Cookie-authenticated writes from
|
|
19
|
+
other sites are refused using `Sec-Fetch-Site` and `Origin`, on top of
|
|
20
|
+
`SameSite=Lax`. Sibling subdomains are not trusted unless you list them.
|
|
21
|
+
- **Hardened cookies.** `HttpOnly`, `__Host-`/`__Secure-` prefixes on HTTPS,
|
|
22
|
+
and a refresh cookie scoped to the auth routes.
|
|
23
|
+
- **Strict JWTs.** The algorithm is pinned, each purpose (access,
|
|
24
|
+
email verification, ...) gets its own HKDF-derived key, expiry is
|
|
25
|
+
mandatory, base64url decoding is canonical, and secrets rotate through
|
|
26
|
+
key ids.
|
|
27
|
+
- **Passwords.** scrypt (OWASP parameters), automatic rehash upgrades,
|
|
28
|
+
Unicode normalization, a size cap against DoS, constant-time dummy work
|
|
29
|
+
for unknown accounts (no timing-based user enumeration), and a NIST-style
|
|
30
|
+
policy with an optional Have I Been Pwned check (k-anonymity).
|
|
31
|
+
- **Brute-force protection** that can't be used to lock someone else out:
|
|
32
|
+
limits per account+IP, per account and per IP, over any shared store.
|
|
33
|
+
- **Two-factor authentication.** TOTP (RFC 6238) with replay protection, and
|
|
34
|
+
hashed one-time recovery codes.
|
|
35
|
+
- **OAuth / social login.** PKCE on every flow, encrypted state cookies, and
|
|
36
|
+
presets for GitHub, Google, Discord, GitLab and Microsoft. Emails count as
|
|
37
|
+
verified only when the provider vouches for them.
|
|
38
|
+
- **AES-GCM sealing** for secrets you store (TOTP keys) or hand to the browser.
|
|
39
|
+
|
|
40
|
+
## Quick start
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
// auth.js
|
|
44
|
+
import { createAuth, sqlAdapter } from '@tylix/auth/web'
|
|
45
|
+
|
|
46
|
+
export const auth = createAuth({
|
|
47
|
+
secret: process.env.AUTH_SECRET, // 32+ random chars: openssl rand -base64 48
|
|
48
|
+
adapter: sqlAdapter({ dialect: 'postgres', query: (sql, params) => pool.query(sql, params) }),
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Logging in is yours: check the password your way, then start a session.
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
import { verifyPassword } from '@tylix/auth/password'
|
|
7
56
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
57
|
+
const user = await db.users.findByEmail(email)
|
|
58
|
+
// Pass null for unknown users: the same work is done, so timing reveals nothing.
|
|
59
|
+
if (!(await verifyPassword(password, user?.passwordHash ?? null))) return unauthorized()
|
|
60
|
+
const { cookies } = await auth.signIn(request, user.id) // send these Set-Cookie headers
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The session endpoints come built in. Mount them at `/api/auth/*`:
|
|
64
|
+
|
|
65
|
+
| Route | |
|
|
66
|
+
| --- | --- |
|
|
67
|
+
| `POST /api/auth/refresh` | rotate the refresh token, issue a new access token |
|
|
68
|
+
| `POST /api/auth/logout` | end this session |
|
|
69
|
+
| `POST /api/auth/logout-all` | end every session of this user |
|
|
70
|
+
| `GET /api/auth/session` | who is signed in (401 for guests) |
|
|
71
|
+
| `GET /api/auth/sessions` | this user's devices |
|
|
72
|
+
| `DELETE /api/auth/sessions/:id` | end one of them |
|
|
16
73
|
|
|
17
|
-
##
|
|
74
|
+
## Frameworks
|
|
75
|
+
|
|
76
|
+
### Next.js (App Router, Node or Edge)
|
|
18
77
|
|
|
19
78
|
```js
|
|
20
|
-
|
|
79
|
+
// app/api/auth/[...auth]/route.js
|
|
80
|
+
import { nextAuthHandlers } from '@tylix/auth/next'
|
|
81
|
+
export const { GET, POST, DELETE } = nextAuthHandlers(auth)
|
|
82
|
+
|
|
83
|
+
// middleware.js: stateless check, runs on the edge
|
|
84
|
+
import { nextMiddleware } from '@tylix/auth/next'
|
|
85
|
+
export default nextMiddleware(auth, { protect: ['/dashboard'], loginPath: '/login' })
|
|
86
|
+
|
|
87
|
+
// app/api/login/route.js
|
|
88
|
+
import { jsonWithCookies } from '@tylix/auth/next'
|
|
89
|
+
export async function POST(request) {
|
|
90
|
+
const { email, password } = await request.json()
|
|
91
|
+
// ...verify the password...
|
|
92
|
+
const { cookies } = await auth.signIn(request, user.id)
|
|
93
|
+
return jsonWithCookies({ ok: true }, { cookies })
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Server Components / Server Actions
|
|
97
|
+
import { headers } from 'next/headers'
|
|
98
|
+
const session = await auth.getSession(await headers())
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Nuxt / Nitro / h3
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
// server/api/auth/[...].ts
|
|
105
|
+
import { h3AuthHandler } from '@tylix/auth/nuxt'
|
|
106
|
+
export default defineEventHandler(h3AuthHandler(auth))
|
|
107
|
+
|
|
108
|
+
// server/middleware/auth.ts: sets event.context.auth
|
|
109
|
+
import { h3AuthMiddleware } from '@tylix/auth/nuxt'
|
|
110
|
+
export default defineEventHandler(h3AuthMiddleware(auth, { protect: ['/dashboard'] }))
|
|
111
|
+
|
|
112
|
+
// a protected handler
|
|
113
|
+
import { requireH3Session } from '@tylix/auth/nuxt'
|
|
114
|
+
export default defineEventHandler(async (event) => {
|
|
115
|
+
const { userId } = await requireH3Session(auth, event)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
// login: const { cookies } = await auth.signIn(event, user.id); applyCookies(event, cookies)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### SvelteKit
|
|
122
|
+
|
|
123
|
+
```js
|
|
124
|
+
// src/hooks.server.js
|
|
125
|
+
import { sveltekitHandle } from '@tylix/auth/sveltekit'
|
|
126
|
+
export const handle = sveltekitHandle(auth, { protect: ['/account'] })
|
|
127
|
+
|
|
128
|
+
// +page.server.js action
|
|
129
|
+
await event.locals.signIn(user.id) // cookies are added to the response for you
|
|
130
|
+
event.locals.auth // the session, or null
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Hono (Node, Bun, Deno, Workers)
|
|
134
|
+
|
|
135
|
+
```js
|
|
136
|
+
import { honoAuth, honoAuthRoutes, honoRequireAuth } from '@tylix/auth/hono'
|
|
137
|
+
app.use('*', honoAuth(auth))
|
|
138
|
+
app.all('/api/auth/*', honoAuthRoutes(auth))
|
|
139
|
+
app.get('/api/me', honoRequireAuth(auth), (c) => c.json({ id: c.get('auth').userId }))
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### Express, Fastify, Koa
|
|
143
|
+
|
|
144
|
+
```js
|
|
145
|
+
import { expressAuth, requireExpressAuth, applyCookies } from '@tylix/auth/express'
|
|
146
|
+
app.use(expressAuth(auth)) // req.auth, and serves /api/auth/*
|
|
147
|
+
app.get('/api/me', requireExpressAuth(), (req, res) => res.json({ id: req.auth.userId }))
|
|
148
|
+
|
|
149
|
+
import { fastifyAuth } from '@tylix/auth/fastify'
|
|
150
|
+
fastifyAuth(app, auth) // request.auth
|
|
151
|
+
|
|
152
|
+
import { koaAuth } from '@tylix/auth/koa'
|
|
153
|
+
app.use(koaAuth(auth)) // ctx.state.auth
|
|
21
154
|
```
|
|
22
155
|
|
|
23
|
-
|
|
156
|
+
### Remix, React Router, Astro, SolidStart, Bun, Deno, Workers
|
|
157
|
+
|
|
158
|
+
These frameworks all speak Web `Request`/`Response`:
|
|
159
|
+
|
|
160
|
+
```js
|
|
161
|
+
import { createAuthHandler } from '@tylix/auth/web'
|
|
162
|
+
const handler = createAuthHandler(auth) // (Request) => Response for /api/auth/*
|
|
163
|
+
const session = await auth.getSession(request)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### The browser
|
|
167
|
+
|
|
168
|
+
```js
|
|
169
|
+
import { createAuthClient } from '@tylix/auth/client'
|
|
170
|
+
const client = createAuthClient({ onSignOut: () => location.assign('/login') })
|
|
171
|
+
await client.fetch('/api/projects') // concurrent 401s share one refresh, then replay
|
|
172
|
+
await client.signOut({ everywhere: true }) // every open tab hears about it
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Tokens stay in `HttpOnly` cookies, so page JavaScript (and XSS) never sees them.
|
|
176
|
+
|
|
177
|
+
## Session storage
|
|
178
|
+
|
|
179
|
+
| Adapter | For |
|
|
180
|
+
| --- | --- |
|
|
181
|
+
| `sqlAdapter({ dialect, query })` | `pg`, `mysql2`, `better-sqlite3`, `node:sqlite`, Drizzle/Kysely raw SQL. `createTableSql()` gives the schema. Rotation uses a real compare-and-swap. |
|
|
182
|
+
| `prismaAdapter(prisma.authSession)` | Prisma. The model definition is in `src/session/adapters/prisma.js`. |
|
|
183
|
+
| `keyValueAdapter(store)` | Redis, Upstash, Vercel KV, Cloudflare KV, Deno KV: anything with `get`, `set(key, value, { ttlMs })` and `delete`. |
|
|
184
|
+
| `modelAdapter(Model)` | Tylix ORM models (`tylix make:auth` sets this up). |
|
|
185
|
+
| `memoryAdapter()` | Tests and single-process development only. |
|
|
186
|
+
|
|
187
|
+
For a custom store, implement the six-method `SessionAdapter` interface in `web.d.ts`.
|
|
188
|
+
|
|
189
|
+
## Options
|
|
190
|
+
|
|
191
|
+
```js
|
|
192
|
+
createAuth({
|
|
193
|
+
secret: [process.env.AUTH_SECRET, process.env.AUTH_SECRET_OLD], // rotation: first signs, all verify
|
|
194
|
+
accessTokenTtl: '15m',
|
|
195
|
+
sessionTtl: '30d', // "remember me" sessions
|
|
196
|
+
shortSessionTtl: '1d', // signIn(req, id, { persistent: false }): browser-session cookies
|
|
197
|
+
idleTimeout: '14d',
|
|
198
|
+
rotationGrace: '30s',
|
|
199
|
+
trustProxy: false, // believe X-Forwarded-* only behind your own proxy
|
|
200
|
+
trustedOrigins: [], // other origins allowed to write with cookies
|
|
201
|
+
cookies: { refreshPath: '/api/auth', sameSite: 'lax', domain: undefined },
|
|
202
|
+
claims: (session) => ({ role: 'admin' }), // extra access-token claims
|
|
203
|
+
validateSession: async (session) => !isBanned(session.userId),
|
|
204
|
+
onEvent: (event) => audit.log(event), // session.created / refreshed / revoked / reuse_detected / ...
|
|
205
|
+
})
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
`auth.getSession(request)` checks revocation by default (one lookup by
|
|
209
|
+
primary key). In edge middleware that can't reach the database, pass
|
|
210
|
+
`{ checkRevocation: false }`. The access token's short lifetime then bounds
|
|
211
|
+
how long a revoked session can still pass.
|
|
212
|
+
|
|
213
|
+
## Two-factor authentication
|
|
214
|
+
|
|
215
|
+
```js
|
|
216
|
+
import { generateTotpSecret, totpUri, verifyTotp, generateRecoveryCodes, verifyRecoveryCode } from '@tylix/auth'
|
|
217
|
+
|
|
218
|
+
const secret = generateTotpSecret()
|
|
219
|
+
const uri = totpUri({ secret, issuer: 'Acme', account: user.email }) // render as a QR code
|
|
220
|
+
await db.users.update(user.id, { totp: await auth.sealer.seal(secret, { purpose: 'totp' }) })
|
|
221
|
+
|
|
222
|
+
const { valid, step } = await verifyTotp(code, await auth.sealer.unseal(user.totp, { purpose: 'totp' }), { lastUsedStep: user.totpStep })
|
|
223
|
+
if (valid) await db.users.update(user.id, { totpStep: step }) // the same code can't be replayed
|
|
224
|
+
|
|
225
|
+
const { codes, hashes } = await generateRecoveryCodes() // show codes once, store hashes
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## OAuth
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
import { createOAuth, github } from '@tylix/auth'
|
|
232
|
+
const oauth = createOAuth({ sealer: auth.sealer })
|
|
233
|
+
const provider = github({ clientId, clientSecret, redirectUri: 'https://app.example/auth/github/callback' })
|
|
234
|
+
|
|
235
|
+
// GET /auth/github
|
|
236
|
+
const { url, cookies } = await oauth.start(provider, request, { returnTo: '/dashboard' })
|
|
237
|
+
// redirect to url, sending cookies
|
|
238
|
+
|
|
239
|
+
// GET /auth/github/callback
|
|
240
|
+
const { profile, returnTo, cookies: clear } = await oauth.callback(provider, request)
|
|
241
|
+
// profile: { provider, id, email, emailVerified, name, avatarUrl }
|
|
242
|
+
// Link to an existing account by email ONLY if profile.emailVerified.
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
In a Tylix app this is already wired up: `make:auth` (and `create-tylix`
|
|
246
|
+
with authentication) generates `oauthStart` / `oauthCallback` on
|
|
247
|
+
`AuthController`, an `OAuthAccount` model, and "Continue with Google /
|
|
248
|
+
GitHub" buttons on the login and register pages. Set
|
|
249
|
+
`GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` and `GITHUB_CLIENT_ID` /
|
|
250
|
+
`GITHUB_CLIENT_SECRET` in `.env`, and register
|
|
251
|
+
`<APP_URL>/api/auth/oauth/<provider>/callback` with each provider. Other
|
|
252
|
+
providers are one row in the controller's `OAUTH_PROVIDERS` table.
|
|
253
|
+
|
|
254
|
+
## Other building blocks
|
|
255
|
+
|
|
256
|
+
- `createTokenSigner({ secret })` signs and verifies typed tokens such as
|
|
257
|
+
email-verification or magic links:
|
|
258
|
+
`sign(claims, { type: 'magic-link', expiresIn: '15m' })`.
|
|
259
|
+
- `createSealer({ secret })` gives you `seal()` and `unseal()` for
|
|
260
|
+
encrypted, purpose-bound values that can expire.
|
|
261
|
+
- `createRateLimiter` and `createLoginThrottle` work over any counter store.
|
|
262
|
+
- `checkPasswordStrength(password, { userInputs, breached })` checks a
|
|
263
|
+
new password.
|
|
264
|
+
- `isCrossSiteRequest(request)` and `safeRedirectPath(next)` are
|
|
265
|
+
standalone CSRF and redirect checks.
|
|
266
|
+
|
|
267
|
+
## In Tylix apps
|
|
268
|
+
|
|
269
|
+
`tylix make:auth` scaffolds all of this into the app. It writes an
|
|
270
|
+
`AuthSession` model and migration, and an `AuthController` built on
|
|
271
|
+
`createAuth` with these routes: register, login, refresh, logout,
|
|
272
|
+
logout-all, sessions, change-password, verify-email, resend-verification,
|
|
273
|
+
forgot-password and reset-password. `requireAuth` (every `.auth()` route)
|
|
274
|
+
rejects tokens whose session has ended.
|
|
275
|
+
|
|
276
|
+
### Upgrading from 1.4
|
|
277
|
+
|
|
278
|
+
Run `tylix make:auth` and then `tylix migrate`. This regenerates the
|
|
279
|
+
controller and models and adds the `auth_sessions` table.
|
|
280
|
+
|
|
281
|
+
- **Everyone signs in once more.** Refresh tokens from the old
|
|
282
|
+
`refresh_tokens` table aren't migrated.
|
|
283
|
+
- **`AUTH_SECRET` must be at least 32 characters in production.** Shorter
|
|
284
|
+
secrets now stop the server from starting.
|
|
285
|
+
- **Old email-verification links stop working.** They were also usable as
|
|
286
|
+
login tokens. Users can request a new link from
|
|
287
|
+
`POST /api/auth/resend-verification`.
|
|
288
|
+
- **Access tokens default to 15 minutes, capped at an hour.** The
|
|
289
|
+
rotating refresh session keeps people signed in.
|
|
290
|
+
- Controllers generated before 1.5 keep working without regenerating.
|
|
291
|
+
They get the stricter `requireAuth` straight away. They also get the
|
|
292
|
+
fixed refresh-cookie path from each user's next login, after which
|
|
293
|
+
logout really revokes the session.
|
package/package.json
CHANGED
|
@@ -1,16 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/auth",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.5.0",
|
|
4
|
+
"description": "Secure authentication for any JavaScript framework (Next.js, Nuxt, SvelteKit, Remix, Astro, Hono, Express, Fastify, Koa, Tylix): rotating sessions with theft detection, JWTs, scrypt passwords, TOTP 2FA, OAuth with PKCE, CSRF and rate limiting. Edge-ready.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Mbiyrukzz",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"keywords": [
|
|
9
|
-
"tylix",
|
|
10
9
|
"auth",
|
|
11
10
|
"authentication",
|
|
11
|
+
"session",
|
|
12
12
|
"jwt",
|
|
13
|
-
"
|
|
13
|
+
"oauth",
|
|
14
|
+
"pkce",
|
|
15
|
+
"totp",
|
|
16
|
+
"2fa",
|
|
17
|
+
"mfa",
|
|
18
|
+
"password",
|
|
19
|
+
"scrypt",
|
|
20
|
+
"csrf",
|
|
21
|
+
"rate-limit",
|
|
22
|
+
"nextjs",
|
|
23
|
+
"nuxt",
|
|
24
|
+
"sveltekit",
|
|
25
|
+
"remix",
|
|
26
|
+
"astro",
|
|
27
|
+
"hono",
|
|
28
|
+
"express",
|
|
29
|
+
"fastify",
|
|
30
|
+
"koa",
|
|
31
|
+
"edge",
|
|
32
|
+
"tylix"
|
|
14
33
|
],
|
|
15
34
|
"homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/auth#readme",
|
|
16
35
|
"repository": {
|
|
@@ -37,14 +56,81 @@
|
|
|
37
56
|
"access": "public"
|
|
38
57
|
},
|
|
39
58
|
"scripts": {
|
|
40
|
-
"test": "node --test src/**/*.test.js"
|
|
59
|
+
"test": "node --test \"src/**/*.test.js\""
|
|
41
60
|
},
|
|
42
61
|
"dependencies": {
|
|
43
|
-
"@tylix/
|
|
44
|
-
"@tylix/orm": "^1.4.0",
|
|
45
|
-
"@tylix/shared": "^1.4.0"
|
|
62
|
+
"@tylix/shared": "^1.5.0"
|
|
46
63
|
},
|
|
47
64
|
"peerDependencies": {
|
|
48
|
-
"@tylix/core": "^1.
|
|
65
|
+
"@tylix/core": "^1.5.0"
|
|
66
|
+
},
|
|
67
|
+
"exports": {
|
|
68
|
+
".": {
|
|
69
|
+
"types": "./src/index.d.ts",
|
|
70
|
+
"import": "./src/index.js",
|
|
71
|
+
"default": "./src/index.js"
|
|
72
|
+
},
|
|
73
|
+
"./web": {
|
|
74
|
+
"types": "./src/web.d.ts",
|
|
75
|
+
"import": "./src/web.js",
|
|
76
|
+
"default": "./src/web.js"
|
|
77
|
+
},
|
|
78
|
+
"./password": {
|
|
79
|
+
"types": "./src/password/index.d.ts",
|
|
80
|
+
"import": "./src/password/index.js",
|
|
81
|
+
"default": "./src/password/index.js"
|
|
82
|
+
},
|
|
83
|
+
"./next": {
|
|
84
|
+
"types": "./src/integrations/next.d.ts",
|
|
85
|
+
"import": "./src/integrations/next.js",
|
|
86
|
+
"default": "./src/integrations/next.js"
|
|
87
|
+
},
|
|
88
|
+
"./nuxt": {
|
|
89
|
+
"types": "./src/integrations/h3.d.ts",
|
|
90
|
+
"import": "./src/integrations/h3.js",
|
|
91
|
+
"default": "./src/integrations/h3.js"
|
|
92
|
+
},
|
|
93
|
+
"./h3": {
|
|
94
|
+
"types": "./src/integrations/h3.d.ts",
|
|
95
|
+
"import": "./src/integrations/h3.js",
|
|
96
|
+
"default": "./src/integrations/h3.js"
|
|
97
|
+
},
|
|
98
|
+
"./sveltekit": {
|
|
99
|
+
"types": "./src/integrations/sveltekit.d.ts",
|
|
100
|
+
"import": "./src/integrations/sveltekit.js",
|
|
101
|
+
"default": "./src/integrations/sveltekit.js"
|
|
102
|
+
},
|
|
103
|
+
"./hono": {
|
|
104
|
+
"types": "./src/integrations/hono.d.ts",
|
|
105
|
+
"import": "./src/integrations/hono.js",
|
|
106
|
+
"default": "./src/integrations/hono.js"
|
|
107
|
+
},
|
|
108
|
+
"./express": {
|
|
109
|
+
"types": "./src/integrations/node.d.ts",
|
|
110
|
+
"import": "./src/integrations/node.js",
|
|
111
|
+
"default": "./src/integrations/node.js"
|
|
112
|
+
},
|
|
113
|
+
"./fastify": {
|
|
114
|
+
"types": "./src/integrations/node.d.ts",
|
|
115
|
+
"import": "./src/integrations/node.js",
|
|
116
|
+
"default": "./src/integrations/node.js"
|
|
117
|
+
},
|
|
118
|
+
"./koa": {
|
|
119
|
+
"types": "./src/integrations/node.d.ts",
|
|
120
|
+
"import": "./src/integrations/node.js",
|
|
121
|
+
"default": "./src/integrations/node.js"
|
|
122
|
+
},
|
|
123
|
+
"./client": {
|
|
124
|
+
"types": "./src/client/client.d.ts",
|
|
125
|
+
"import": "./src/client/client.js",
|
|
126
|
+
"default": "./src/client/client.js"
|
|
127
|
+
},
|
|
128
|
+
"./package.json": "./package.json"
|
|
129
|
+
},
|
|
130
|
+
"sideEffects": false,
|
|
131
|
+
"peerDependenciesMeta": {
|
|
132
|
+
"@tylix/core": {
|
|
133
|
+
"optional": true
|
|
134
|
+
}
|
|
49
135
|
}
|
|
50
136
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { PublicSession } from '../web.js'
|
|
2
|
+
export interface AuthClient {
|
|
3
|
+
/** fetch() with credentials that refreshes once on 401 and replays the request. */
|
|
4
|
+
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
|
|
5
|
+
refresh(): Promise<boolean>
|
|
6
|
+
session(): Promise<{ userId: string | number; session: PublicSession | null; user?: unknown } | null>
|
|
7
|
+
sessions(): Promise<PublicSession[]>
|
|
8
|
+
revokeSession(id: string): Promise<boolean>
|
|
9
|
+
signOut(options?: { everywhere?: boolean }): Promise<void>
|
|
10
|
+
/** Fires in every tab when any tab signs out or a refresh fails. */
|
|
11
|
+
onSignOut(listener: () => void): () => void
|
|
12
|
+
close(): void
|
|
13
|
+
}
|
|
14
|
+
export declare function createAuthClient(options?: { baseUrl?: string; basePath?: string; fetch?: typeof fetch; onSignOut?: () => void }): AuthClient
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Browser client for any frontend (React, Vue, Svelte, Solid, Angular,
|
|
2
|
+
// vanilla). Tokens stay in httpOnly cookies, out of reach of page
|
|
3
|
+
// JavaScript (and so of XSS); this only handles the refresh dance:
|
|
4
|
+
//
|
|
5
|
+
// const client = createAuthClient()
|
|
6
|
+
// const res = await client.fetch('/api/projects') // refreshes once on 401, then replays
|
|
7
|
+
// await client.signOut()
|
|
8
|
+
//
|
|
9
|
+
// Concurrent 401s share one refresh. Tabs hear about sign-outs from each
|
|
10
|
+
// other through BroadcastChannel, so `onSignOut` fires everywhere.
|
|
11
|
+
|
|
12
|
+
export function createAuthClient({ baseUrl = '', basePath = '/api/auth', fetch: fetchImpl = globalThis.fetch?.bind(globalThis), onSignOut } = {}) {
|
|
13
|
+
let refreshing = null
|
|
14
|
+
const channel = typeof BroadcastChannel !== 'undefined' ? new BroadcastChannel('tylix-auth') : null
|
|
15
|
+
// Server-side (SSR, tests) the channel must not keep the process alive.
|
|
16
|
+
channel?.unref?.()
|
|
17
|
+
const listeners = new Set(onSignOut ? [onSignOut] : [])
|
|
18
|
+
channel?.addEventListener('message', (event) => {
|
|
19
|
+
if (event.data === 'signed-out') for (const fn of listeners) fn()
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const url = (path) => `${baseUrl}${basePath}${path}`
|
|
23
|
+
const authPaths = new Set(['/refresh', '/logout', '/logout-all'].map((p) => `${basePath}${p}`))
|
|
24
|
+
|
|
25
|
+
function refresh() {
|
|
26
|
+
refreshing ??= fetchImpl(url('/refresh'), { method: 'POST', credentials: 'include' })
|
|
27
|
+
.then((r) => r.ok)
|
|
28
|
+
.catch(() => false)
|
|
29
|
+
.finally(() => {
|
|
30
|
+
refreshing = null
|
|
31
|
+
})
|
|
32
|
+
return refreshing
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function authFetch(input, init = {}) {
|
|
36
|
+
const request = { credentials: 'include', ...init }
|
|
37
|
+
const response = await fetchImpl(input, request)
|
|
38
|
+
const path = (() => {
|
|
39
|
+
try {
|
|
40
|
+
return new URL(typeof input === 'string' ? input : input.url, globalThis.location?.href ?? 'http://localhost').pathname
|
|
41
|
+
} catch {
|
|
42
|
+
return ''
|
|
43
|
+
}
|
|
44
|
+
})()
|
|
45
|
+
if (response.status !== 401 || authPaths.has(path)) return response
|
|
46
|
+
// A body stream can't be sent twice.
|
|
47
|
+
if (typeof ReadableStream !== 'undefined' && init.body instanceof ReadableStream) return response
|
|
48
|
+
if (!(await refresh())) {
|
|
49
|
+
for (const fn of listeners) fn()
|
|
50
|
+
return response
|
|
51
|
+
}
|
|
52
|
+
return fetchImpl(input, request)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
fetch: authFetch,
|
|
57
|
+
refresh,
|
|
58
|
+
async session() {
|
|
59
|
+
const response = await authFetch(url('/session'))
|
|
60
|
+
return response.ok ? response.json() : null
|
|
61
|
+
},
|
|
62
|
+
async sessions() {
|
|
63
|
+
const response = await authFetch(url('/sessions'))
|
|
64
|
+
return response.ok ? (await response.json()).sessions : []
|
|
65
|
+
},
|
|
66
|
+
async revokeSession(id) {
|
|
67
|
+
return (await authFetch(url(`/sessions/${encodeURIComponent(id)}`), { method: 'DELETE' })).ok
|
|
68
|
+
},
|
|
69
|
+
async signOut({ everywhere = false } = {}) {
|
|
70
|
+
await fetchImpl(url(everywhere ? '/logout-all' : '/logout'), { method: 'POST', credentials: 'include' }).catch(() => {})
|
|
71
|
+
channel?.postMessage('signed-out')
|
|
72
|
+
for (const fn of listeners) fn()
|
|
73
|
+
},
|
|
74
|
+
onSignOut(fn) {
|
|
75
|
+
listeners.add(fn)
|
|
76
|
+
return () => listeners.delete(fn)
|
|
77
|
+
},
|
|
78
|
+
close() {
|
|
79
|
+
channel?.close()
|
|
80
|
+
listeners.clear()
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import type { TylixRequest, TylixResponse } from '@tylix/core'
|
|
2
|
-
|
|
3
1
|
export declare const ACCESS_TOKEN_COOKIE: string
|
|
4
2
|
export declare const REFRESH_TOKEN_COOKIE: string
|
|
3
|
+
export declare const REFRESH_TOKEN_PATH: string
|
|
5
4
|
|
|
6
5
|
export interface SetAuthCookiesOptions {
|
|
7
6
|
accessToken?: string
|
|
@@ -10,7 +9,10 @@ export interface SetAuthCookiesOptions {
|
|
|
10
9
|
refreshTtlSeconds?: number
|
|
11
10
|
}
|
|
12
11
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
export declare function
|
|
12
|
+
type Res = { setHeader(name: string, value: string | string[]): unknown; getHeader?(name: string): unknown }
|
|
13
|
+
type Req = { headers?: Record<string, unknown>; cookies?: Record<string, string> }
|
|
14
|
+
|
|
15
|
+
export declare function setAuthCookies(res: Res, options?: SetAuthCookiesOptions): void
|
|
16
|
+
export declare function clearAuthCookies(res: Res): void
|
|
17
|
+
export declare function readAccessToken(req: Req): string | null
|
|
18
|
+
export declare function readRefreshToken(req: Req): string | null
|
|
@@ -1,21 +1,35 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* httpOnly cookie helpers for access/refresh tokens
|
|
2
|
+
* httpOnly cookie helpers for access/refresh tokens, for AuthControllers
|
|
3
|
+
* generated before 1.5 (current ones get their cookies from createAuth()).
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* import cookieParser from "cookie-parser";
|
|
8
|
-
* app.use(cookieParser());
|
|
5
|
+
* Works with any response that has res.cookie() (Express, Tylix) or
|
|
6
|
+
* setHeader(); reads from req.cookies or the raw Cookie header.
|
|
9
7
|
*/
|
|
10
8
|
|
|
9
|
+
import { expireCookie, parseCookieHeaderAll, serializeCookie } from '../http/cookies.js'
|
|
10
|
+
|
|
11
11
|
const ACCESS_TOKEN_COOKIE = 'tylix_access_token'
|
|
12
12
|
const REFRESH_TOKEN_COOKIE = 'tylix_refresh_token'
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
// The refresh cookie used to be scoped to /api/auth/refresh only, so it
|
|
15
|
+
// never reached /api/auth/logout and logging out could not revoke it.
|
|
16
|
+
// It now covers /api/auth; the old path is expired whenever it's set.
|
|
17
|
+
export const REFRESH_TOKEN_PATH = '/api/auth'
|
|
18
|
+
const LEGACY_REFRESH_PATH = '/api/auth/refresh'
|
|
19
|
+
|
|
20
|
+
function secure(req) {
|
|
21
|
+
return process.env.NODE_ENV === 'production' || req?.secure === true
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function setCookie(res, value) {
|
|
25
|
+
if (typeof res.setHeader !== 'function') return
|
|
26
|
+
const existing = res.getHeader?.('Set-Cookie')
|
|
27
|
+
const list = existing == null ? [] : Array.isArray(existing) ? existing : [String(existing)]
|
|
28
|
+
res.setHeader('Set-Cookie', [...list, value])
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function options(res, path) {
|
|
32
|
+
return { httpOnly: true, sameSite: 'lax', secure: secure(res?.req), path }
|
|
19
33
|
}
|
|
20
34
|
|
|
21
35
|
export function setAuthCookies(
|
|
@@ -23,36 +37,37 @@ export function setAuthCookies(
|
|
|
23
37
|
{ accessToken, refreshToken, accessTtlSeconds, refreshTtlSeconds } = {},
|
|
24
38
|
) {
|
|
25
39
|
if (accessToken) {
|
|
26
|
-
res
|
|
27
|
-
...baseCookieOptions,
|
|
28
|
-
maxAge: accessTtlSeconds * 1000,
|
|
29
|
-
})
|
|
40
|
+
setCookie(res, serializeCookie(ACCESS_TOKEN_COOKIE, accessToken, { ...options(res, '/'), maxAge: accessTtlSeconds }))
|
|
30
41
|
}
|
|
31
42
|
|
|
32
43
|
if (refreshToken) {
|
|
33
|
-
res
|
|
34
|
-
|
|
35
|
-
maxAge: refreshTtlSeconds * 1000,
|
|
36
|
-
// Scoped so the browser only sends it to the refresh endpoint.
|
|
37
|
-
path: '/api/auth/refresh',
|
|
38
|
-
})
|
|
44
|
+
setCookie(res, serializeCookie(REFRESH_TOKEN_COOKIE, refreshToken, { ...options(res, REFRESH_TOKEN_PATH), maxAge: refreshTtlSeconds }))
|
|
45
|
+
setCookie(res, expireCookie(REFRESH_TOKEN_COOKIE, options(res, LEGACY_REFRESH_PATH)))
|
|
39
46
|
}
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
export function clearAuthCookies(res) {
|
|
43
|
-
res
|
|
44
|
-
res
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
50
|
+
setCookie(res, expireCookie(ACCESS_TOKEN_COOKIE, options(res, '/')))
|
|
51
|
+
setCookie(res, expireCookie(REFRESH_TOKEN_COOKIE, options(res, REFRESH_TOKEN_PATH)))
|
|
52
|
+
setCookie(res, expireCookie(REFRESH_TOKEN_COOKIE, options(res, LEGACY_REFRESH_PATH)))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readAll(req, name) {
|
|
56
|
+
const fromHeader = parseCookieHeaderAll(req?.headers?.cookie)[name]
|
|
57
|
+
if (fromHeader?.length) return fromHeader
|
|
58
|
+
const value = req?.cookies?.[name]
|
|
59
|
+
return value ? [value] : []
|
|
48
60
|
}
|
|
49
61
|
|
|
50
62
|
export function readAccessToken(req) {
|
|
51
|
-
return req
|
|
63
|
+
return readAll(req, ACCESS_TOKEN_COOKIE)[0] ?? null
|
|
52
64
|
}
|
|
53
65
|
|
|
66
|
+
// With both an old-path and a new-path cookie present, the browser sends
|
|
67
|
+
// the more specific (old) one first; the newest is the last one.
|
|
54
68
|
export function readRefreshToken(req) {
|
|
55
|
-
|
|
69
|
+
const all = readAll(req, REFRESH_TOKEN_COOKIE)
|
|
70
|
+
return all[all.length - 1] ?? null
|
|
56
71
|
}
|
|
57
72
|
|
|
58
73
|
export { ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE }
|