@adaptive-js/extension-auth 0.0.0-stage β 0.0.2
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/LICENSE +21 -0
- package/README.md +412 -3
- package/dist/api-adapter.d.ts +2 -0
- package/dist/api-adapter.js +8 -0
- package/dist/api-adapter.js.map +1 -0
- package/dist/client.d.ts +41 -0
- package/dist/client.js +128 -0
- package/dist/client.js.map +1 -0
- package/dist/cookies.d.ts +10 -0
- package/dist/cookies.js +107 -0
- package/dist/cookies.js.map +1 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +11 -0
- package/dist/errors.js.map +1 -0
- package/dist/external-adapter.d.ts +93 -0
- package/dist/external-adapter.js +235 -0
- package/dist/external-adapter.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/intended-url.d.ts +18 -0
- package/dist/intended-url.js +55 -0
- package/dist/intended-url.js.map +1 -0
- package/dist/memory-adapter.d.ts +16 -0
- package/dist/memory-adapter.js +112 -0
- package/dist/memory-adapter.js.map +1 -0
- package/dist/rate-limit.d.ts +28 -0
- package/dist/rate-limit.js +104 -0
- package/dist/rate-limit.js.map +1 -0
- package/dist/server.d.ts +54 -0
- package/dist/server.js +745 -0
- package/dist/server.js.map +1 -0
- package/dist/types.d.ts +225 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/01-getting-started.md +347 -0
- package/docs/02-server-actions.md +176 -0
- package/docs/03-protecting-pages.md +144 -0
- package/docs/04-session-lifecycle.md +169 -0
- package/docs/05-adapters.md +242 -0
- package/docs/06-client.md +126 -0
- package/docs/07-security-checklist.md +93 -0
- package/docs/08-integration.md +134 -0
- package/docs/09-troubleshooting.md +96 -0
- package/docs/README.md +17 -0
- package/package.json +72 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Antonio Johnathan
|
|
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,412 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @adaptive-js/extension-auth
|
|
2
|
+
|
|
3
|
+
[π§π· PortuguΓͺs](./README_PT-BR.md) | [πΊπΈ English](./README.md)
|
|
4
|
+
|
|
5
|
+
Server-first, secure-by-default authentication and session primitives for AdaptiveJS applications.
|
|
6
|
+
|
|
7
|
+
The package intentionally separates server authority from client UI state:
|
|
8
|
+
|
|
9
|
+
- `@adaptive-js/extension-auth/server` creates, reads, renews, and invalidates sessions, secures Server Actions, and handles CSRF/cookies.
|
|
10
|
+
- `@adaptive-js/extension-auth/client` exposes authenticated user state and reactive session expiry to hydrated UI components.
|
|
11
|
+
- `@adaptive-js/extension-auth/memory-adapter` is a development/testing session adapter with proactive expiry cleanup.
|
|
12
|
+
- `@adaptive-js/extension-auth` contains shared types, cookie utilities, rate limiting, intended URL helpers, and errors.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Architecture
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
@adaptive-js/extension-auth
|
|
20
|
+
β
|
|
21
|
+
AuthAdapter
|
|
22
|
+
β
|
|
23
|
+
βββββββββββββββ΄ββββββββββββββ
|
|
24
|
+
β β
|
|
25
|
+
βΌ βΌ
|
|
26
|
+
MemoryAuthAdapter Application Adapter
|
|
27
|
+
β β
|
|
28
|
+
βΌ βΌ
|
|
29
|
+
Dev Server / tests Production / Database
|
|
30
|
+
(no external backend) (Postgres, Redis, Mongo, etc.)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### MemoryAuthAdapter
|
|
34
|
+
|
|
35
|
+
Use `createMemoryAuthAdapter()` for development, tests, and quick prototyping:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
'server'
|
|
39
|
+
import { createMemoryAuthAdapter } from "@adaptive-js/extension-auth/memory-adapter";
|
|
40
|
+
|
|
41
|
+
const adapter = createMemoryAuthAdapter({
|
|
42
|
+
users: [{ id: "u-1", email: "alice@example.com", roles: ["admin"] }],
|
|
43
|
+
cleanupIntervalMs: 60_000 // proactive cleanup of expired sessions
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
> [!WARNING]
|
|
48
|
+
> In-memory session data is lost whenever the process restarts. Do **not** use the memory adapter in production.
|
|
49
|
+
|
|
50
|
+
### AuthAdapter
|
|
51
|
+
|
|
52
|
+
`AuthAdapter` is the contract connecting AdaptiveJS auth to your persistence layer. The core package stays completely storage-agnostic.
|
|
53
|
+
|
|
54
|
+
Required methods:
|
|
55
|
+
- `getUser(userId)`
|
|
56
|
+
- `getSession(sessionId)`
|
|
57
|
+
- `createSession(session)`
|
|
58
|
+
- `updateSession(session)`
|
|
59
|
+
- `deleteSession(sessionId)`
|
|
60
|
+
|
|
61
|
+
Optional methods:
|
|
62
|
+
- `deleteUserSessions(userId)`
|
|
63
|
+
- `deleteUserSessionsExcept(userId, exceptSessionId)`
|
|
64
|
+
- `listUserSessions(userId)`
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Quick Start & Server Setup
|
|
69
|
+
|
|
70
|
+
CSRF protection is **mandatory at boot**. If `csrf.allowedOrigins` is not provided or empty, `createAuth()` fails fast:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
// src/auth.ts
|
|
74
|
+
'server'
|
|
75
|
+
import { createAuth } from "@adaptive-js/extension-auth/server";
|
|
76
|
+
import { createMemoryAuthAdapter } from "@adaptive-js/extension-auth/memory-adapter";
|
|
77
|
+
|
|
78
|
+
export const auth = createAuth({
|
|
79
|
+
adapter: createMemoryAuthAdapter(),
|
|
80
|
+
csrf: {
|
|
81
|
+
allowedOrigins: ["https://app.example.com"]
|
|
82
|
+
},
|
|
83
|
+
sessionDuration: 60 * 60 * 24 * 30, // 30 days idle timeout
|
|
84
|
+
absoluteSessionDuration: 60 * 60 * 24 * 90, // 90 days max session lifetime
|
|
85
|
+
renewBefore: 60 * 60 * 24 * 7, // rotate ID 7 days before expiry
|
|
86
|
+
|
|
87
|
+
// Optional: Rate limit session creation (login brute-force protection)
|
|
88
|
+
rateLimit: {
|
|
89
|
+
createSession: {
|
|
90
|
+
max: 10,
|
|
91
|
+
windowMs: 15 * 60 * 1000 // 10 attempts per 15 minutes
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
// Optional: Session binding (anti-hijacking)
|
|
96
|
+
sessionBinding: {
|
|
97
|
+
userAgent: true
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
// Optional: Risk event hooks
|
|
101
|
+
onPasswordChanged(userId) { /* ... */ },
|
|
102
|
+
onRoleChanged(userId) { /* ... */ },
|
|
103
|
+
onSuspiciousActivity(userId, reason) { /* ... */ },
|
|
104
|
+
|
|
105
|
+
// Audit logging (best-effort)
|
|
106
|
+
onAuditEvent(event) {
|
|
107
|
+
console.info("auth event:", event);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Cookie Security & Production Defaults
|
|
113
|
+
|
|
114
|
+
By default, session cookies use:
|
|
115
|
+
- Name: `__Host-adaptive-session`
|
|
116
|
+
- `Path=/`
|
|
117
|
+
- `Secure: true`
|
|
118
|
+
- `HttpOnly: true`
|
|
119
|
+
- `SameSite: "Lax"`
|
|
120
|
+
|
|
121
|
+
The `__Host-` prefix protects against subdomain cookie shadowing and prohibits the `Domain` attribute. In production (`NODE_ENV=production`), disabling `Secure` or `HttpOnly` throws an explicit `AuthError("AUTH_CONFIGURATION_INVALID")`.
|
|
122
|
+
|
|
123
|
+
For non-HTTPS local development only:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
cookie: {
|
|
127
|
+
name: "adaptive.session.dev",
|
|
128
|
+
secure: false
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## Server Actions (`auth.action`)
|
|
135
|
+
|
|
136
|
+
The recommended way to author server actions. It automatically validates the user session and CSRF token before running your logic:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
// src/actions/profile.ts
|
|
140
|
+
import { auth } from "../auth";
|
|
141
|
+
|
|
142
|
+
export const updateProfile = auth.action(async ({ session, formData, request, args }) => {
|
|
143
|
+
// Session is guaranteed to be authenticated
|
|
144
|
+
// CSRF token and origin have already been verified
|
|
145
|
+
const name = formData?.get("name");
|
|
146
|
+
await db.user.update({ where: { id: session.userId }, data: { name } });
|
|
147
|
+
|
|
148
|
+
return { ok: true };
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Role Enforcement in Actions
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
export const deleteAccount = auth.action({ roles: ["admin"] }, async ({ session }) => {
|
|
156
|
+
// Only accessible if session.user.roles includes "admin"
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
**CSRF Token Resolution:**
|
|
161
|
+
`auth.action` automatically extracts the token from either:
|
|
162
|
+
1. HTTP header `x-adaptive-csrf-token`
|
|
163
|
+
2. Form field `csrfToken` or `_csrf`
|
|
164
|
+
3. JSON argument object containing `csrfToken` or `_csrf`
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## Protecting Pages (`auth.protectPage`)
|
|
169
|
+
|
|
170
|
+
Protect server-rendered pages without central route lists:
|
|
171
|
+
|
|
172
|
+
```tsx
|
|
173
|
+
// src/pages/dashboard.tsx
|
|
174
|
+
import { auth } from "../auth";
|
|
175
|
+
|
|
176
|
+
export default auth.protectPage(async ({ session }) => {
|
|
177
|
+
return <h1>Welcome back, {session.user.name}</h1>;
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Configurable Unauthorized & Forbidden Behaviors
|
|
182
|
+
|
|
183
|
+
Customize what happens when a visitor is unauthenticated or lacks required roles:
|
|
184
|
+
|
|
185
|
+
```tsx
|
|
186
|
+
// src/pages/admin/index.tsx
|
|
187
|
+
import { auth } from "../../auth";
|
|
188
|
+
|
|
189
|
+
export default auth.protectPage(
|
|
190
|
+
async ({ session }) => <AdminPanel user={session.user} />,
|
|
191
|
+
{
|
|
192
|
+
roles: ["admin"],
|
|
193
|
+
// Redirect unauthenticated visitors to login with safe returnTo
|
|
194
|
+
onUnauthenticated: "redirect",
|
|
195
|
+
redirectTo: "/login",
|
|
196
|
+
returnTo: true,
|
|
197
|
+
|
|
198
|
+
// Return 403 Forbidden instead of 404
|
|
199
|
+
onForbidden: "403"
|
|
200
|
+
}
|
|
201
|
+
);
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Available options:
|
|
205
|
+
- `onUnauthenticated`: `"404"` (default) | `"401"` | `"redirect"` | `(context) => any`
|
|
206
|
+
- `redirectTo`: string (defaults to `"/login"`)
|
|
207
|
+
- `returnTo`: boolean (automatically validates with `sanitizeReturnTo`)
|
|
208
|
+
- `onForbidden`: `"404"` (default) | `"403"` | `(context) => any`
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
## Session Lifecycle & High-Level Helpers
|
|
213
|
+
|
|
214
|
+
### Login & Logout
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
// Login
|
|
218
|
+
const { session, cookie } = await auth.login(user, request);
|
|
219
|
+
response.headers.append("Set-Cookie", cookie.header);
|
|
220
|
+
|
|
221
|
+
// Logout current device
|
|
222
|
+
const { cookie: blankCookie } = await auth.logout(request);
|
|
223
|
+
response.headers.append("Set-Cookie", blankCookie.header);
|
|
224
|
+
|
|
225
|
+
// Logout all devices
|
|
226
|
+
await auth.logoutEverywhere(userId);
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### Risk Events (Automatic Invalidation)
|
|
230
|
+
|
|
231
|
+
When security-critical events happen, call these high-level methods to invalidate existing sessions and record audit trails:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
await auth.passwordChanged(userId); // Invalidates all sessions + audits "password-changed" + runs hook
|
|
235
|
+
await auth.roleElevated(userId); // Invalidates all sessions + audits "role-elevated" + runs hook
|
|
236
|
+
await auth.forceReauth(userId, reason); // Invalidates all sessions + audits reason + runs hook
|
|
237
|
+
await auth.mfaEnabled(userId); // Invalidates all sessions + audits "mfa-enabled" + runs hook
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### Updating Session Data
|
|
241
|
+
|
|
242
|
+
Update session metadata without rotating the session ID or CSRF token:
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
await auth.updateSessionData(sessionId, { mfaVerified: true });
|
|
246
|
+
|
|
247
|
+
// Or with a functional updater:
|
|
248
|
+
await auth.updateSessionData(sessionId, (prev) => ({
|
|
249
|
+
cartCount: (prev.cartCount ?? 0) + 1
|
|
250
|
+
}));
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
### Automatic Cookie Renewal (`withSession`)
|
|
254
|
+
|
|
255
|
+
Session renewal rotates the session ID periodically. Use `withSession` to execute logic and ensure any renewed `Set-Cookie` is automatically applied to standard `Response` objects:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
export async function handleRequest(request: Request) {
|
|
259
|
+
return auth.withSession(request, async ({ session, freshCookie }) => {
|
|
260
|
+
return new Response(JSON.stringify({ userId: session.userId }));
|
|
261
|
+
// If session was renewed, fresh Set-Cookie header is appended automatically!
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
#### Renewal Concurrency (Race Condition Mitigation)
|
|
267
|
+
When multiple parallel requests arrive during a renewal window, AdaptiveJS auth:
|
|
268
|
+
- **Deduplicates in-flight renewals:** concurrent requests share the same renewal operation.
|
|
269
|
+
- **Applies a 15-second grace period:** parallel requests carrying the previous session ID still succeed and receive the renewed session.
|
|
270
|
+
|
|
271
|
+
---
|
|
272
|
+
|
|
273
|
+
## Rate Limiting
|
|
274
|
+
|
|
275
|
+
Protect `createSession` and `auth.login` against brute-force attacks:
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
export const auth = createAuth({
|
|
279
|
+
adapter,
|
|
280
|
+
csrf: { allowedOrigins: ["https://app.example.com"] },
|
|
281
|
+
rateLimit: {
|
|
282
|
+
createSession: {
|
|
283
|
+
max: 5,
|
|
284
|
+
windowMs: 15 * 60 * 1000, // 5 attempts per 15 min per IP
|
|
285
|
+
key: (ctx) => `${ctx.ip}:${ctx.userId ?? "anonymous"}`
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
When exceeded, `createSession` throws an `AuthError` with:
|
|
292
|
+
- `code: "RATE_LIMIT_EXCEEDED"`
|
|
293
|
+
- `status: 429`
|
|
294
|
+
- `retryAfterSeconds`
|
|
295
|
+
|
|
296
|
+
---
|
|
297
|
+
|
|
298
|
+
## Session Binding (Anti-Hijacking)
|
|
299
|
+
|
|
300
|
+
Optionally bind sessions to the client's User-Agent, IP, or custom fingerprint:
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
export const auth = createAuth({
|
|
304
|
+
adapter,
|
|
305
|
+
csrf: { allowedOrigins: ["https://app.example.com"] },
|
|
306
|
+
sessionBinding: {
|
|
307
|
+
userAgent: true,
|
|
308
|
+
// ip: true, // Caution: mobile networks and CGNAT frequently change IPs
|
|
309
|
+
// fingerprint: true // Custom header x-client-fingerprint
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
If a session is presented with a mismatched User-Agent, it is immediately deleted and rejected (`session.rejected` audit event).
|
|
315
|
+
|
|
316
|
+
---
|
|
317
|
+
|
|
318
|
+
## Intended URL (Post-Login Redirects)
|
|
319
|
+
|
|
320
|
+
```ts
|
|
321
|
+
import {
|
|
322
|
+
buildLoginReturnUrl,
|
|
323
|
+
readReturnToFromSearchParams,
|
|
324
|
+
sanitizeReturnTo
|
|
325
|
+
} from "@adaptive-js/extension-auth";
|
|
326
|
+
|
|
327
|
+
const loginUrl = buildLoginReturnUrl("/login", "/account/settings");
|
|
328
|
+
// "/login?returnTo=%2Faccount%2Fsettings"
|
|
329
|
+
|
|
330
|
+
const safePath = sanitizeReturnTo("https://evil.example.com");
|
|
331
|
+
// null β open redirects and external URLs are strictly rejected
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
---
|
|
335
|
+
|
|
336
|
+
## Client State (`@adaptive-js/extension-auth/client`)
|
|
337
|
+
|
|
338
|
+
Presentational state for client components:
|
|
339
|
+
|
|
340
|
+
```tsx
|
|
341
|
+
"hydrate";
|
|
342
|
+
|
|
343
|
+
import { createAuthClient, toAuthClientState } from "@adaptive-js/extension-auth/client";
|
|
344
|
+
|
|
345
|
+
export const { AuthProvider, useAuth } = createAuthClient({
|
|
346
|
+
autoClearOnExpired: true,
|
|
347
|
+
onExpired() {
|
|
348
|
+
window.location.href = "/login?expired=1";
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
Using in components:
|
|
354
|
+
|
|
355
|
+
```tsx
|
|
356
|
+
function UserGreeting() {
|
|
357
|
+
const auth = useAuth();
|
|
358
|
+
|
|
359
|
+
if (!auth.authenticated()) {
|
|
360
|
+
return <a href="/login">Sign in</a>;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
return (
|
|
364
|
+
<div>
|
|
365
|
+
<p>Hello, {auth.user()?.name}!</p>
|
|
366
|
+
{auth.isExpired() && <span>Session has expired</span>}
|
|
367
|
+
</div>
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
> [!NOTE]
|
|
373
|
+
> Client state is purely for UI responsiveness. The server always re-verifies session validity and role permissions on every request.
|
|
374
|
+
|
|
375
|
+
---
|
|
376
|
+
|
|
377
|
+
## Error Handling
|
|
378
|
+
|
|
379
|
+
All auth errors throw `AuthError`:
|
|
380
|
+
|
|
381
|
+
```ts
|
|
382
|
+
import { AuthError } from "@adaptive-js/extension-auth";
|
|
383
|
+
|
|
384
|
+
try {
|
|
385
|
+
await auth.requireSession(request);
|
|
386
|
+
} catch (error) {
|
|
387
|
+
if (error instanceof AuthError) {
|
|
388
|
+
console.error(error.code, error.status, error.message);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Codes:
|
|
394
|
+
- `AUTHENTICATION_REQUIRED` (401)
|
|
395
|
+
- `AUTHORIZATION_FAILED` (403)
|
|
396
|
+
- `SESSION_USER_NOT_FOUND` (401)
|
|
397
|
+
- `CSRF_TOKEN_INVALID` (403)
|
|
398
|
+
- `CSRF_ORIGIN_INVALID` (403)
|
|
399
|
+
- `CSRF_CONFIGURATION_INVALID` (500)
|
|
400
|
+
- `AUTH_CONFIGURATION_INVALID` (500)
|
|
401
|
+
- `RATE_LIMIT_EXCEEDED` (429)
|
|
402
|
+
- `SESSION_BINDING_MISMATCH` (401)
|
|
403
|
+
|
|
404
|
+
---
|
|
405
|
+
|
|
406
|
+
## Testing
|
|
407
|
+
|
|
408
|
+
Run the official test suite covering CSRF, cookies, rate limiting, session binding, concurrency, and risk events:
|
|
409
|
+
|
|
410
|
+
```bash
|
|
411
|
+
npm test
|
|
412
|
+
```
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Antonio Johnathan
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the MIT License.
|
|
5
|
+
* See LICENSE file in the project root for full license information.
|
|
6
|
+
*/
|
|
7
|
+
export { createApiExternalAdapter, createExternalAuthAdapter } from "./external-adapter.js";
|
|
8
|
+
//# sourceMappingURL=api-adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-adapter.js","sourceRoot":"","sources":["../src/api-adapter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EAE1B,MAAM,uBAAuB,CAAC"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { AuthClientState, AuthUser } from "./types.js";
|
|
2
|
+
export interface AuthProviderProps<TUser extends AuthUser = AuthUser> {
|
|
3
|
+
initialState?: AuthClientState<TUser>;
|
|
4
|
+
autoClearOnExpired?: boolean;
|
|
5
|
+
onExpired?: () => void;
|
|
6
|
+
children?: any;
|
|
7
|
+
}
|
|
8
|
+
export interface AuthClientApi<TUser extends AuthUser = AuthUser> {
|
|
9
|
+
state: () => AuthClientState<TUser>;
|
|
10
|
+
user: () => TUser | null;
|
|
11
|
+
authenticated: () => boolean;
|
|
12
|
+
isExpired: () => boolean;
|
|
13
|
+
expiresInMs: () => number | null;
|
|
14
|
+
setState: (state: AuthClientState<TUser>) => void;
|
|
15
|
+
clear: () => void;
|
|
16
|
+
}
|
|
17
|
+
export interface CreateAuthClientOptions {
|
|
18
|
+
autoClearOnExpired?: boolean;
|
|
19
|
+
onExpired?: () => void;
|
|
20
|
+
}
|
|
21
|
+
export declare function createAuthClient<TUser extends AuthUser = AuthUser>(clientOptions?: CreateAuthClientOptions): {
|
|
22
|
+
AuthProvider: (props: AuthProviderProps<TUser>) => {
|
|
23
|
+
tag: symbol;
|
|
24
|
+
props: {
|
|
25
|
+
context: import("@adaptive-js/web").AdaptiveContext<AuthClientApi<TUser> | null>;
|
|
26
|
+
value: AuthClientApi<TUser> | null;
|
|
27
|
+
};
|
|
28
|
+
children: any;
|
|
29
|
+
};
|
|
30
|
+
useAuth: () => AuthClientApi<TUser>;
|
|
31
|
+
};
|
|
32
|
+
export declare function toAuthClientState<TUser extends AuthUser>(session: {
|
|
33
|
+
user: TUser;
|
|
34
|
+
expiresAt: Date;
|
|
35
|
+
} | null): AuthClientState<AuthUser>;
|
|
36
|
+
export declare function toAuthClientState<TUser extends AuthUser, TClientUser extends AuthUser>(session: {
|
|
37
|
+
user: TUser;
|
|
38
|
+
expiresAt: Date;
|
|
39
|
+
} | null, selectUser: (user: TUser) => TClientUser): AuthClientState<TClientUser>;
|
|
40
|
+
export declare function isAuthStateExpired(state: AuthClientState): boolean;
|
|
41
|
+
export declare function getAuthStateExpiresInMs(state: AuthClientState): number | null;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createContext, useContext, signal } from "@adaptive-js/web";
|
|
2
|
+
const EMPTY_AUTH_STATE = {
|
|
3
|
+
authenticated: false,
|
|
4
|
+
user: null,
|
|
5
|
+
expiresAt: null
|
|
6
|
+
};
|
|
7
|
+
export function createAuthClient(clientOptions = {}) {
|
|
8
|
+
const AuthContext = createContext(null);
|
|
9
|
+
function AuthProvider(props) {
|
|
10
|
+
const [state, setState] = signal(props.initialState ?? EMPTY_AUTH_STATE);
|
|
11
|
+
const autoClear = props.autoClearOnExpired ?? clientOptions.autoClearOnExpired ?? false;
|
|
12
|
+
const onExpiredCallback = props.onExpired ?? clientOptions.onExpired;
|
|
13
|
+
let timerId = null;
|
|
14
|
+
function scheduleExpiryCheck(currentState) {
|
|
15
|
+
if (typeof setTimeout === "undefined")
|
|
16
|
+
return;
|
|
17
|
+
if (timerId) {
|
|
18
|
+
clearTimeout(timerId);
|
|
19
|
+
timerId = null;
|
|
20
|
+
}
|
|
21
|
+
if (!currentState.authenticated || !currentState.expiresAt) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const remaining = getAuthStateExpiresInMs(currentState);
|
|
25
|
+
if (remaining === null)
|
|
26
|
+
return;
|
|
27
|
+
if (remaining <= 0) {
|
|
28
|
+
if (autoClear) {
|
|
29
|
+
setState(EMPTY_AUTH_STATE);
|
|
30
|
+
}
|
|
31
|
+
onExpiredCallback?.();
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
// Schedule callback slightly after expiration
|
|
35
|
+
timerId = setTimeout(() => {
|
|
36
|
+
if (autoClear) {
|
|
37
|
+
setState(EMPTY_AUTH_STATE);
|
|
38
|
+
}
|
|
39
|
+
onExpiredCallback?.();
|
|
40
|
+
}, remaining + 50);
|
|
41
|
+
}
|
|
42
|
+
// Schedule on initial state
|
|
43
|
+
scheduleExpiryCheck(state());
|
|
44
|
+
function updateState(next) {
|
|
45
|
+
setState(next);
|
|
46
|
+
scheduleExpiryCheck(next);
|
|
47
|
+
}
|
|
48
|
+
function clear() {
|
|
49
|
+
if (timerId) {
|
|
50
|
+
clearTimeout(timerId);
|
|
51
|
+
timerId = null;
|
|
52
|
+
}
|
|
53
|
+
setState(EMPTY_AUTH_STATE);
|
|
54
|
+
}
|
|
55
|
+
const api = {
|
|
56
|
+
state,
|
|
57
|
+
user: () => state().user,
|
|
58
|
+
authenticated: () => {
|
|
59
|
+
const s = state();
|
|
60
|
+
if (!s.authenticated)
|
|
61
|
+
return false;
|
|
62
|
+
if (isAuthStateExpired(s)) {
|
|
63
|
+
if (autoClear) {
|
|
64
|
+
clear();
|
|
65
|
+
}
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
},
|
|
70
|
+
isExpired: () => isAuthStateExpired(state()),
|
|
71
|
+
expiresInMs: () => getAuthStateExpiresInMs(state()),
|
|
72
|
+
setState: updateState,
|
|
73
|
+
clear
|
|
74
|
+
};
|
|
75
|
+
return AuthContext.Provider({
|
|
76
|
+
value: api,
|
|
77
|
+
children: props.children
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function useAuth() {
|
|
81
|
+
const auth = useContext(AuthContext);
|
|
82
|
+
if (!auth) {
|
|
83
|
+
throw new Error("useAuth must be used inside an AuthProvider.");
|
|
84
|
+
}
|
|
85
|
+
return auth;
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
AuthProvider,
|
|
89
|
+
useAuth
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export function toAuthClientState(session, selectUser) {
|
|
93
|
+
if (!session) {
|
|
94
|
+
return EMPTY_AUTH_STATE;
|
|
95
|
+
}
|
|
96
|
+
// Never expose arbitrary adapter fields (for example passwordHash) by default.
|
|
97
|
+
const user = selectUser
|
|
98
|
+
? selectUser(session.user)
|
|
99
|
+
: {
|
|
100
|
+
id: session.user.id,
|
|
101
|
+
email: session.user.email,
|
|
102
|
+
name: session.user.name,
|
|
103
|
+
roles: session.user.roles ? [...session.user.roles] : undefined
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
authenticated: true,
|
|
107
|
+
user,
|
|
108
|
+
expiresAt: session.expiresAt.toISOString()
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
export function isAuthStateExpired(state) {
|
|
112
|
+
if (!state.expiresAt) {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
const expiresAt = Date.parse(state.expiresAt);
|
|
116
|
+
return Number.isFinite(expiresAt) && expiresAt <= Date.now();
|
|
117
|
+
}
|
|
118
|
+
export function getAuthStateExpiresInMs(state) {
|
|
119
|
+
if (!state.expiresAt) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
const expiresAt = Date.parse(state.expiresAt);
|
|
123
|
+
if (!Number.isFinite(expiresAt)) {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
return Math.max(0, expiresAt - Date.now());
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAyBrE,MAAM,gBAAgB,GAAoB;IACxC,aAAa,EAAE,KAAK;IACpB,IAAI,EAAE,IAAI;IACV,SAAS,EAAE,IAAI;CAChB,CAAC;AAEF,MAAM,UAAU,gBAAgB,CAC9B,gBAAyC,EAAE;IAE3C,MAAM,WAAW,GAAG,aAAa,CAA8B,IAAI,CAAC,CAAC;IAErE,SAAS,YAAY,CAAC,KAA+B;QACnD,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,MAAM,CAC9B,KAAK,CAAC,YAAY,IAAK,gBAA2C,CACnE,CAAC;QAEF,MAAM,SAAS,GAAG,KAAK,CAAC,kBAAkB,IAAI,aAAa,CAAC,kBAAkB,IAAI,KAAK,CAAC;QACxF,MAAM,iBAAiB,GAAG,KAAK,CAAC,SAAS,IAAI,aAAa,CAAC,SAAS,CAAC;QAErE,IAAI,OAAO,GAAQ,IAAI,CAAC;QAExB,SAAS,mBAAmB,CAAC,YAAoC;YAC/D,IAAI,OAAO,UAAU,KAAK,WAAW;gBAAE,OAAO;YAC9C,IAAI,OAAO,EAAE,CAAC;g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CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS;SAChE,CAAC;IAEN,OAAO;QACL,aAAa,EAAE,IAAI;QACnB,IAAI;QACJ,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,WAAW,EAAE;KAC3C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAsB;IACvD,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IAC9C,OAAO,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,SAAS,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;AAC/D,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,KAAsB;IAC5D,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IAC9C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;AAC7C,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AuthCookieOptions, AuthCookieResult, AuthRequestLike } from "./types.js";
|
|
2
|
+
export declare const DEFAULT_AUTH_COOKIE_NAME = "__Host-adaptive-session";
|
|
3
|
+
export declare const DEFAULT_AUTH_COOKIE_OPTIONS: Required<Pick<AuthCookieOptions, "path" | "sameSite" | "secure" | "httpOnly">>;
|
|
4
|
+
export declare function validateCookieOptions(name?: string, options?: AuthCookieOptions, isProduction?: boolean): void;
|
|
5
|
+
export declare function readCookieHeader(source: AuthRequestLike | Headers | Record<string, string | string[] | undefined> | string): string;
|
|
6
|
+
export declare function parseCookies(cookieHeader: string): Record<string, string>;
|
|
7
|
+
export declare function getCookie(source: AuthRequestLike | Headers | Record<string, string | string[] | undefined> | string, name: string): string;
|
|
8
|
+
export declare function serializeCookie(name: string, value: string, options?: AuthCookieOptions): string;
|
|
9
|
+
export declare function createSessionCookie(sessionId: string, options?: AuthCookieOptions): AuthCookieResult;
|
|
10
|
+
export declare function createBlankSessionCookie(options?: AuthCookieOptions): AuthCookieResult;
|