@jskit-ai/auth-provider-local-core 0.2.25 → 0.2.27
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/CHANGELOG.md +5 -0
- package/locales/en.json +10 -0
- package/package.json +7 -6
- package/src/server/lib/config.js +46 -9
- package/src/server/lib/fileBackend.js +72 -3
- package/src/server/lib/fileRecords.js +56 -3
- package/src/server/lib/index.js +1 -0
- package/src/server/lib/oauthFlows.js +5 -2
- package/src/server/lib/secondFactor.js +408 -0
- package/src/server/lib/secondFactorCrypto.js +239 -0
- package/src/server/lib/securityStatus.js +11 -3
- package/src/server/lib/service.js +32 -3
- package/src/server/lib/sessions.js +21 -11
- package/src/server/lib/signInThrottle.js +34 -11
- package/src/server/providers/AuthLocalProvider.js +9 -3
- package/src/server/types.js +61 -3
- package/test/codedTexts.test.js +28 -0
- package/test/cookieSameSite.test.js +94 -0
- package/test/secondFactor.test.js +128 -0
- package/test-support/localService.js +3 -1
- package/test-support/oauthHarness.js +12 -5
- package/test-support/secondFactorScenario.js +262 -0
|
@@ -9,9 +9,22 @@ import { createFirstAccountSetup } from "./firstAccountSetup.js";
|
|
|
9
9
|
import { createLocalOAuthFlows } from "./oauthFlows.js";
|
|
10
10
|
import { createLocalPasswordFlows } from "./passwordFlows.js";
|
|
11
11
|
import { normalizePasswordStrategy } from "./passwords.js";
|
|
12
|
+
import { createLocalSecondFactor } from "./secondFactor.js";
|
|
12
13
|
import { createLocalSecurityStatus } from "./securityStatus.js";
|
|
13
14
|
import { createLocalSessions } from "./sessions.js";
|
|
14
15
|
|
|
16
|
+
// A production server without AUTH_LOCAL_SECOND_FACTOR_KEY has no second factor: each operation is unsupported.
|
|
17
|
+
const NO_SECOND_FACTOR = Object.freeze({
|
|
18
|
+
getSecondFactorStatus: () => throwUnsupportedAuthOperation("getSecondFactorStatus"),
|
|
19
|
+
startSecondFactorSetup: () => throwUnsupportedAuthOperation("startSecondFactorSetup"),
|
|
20
|
+
confirmSecondFactorSetup: () => throwUnsupportedAuthOperation("confirmSecondFactorSetup"),
|
|
21
|
+
verifySecondFactor: () => throwUnsupportedAuthOperation("verifySecondFactor"),
|
|
22
|
+
replaceSecondFactorRecoveryCodes: () => throwUnsupportedAuthOperation("replaceSecondFactorRecoveryCodes"),
|
|
23
|
+
removeSecondFactor: () => throwUnsupportedAuthOperation("removeSecondFactor"),
|
|
24
|
+
listSecondFactors: () => throwUnsupportedAuthOperation("listSecondFactors"),
|
|
25
|
+
resetSecondFactor: () => throwUnsupportedAuthOperation("resetSecondFactor")
|
|
26
|
+
});
|
|
27
|
+
|
|
15
28
|
/**
|
|
16
29
|
* The `auth.service` of local auth, from the collaborators its provider
|
|
17
30
|
* resolved once.
|
|
@@ -32,6 +45,8 @@ import { createLocalSessions } from "./sessions.js";
|
|
|
32
45
|
* `auth.profile.projector`, or noAppProfiles.
|
|
33
46
|
* @param {import("../types.js").AuthLocalRecoverySender} dependencies.recoverySender The
|
|
34
47
|
* `auth.local.recovery-sender`, or one made by createLoggedRecoverySender.
|
|
48
|
+
* @param {import("../types.js").AuthLocalSecondFactorEvents} dependencies.secondFactorEvents The
|
|
49
|
+
* `auth.local.second-factor-events`, or one made by createLoggedSecondFactorEvents.
|
|
35
50
|
*/
|
|
36
51
|
function createLocalAuthService({
|
|
37
52
|
backend,
|
|
@@ -43,7 +58,8 @@ function createLocalAuthService({
|
|
|
43
58
|
logger,
|
|
44
59
|
passwordStrategy,
|
|
45
60
|
profileProjector,
|
|
46
|
-
recoverySender
|
|
61
|
+
recoverySender,
|
|
62
|
+
secondFactorEvents
|
|
47
63
|
}) {
|
|
48
64
|
const passwords = normalizePasswordStrategy(passwordStrategy);
|
|
49
65
|
const firstAccountSetup = givenFirstAccountSetup ?? createFirstAccountSetup({ backend, config, logger });
|
|
@@ -86,7 +102,8 @@ function createLocalAuthService({
|
|
|
86
102
|
securityStatus: true,
|
|
87
103
|
signOutOtherSessions: true,
|
|
88
104
|
appProfileProjection,
|
|
89
|
-
devLoginAs: isDevAuthBootstrapEnabled(config.devAuth)
|
|
105
|
+
devLoginAs: isDevAuthBootstrapEnabled(config.devAuth),
|
|
106
|
+
secondFactor: Boolean(config.secondFactorKey)
|
|
90
107
|
}
|
|
91
108
|
});
|
|
92
109
|
// While the app has no account, its first one may register, and on a production server that asks for the setup code.
|
|
@@ -143,6 +160,10 @@ function createLocalAuthService({
|
|
|
143
160
|
sessions
|
|
144
161
|
});
|
|
145
162
|
|
|
163
|
+
const secondFactor = config.secondFactorKey
|
|
164
|
+
? createLocalSecondFactor({ backend, config, logger, secondFactorEvents, sessions })
|
|
165
|
+
: NO_SECOND_FACTOR;
|
|
166
|
+
|
|
146
167
|
function getCapabilities() {
|
|
147
168
|
if (firstAccountSetup.isWaiting()) {
|
|
148
169
|
return capabilitiesWaitingForFirstAccount;
|
|
@@ -206,7 +227,15 @@ function createLocalAuthService({
|
|
|
206
227
|
startProviderLink: oauthFlows.startProviderLink,
|
|
207
228
|
unlinkProvider: oauthFlows.unlinkProvider,
|
|
208
229
|
signOutOtherSessions: sessions.signOutOtherSessions,
|
|
209
|
-
logout: sessions.logout
|
|
230
|
+
logout: sessions.logout,
|
|
231
|
+
getSecondFactorStatus: secondFactor.getSecondFactorStatus,
|
|
232
|
+
startSecondFactorSetup: secondFactor.startSecondFactorSetup,
|
|
233
|
+
confirmSecondFactorSetup: secondFactor.confirmSecondFactorSetup,
|
|
234
|
+
verifySecondFactor: secondFactor.verifySecondFactor,
|
|
235
|
+
replaceSecondFactorRecoveryCodes: secondFactor.replaceSecondFactorRecoveryCodes,
|
|
236
|
+
removeSecondFactor: secondFactor.removeSecondFactor,
|
|
237
|
+
listSecondFactors: secondFactor.listSecondFactors,
|
|
238
|
+
resetSecondFactor: secondFactor.resetSecondFactor
|
|
210
239
|
});
|
|
211
240
|
}
|
|
212
241
|
|
|
@@ -26,21 +26,25 @@ function unauthenticatedAuthResult(clearSession = false) {
|
|
|
26
26
|
};
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
/**
|
|
30
|
+
* A local auth cookie: httpOnly at Path=/, Secure in production, with the application's SameSite
|
|
31
|
+
* (AUTH_COOKIE_SAME_SITE).
|
|
32
|
+
* @param {Pick<import("../types.js").AuthLocalConfig, "isProduction" | "cookieSameSite">} config
|
|
33
|
+
* @param {number} maxAge
|
|
34
|
+
*/
|
|
35
|
+
function cookieOptions({ isProduction, cookieSameSite }, maxAge) {
|
|
30
36
|
return {
|
|
31
37
|
path: "/",
|
|
32
38
|
httpOnly: true,
|
|
33
|
-
sameSite:
|
|
39
|
+
sameSite: cookieSameSite,
|
|
34
40
|
secure: isProduction,
|
|
35
41
|
maxAge
|
|
36
42
|
};
|
|
37
43
|
}
|
|
38
44
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
{ path: "/api", httpOnly: true, sameSite: "lax", secure: isProduction, maxAge: 0 }
|
|
43
|
-
];
|
|
45
|
+
/** @param {Pick<import("../types.js").AuthLocalConfig, "isProduction" | "cookieSameSite">} config */
|
|
46
|
+
function clearCookieOptions(config) {
|
|
47
|
+
return [cookieOptions(config, 0), { ...cookieOptions(config, 0), path: "/api" }];
|
|
44
48
|
}
|
|
45
49
|
|
|
46
50
|
function buildAccessToken({ user, session, secret, ttlSeconds = ACCESS_TTL_SECONDS }) {
|
|
@@ -75,7 +79,9 @@ function buildSessionPayload({ user, session, refreshToken, secret }) {
|
|
|
75
79
|
|
|
76
80
|
/**
|
|
77
81
|
* The sessions of local auth: creating one, authenticating a request from its
|
|
78
|
-
* cookies, writing and clearing those cookies, and revoking sessions.
|
|
82
|
+
* cookies, writing and clearing those cookies, and revoking sessions. An
|
|
83
|
+
* authenticated request's answer names its session (`sessionId`) and when the
|
|
84
|
+
* session last proved its second factor (`secondFactorAt`, "" when it has not).
|
|
79
85
|
* @param {object} dependencies
|
|
80
86
|
* @param {boolean} dependencies.appProfileProjection True when the application keeps profiles.
|
|
81
87
|
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
@@ -201,6 +207,8 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
|
|
|
201
207
|
authenticated: true,
|
|
202
208
|
...authPayload,
|
|
203
209
|
session: null,
|
|
210
|
+
sessionId: resolved.session.id,
|
|
211
|
+
secondFactorAt: resolved.session.secondFactorAt || "",
|
|
204
212
|
sessionPurpose: resolved.session.purpose || "normal",
|
|
205
213
|
clearSession: false,
|
|
206
214
|
transientFailure: false
|
|
@@ -244,6 +252,8 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
|
|
|
244
252
|
refreshToken,
|
|
245
253
|
secret: config.sessionSecret
|
|
246
254
|
}),
|
|
255
|
+
sessionId: resolved.session.id,
|
|
256
|
+
secondFactorAt: resolved.session.secondFactorAt || "",
|
|
247
257
|
sessionPurpose: resolved.session.purpose || "normal",
|
|
248
258
|
clearSession: false,
|
|
249
259
|
transientFailure: false
|
|
@@ -286,11 +296,11 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
|
|
|
286
296
|
reply.setCookie(
|
|
287
297
|
isRecoverySession ? RECOVERY_TOKEN_COOKIE : ACCESS_TOKEN_COOKIE,
|
|
288
298
|
accessToken,
|
|
289
|
-
cookieOptions(
|
|
299
|
+
cookieOptions(config, accessMaxAge)
|
|
290
300
|
);
|
|
291
301
|
}
|
|
292
302
|
if (refreshToken) {
|
|
293
|
-
reply.setCookie(REFRESH_TOKEN_COOKIE, refreshToken, cookieOptions(
|
|
303
|
+
reply.setCookie(REFRESH_TOKEN_COOKIE, refreshToken, cookieOptions(config, refreshMaxAge));
|
|
294
304
|
}
|
|
295
305
|
}
|
|
296
306
|
|
|
@@ -298,7 +308,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
|
|
|
298
308
|
if (!reply) {
|
|
299
309
|
return;
|
|
300
310
|
}
|
|
301
|
-
for (const options of clearCookieOptions(
|
|
311
|
+
for (const options of clearCookieOptions(config)) {
|
|
302
312
|
// A __Host- cookie only exists at Path=/.
|
|
303
313
|
if (options.path === "/" || !isProduction) {
|
|
304
314
|
reply.clearCookie(ACCESS_TOKEN_COOKIE, options);
|
|
@@ -72,52 +72,75 @@ function signInWaitMs(record, now) {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
/**
|
|
75
|
-
*
|
|
75
|
+
* A record's failures after one more: how many in a row (those older than a day
|
|
76
|
+
* are forgotten), the last one, and until when the next attempt must wait. The
|
|
77
|
+
* sign-in throttle counts an account email's failed sign-ins this way, and the
|
|
78
|
+
* second factor an account's wrong codes.
|
|
76
79
|
* @param {ReturnType<typeof resolveSignInThrottle>} throttle
|
|
77
80
|
* @param {{ failures: number, lastFailedAt: string } | null} record
|
|
78
|
-
* @param {string} email
|
|
79
81
|
* @param {number} now
|
|
80
82
|
*/
|
|
81
|
-
function
|
|
83
|
+
function nextFailures(throttle, record, now) {
|
|
82
84
|
const lastFailedAt = Date.parse(record?.lastFailedAt || "");
|
|
83
85
|
const recent = Number.isFinite(lastFailedAt) && now - lastFailedAt < FORGET_FAILURES_AFTER_MS;
|
|
84
86
|
const failures = (recent ? record.failures : 0) + 1;
|
|
85
87
|
const waits = failures - throttle.failuresBeforeWait + 1;
|
|
86
88
|
const waitMs = waits > 0 ? Math.min(throttle.maxWaitMs, throttle.firstWaitMs * 2 ** (waits - 1)) : 0;
|
|
87
89
|
return {
|
|
88
|
-
email,
|
|
89
90
|
failures,
|
|
90
91
|
lastFailedAt: new Date(now).toISOString(),
|
|
91
92
|
lockedUntil: waitMs > 0 ? new Date(now + waitMs).toISOString() : ""
|
|
92
93
|
};
|
|
93
94
|
}
|
|
94
95
|
|
|
96
|
+
/**
|
|
97
|
+
* The account's record after one more failed sign-in.
|
|
98
|
+
* @param {ReturnType<typeof resolveSignInThrottle>} throttle
|
|
99
|
+
* @param {{ failures: number, lastFailedAt: string } | null} record
|
|
100
|
+
* @param {string} email
|
|
101
|
+
* @param {number} now
|
|
102
|
+
*/
|
|
103
|
+
function recordSignInFailure(throttle, record, email, now) {
|
|
104
|
+
return { email, ...nextFailures(throttle, record, now) };
|
|
105
|
+
}
|
|
106
|
+
|
|
95
107
|
/** Failure records whose last failure is old enough to forget. */
|
|
96
108
|
function forgottenFailuresBefore(now) {
|
|
97
109
|
return new Date(now - FORGET_FAILURES_AFTER_MS).toISOString();
|
|
98
110
|
}
|
|
99
111
|
|
|
112
|
+
/**
|
|
113
|
+
* A wait's refusal params: the minutes to wait, rounded up, and the exact
|
|
114
|
+
* seconds, which Retry-After also gives.
|
|
115
|
+
* @param {number} waitMs
|
|
116
|
+
*/
|
|
117
|
+
function waitParams(waitMs) {
|
|
118
|
+
const retryAfterSeconds = Math.max(1, Math.ceil(waitMs / 1000));
|
|
119
|
+
return { count: Math.ceil(retryAfterSeconds / 60), retryAfterSeconds };
|
|
120
|
+
}
|
|
121
|
+
|
|
100
122
|
/**
|
|
101
123
|
* The refusal of a sign-in while its account waits, with the minutes to wait;
|
|
102
124
|
* Retry-After gives the exact seconds.
|
|
103
125
|
* @param {number} waitMs
|
|
104
126
|
*/
|
|
105
127
|
function signInLockedError(waitMs) {
|
|
106
|
-
const
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
return new AppError(429, `Too many failed sign-ins for this account. Try again in ${count} ${unit}.`, {
|
|
128
|
+
const params = waitParams(waitMs);
|
|
129
|
+
const unit = params.count === 1 ? "minute" : "minutes";
|
|
130
|
+
return new AppError(429, `Too many failed sign-ins for this account. Try again in ${params.count} ${unit}.`, {
|
|
110
131
|
code: "auth.local.login.locked",
|
|
111
|
-
params
|
|
112
|
-
headers: { "retry-after": String(
|
|
132
|
+
params,
|
|
133
|
+
headers: { "retry-after": String(params.retryAfterSeconds) }
|
|
113
134
|
});
|
|
114
135
|
}
|
|
115
136
|
|
|
116
137
|
export {
|
|
117
138
|
DEFAULT_SIGN_IN_THROTTLE,
|
|
118
139
|
forgottenFailuresBefore,
|
|
140
|
+
nextFailures,
|
|
119
141
|
recordSignInFailure,
|
|
120
142
|
resolveSignInThrottle,
|
|
121
143
|
signInLockedError,
|
|
122
|
-
signInWaitMs
|
|
144
|
+
signInWaitMs,
|
|
145
|
+
waitParams
|
|
123
146
|
};
|
|
@@ -15,6 +15,7 @@ import { createLocalFileBackend } from "../lib/fileBackend.js";
|
|
|
15
15
|
import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
|
|
16
16
|
import { createLoggedRecoverySender, createSimulatedRecoverySender } from "../lib/passwordFlows.js";
|
|
17
17
|
import { scryptPasswordStrategy } from "../lib/passwords.js";
|
|
18
|
+
import { createLoggedSecondFactorEvents } from "../lib/secondFactor.js";
|
|
18
19
|
import { createLocalAuthService } from "../lib/service.js";
|
|
19
20
|
|
|
20
21
|
const AuthLocalProvider = defineProvider({
|
|
@@ -31,7 +32,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
31
32
|
confirmationSender: "auth.local.confirmation-sender",
|
|
32
33
|
passwordStrategy: "auth.local.password-strategy",
|
|
33
34
|
profileProjector: "auth.profile.projector",
|
|
34
|
-
recoverySender: "auth.local.recovery-sender"
|
|
35
|
+
recoverySender: "auth.local.recovery-sender",
|
|
36
|
+
secondFactorEvents: "auth.local.second-factor-events"
|
|
35
37
|
},
|
|
36
38
|
provides: {
|
|
37
39
|
authService: "auth.service"
|
|
@@ -53,6 +55,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
53
55
|
* @param {import("../types.js").AuthLocalPasswordStrategy | null} dependencies.passwordStrategy The `auth.local.password-strategy`, when one is installed.
|
|
54
56
|
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector | null} dependencies.profileProjector The `auth.profile.projector`, when one is installed.
|
|
55
57
|
* @param {import("../types.js").AuthLocalRecoverySender | null} dependencies.recoverySender The `auth.local.recovery-sender`, when one is installed.
|
|
58
|
+
* @param {import("../types.js").AuthLocalSecondFactorEvents | null} dependencies.secondFactorEvents The
|
|
59
|
+
* `auth.local.second-factor-events`, when one is installed.
|
|
56
60
|
*/
|
|
57
61
|
async boot(
|
|
58
62
|
{
|
|
@@ -65,7 +69,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
65
69
|
logger,
|
|
66
70
|
passwordStrategy,
|
|
67
71
|
profileProjector,
|
|
68
|
-
recoverySender
|
|
72
|
+
recoverySender,
|
|
73
|
+
secondFactorEvents
|
|
69
74
|
},
|
|
70
75
|
{ outputs }
|
|
71
76
|
) {
|
|
@@ -94,7 +99,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
94
99
|
profileProjector: profileProjector ?? noAppProfiles,
|
|
95
100
|
recoverySender: emailRecovery
|
|
96
101
|
? (live ? recoverySender : createSimulatedRecoverySender(logger))
|
|
97
|
-
: createLoggedRecoverySender(logger)
|
|
102
|
+
: createLoggedRecoverySender(logger),
|
|
103
|
+
secondFactorEvents: secondFactorEvents ?? createLoggedSecondFactorEvents(logger)
|
|
98
104
|
});
|
|
99
105
|
// readable-check: allow setter-seam - deferred until boot: auth.service is built after every setup has registered its auth extensions, and those setups already receive it
|
|
100
106
|
attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
|
package/src/server/types.js
CHANGED
|
@@ -21,8 +21,11 @@
|
|
|
21
21
|
* findById(sessionId: string): Promise<object | null>,
|
|
22
22
|
* findByTokenHash(tokenHash: string): Promise<object | null>,
|
|
23
23
|
* revoke(sessionId: string): Promise<object | null>,
|
|
24
|
-
* revokeForUser(userId: string, options?: object): Promise<number
|
|
25
|
-
*
|
|
24
|
+
* revokeForUser(userId: string, options?: object): Promise<number>,
|
|
25
|
+
* markSecondFactorProved(sessionId: string, secondFactorAt: string): Promise<object | null>,
|
|
26
|
+
* clearSecondFactorForUser(userId: string): Promise<number>
|
|
27
|
+
* }} sessions A session's `secondFactorAt` is when it last proved its second factor ("" when it has not):
|
|
28
|
+
* `markSecondFactorProved` marks one session, `clearSecondFactorForUser` every session of the user.
|
|
26
29
|
* @property {{
|
|
27
30
|
* create(input: object): Promise<object>,
|
|
28
31
|
* findByTokenHash(tokenHash: string): Promise<object | null>,
|
|
@@ -49,6 +52,14 @@
|
|
|
49
52
|
* transaction ends, so concurrent failures count one after another, `save` replaces the email's record and
|
|
50
53
|
* `deleteBefore` removes those whose last failure is older.
|
|
51
54
|
* @property {{
|
|
55
|
+
* find(userId: string): Promise<AuthLocalSecondFactor | null>,
|
|
56
|
+
* findMany(userIds: string[]): Promise<AuthLocalSecondFactor[]>,
|
|
57
|
+
* save(record: AuthLocalSecondFactor): Promise<AuthLocalSecondFactor>,
|
|
58
|
+
* delete(userId: string): Promise<number>
|
|
59
|
+
* }} secondFactors One second factor per account; `find` holds the account's record until the transaction ends, so
|
|
60
|
+
* concurrent codes are checked one after another, `findMany` reads without holding, and `save` replaces the
|
|
61
|
+
* account's record.
|
|
62
|
+
* @property {{
|
|
52
63
|
* save(record: AuthLocalRegistration): Promise<AuthLocalRegistration>,
|
|
53
64
|
* findByEmail(email: string): Promise<AuthLocalRegistration | null>,
|
|
54
65
|
* findByTokenHash(tokenHash: string): Promise<AuthLocalRegistration | null>,
|
|
@@ -73,6 +84,53 @@
|
|
|
73
84
|
* @property {string} expiresAt
|
|
74
85
|
*/
|
|
75
86
|
|
|
87
|
+
/**
|
|
88
|
+
* An account's second factor: its authenticator secret sealed with the
|
|
89
|
+
* application's key, when the first code confirmed it ("" while it is being
|
|
90
|
+
* set up), the 30-second step of the last code accepted (no code of that step
|
|
91
|
+
* or an earlier one is accepted again), the keyed hashes of its unused recovery
|
|
92
|
+
* codes, and its wrong codes as failed sign-ins count them. Times are ISO
|
|
93
|
+
* strings.
|
|
94
|
+
* @typedef {object} AuthLocalSecondFactor
|
|
95
|
+
* @property {string} userId
|
|
96
|
+
* @property {string} secretSealed
|
|
97
|
+
* @property {string} confirmedAt
|
|
98
|
+
* @property {number} lastUsedStep
|
|
99
|
+
* @property {string[]} recoveryCodes
|
|
100
|
+
* @property {number} failures
|
|
101
|
+
* @property {string} lastFailedAt
|
|
102
|
+
* @property {string} lockedUntil
|
|
103
|
+
* @property {string} createdAt
|
|
104
|
+
* @property {string} updatedAt
|
|
105
|
+
*/
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* One second factor event: an authenticator setup started or confirmed, a
|
|
109
|
+
* session's second factor verified (by a `code` or a `recoveryCode`, with the
|
|
110
|
+
* recovery codes left), a failed attempt (`reason`: codeInvalid, codeUsed,
|
|
111
|
+
* recoveryCodeInvalid or locked), the recovery codes replaced, the
|
|
112
|
+
* authenticator removed by its person, or reset by the application for the
|
|
113
|
+
* account `byUserId` names. `userId` is the local account's id, `ip` the
|
|
114
|
+
* request's address ("" for a reset), `at` an ISO time.
|
|
115
|
+
* @typedef {object} AuthLocalSecondFactorEvent
|
|
116
|
+
* @property {"setupStarted" | "setupConfirmed" | "verified" | "failed" | "recoveryCodesReplaced" | "removed" | "reset"} type
|
|
117
|
+
* @property {string} userId
|
|
118
|
+
* @property {string} ip
|
|
119
|
+
* @property {string} at
|
|
120
|
+
* @property {"code" | "recoveryCode"} [method]
|
|
121
|
+
* @property {number} [recoveryCodesLeft]
|
|
122
|
+
* @property {"codeInvalid" | "codeUsed" | "recoveryCodeInvalid" | "locked"} [reason]
|
|
123
|
+
* @property {string} [byUserId]
|
|
124
|
+
*/
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The `auth.local.second-factor-events` capability: records each second
|
|
128
|
+
* factor event, for an application's audit log. It runs after the change is
|
|
129
|
+
* stored; when it fails, local auth logs the failure and the operation still
|
|
130
|
+
* answers. Without one, local auth logs each event.
|
|
131
|
+
* @typedef {(event: AuthLocalSecondFactorEvent) => Promise<void>} AuthLocalSecondFactorEvents
|
|
132
|
+
*/
|
|
133
|
+
|
|
76
134
|
/**
|
|
77
135
|
* An account's recent failed sign-ins: how many, the last one, and when it may
|
|
78
136
|
* try again ("" when it need not wait). Times are ISO strings.
|
|
@@ -82,7 +140,7 @@
|
|
|
82
140
|
/**
|
|
83
141
|
* The `auth.local.backend` capability: where local auth keeps its users,
|
|
84
142
|
* sessions, recovery tokens, linked identities, OAuth attempts, failed
|
|
85
|
-
* sign-ins and
|
|
143
|
+
* sign-ins, unconfirmed registrations and second factors. Without
|
|
86
144
|
* one, local auth keeps them in files under AUTH_LOCAL_STORE_DIR;
|
|
87
145
|
* `@jskit-ai/auth-provider-local-db-core` provides one that keeps them in the
|
|
88
146
|
* database. Each backend implements this contract.
|
package/test/codedTexts.test.js
CHANGED
|
@@ -8,6 +8,8 @@ import authCoreEnglish from "@jskit-ai/auth-core/locales/en.json" with { type: "
|
|
|
8
8
|
import localEnglish from "../locales/en.json" with { type: "json" };
|
|
9
9
|
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
10
10
|
import { localServiceOptions } from "../test-support/localService.js";
|
|
11
|
+
import { sessionCookies } from "../test-support/oauthHarness.js";
|
|
12
|
+
import { SCENARIO_START, codeAt } from "../test-support/secondFactorScenario.js";
|
|
11
13
|
|
|
12
14
|
const english = mergeCatalogs(authCoreEnglish, localEnglish);
|
|
13
15
|
|
|
@@ -77,3 +79,29 @@ test("local auth success texts carry a message code next to the English", async
|
|
|
77
79
|
assert.equal(requested.messageCode, "auth.local.recovery.requested");
|
|
78
80
|
assert.equal(rendered(requested.messageCode, requested.messageParams), requested.message);
|
|
79
81
|
});
|
|
82
|
+
|
|
83
|
+
test("second factor refusals carry codes whose English is the thrown message", async (t) => {
|
|
84
|
+
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
85
|
+
const service = await createService(t);
|
|
86
|
+
await service.register({ email: "ada@example.com", password: "correct horse" });
|
|
87
|
+
const cookies = sessionCookies((await service.login({ email: "ada@example.com", password: "correct horse" })).session);
|
|
88
|
+
const request = () => ({ cookies });
|
|
89
|
+
const coded = (code) => (error) => assertCoded(error, code);
|
|
90
|
+
|
|
91
|
+
await assert.rejects(service.verifySecondFactor(request(), { code: "123456" }), coded("auth.local.secondFactor.notSetUp"));
|
|
92
|
+
await assert.rejects(service.confirmSecondFactorSetup(request(), { code: "123456" }), coded("auth.local.secondFactor.setupNotStarted"));
|
|
93
|
+
const { secret } = await service.startSecondFactorSetup(request());
|
|
94
|
+
await service.confirmSecondFactorSetup(request(), { code: codeAt(secret) });
|
|
95
|
+
await assert.rejects(service.startSecondFactorSetup(request()), coded("auth.local.secondFactor.alreadySetUp"));
|
|
96
|
+
await assert.rejects(service.verifySecondFactor(request(), {}), coded("auth.local.secondFactor.proofRequired"));
|
|
97
|
+
await assert.rejects(service.verifySecondFactor(request(), { code: codeAt(secret) }), coded("auth.local.secondFactor.codeUsed"));
|
|
98
|
+
await assert.rejects(service.verifySecondFactor(request(), { recoveryCode: "abcde-fghjk" }),
|
|
99
|
+
coded("auth.local.secondFactor.recoveryCodeInvalid"));
|
|
100
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
101
|
+
await assert.rejects(service.verifySecondFactor(request(), { code: "12345" }), coded("auth.local.secondFactor.codeInvalid"));
|
|
102
|
+
}
|
|
103
|
+
await assert.rejects(service.verifySecondFactor(request(), { code: codeAt(secret, 1) }), (error) => {
|
|
104
|
+
assert.equal(error.message, "Too many wrong codes. Try again in 1 minute.");
|
|
105
|
+
return assertCoded(error, "auth.local.secondFactor.locked");
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
7
|
+
import { createLocalFileBackend } from "../src/server/lib/index.js";
|
|
8
|
+
import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
9
|
+
import { approveAtProvider, createService, oidcProviderEntry, startOidcProvider } from "../test-support/oauthHarness.js";
|
|
10
|
+
|
|
11
|
+
const PASSWORD = "correct horse battery staple";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Every cookie local auth sets and clears in one person's sign-in, password recovery, sign-out and Google sign-in,
|
|
15
|
+
* as [name, "set" or "cleared", path, sameSite].
|
|
16
|
+
* @param {import("node:test").TestContext} t
|
|
17
|
+
* @param {Record<string, string>} env
|
|
18
|
+
*/
|
|
19
|
+
async function cookiesOfEveryFlow(t, env) {
|
|
20
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-same-site-"));
|
|
21
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
22
|
+
const issuer = await startOidcProvider();
|
|
23
|
+
t.after(() => issuer.close());
|
|
24
|
+
const service = createService({
|
|
25
|
+
backend: createLocalFileBackend({ storeDir }),
|
|
26
|
+
oauthProviders: [oidcProviderEntry(issuer)],
|
|
27
|
+
profileProjector: noAppProfiles,
|
|
28
|
+
env
|
|
29
|
+
});
|
|
30
|
+
const written = [];
|
|
31
|
+
const reply = {
|
|
32
|
+
setCookie: (name, _value, options) => written.push([name, "set", options.path, options.sameSite]),
|
|
33
|
+
clearCookie: (name, options) => written.push([name, "cleared", options.path, options.sameSite])
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
service.writeSessionCookies(reply, (await service.register({ email: "ada@example.com", password: PASSWORD })).session);
|
|
37
|
+
const { recoveryUrl } = await service.requestPasswordReset({ email: "ada@example.com" });
|
|
38
|
+
const recovery = await service.completePasswordRecovery({
|
|
39
|
+
code: new URL(recoveryUrl).searchParams.get("token"),
|
|
40
|
+
type: "recovery"
|
|
41
|
+
});
|
|
42
|
+
service.writeSessionCookies(reply, recovery.session);
|
|
43
|
+
service.clearSessionCookies(reply);
|
|
44
|
+
|
|
45
|
+
const { started, input, request } = await approveAtProvider(service);
|
|
46
|
+
service.writeOAuthStartCookies(reply, started);
|
|
47
|
+
const signedIn = await service.oauthComplete(input, request);
|
|
48
|
+
service.clearOAuthStartCookies(reply);
|
|
49
|
+
service.writeSessionCookies(reply, signedIn.session);
|
|
50
|
+
return written;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** What cookiesOfEveryFlow answers when every cookie has the SameSite given. */
|
|
54
|
+
function everyCookie(sameSite) {
|
|
55
|
+
const cleared = (pathName) => ["access", "refresh", "recovery"]
|
|
56
|
+
.map((kind) => [`jskit_local_${kind}_token`, "cleared", pathName, sameSite]);
|
|
57
|
+
return [
|
|
58
|
+
["jskit_local_access_token", "set", "/", sameSite],
|
|
59
|
+
["jskit_local_refresh_token", "set", "/", sameSite],
|
|
60
|
+
["jskit_local_recovery_token", "set", "/", sameSite],
|
|
61
|
+
["jskit_local_refresh_token", "set", "/", sameSite],
|
|
62
|
+
...cleared("/"),
|
|
63
|
+
...cleared("/api"),
|
|
64
|
+
["jskit_local_oauth_attempt", "set", "/", sameSite],
|
|
65
|
+
["jskit_local_oauth_attempt", "cleared", "/", sameSite],
|
|
66
|
+
["jskit_local_access_token", "set", "/", sameSite],
|
|
67
|
+
["jskit_local_refresh_token", "set", "/", sameSite]
|
|
68
|
+
];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
test("without AUTH_COOKIE_SAME_SITE every local auth cookie, the OAuth attempt's included, is SameSite=Lax", async (t) => {
|
|
72
|
+
assert.deepEqual(await cookiesOfEveryFlow(t, {}), everyCookie("lax"));
|
|
73
|
+
assert.deepEqual(await cookiesOfEveryFlow(t, { AUTH_COOKIE_SAME_SITE: " " }), everyCookie("lax"));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("AUTH_COOKIE_SAME_SITE=strict makes every local auth cookie and its clearing SameSite=Strict", async (t) => {
|
|
77
|
+
assert.deepEqual(await cookiesOfEveryFlow(t, { AUTH_COOKIE_SAME_SITE: "strict" }), everyCookie("strict"));
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("an AUTH_COOKIE_SAME_SITE other than lax or strict stops local auth's startup", () => {
|
|
81
|
+
const resolve = (value) => resolveLocalAuthConfig({
|
|
82
|
+
appRoot: os.tmpdir(),
|
|
83
|
+
env: { NODE_ENV: "test", AUTH_LOCAL_SESSION_SECRET: "test-session-secret", AUTH_COOKIE_SAME_SITE: value },
|
|
84
|
+
fileBackend: false,
|
|
85
|
+
emailRecovery: false
|
|
86
|
+
});
|
|
87
|
+
assert.equal(resolve("Lax").cookieSameSite, "lax");
|
|
88
|
+
assert.equal(resolve(" Strict ").cookieSameSite, "strict");
|
|
89
|
+
for (const value of ["none", "None", "secure", "strict;", "lax strict"]) {
|
|
90
|
+
assert.throws(() => resolve(value), {
|
|
91
|
+
message: `AUTH_COOKIE_SAME_SITE must be lax or strict, not "${value}".`
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
});
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
7
|
+
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
8
|
+
import { __testables, deriveSecondFactorKeys, openSecret, sealSecret } from "../src/server/lib/secondFactorCrypto.js";
|
|
9
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
10
|
+
import { sessionCookies } from "../test-support/oauthHarness.js";
|
|
11
|
+
import {
|
|
12
|
+
SCENARIO_START,
|
|
13
|
+
SECOND_FACTOR_KEY,
|
|
14
|
+
codeAt,
|
|
15
|
+
exerciseSecondFactor,
|
|
16
|
+
secondFactorServiceOptions
|
|
17
|
+
} from "../test-support/secondFactorScenario.js";
|
|
18
|
+
|
|
19
|
+
const { fromBase32, stepAt, toBase32, totpCodeAt } = __testables;
|
|
20
|
+
|
|
21
|
+
async function storeDirFor(t) {
|
|
22
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-second-factor-"));
|
|
23
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
24
|
+
return storeDir;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
test("authenticator codes are RFC 6238's: its test vectors, as six-digit codes", () => {
|
|
28
|
+
const secret = toBase32(Buffer.from("12345678901234567890"));
|
|
29
|
+
assert.equal(secret, "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
|
|
30
|
+
assert.deepEqual(fromBase32(secret), Buffer.from("12345678901234567890"));
|
|
31
|
+
for (const [seconds, code] of [
|
|
32
|
+
[59, "287082"],
|
|
33
|
+
[1111111109, "081804"],
|
|
34
|
+
[1111111111, "050471"],
|
|
35
|
+
[1234567890, "005924"],
|
|
36
|
+
[2000000000, "279037"],
|
|
37
|
+
[20000000000, "353130"]
|
|
38
|
+
]) {
|
|
39
|
+
assert.equal(totpCodeAt(secret, stepAt(seconds * 1000)), code, `T = ${seconds}`);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("a sealed secret opens only for its own account and with the key that sealed it", () => {
|
|
44
|
+
const keys = deriveSecondFactorKeys(SECOND_FACTOR_KEY);
|
|
45
|
+
const sealed = sealSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
|
|
46
|
+
assert.match(sealed, /^v1\.[\w-]+\.[\w-]+\.[\w-]+$/u);
|
|
47
|
+
assert.equal(sealed.includes("GEZDGNBV"), false);
|
|
48
|
+
assert.notEqual(sealSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"), sealed, "each seal has its own nonce");
|
|
49
|
+
assert.equal(openSecret(keys, "usr_ada", sealed), "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
|
|
50
|
+
assert.throws(() => openSecret(keys, "usr_bob", sealed), /does not open with AUTH_LOCAL_SECOND_FACTOR_KEY/u);
|
|
51
|
+
assert.throws(() => openSecret(deriveSecondFactorKeys(`${SECOND_FACTOR_KEY}!`), "usr_ada", sealed), /does not open/u);
|
|
52
|
+
assert.throws(() => openSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"), /is not a sealed secret/u);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("an authenticator sets up, proves sessions, refuses wrong, used and expired codes, waits, and resets (file backend)", async (t) => {
|
|
56
|
+
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
57
|
+
const storeDir = await storeDirFor(t);
|
|
58
|
+
const { events, options } = secondFactorServiceOptions();
|
|
59
|
+
const service = createLocalAuthService({ ...options, backend: createLocalFileBackend({ storeDir }) });
|
|
60
|
+
await exerciseSecondFactor(t, {
|
|
61
|
+
service,
|
|
62
|
+
events,
|
|
63
|
+
async storedText() {
|
|
64
|
+
const files = await fs.readdir(storeDir);
|
|
65
|
+
return (await Promise.all(files.map((file) => fs.readFile(path.join(storeDir, file), "utf8")))).join("\n");
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("the file store keeps a factor and its session's proof across restarts, and another key cannot open it", async (t) => {
|
|
71
|
+
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
72
|
+
const storeDir = await storeDirFor(t);
|
|
73
|
+
const start = (env = {}) => createLocalAuthService({ ...secondFactorServiceOptions({ env }).options, backend: createLocalFileBackend({ storeDir }) });
|
|
74
|
+
const first = start();
|
|
75
|
+
await first.register({ email: "ada@example.com", password: "correct horse battery staple" });
|
|
76
|
+
const cookies = sessionCookies((await first.login({ email: "ada@example.com", password: "correct horse battery staple" })).session);
|
|
77
|
+
const { secret } = await first.startSecondFactorSetup({ cookies });
|
|
78
|
+
const { recoveryCodes } = await first.confirmSecondFactorSetup({ cookies }, { code: codeAt(secret) });
|
|
79
|
+
|
|
80
|
+
const restarted = start();
|
|
81
|
+
assert.deepEqual(await restarted.getSecondFactorStatus({ cookies }), {
|
|
82
|
+
enrolled: true,
|
|
83
|
+
enrolledAt: new Date(SCENARIO_START).toISOString(),
|
|
84
|
+
recoveryCodesLeft: 10,
|
|
85
|
+
verifiedAt: new Date(SCENARIO_START).toISOString()
|
|
86
|
+
});
|
|
87
|
+
assert.equal((await restarted.verifySecondFactor({ cookies }, { recoveryCode: recoveryCodes[0] })).recoveryCodesLeft, 9);
|
|
88
|
+
|
|
89
|
+
t.mock.timers.tick(30_000);
|
|
90
|
+
const rekeyed = start({ AUTH_LOCAL_SECOND_FACTOR_KEY: `another key, also 32 characters or more` });
|
|
91
|
+
await assert.rejects(rekeyed.verifySecondFactor({ cookies }, { code: codeAt(secret) }), (error) => {
|
|
92
|
+
assert.equal(error.status, undefined, "a key that cannot open the secret is a server failure, not a refusal");
|
|
93
|
+
assert.match(error.message, /does not open with AUTH_LOCAL_SECOND_FACTOR_KEY/u);
|
|
94
|
+
return true;
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("a production server has a second factor only with its key, at least 32 characters, and APP_PUBLIC_URL", async (t) => {
|
|
99
|
+
const production = { NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "", AUTH_LOCAL_SECOND_FACTOR_KEY: "" };
|
|
100
|
+
const service = createLocalAuthService({
|
|
101
|
+
...localServiceOptions({ env: production }),
|
|
102
|
+
backend: createLocalFileBackend({ storeDir: await storeDirFor(t) })
|
|
103
|
+
});
|
|
104
|
+
assert.equal(service.getCapabilities().features.secondFactor, false);
|
|
105
|
+
assert.throws(() => service.getSecondFactorStatus({ cookies: {} }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
106
|
+
assert.throws(() => service.listSecondFactors({ userIds: [] }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
107
|
+
|
|
108
|
+
const resolve = (env) => resolveLocalAuthConfig({
|
|
109
|
+
appRoot: os.tmpdir(),
|
|
110
|
+
env: {
|
|
111
|
+
AUTH_LOCAL_SESSION_SECRET: "test-session-secret",
|
|
112
|
+
AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
|
|
113
|
+
APP_PUBLIC_URL: "https://console.example.com",
|
|
114
|
+
...env
|
|
115
|
+
},
|
|
116
|
+
fileBackend: false,
|
|
117
|
+
emailRecovery: false
|
|
118
|
+
});
|
|
119
|
+
assert.equal(resolve({ NODE_ENV: "production" }).secondFactorKey, "");
|
|
120
|
+
assert.equal(resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY }).secondFactorKey, SECOND_FACTOR_KEY);
|
|
121
|
+
assert.throws(() => resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: "too short" }), /at least 32 characters/u);
|
|
122
|
+
assert.throws(() => resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY, APP_PUBLIC_URL: "" }),
|
|
123
|
+
/APP_PUBLIC_URL is required when AUTH_LOCAL_SECOND_FACTOR_KEY is set/u);
|
|
124
|
+
// Outside production the session secret stands in for the key.
|
|
125
|
+
assert.equal(resolve({ NODE_ENV: "development" }).secondFactorKey, "test-session-secret");
|
|
126
|
+
assert.equal(createLocalAuthService({ ...localServiceOptions(), backend: createLocalFileBackend({ storeDir: await storeDirFor(t) }) })
|
|
127
|
+
.getCapabilities().features.secondFactor, true);
|
|
128
|
+
});
|