@astratra/saas-kit 1.6.0 → 1.7.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/LICENSE +1 -1
- package/README.md +24 -0
- package/package.json +1 -1
- package/src/app.js +22 -3
- package/src/index.d.ts +16 -0
- package/src/modules/auth.js +23 -10
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -90,6 +90,30 @@ L'app retournée expose aussi directement `app.authMiddleware`,
|
|
|
90
90
|
`app.csrfMiddleware` et `app.authorizeAdmin`, au cas où tu préfères les
|
|
91
91
|
monter toi-même après coup plutôt que via `extendRoutes`.
|
|
92
92
|
|
|
93
|
+
### Ouvrir une session depuis ta propre route (Google, Apple, invitation)
|
|
94
|
+
|
|
95
|
+
Quand ta route a prouvé l'identité elle-même (jeton d'identité vérifié par
|
|
96
|
+
`createGoogleIdTokenVerifier` de `@astratra/security`, invitation acceptée),
|
|
97
|
+
`issueSession(res, compte)` ouvre **exactement** la session de `/auth/login` :
|
|
98
|
+
même jeton d'accès, même cookie `HttpOnly`, même chaîne de renouvellement.
|
|
99
|
+
Une seule fabrique, pour que les deux portes ne divergent jamais.
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
createSaasApp({
|
|
103
|
+
// ...
|
|
104
|
+
extendRoutes: (app, { issueSession }) => {
|
|
105
|
+
app.post('/auth/external/google', async (req, res) => {
|
|
106
|
+
const profile = await google(req.body.idToken);
|
|
107
|
+
const account = await accounts.findBySubject('google', profile.subject);
|
|
108
|
+
if (!account) return res.status(403).json({ code: 'not_invited' });
|
|
109
|
+
res.json(await issueSession(res, account)); // { token, user, refreshToken? }
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Elle est aussi exposée en `app.issueSession`.
|
|
116
|
+
|
|
93
117
|
## CORS
|
|
94
118
|
|
|
95
119
|
`options.cors` active le CORS pour toute l'app en un seul champ de
|
package/package.json
CHANGED
package/src/app.js
CHANGED
|
@@ -198,11 +198,29 @@ function createSaasApp(options = {}) {
|
|
|
198
198
|
skip: (req) => isBearerAuthenticated(req) || (normalized.csrf && normalized.csrf.skip && normalized.csrf.skip(req))
|
|
199
199
|
});
|
|
200
200
|
|
|
201
|
-
|
|
201
|
+
/*
|
|
202
|
+
* Le limiteur de connexion ne compte que les routes où l'on devine un secret :
|
|
203
|
+
* la connexion et la réinitialisation du mot de passe. Monté sur tout /auth, il
|
|
204
|
+
* comptait aussi /auth/me et /auth/refresh, qu'une app appelle à chaque lancement :
|
|
205
|
+
* après une dizaine d'ouvertures, l'app restait bloquée (« Too many login attempts »).
|
|
206
|
+
*/
|
|
207
|
+
const LIMITED_AUTH_PATHS = new Set(['/login', '/forgot-password', '/reset-password']);
|
|
208
|
+
const userLoginSkip = normalized.loginRateLimit && normalized.loginRateLimit.skip;
|
|
209
|
+
const loginLimiter = createLoginLimiter({
|
|
210
|
+
...normalized.loginRateLimit,
|
|
211
|
+
skip: (req, res) => !(req.method === 'POST' && LIMITED_AUTH_PATHS.has(req.path))
|
|
212
|
+
|| Boolean(userLoginSkip && userLoginSkip(req, res))
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
const authRoutes = createAuthRoutes({
|
|
202
216
|
...normalized,
|
|
203
217
|
authMiddleware,
|
|
204
218
|
csrfMiddleware
|
|
205
|
-
})
|
|
219
|
+
});
|
|
220
|
+
app.use('/auth', loginLimiter, authRoutes);
|
|
221
|
+
/* Opens the same session as /auth/login for an identity the product proved
|
|
222
|
+
itself (Google, Apple, an invitation): one issuer, never a second one. */
|
|
223
|
+
const issueSession = authRoutes.issueSession;
|
|
206
224
|
|
|
207
225
|
app.use('/users', authMiddleware, csrfMiddleware, createUsersRoutes({
|
|
208
226
|
usersStore: normalized.usersStore,
|
|
@@ -228,6 +246,7 @@ function createSaasApp(options = {}) {
|
|
|
228
246
|
app.authMiddleware = authMiddleware;
|
|
229
247
|
app.csrfMiddleware = csrfMiddleware;
|
|
230
248
|
app.authorizeAdmin = authorizeAdmin;
|
|
249
|
+
app.issueSession = issueSession;
|
|
231
250
|
|
|
232
251
|
// createSaasApp() already terminates its own middleware stack with a
|
|
233
252
|
// catch-all 404 + error handler below. Any route registered on `app`
|
|
@@ -244,7 +263,7 @@ function createSaasApp(options = {}) {
|
|
|
244
263
|
// }
|
|
245
264
|
// });
|
|
246
265
|
if (typeof normalized.extendRoutes === 'function') {
|
|
247
|
-
normalized.extendRoutes(app, { authMiddleware, csrfMiddleware, authorizeAdmin, authorizeRoles });
|
|
266
|
+
normalized.extendRoutes(app, { authMiddleware, csrfMiddleware, authorizeAdmin, authorizeRoles, issueSession });
|
|
248
267
|
}
|
|
249
268
|
|
|
250
269
|
app.use(notFoundMiddleware);
|
package/src/index.d.ts
CHANGED
|
@@ -79,14 +79,30 @@ export interface SaasApp {
|
|
|
79
79
|
csrfMiddleware: RequestHandler;
|
|
80
80
|
/** authorizeRoles(...options.roles.adminRoles) — the exact admin-role guard used internally. */
|
|
81
81
|
authorizeAdmin: RequestHandler;
|
|
82
|
+
/** Opens the same session as /auth/login for an account the product proved itself. */
|
|
83
|
+
issueSession: IssueSession;
|
|
82
84
|
[key: string]: unknown;
|
|
83
85
|
}
|
|
84
86
|
|
|
87
|
+
/** The body /auth/login answers with. */
|
|
88
|
+
export interface IssuedSession {
|
|
89
|
+
token: string;
|
|
90
|
+
user: Record<string, unknown>;
|
|
91
|
+
refreshToken?: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Opens a session (access token, session cookie when `res` is given, refresh
|
|
96
|
+
* chain when enabled) for an account whose identity is already proven.
|
|
97
|
+
*/
|
|
98
|
+
export type IssueSession = (res: unknown, user: { id: unknown; [key: string]: unknown }) => Promise<IssuedSession>;
|
|
99
|
+
|
|
85
100
|
export interface ExtendRoutesContext {
|
|
86
101
|
authMiddleware: RequestHandler;
|
|
87
102
|
csrfMiddleware: RequestHandler;
|
|
88
103
|
authorizeAdmin: RequestHandler;
|
|
89
104
|
authorizeRoles: (...roles: string[]) => RequestHandler;
|
|
105
|
+
issueSession: IssueSession;
|
|
90
106
|
}
|
|
91
107
|
|
|
92
108
|
export interface CreateSaasAppOptions {
|
package/src/modules/auth.js
CHANGED
|
@@ -70,13 +70,15 @@ function createAuthRoutes(options) {
|
|
|
70
70
|
}
|
|
71
71
|
);
|
|
72
72
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
73
|
+
/**
|
|
74
|
+
* Open a session for an account whose identity is already proven — by the
|
|
75
|
+
* password here, or by the product's own route (an ID token from Google or
|
|
76
|
+
* Apple, an invitation). One function, so that every way in yields exactly
|
|
77
|
+
* the same session: same access token, same cookie, same refresh chain.
|
|
78
|
+
* Returns the body the login route answers with.
|
|
79
|
+
*/
|
|
80
|
+
async function issueSession(res, user) {
|
|
81
|
+
if (!user || user.id === undefined || user.id === null) throw new Error('issueSession requires an account with an id.');
|
|
80
82
|
const publicUser = pickPublicUser(user, publicUserFields);
|
|
81
83
|
|
|
82
84
|
/* A refresh token is issued only when the product asked for one. The web
|
|
@@ -90,13 +92,23 @@ function createAuthRoutes(options) {
|
|
|
90
92
|
/* The family id travels in the access token so that signing out can revoke
|
|
91
93
|
the refresh chain without the client having to hand it back. */
|
|
92
94
|
const token = signAccessToken(publicUser, refresh ? { rfid: refresh.familyId } : {});
|
|
93
|
-
setSessionCookie(res, token, cookieOptions);
|
|
95
|
+
if (res) setSessionCookie(res, token, cookieOptions);
|
|
94
96
|
|
|
95
|
-
return
|
|
97
|
+
return {
|
|
96
98
|
token,
|
|
97
99
|
user: publicUser,
|
|
98
100
|
...(refresh ? { refreshToken: refresh.token } : {})
|
|
99
|
-
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
router.post('/login', validateMiddleware(loginValidation), asyncHandler(async (req, res) => {
|
|
105
|
+
const user = await usersStore.findByEmail(req.body.email);
|
|
106
|
+
const valid = user ? await verifyPassword(user, req.body.password) : false;
|
|
107
|
+
if (!user || !valid) {
|
|
108
|
+
throw new AppError('Invalid credentials.', 401);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return apiResponse(res, 200, 'Login successful', await issueSession(res, user));
|
|
100
112
|
}));
|
|
101
113
|
|
|
102
114
|
if (refreshTokenService) {
|
|
@@ -253,6 +265,7 @@ function createAuthRoutes(options) {
|
|
|
253
265
|
}));
|
|
254
266
|
}
|
|
255
267
|
|
|
268
|
+
router.issueSession = issueSession;
|
|
256
269
|
return router;
|
|
257
270
|
}
|
|
258
271
|
|