webspresso 0.0.108 → 0.0.110
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 +3 -3
- package/bin/commands/add-esbuild.js +7 -3
- package/bin/commands/add-tailwind.js +9 -5
- package/bin/commands/build.js +20 -4
- package/bin/commands/dev.js +57 -7
- package/bin/commands/doctor.js +42 -1
- package/bin/commands/favicon-generate.js +10 -3
- package/bin/commands/new.js +8 -3
- package/bin/commands/start.js +3 -1
- package/bin/utils/add-command.js +16 -0
- package/core/app.js +45 -3
- package/core/auth/authenticate.js +3 -3
- package/core/auth/hash.js +167 -43
- package/core/auth/index.js +13 -1
- package/core/auth/jwt.js +21 -2
- package/core/auth/manager.js +63 -14
- package/core/auth/middleware.js +4 -2
- package/core/auth/oauth.js +5 -1
- package/core/auth/tokens.js +7 -2
- package/core/auth/totp.js +42 -6
- package/core/auth/user-agent.js +2 -0
- package/core/client/adapter/datastar.js +1401 -0
- package/core/client/api.js +1337 -0
- package/core/client/controller.js +1706 -0
- package/core/client/debug.js +367 -0
- package/core/client/devtool.js +1134 -0
- package/core/client/forms.js +1164 -0
- package/core/client/fragments.js +894 -0
- package/core/client/index.d.ts +59 -0
- package/core/client/index.js +391 -0
- package/core/client/lite.js +175 -0
- package/core/client/server-fragments.js +868 -0
- package/core/client/storage.js +339 -0
- package/core/client/utils.js +281 -0
- package/core/compression/middleware.js +277 -26
- package/core/context/app-context.js +25 -3
- package/core/context/request.js +32 -4
- package/core/errors/middleware.js +14 -0
- package/core/events/dispatcher.js +33 -0
- package/core/forms/flash.js +136 -102
- package/core/health/middleware.js +36 -6
- package/core/http/pipeline.js +45 -6
- package/core/index.js +25 -7
- package/core/kernel/view.js +41 -10
- package/core/metrics/middleware.js +30 -6
- package/core/metrics/registry.js +13 -5
- package/core/orm/cache/fingerprint.js +32 -11
- package/core/orm/cache/layer.js +19 -2
- package/core/orm/hidden.js +145 -0
- package/core/orm/model.js +48 -2
- package/core/orm/query-builder.js +343 -6
- package/core/orm/query-filters.js +14 -2
- package/core/orm/repository.js +64 -13
- package/core/orm/schema-helpers.js +9 -6
- package/core/orm/transaction.js +50 -6
- package/core/orm/types.js +4 -0
- package/core/queue/adapters/database.js +184 -2
- package/core/queue/adapters/memory.js +153 -5
- package/core/queue/adapters/redis.js +59 -4
- package/core/queue/job.js +14 -1
- package/core/queue/manager.js +115 -0
- package/core/resilience/circuit-breaker.js +27 -8
- package/core/services/builtins/exchange.js +174 -7
- package/core/services/builtins/file-manager.js +36 -0
- package/core/services/builtins/mail.js +27 -0
- package/core/services/builtins/queue.js +144 -0
- package/core/services/builtins/security.js +118 -0
- package/core/services/builtins/webhook.js +110 -0
- package/core/services/executor.js +38 -16
- package/core/services/index.js +4 -1
- package/core/sse/stream.js +28 -5
- package/core/utils/timeout.js +8 -1
- package/core/validation/compiler.js +10 -7
- package/index.d.ts +1320 -74
- package/index.js +128 -8
- package/package.json +75 -27
- package/plugins/admin-panel/client/parts/08-record-list.js +717 -70
- package/plugins/admin-panel/index.js +19 -8
- package/plugins/csrf/index.js +3 -3
- package/plugins/data-exchange/export.js +214 -0
- package/plugins/data-exchange/import.js +48 -5
- package/plugins/data-exchange/index.js +70 -28
- package/plugins/data-exchange/preview.js +266 -0
- package/plugins/data-exchange/template.js +242 -0
- package/plugins/email/admin-component.js +783 -141
- package/plugins/email/api-handlers.js +51 -1
- package/plugins/email/index.js +5 -0
- package/plugins/email/service.js +48 -0
- package/plugins/file-manager/admin-component.js +1546 -70
- package/plugins/file-manager/api-handlers.js +166 -1
- package/plugins/file-manager/core.js +598 -8
- package/plugins/file-manager/index.js +8 -0
- package/plugins/index.js +7 -0
- package/plugins/mcp/auth.js +3 -3
- package/plugins/oauth/index.js +36 -3
- package/plugins/queue/admin-component.js +1092 -0
- package/plugins/queue/api-handlers.js +248 -0
- package/plugins/queue/index.js +69 -0
- package/plugins/rest-resources/index.js +7 -2
- package/plugins/security/admin-component.js +689 -0
- package/plugins/security/api-handlers.js +169 -0
- package/plugins/security/audit.js +153 -0
- package/plugins/security/bruteforce.js +244 -0
- package/plugins/security/firewall.js +459 -0
- package/plugins/security/headers.js +214 -0
- package/plugins/security/honeypot.js +234 -0
- package/plugins/security/incident-recorder.js +137 -0
- package/plugins/security/index.js +211 -0
- package/plugins/seo-checker/analyzer.js +20 -7
- package/plugins/upload/index.js +36 -0
- package/plugins/webhooks/admin-component.js +702 -175
- package/plugins/webhooks/api-handlers.js +75 -1
- package/plugins/webhooks/dispatcher.js +290 -11
- package/plugins/webhooks/index.js +37 -2
- package/plugins/webhooks/sender.js +56 -0
- package/plugins/xlsx/engine.js +19 -4
- package/src/api/api-loader.js +19 -1
- package/src/bundle/index.js +443 -17
- package/src/client-runtime/bootstrap-swup.js +9 -0
- package/src/client-runtime/mount.js +15 -20
- package/src/client-runtime/resolve.js +3 -2
- package/src/dev/api-typegen.js +1300 -0
- package/src/dev/banner.js +10 -1
- package/src/dev/colors.js +1 -1
- package/src/dev/index.js +7 -1
- package/src/dev/typegen.js +173 -17
- package/src/dev-reload/index.js +1 -1
- package/src/discovery/file-route-parser.js +17 -3
- package/src/discovery/scan-routes.js +4 -1
- package/src/file-router.js +253 -69
- package/src/helpers.js +46 -26
- package/src/njk-frontmatter.js +30 -4
- package/src/routing/cascading.js +26 -8
- package/src/routing/mount-discovered-routes.js +76 -0
- package/src/server.js +231 -70
- package/views/partials/webspresso-client-runtime.njk +1 -9
- package/.agents/ADMIN.md +0 -426
- package/.agents/AGENTS.md +0 -96
- package/.agents/ARCHITECTURE.md +0 -163
- package/.agents/AUTH.md +0 -581
- package/.agents/CACHE.md +0 -148
- package/.agents/CLI.md +0 -649
- package/.agents/COMPRESSION.md +0 -59
- package/.agents/CONTEXT.md +0 -152
- package/.agents/CONVENTIONS.md +0 -50
- package/.agents/EARLY_HINTS.md +0 -120
- package/.agents/EMAIL.md +0 -223
- package/.agents/ERRORS.md +0 -260
- package/.agents/EVENTS.md +0 -179
- package/.agents/FLAGS.md +0 -118
- package/.agents/HEALTH.md +0 -118
- package/.agents/LIMITS.md +0 -109
- package/.agents/LOGGING.md +0 -93
- package/.agents/MCP.md +0 -103
- package/.agents/METRICS.md +0 -127
- package/.agents/MIGRATION_JOBS.md +0 -95
- package/.agents/ORM.md +0 -700
- package/.agents/PLUGINS.md +0 -729
- package/.agents/QUEUE.md +0 -290
- package/.agents/RATE_LIMIT.md +0 -147
- package/.agents/REALTIME.md +0 -213
- package/.agents/RESILIENCE.md +0 -235
- package/.agents/ROUTING.md +0 -605
- package/.agents/SCALE_OUT.md +0 -109
- package/.agents/SECRETS.md +0 -117
- package/.agents/SERVICES.md +0 -341
- package/.agents/SHUTDOWN.md +0 -74
- package/.agents/STREAMING.md +0 -108
- package/.agents/WORKFLOW.md +0 -27
- package/.agents/internal/DOCUMENTATION_REVIEW.md +0 -485
- package/.agents/internal/TECHNICAL_REVIEW.md +0 -428
- package/.agents/skills/webspresso-admin-and-plugins/SKILL.md +0 -122
- package/.agents/skills/webspresso-framework/SKILL.md +0 -89
- package/.agents/skills/webspresso-orm-and-database/SKILL.md +0 -127
- package/.agents/skills/webspresso-routing-and-api/SKILL.md +0 -130
- package/.agents/skills/webspresso-services/SKILL.md +0 -134
- package/.cursorrules +0 -14
- package/AGENTS.md +0 -203
- package/CLAUDE.md +0 -54
- package/core/kernel/run-demo.js +0 -58
- package/plugins/admin-panel/styles.js +0 -9
- package/plugins/data-exchange/export-xlsx.js +0 -119
- package/src/client-runtime/bootstrap-alpine-swup.js +0 -34
package/.agents/AUTH.md
DELETED
|
@@ -1,581 +0,0 @@
|
|
|
1
|
-
# Webspresso Dual Authentication Architecture
|
|
2
|
-
|
|
3
|
-
[← Back to AGENTS.md](.agents/AGENTS.md)
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## 1. Overview
|
|
8
|
-
|
|
9
|
-
Webspresso provides a zero-dependency **Dual Authentication** system (`webspresso/core/auth` — resolved via package exports, no `/index.js` suffix required):
|
|
10
|
-
- **Stateful Session + Cookie**: Used for browser SSR routes and Admin Panel (`/`, `/_admin`).
|
|
11
|
-
- **Stateless HS256 JWT + Refresh Tokens**: Used for REST APIs, Mobile Apps, and SPAs (`/api/*`).
|
|
12
|
-
|
|
13
|
-
---
|
|
14
|
-
|
|
15
|
-
## ⚠️ STRICT RULE: Use Native Dual Auth (NO External JWT/Passport Packages)
|
|
16
|
-
|
|
17
|
-
- **NEVER** install `jsonwebtoken`, `bcryptjs`, `passport`, or `express-session`.
|
|
18
|
-
- **ALWAYS** use Webspresso's native `req.auth` and `webspresso/core/auth`:
|
|
19
|
-
- Session login: `await req.auth.attempt(email, password, { remember: true })`
|
|
20
|
-
- Stateless JWT generation: `req.auth.generateUserToken(user)`
|
|
21
|
-
- Refresh Tokens: `req.auth.generateRefreshToken(user)` / `req.auth.refreshAccessToken(token)`
|
|
22
|
-
- Route Guards: `middleware: ['auth']` (web session) or `middleware: ['jwt']` (API Bearer token)
|
|
23
|
-
|
|
24
|
-
---
|
|
25
|
-
|
|
26
|
-
## 2. Token Generation & Rotation
|
|
27
|
-
|
|
28
|
-
- **Access Token**: Short-lived HS256 JWT token generated via `req.auth.generateUserToken(user, options)`. Default duration is `15m` (configurable).
|
|
29
|
-
- **Refresh Token**: Long-lived HS256 JWT token generated via `req.auth.generateRefreshToken(user, options)` with cryptographically unique `jti` nonces. Default duration is `30d` (configurable).
|
|
30
|
-
- **Token Rotation**: `req.auth.refreshAccessToken(refreshToken, { rotate: true })` verifies the refresh token and generates a new Access Token alongside a rotated Refresh Token pair.
|
|
31
|
-
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
## 3. Request-Bound Auth Helper (`req.auth`)
|
|
35
|
-
|
|
36
|
-
Attached to Express request during auth middleware execution:
|
|
37
|
-
|
|
38
|
-
| Method | Description |
|
|
39
|
-
|--------|-------------|
|
|
40
|
-
| `req.auth.attempt(identifier, password, { remember })` | Authenticate user with credentials and login |
|
|
41
|
-
| `req.auth.login(user, { remember })` | Log in user and establish session |
|
|
42
|
-
| `req.auth.logout({ everywhere })` | Log out user and destroy session |
|
|
43
|
-
| `req.auth.generateUserToken(user, options)` | Generate short-lived JWT Access Token |
|
|
44
|
-
| `req.auth.generateRefreshToken(user, options)` | Generate long-lived JWT Refresh Token |
|
|
45
|
-
| `req.auth.refreshAccessToken(refreshToken, options)` | Refresh access token & rotate refresh token |
|
|
46
|
-
| `req.auth.check()` / `req.auth.guest()` | Check if user is authenticated or guest |
|
|
47
|
-
| `req.auth.user()` / `req.auth.id()` | Get current user object or ID |
|
|
48
|
-
| `req.auth.sessions()` | List active sessions & device info for current user |
|
|
49
|
-
| `req.auth.revokeSession(sessionId)` | Revoke a specific session (remotely log out device) |
|
|
50
|
-
| `req.auth.revokeOtherSessions()` | Revoke all sessions except the current active session |
|
|
51
|
-
| `req.auth.revokeAllSessions(userId?)` | Revoke all active sessions (force logout from all devices) |
|
|
52
|
-
|
|
53
|
-
---
|
|
54
|
-
|
|
55
|
-
## 4. File-Based API Route Examples (`pages/api/*`)
|
|
56
|
-
|
|
57
|
-
### 4.1 Login & Token Generation (`pages/api/auth/login.post.js`)
|
|
58
|
-
```javascript
|
|
59
|
-
module.exports = {
|
|
60
|
-
schema: ({ z }) => ({
|
|
61
|
-
body: z.object({
|
|
62
|
-
email: z.string().email(),
|
|
63
|
-
password: z.string().min(1),
|
|
64
|
-
}),
|
|
65
|
-
}),
|
|
66
|
-
async handler(req, res) {
|
|
67
|
-
const { email, password } = req.input.body;
|
|
68
|
-
const user = await req.auth.attempt(email, password);
|
|
69
|
-
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
|
|
70
|
-
|
|
71
|
-
const accessToken = req.auth.generateUserToken(user);
|
|
72
|
-
const refreshToken = req.auth.generateRefreshToken(user);
|
|
73
|
-
|
|
74
|
-
return res.json({ accessToken, refreshToken, user: { id: user.id, email: user.email } });
|
|
75
|
-
},
|
|
76
|
-
};
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
### 4.2 Token Refresh Endpoint (`pages/api/auth/refresh.post.js`)
|
|
80
|
-
```javascript
|
|
81
|
-
module.exports = {
|
|
82
|
-
schema: ({ z }) => ({
|
|
83
|
-
body: z.object({
|
|
84
|
-
refreshToken: z.string(),
|
|
85
|
-
}),
|
|
86
|
-
}),
|
|
87
|
-
async handler(req, res) {
|
|
88
|
-
const { refreshToken } = req.input.body;
|
|
89
|
-
try {
|
|
90
|
-
const result = await req.auth.refreshAccessToken(refreshToken, { rotate: true });
|
|
91
|
-
return res.json({ accessToken: result.accessToken, refreshToken: result.refreshToken });
|
|
92
|
-
} catch (err) {
|
|
93
|
-
return res.status(401).json({ error: err.message });
|
|
94
|
-
}
|
|
95
|
-
},
|
|
96
|
-
};
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
### 4.3 Protected API Route (`pages/api/profile.get.js`)
|
|
100
|
-
```javascript
|
|
101
|
-
module.exports = {
|
|
102
|
-
middleware: ['jwt'],
|
|
103
|
-
async handler(req, res) {
|
|
104
|
-
return res.json({ user: req.user, token: req.token });
|
|
105
|
-
},
|
|
106
|
-
};
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
---
|
|
110
|
-
|
|
111
|
-
## 5. Zero-Dependency OAuth 2.0 & Social Login (`plugins/oauth`, `core/auth/oauth`)
|
|
112
|
-
|
|
113
|
-
Webspresso includes a built-in, zero-dependency OAuth 2.0 client and plugin with RFC 7636 PKCE, HMAC-SHA256 signed anti-CSRF state tokens, profile normalization, and seamless Dual Auth integration:
|
|
114
|
-
|
|
115
|
-
### 5.1 Plugin Configuration
|
|
116
|
-
```javascript
|
|
117
|
-
const { createApp, oauthPlugin } = require('webspresso');
|
|
118
|
-
|
|
119
|
-
const app = createApp({
|
|
120
|
-
plugins: [
|
|
121
|
-
oauthPlugin({
|
|
122
|
-
secret: process.env.SESSION_SECRET,
|
|
123
|
-
providers: {
|
|
124
|
-
google: {
|
|
125
|
-
clientId: process.env.GOOGLE_CLIENT_ID,
|
|
126
|
-
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
|
127
|
-
// redirectUri is optional; auto-inferred from request host if omitted
|
|
128
|
-
},
|
|
129
|
-
github: {
|
|
130
|
-
clientId: process.env.GITHUB_CLIENT_ID,
|
|
131
|
-
clientSecret: process.env.GITHUB_CLIENT_SECRET,
|
|
132
|
-
},
|
|
133
|
-
},
|
|
134
|
-
// Optional hook to find or create the user in your database
|
|
135
|
-
async findOrCreateUser({ provider, profile, tokens, db }) {
|
|
136
|
-
let user = await db.getRepository('User').findOne({ email: profile.email });
|
|
137
|
-
if (!user) {
|
|
138
|
-
user = await db.getRepository('User').create({
|
|
139
|
-
email: profile.email,
|
|
140
|
-
name: profile.name,
|
|
141
|
-
avatar_url: profile.avatarUrl,
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
return user;
|
|
145
|
-
},
|
|
146
|
-
defaultReturnTo: '/dashboard',
|
|
147
|
-
}),
|
|
148
|
-
],
|
|
149
|
-
});
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
### 5.2 Automatic Routes
|
|
153
|
-
- `GET /auth/:provider` (e.g. `/auth/google?returnTo=/dashboard`): Generates PKCE code challenge and HMAC-signed state token with embedded return URL, redirecting the browser to the provider's authorization page.
|
|
154
|
-
- `GET /auth/:provider/callback`: Validates anti-CSRF state, exchanges authorization code for tokens, fetches normalized profile, calls `findOrCreateUser`, automatically establishes session via `req.auth.login(user)`, and redirects to `returnTo`. For API/mobile clients (`format=json` or `Accept: application/json`), returns `{ success: true, user, token }`.
|
|
155
|
-
|
|
156
|
-
### 5.3 Template Helper (`fsy.oauthUrl`)
|
|
157
|
-
In Nunjucks templates:
|
|
158
|
-
```html
|
|
159
|
-
<a href="{{ fsy.oauthUrl('google') }}" class="btn">Sign in with Google</a>
|
|
160
|
-
<a href="{{ fsy.oauthUrl('github', { returnTo: '/settings' }) }}" class="btn">Connect GitHub</a>
|
|
161
|
-
```
|
|
162
|
-
|
|
163
|
-
---
|
|
164
|
-
|
|
165
|
-
## 6. Zero-Dependency Two-Factor Authentication (2FA / TOTP)
|
|
166
|
-
|
|
167
|
-
Webspresso provides an enterprise-grade, zero-dependency 2FA/TOTP suite adhering strictly to **RFC 6238 (TOTP)**, **RFC 4226 (HOTP)**, and **RFC 4648 (Base32)**. It requires NO external npm libraries and features offline SVG QR code generation to prevent leaking secret keys to third-party APIs.
|
|
168
|
-
|
|
169
|
-
### 6.1 Key Capabilities
|
|
170
|
-
- **RFC 6238 Time-Based OTP**: Standard 30s step, 6/8 digits, HMAC-SHA1/SHA256/SHA512.
|
|
171
|
-
- **Time Drift Tolerance**: Built-in clock drift window (`window: 1` verifies $t \pm 30s$) and detailed delta analysis.
|
|
172
|
-
- **Offline QR Code Generator**: Generates crisp vector SVG strings and data URIs directly in pure Node.js.
|
|
173
|
-
- **Single-Use Recovery Codes**: Cryptographically secure alphanumeric codes, SHA-256 hashed storage, and timing-safe single-use burning.
|
|
174
|
-
- **Session & Guard Integration**: `req.auth.verify2Fa()`, `req.auth.is2FaVerified()`, and `middleware: ['2fa']`.
|
|
175
|
-
|
|
176
|
-
### 6.2 Initializing 2FA Setup for a User
|
|
177
|
-
```javascript
|
|
178
|
-
const { totp } = require('webspresso');
|
|
179
|
-
|
|
180
|
-
// In an API route: POST /api/user/2fa/setup
|
|
181
|
-
module.exports = {
|
|
182
|
-
middleware: ['auth'],
|
|
183
|
-
async handler(req, res) {
|
|
184
|
-
const setup = totp.createTotpSetup({
|
|
185
|
-
user: req.user,
|
|
186
|
-
issuer: 'My SaaS App',
|
|
187
|
-
recoveryCodeCount: 8,
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
// 1. Temporarily save secret and hashed recovery codes to DB for confirmation
|
|
191
|
-
await req.db.getRepository('User').update(req.user.id, {
|
|
192
|
-
temp_totp_secret: setup.secret,
|
|
193
|
-
temp_recovery_codes: JSON.stringify(setup.recoveryCodesHashed),
|
|
194
|
-
});
|
|
195
|
-
|
|
196
|
-
// 2. Return QR SVG and plaintext recovery codes for user to record
|
|
197
|
-
return res.json({
|
|
198
|
-
secret: setup.secret,
|
|
199
|
-
qrSvg: setup.qrSvg,
|
|
200
|
-
qrDataUri: setup.qrDataUri,
|
|
201
|
-
recoveryCodes: setup.recoveryCodes,
|
|
202
|
-
});
|
|
203
|
-
},
|
|
204
|
-
};
|
|
205
|
-
```
|
|
206
|
-
|
|
207
|
-
### 6.3 Confirming 2FA Activation
|
|
208
|
-
```javascript
|
|
209
|
-
// In an API route: POST /api/user/2fa/confirm
|
|
210
|
-
module.exports = {
|
|
211
|
-
middleware: ['auth'],
|
|
212
|
-
schema: ({ z }) => ({
|
|
213
|
-
body: z.object({ token: z.string().min(6).max(8) }),
|
|
214
|
-
}),
|
|
215
|
-
async handler(req, res) {
|
|
216
|
-
const user = req.user;
|
|
217
|
-
const { token } = req.input.body;
|
|
218
|
-
|
|
219
|
-
const isValid = totp.verifyTotp(token, user.temp_totp_secret);
|
|
220
|
-
if (!isValid) {
|
|
221
|
-
return res.status(400).json({ error: 'Invalid verification code' });
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Activate 2FA on user record
|
|
225
|
-
await req.db.getRepository('User').update(user.id, {
|
|
226
|
-
two_factor_enabled: true,
|
|
227
|
-
totp_secret: user.temp_totp_secret,
|
|
228
|
-
recovery_codes: user.temp_recovery_codes,
|
|
229
|
-
temp_totp_secret: null,
|
|
230
|
-
temp_recovery_codes: null,
|
|
231
|
-
});
|
|
232
|
-
|
|
233
|
-
req.auth.set2FaVerified(true);
|
|
234
|
-
return res.json({ success: true, message: '2FA enabled successfully' });
|
|
235
|
-
},
|
|
236
|
-
};
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
### 6.4 2FA Login Flow & Guard Middleware
|
|
240
|
-
```javascript
|
|
241
|
-
// Step 1: Initial password login
|
|
242
|
-
const user = await req.auth.findUserByCredentials(email, password);
|
|
243
|
-
if (user.two_factor_enabled) {
|
|
244
|
-
// Mark session as 2FA pending without full login
|
|
245
|
-
req.auth.set2FaPending(user);
|
|
246
|
-
return res.json({ require2Fa: true });
|
|
247
|
-
}
|
|
248
|
-
await req.auth.login(user);
|
|
249
|
-
|
|
250
|
-
// Step 2: 2FA Verification Endpoint (accepts 6-digit TOTP token OR recovery code)
|
|
251
|
-
const verification = req.auth.verify2Fa(tokenOrRecoveryCode, user);
|
|
252
|
-
if (verification.success) {
|
|
253
|
-
if (verification.type === 'recovery_code') {
|
|
254
|
-
// Burn used recovery code
|
|
255
|
-
await req.db.getRepository('User').update(user.id, {
|
|
256
|
-
recovery_codes: JSON.stringify(verification.remainingHashedCodes),
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
await req.auth.login(user);
|
|
260
|
-
req.auth.set2FaVerified(true);
|
|
261
|
-
return res.json({ success: true });
|
|
262
|
-
}
|
|
263
|
-
```
|
|
264
|
-
|
|
265
|
-
### 6.5 Route Protection with `middleware: ['2fa']`
|
|
266
|
-
```javascript
|
|
267
|
-
// In pages/api/account/billing.get.js or pages/security/index.njk
|
|
268
|
-
module.exports = {
|
|
269
|
-
middleware: ['auth', '2fa'], // Rejects unverified users with 403 or redirects to /2fa
|
|
270
|
-
async handler(req, res) {
|
|
271
|
-
return res.json({ secureData: true });
|
|
272
|
-
},
|
|
273
|
-
};
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
---
|
|
277
|
-
|
|
278
|
-
## 7. Magic Link & Passwordless Authentication
|
|
279
|
-
|
|
280
|
-
Webspresso includes zero-dependency, cryptographically secure **Magic Link / Passwordless Authentication**:
|
|
281
|
-
- **Single-Use Timed Tokens**: 32-byte cryptographically secure random tokens stored hashed (`SHA-256`) in the `auth_tokens` table (`type = 'magic_link'`) with a default 15-minute TTL.
|
|
282
|
-
- **Anti-Enumeration Protection**: `requestMagicLink` returns `{ sent: true, userFound: false }` for unknown emails by default so attackers cannot probe user existence.
|
|
283
|
-
- **Auto-Verification**: Successfully signing in via a magic link automatically marks `email_verified_at` if the user is not yet verified.
|
|
284
|
-
- **Dual Session & JWT Support**: Seamlessly establishes web sessions (`req.auth.login`) and/or issues JWT access/refresh token pairs.
|
|
285
|
-
- **Native Email Plugin Integration**: Built-in `auth-magic-link` MJML template, automated delivery via `plugins/email`'s `wireAuthEmails`, and pre-wired `/api/auth/magic-link` routes.
|
|
286
|
-
|
|
287
|
-
### 7.1 Setup in `quickAuth`
|
|
288
|
-
```javascript
|
|
289
|
-
const { quickAuth } = require('webspresso/core/auth');
|
|
290
|
-
|
|
291
|
-
const auth = quickAuth({
|
|
292
|
-
db,
|
|
293
|
-
userModel: 'User',
|
|
294
|
-
identifierField: 'email',
|
|
295
|
-
magicLink: true, // Automatically provisions Knex auth_tokens adapter
|
|
296
|
-
});
|
|
297
|
-
```
|
|
298
|
-
|
|
299
|
-
### 7.2 Requesting a Magic Link (`pages/api/auth/magic-link.post.js`)
|
|
300
|
-
```javascript
|
|
301
|
-
const { defineApi } = require('webspresso');
|
|
302
|
-
|
|
303
|
-
module.exports = defineApi({
|
|
304
|
-
schema: ({ z }) => ({
|
|
305
|
-
body: z.object({
|
|
306
|
-
email: z.string().email(),
|
|
307
|
-
}),
|
|
308
|
-
}),
|
|
309
|
-
async handler(req, res) {
|
|
310
|
-
const { email } = req.input.body;
|
|
311
|
-
|
|
312
|
-
// Dispatches email notification via plugins/email (if active)
|
|
313
|
-
await req.auth.requestMagicLink(email, {
|
|
314
|
-
tokenTtlMs: 15 * 60 * 1000, // 15 mins (default)
|
|
315
|
-
path: '/auth/magic-link/verify',
|
|
316
|
-
});
|
|
317
|
-
|
|
318
|
-
return res.json({
|
|
319
|
-
ok: true,
|
|
320
|
-
message: 'If an account exists with this email, a sign-in link has been sent.',
|
|
321
|
-
});
|
|
322
|
-
},
|
|
323
|
-
});
|
|
324
|
-
```
|
|
325
|
-
|
|
326
|
-
### 7.3 Verifying & Logging In (`pages/api/auth/magic-link/verify.get.js`)
|
|
327
|
-
```javascript
|
|
328
|
-
const { defineApi } = require('webspresso');
|
|
329
|
-
|
|
330
|
-
module.exports = defineApi({
|
|
331
|
-
schema: ({ z }) => ({
|
|
332
|
-
query: z.object({
|
|
333
|
-
token: z.string().min(1),
|
|
334
|
-
}),
|
|
335
|
-
}),
|
|
336
|
-
async handler(req, res) {
|
|
337
|
-
const { token } = req.input.query;
|
|
338
|
-
|
|
339
|
-
// Verifies token, consumes it, marks email verified, logs into session and/or generates JWTs
|
|
340
|
-
const result = await req.auth.loginWithMagicLink(token, {
|
|
341
|
-
remember: true,
|
|
342
|
-
jwt: false, // Set to true to receive accessToken and refreshToken
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
// For browser requests, redirect to dashboard:
|
|
346
|
-
if (req.accepts('html')) {
|
|
347
|
-
return res.redirect('/dashboard');
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
return res.json({ ok: true, user: result.user });
|
|
351
|
-
},
|
|
352
|
-
});
|
|
353
|
-
```
|
|
354
|
-
|
|
355
|
-
### 7.4 Using Built-in Route Middlewares
|
|
356
|
-
You can also mount Webspresso's pre-configured Express middlewares directly:
|
|
357
|
-
```javascript
|
|
358
|
-
const {
|
|
359
|
-
createMagicLinkRequestHandler,
|
|
360
|
-
createMagicLinkVerifyMiddleware,
|
|
361
|
-
} = require('webspresso/core/auth');
|
|
362
|
-
|
|
363
|
-
// Request link: POST /auth/magic-link
|
|
364
|
-
app.post('/auth/magic-link', createMagicLinkRequestHandler(authManager));
|
|
365
|
-
|
|
366
|
-
// Verify & Login: GET /auth/magic-link/verify
|
|
367
|
-
app.get('/auth/magic-link/verify', createMagicLinkVerifyMiddleware(authManager, {
|
|
368
|
-
redirectTo: '/dashboard',
|
|
369
|
-
failureRedirect: '/login?error=invalid_magic_link',
|
|
370
|
-
jwt: false,
|
|
371
|
-
}));
|
|
372
|
-
```
|
|
373
|
-
|
|
374
|
-
### 7.5 AuthManager Magic Link Events
|
|
375
|
-
`AuthManager` extends `EventEmitter`, allowing you to hook into magic link lifecycle events:
|
|
376
|
-
```javascript
|
|
377
|
-
authManager.on('magicLink:requested', ({ userId, email, expiresAt }) => {
|
|
378
|
-
console.log(`Magic link requested for ${email}, expires at ${expiresAt}`);
|
|
379
|
-
});
|
|
380
|
-
|
|
381
|
-
authManager.on('magicLink:verified', ({ userId }) => {
|
|
382
|
-
console.log(`User ${userId} signed in via magic link`);
|
|
383
|
-
});
|
|
384
|
-
```
|
|
385
|
-
|
|
386
|
-
---
|
|
387
|
-
|
|
388
|
-
## 8. Active Devices & Remote Session Revocation
|
|
389
|
-
|
|
390
|
-
Webspresso provides a zero-dependency session management and device tracking system (`webspresso/core/auth`) allowing users to view all active logins, detect browser/OS/hardware types, and remotely revoke unwanted sessions.
|
|
391
|
-
|
|
392
|
-
### 8.1 Database Migration
|
|
393
|
-
Create the `user_sessions` table using the built-in migration helper:
|
|
394
|
-
```javascript
|
|
395
|
-
const { createUserSessionsTable } = require('webspresso/core/auth');
|
|
396
|
-
|
|
397
|
-
exports.up = async function(knex) {
|
|
398
|
-
await createUserSessionsTable(knex);
|
|
399
|
-
};
|
|
400
|
-
|
|
401
|
-
exports.down = async function(knex) {
|
|
402
|
-
const { dropUserSessionsTable } = require('webspresso/core/auth');
|
|
403
|
-
await dropUserSessionsTable(knex);
|
|
404
|
-
};
|
|
405
|
-
```
|
|
406
|
-
|
|
407
|
-
Schema columns:
|
|
408
|
-
- `id`: Bigint primary key
|
|
409
|
-
- `session_id`: Unique Express session ID
|
|
410
|
-
- `user_id`: User ID reference
|
|
411
|
-
- `ip_address`: Proxy-safe client IP (`x-forwarded-for`, `x-real-ip`, or socket)
|
|
412
|
-
- `user_agent`: Raw User-Agent string
|
|
413
|
-
- `browser`: Detected browser and version (e.g. `Chrome 128`, `Safari 17`, `Firefox 125`, `Edge 122`)
|
|
414
|
-
- `os`: Detected operating system (e.g. `macOS 14`, `Windows 10/11`, `iOS 17.4`, `Android 14`, `Ubuntu Linux`)
|
|
415
|
-
- `device`: Device form factor (`desktop`, `mobile`, `tablet`, `bot`)
|
|
416
|
-
- `last_active_at`: Last seen timestamp (throttled to 60s by default to protect DB performance)
|
|
417
|
-
- `created_at`: Initial login timestamp
|
|
418
|
-
|
|
419
|
-
### 8.2 Enabling Session Tracking
|
|
420
|
-
Enable session tracking in `createAuth` or `quickAuth`:
|
|
421
|
-
```javascript
|
|
422
|
-
const { quickAuth } = require('webspresso/core/auth');
|
|
423
|
-
|
|
424
|
-
const auth = quickAuth({
|
|
425
|
-
db,
|
|
426
|
-
sessionTracking: true, // Automatically enables Knex session tracker and active session verification
|
|
427
|
-
});
|
|
428
|
-
```
|
|
429
|
-
|
|
430
|
-
Or manually with custom options:
|
|
431
|
-
```javascript
|
|
432
|
-
const { createAuth, createKnexSessionTracker } = require('webspresso/core/auth');
|
|
433
|
-
|
|
434
|
-
const auth = createAuth({
|
|
435
|
-
db,
|
|
436
|
-
sessionTracking: true,
|
|
437
|
-
sessionTracker: createKnexSessionTracker(db),
|
|
438
|
-
sessionTouchThrottleMs: 60000, // Touch session at most once per minute
|
|
439
|
-
// ...other config
|
|
440
|
-
});
|
|
441
|
-
```
|
|
442
|
-
|
|
443
|
-
### 8.3 File-Based API Routes (`pages/api/*`)
|
|
444
|
-
|
|
445
|
-
#### List Active Devices (`pages/api/auth/sessions.get.js`)
|
|
446
|
-
```javascript
|
|
447
|
-
const { defineApi } = require('webspresso');
|
|
448
|
-
|
|
449
|
-
module.exports = defineApi({
|
|
450
|
-
middleware: ['auth'],
|
|
451
|
-
async handler(req, res) {
|
|
452
|
-
// Returns array of active sessions with is_current flag for current device
|
|
453
|
-
const sessions = await req.auth.sessions();
|
|
454
|
-
return res.json({ ok: true, sessions });
|
|
455
|
-
},
|
|
456
|
-
});
|
|
457
|
-
```
|
|
458
|
-
|
|
459
|
-
#### Revoke Session / Remote Logout (`pages/api/auth/sessions/revoke.post.js`)
|
|
460
|
-
```javascript
|
|
461
|
-
const { defineApi } = require('webspresso');
|
|
462
|
-
|
|
463
|
-
module.exports = defineApi({
|
|
464
|
-
middleware: ['auth'],
|
|
465
|
-
schema: ({ z }) => ({
|
|
466
|
-
body: z.object({
|
|
467
|
-
sessionId: z.string().optional(),
|
|
468
|
-
allOthers: z.boolean().optional(),
|
|
469
|
-
}),
|
|
470
|
-
}),
|
|
471
|
-
async handler(req, res) {
|
|
472
|
-
const { sessionId, allOthers } = req.input.body;
|
|
473
|
-
|
|
474
|
-
if (allOthers) {
|
|
475
|
-
// Revokes all sessions except current device
|
|
476
|
-
const count = await req.auth.revokeOtherSessions();
|
|
477
|
-
return res.json({ ok: true, revokedCount: count, message: 'All other sessions revoked' });
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
if (sessionId) {
|
|
481
|
-
// Revokes specified session (logs out current user if it is the current session)
|
|
482
|
-
await req.auth.revokeSession(sessionId);
|
|
483
|
-
return res.json({ ok: true, message: 'Session revoked' });
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
return res.status(400).json({ error: 'sessionId or allOthers is required' });
|
|
487
|
-
},
|
|
488
|
-
});
|
|
489
|
-
```
|
|
490
|
-
|
|
491
|
-
### 8.4 Automatic Invalidation in Middleware
|
|
492
|
-
When a session is revoked remotely, Webspresso's `authenticate` middleware automatically detects it on the next incoming request from that device:
|
|
493
|
-
- The revoked session is destroyed in `req.sessionStore`.
|
|
494
|
-
- `req.user` is set to `null`.
|
|
495
|
-
- Any subsequent `requireAuth` or `middleware: ['auth']` guard immediately redirects or rejects the request with `401 Unauthorized`.
|
|
496
|
-
|
|
497
|
-
### 8.5 Session Lifecycle Events
|
|
498
|
-
`AuthManager` emits EventEmitter events for monitoring and security audits:
|
|
499
|
-
```javascript
|
|
500
|
-
auth.on('session:created', ({ sessionId, userId, ip, browser, os, device }) => {
|
|
501
|
-
console.log(`New session created for user ${userId} from ${device} (${browser} on ${os}) at ${ip}`);
|
|
502
|
-
});
|
|
503
|
-
|
|
504
|
-
auth.on('session:revoked', ({ sessionId, userId, revokedBy }) => {
|
|
505
|
-
console.log(`Session ${sessionId} was revoked`);
|
|
506
|
-
});
|
|
507
|
-
|
|
508
|
-
auth.on('sessions:revoked_others', ({ userId, currentSessionId, count }) => {
|
|
509
|
-
console.log(`User ${userId} revoked ${count} other sessions`);
|
|
510
|
-
});
|
|
511
|
-
|
|
512
|
-
auth.on('sessions:revoked_all', ({ userId, count }) => {
|
|
513
|
-
console.log(`All ${count} sessions revoked for user ${userId}`);
|
|
514
|
-
});
|
|
515
|
-
```
|
|
516
|
-
|
|
517
|
-
---
|
|
518
|
-
|
|
519
|
-
## 9. Authorization & Policies (AdonisJS Bouncer & Django Permissions-inspired)
|
|
520
|
-
|
|
521
|
-
Webspresso provides an authorization layer combining AdonisJS Bouncer policies/gates with Django-style permission matrices and superuser bypass:
|
|
522
|
-
|
|
523
|
-
### 9.1 Defining Policies & Gates
|
|
524
|
-
Define domain policies and simple gates using `definePolicy` and `defineGate`:
|
|
525
|
-
|
|
526
|
-
```javascript
|
|
527
|
-
const { definePolicy, defineGate } = require('webspresso');
|
|
528
|
-
|
|
529
|
-
// 1. Resource Policy
|
|
530
|
-
definePolicy('Post', {
|
|
531
|
-
view: (user, post) => true,
|
|
532
|
-
update: (user, post) => user && (user.id === post.user_id || user.role === 'admin'),
|
|
533
|
-
delete: (user, post) => user && user.role === 'admin',
|
|
534
|
-
});
|
|
535
|
-
|
|
536
|
-
// 2. Named Gate
|
|
537
|
-
defineGate('admin-only', (user) => Boolean(user && user.role === 'admin'));
|
|
538
|
-
```
|
|
539
|
-
|
|
540
|
-
### 9.2 Request Bouncer (`req.bouncer`)
|
|
541
|
-
Incoming requests automatically receive `req.bouncer` bound to `req.user`:
|
|
542
|
-
|
|
543
|
-
```javascript
|
|
544
|
-
// Inside API Route or Loader:
|
|
545
|
-
if (req.bouncer.allows('Post.update', post)) {
|
|
546
|
-
// Authorized
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
if (req.bouncer.denies('admin-only')) {
|
|
550
|
-
// Denied
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
// Throws ForbiddenError (403) or UnauthorizedError (401) on failure:
|
|
554
|
-
req.bouncer.authorize('Post.update', post);
|
|
555
|
-
|
|
556
|
-
// Inline rule check:
|
|
557
|
-
req.bouncer.authorize((user) => user.isVip);
|
|
558
|
-
```
|
|
559
|
-
|
|
560
|
-
### 9.3 Django Permissions Matrix & Superuser Bypass
|
|
561
|
-
Users with permissions arrays or superuser flags are evaluated automatically:
|
|
562
|
-
- `user.permissions = ['post.create', 'post.update']`
|
|
563
|
-
- Wildcards: `user.permissions = ['post.*']` or `['*']`
|
|
564
|
-
- Django Superuser: `user.isSuperuser = true` or `user.is_superuser = true` automatically bypasses all permission checks.
|
|
565
|
-
- Custom methods: `user.hasPerm(perm, resource)` or `user.hasPermission(...)`.
|
|
566
|
-
|
|
567
|
-
### 9.4 Nunjucks Template Helpers (`fsy.can`, `fsy.cannot`)
|
|
568
|
-
Check permissions directly in `.njk` templates:
|
|
569
|
-
|
|
570
|
-
```jinja
|
|
571
|
-
{% if fsy.can('Post.update', post) %}
|
|
572
|
-
<a href="/posts/{{ post.id }}/edit" class="btn">Edit Post</a>
|
|
573
|
-
{% endif %}
|
|
574
|
-
|
|
575
|
-
{% if fsy.cannot('admin-only') %}
|
|
576
|
-
<p class="text-muted">Admin access required</p>
|
|
577
|
-
{% endif %}
|
|
578
|
-
```
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|