@jskit-ai/auth-core 0.2.21 → 0.2.22
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 +2 -0
- package/locales/en.json +4 -0
- package/package.json +6 -2
- package/src/server/actions/secondFactorActions.js +92 -0
- package/src/server/lib/authPolicySupport.js +2 -0
- package/src/server/lib/errors.js +2 -1
- package/src/server/lib/plugin.js +19 -0
- package/src/server/lib/routeMeta.js +5 -2
- package/src/server/providers/AuthFeature.js +4 -1
- package/src/server/secondFactor.js +56 -0
- package/src/server/types.js +60 -0
- package/src/shared/authCapabilities.js +12 -2
- package/src/shared/authPaths.js +6 -1
- package/src/shared/authSecondFactor.js +16 -0
- package/src/shared/authSecurityStatus.js +8 -2
- package/src/shared/commands/authCommandValidators.js +3 -1
- package/src/shared/commands/authSecondFactorCommands.js +172 -0
- package/src/shared/commands/index.js +8 -0
- package/src/shared/index.js +1 -0
- package/test/authActions.test.js +40 -0
- package/test/authContract.test.js +20 -0
- package/test/commandValidators.test.js +34 -2
- package/test/routeMeta.test.js +4 -2
- package/test/secondFactorPolicy.test.js +94 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- **Second factor.** A route asks for one with the kernel's `secondFactor` option (`true`, or `{ maxAgeSeconds }` for a dangerous action), and the auth policy enforces it: a signed-in session that has not proved its second factor, or proved it longer ago than `maxAgeSeconds`, is refused with 403 `auth.secondFactor.required` (params `{ maxAgeSeconds }` when the route names one), checked after the CSRF token, the sign-in and the route's permission. The policy sets `request.secondFactorAt`, when the session last proved it (`""` when it has not), from the provider's `authenticate` result. `./server/secondFactor` gives `requireSecondFactor(request, requirement)`, the same refusal for an action whose requirement depends on more than its route (the actor's role, say; a call without a request, as from the server's own code, is refused too), with `isSecondFactorMet()` and `secondFactorRequiredParams()`; `./shared/authSecondFactor` gives `SECOND_FACTOR_REQUIRED` and `isSecondFactorRequired(error)` for clients.
|
|
6
|
+
- The second factor's actions and commands, each one call to the installed `auth.service` for the request's own session (channels `api` and `internal`, never automation): `auth.secondFactor.read`, `auth.secondFactor.setup.start`, `auth.secondFactor.setup.confirm` (body `{ code }`), `auth.secondFactor.verify`, `auth.secondFactor.recoveryCodes.replace` and `auth.secondFactor.remove` (body `{ code }` or `{ recoveryCode }`), exported from `./server/actions/secondFactorActions` and `./shared/commands`, at `AUTH_PATHS.SECOND_FACTOR`, `SECOND_FACTOR_SETUP`, `SECOND_FACTOR_SETUP_CONFIRM`, `SECOND_FACTOR_VERIFY` and `SECOND_FACTOR_RECOVERY_CODES`. `AuthService` documents the provider operations behind them, plus `listSecondFactors({ userIds })` and `resetSecondFactor({ userId, byUserId })` for an application's own screens (an owner resetting staff who lost their authenticator); a provider without a second factor answers 501 `AUTH_OPERATION_UNSUPPORTED`. The capability `features.secondFactor` says the provider has one, and the security status's `mfa` says whether the account has one set up. New codes: `auth.secondFactor.required`, `auth.validation.secondFactorCodeRequired`; new message keys `jskit.auth.secondFactor.required` and `jskit.auth.validation.secondFactorCodeRequired` (an app with other locales adds them with `npx jskit i18n export <locale>`).
|
|
5
7
|
- A route's `permission` now matches the actor's grants as action permissions do: `*` grants every route, and a grant ending in `.*`, such as `crud.labels.*`, grants every permission under that prefix. It used to need the exact name, so a workspace owner holding `*` was refused a route requiring `crud.labels.update`.
|
|
6
8
|
- The `AuthInvitationContextResolver` type documents what local auth relies on: the resolver throws for an invitation the registration cannot use, and the context it answers names, in `email`, the address the invitation was sent to and, in `expiresAt`, when it stops working, so a registration through it can skip email confirmation.
|
|
7
9
|
- `AuthProfileProjector.syncIdentityProfile` documents `onlyWhenChanged`, which providers pass on an ordinary request so a profile that already matches is only read; sign-in and session refresh synchronize in full.
|
package/locales/en.json
CHANGED
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
"otpTokenHashInvalid": "One-time token hash is invalid.",
|
|
51
51
|
"otpTypeUnsupported": "Only email OTP verification is supported.",
|
|
52
52
|
"recoveryCodeInvalid": "Recovery code is invalid.",
|
|
53
|
+
"secondFactorCodeRequired": "Enter the code from your authenticator app.",
|
|
53
54
|
"recoveryTokenHashInvalid": "Recovery token hash is invalid.",
|
|
54
55
|
"recoveryTypeUnsupported": "Only recovery links are supported.",
|
|
55
56
|
"confirmationCodeRequired": "Enter the confirmation code or link from the email.",
|
|
@@ -70,6 +71,9 @@
|
|
|
70
71
|
"notAllowlistedDefault": "This account is not allowed to access this application.",
|
|
71
72
|
"blockedDefault": "This account has been blocked from accessing this application.",
|
|
72
73
|
"unspecified": "This account cannot access this application."
|
|
74
|
+
},
|
|
75
|
+
"secondFactor": {
|
|
76
|
+
"required": "Confirm it's you with a code from your authenticator app."
|
|
73
77
|
}
|
|
74
78
|
}
|
|
75
79
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.22",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"./server/providers/AuthFeature": "./src/server/providers/AuthFeature.js",
|
|
12
12
|
"./server/providers/AuthPolicyProvider": "./src/server/providers/AuthPolicyProvider.js",
|
|
13
13
|
"./server/actions/authActions": "./src/server/actions/authActions.js",
|
|
14
|
+
"./server/actions/secondFactorActions": "./src/server/actions/secondFactorActions.js",
|
|
14
15
|
"./server/authExtensions": "./src/server/authExtensions.js",
|
|
15
16
|
"./server/noAppProfiles": "./src/server/noAppProfiles.js",
|
|
16
17
|
"./server/authPolicyContextResolverRegistry": "./src/server/authPolicyContextResolverRegistry.js",
|
|
@@ -19,6 +20,7 @@
|
|
|
19
20
|
"./server/authTexts": "./src/server/authTexts.js",
|
|
20
21
|
"./server/booleanFlag": "./src/server/booleanFlag.js",
|
|
21
22
|
"./server/devAuth": "./src/server/devAuth.js",
|
|
23
|
+
"./server/secondFactor": "./src/server/secondFactor.js",
|
|
22
24
|
"./server/deferredAuthService": "./src/server/deferredAuthService.js",
|
|
23
25
|
"./server/unsupportedOperation": "./src/server/unsupportedOperation.js",
|
|
24
26
|
"./server/utils": "./src/server/utils.js",
|
|
@@ -37,6 +39,7 @@
|
|
|
37
39
|
"./shared/signOutFlow": "./src/shared/signOutFlow.js",
|
|
38
40
|
"./shared/authDenied": "./src/shared/authDenied.js",
|
|
39
41
|
"./shared/authPaths": "./src/shared/authPaths.js",
|
|
42
|
+
"./shared/authSecondFactor": "./src/shared/authSecondFactor.js",
|
|
40
43
|
"./shared/authConstraints": "./src/shared/authConstraints.js",
|
|
41
44
|
"./shared/authCapabilities": "./src/shared/authCapabilities.js",
|
|
42
45
|
"./shared/authSecurityStatus": "./src/shared/authSecurityStatus.js",
|
|
@@ -60,6 +63,7 @@
|
|
|
60
63
|
"./shared/commands/authPasswordResetCommand": "./src/shared/commands/authPasswordResetCommand.js",
|
|
61
64
|
"./shared/commands/authLogoutCommand": "./src/shared/commands/authLogoutCommand.js",
|
|
62
65
|
"./shared/commands/authSessionReadCommand": "./src/shared/commands/authSessionReadCommand.js",
|
|
66
|
+
"./shared/commands/authSecondFactorCommands": "./src/shared/commands/authSecondFactorCommands.js",
|
|
63
67
|
"./locales/en.json": "./locales/en.json"
|
|
64
68
|
},
|
|
65
69
|
"dependencies": {
|
|
@@ -143,6 +147,6 @@
|
|
|
143
147
|
}
|
|
144
148
|
},
|
|
145
149
|
"peerDependencies": {
|
|
146
|
-
"@jskit-ai/kernel": "0.2.
|
|
150
|
+
"@jskit-ai/kernel": "0.2.22"
|
|
147
151
|
}
|
|
148
152
|
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { emptyInputValidator, resolveRequest } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
|
|
2
|
+
import {
|
|
3
|
+
authSecondFactorRecoveryCodesReplaceCommand,
|
|
4
|
+
authSecondFactorRemoveCommand,
|
|
5
|
+
authSecondFactorSetupConfirmCommand,
|
|
6
|
+
authSecondFactorVerifyCommand
|
|
7
|
+
} from "../../shared/commands/authSecondFactorCommands.js";
|
|
8
|
+
|
|
9
|
+
const ACTION_READ_SECOND_FACTOR = "auth.secondFactor.read";
|
|
10
|
+
const ACTION_START_SECOND_FACTOR_SETUP = "auth.secondFactor.setup.start";
|
|
11
|
+
const ACTION_CONFIRM_SECOND_FACTOR_SETUP = "auth.secondFactor.setup.confirm";
|
|
12
|
+
const ACTION_VERIFY_SECOND_FACTOR = "auth.secondFactor.verify";
|
|
13
|
+
const ACTION_REPLACE_SECOND_FACTOR_RECOVERY_CODES = "auth.secondFactor.recoveryCodes.replace";
|
|
14
|
+
const ACTION_REMOVE_SECOND_FACTOR = "auth.secondFactor.remove";
|
|
15
|
+
|
|
16
|
+
// Only the signed-in person works with their own second factor, over HTTP or from the server's own code; codes and
|
|
17
|
+
// secrets never reach automation.
|
|
18
|
+
const SECOND_FACTOR_QUERY = Object.freeze({
|
|
19
|
+
version: 1,
|
|
20
|
+
kind: "query",
|
|
21
|
+
channels: Object.freeze(["api", "internal"]),
|
|
22
|
+
surfaces: Object.freeze(["*"])
|
|
23
|
+
});
|
|
24
|
+
const SECOND_FACTOR_COMMAND = Object.freeze({
|
|
25
|
+
version: 1,
|
|
26
|
+
kind: "command",
|
|
27
|
+
channels: Object.freeze(["api", "internal"]),
|
|
28
|
+
surfaces: Object.freeze(["*"])
|
|
29
|
+
});
|
|
30
|
+
const SIGNED_IN = Object.freeze({ require: "authenticated" });
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The second factor's actions, each one call to the installed provider's
|
|
34
|
+
* auth.service for the request's own session.
|
|
35
|
+
* @param {{ authService: import("../types.js").AuthService }} dependencies
|
|
36
|
+
*/
|
|
37
|
+
function createSecondFactorActions({ authService }) {
|
|
38
|
+
return Object.freeze([
|
|
39
|
+
Object.freeze({
|
|
40
|
+
...SECOND_FACTOR_QUERY,
|
|
41
|
+
id: ACTION_READ_SECOND_FACTOR,
|
|
42
|
+
input: emptyInputValidator,
|
|
43
|
+
permission: SIGNED_IN,
|
|
44
|
+
execute: (input, context) => authService.getSecondFactorStatus(resolveRequest(context))
|
|
45
|
+
}),
|
|
46
|
+
Object.freeze({
|
|
47
|
+
...SECOND_FACTOR_COMMAND,
|
|
48
|
+
id: ACTION_START_SECOND_FACTOR_SETUP,
|
|
49
|
+
input: emptyInputValidator,
|
|
50
|
+
permission: SIGNED_IN,
|
|
51
|
+
execute: (input, context) => authService.startSecondFactorSetup(resolveRequest(context))
|
|
52
|
+
}),
|
|
53
|
+
Object.freeze({
|
|
54
|
+
...SECOND_FACTOR_COMMAND,
|
|
55
|
+
id: ACTION_CONFIRM_SECOND_FACTOR_SETUP,
|
|
56
|
+
input: authSecondFactorSetupConfirmCommand.operation.body,
|
|
57
|
+
permission: SIGNED_IN,
|
|
58
|
+
execute: (input, context) => authService.confirmSecondFactorSetup(resolveRequest(context), input)
|
|
59
|
+
}),
|
|
60
|
+
Object.freeze({
|
|
61
|
+
...SECOND_FACTOR_COMMAND,
|
|
62
|
+
id: ACTION_VERIFY_SECOND_FACTOR,
|
|
63
|
+
input: authSecondFactorVerifyCommand.operation.body,
|
|
64
|
+
permission: SIGNED_IN,
|
|
65
|
+
execute: (input, context) => authService.verifySecondFactor(resolveRequest(context), input)
|
|
66
|
+
}),
|
|
67
|
+
Object.freeze({
|
|
68
|
+
...SECOND_FACTOR_COMMAND,
|
|
69
|
+
id: ACTION_REPLACE_SECOND_FACTOR_RECOVERY_CODES,
|
|
70
|
+
input: authSecondFactorRecoveryCodesReplaceCommand.operation.body,
|
|
71
|
+
permission: SIGNED_IN,
|
|
72
|
+
execute: (input, context) => authService.replaceSecondFactorRecoveryCodes(resolveRequest(context), input)
|
|
73
|
+
}),
|
|
74
|
+
Object.freeze({
|
|
75
|
+
...SECOND_FACTOR_COMMAND,
|
|
76
|
+
id: ACTION_REMOVE_SECOND_FACTOR,
|
|
77
|
+
input: authSecondFactorRemoveCommand.operation.body,
|
|
78
|
+
permission: SIGNED_IN,
|
|
79
|
+
execute: (input, context) => authService.removeSecondFactor(resolveRequest(context), input)
|
|
80
|
+
})
|
|
81
|
+
]);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export {
|
|
85
|
+
ACTION_CONFIRM_SECOND_FACTOR_SETUP,
|
|
86
|
+
ACTION_READ_SECOND_FACTOR,
|
|
87
|
+
ACTION_REMOVE_SECOND_FACTOR,
|
|
88
|
+
ACTION_REPLACE_SECOND_FACTOR_RECOVERY_CODES,
|
|
89
|
+
ACTION_START_SECOND_FACTOR_SETUP,
|
|
90
|
+
ACTION_VERIFY_SECOND_FACTOR,
|
|
91
|
+
createSecondFactorActions
|
|
92
|
+
};
|
|
@@ -36,6 +36,8 @@ function normalizeActorResolution(result) {
|
|
|
36
36
|
return {
|
|
37
37
|
authenticated: Boolean(source.authenticated),
|
|
38
38
|
actor: Object.hasOwn(source, "actor") ? source.actor : null,
|
|
39
|
+
// When the session last proved its second factor, as ISO text, or "".
|
|
40
|
+
secondFactorAt: typeof source.secondFactorAt === "string" ? source.secondFactorAt : "",
|
|
39
41
|
transientFailure: Boolean(source.transientFailure)
|
|
40
42
|
};
|
|
41
43
|
}
|
package/src/server/lib/errors.js
CHANGED
|
@@ -4,7 +4,8 @@ const AUTH_POLICY_DENY_REASONS = Object.freeze({
|
|
|
4
4
|
OWNER_UNRESOLVED: "owner_unresolved",
|
|
5
5
|
FORBIDDEN_OWNER_MISMATCH: "forbidden_owner_mismatch",
|
|
6
6
|
INVALID_AUTH_POLICY: "invalid_auth_policy",
|
|
7
|
-
FORBIDDEN_PERMISSION: "forbidden_permission"
|
|
7
|
+
FORBIDDEN_PERMISSION: "forbidden_permission",
|
|
8
|
+
SECOND_FACTOR_REQUIRED: "second_factor_required"
|
|
8
9
|
});
|
|
9
10
|
|
|
10
11
|
/**
|
package/src/server/lib/plugin.js
CHANGED
|
@@ -2,6 +2,8 @@ import fastifyCookie from "@fastify/cookie";
|
|
|
2
2
|
import fastifyCsrfProtection from "@fastify/csrf-protection";
|
|
3
3
|
import { safeRequestUrl } from "@jskit-ai/kernel/server/runtime/requestUrl";
|
|
4
4
|
import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
|
|
5
|
+
import { SECOND_FACTOR_REQUIRED } from "../../shared/authSecondFactor.js";
|
|
6
|
+
import { isSecondFactorMet, secondFactorRequiredParams } from "../secondFactor.js";
|
|
5
7
|
import { hostOnlyCookieName } from "../utils.js";
|
|
6
8
|
|
|
7
9
|
import { assertAuthPolicyDeps, normalizeActorResolution } from "./authPolicySupport.js";
|
|
@@ -103,6 +105,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
|
|
|
103
105
|
fastify.decorateRequest("workspace", null);
|
|
104
106
|
fastify.decorateRequest("membership", null);
|
|
105
107
|
fastify.decorateRequest("permissions", null);
|
|
108
|
+
fastify.decorateRequest("secondFactorAt", "");
|
|
106
109
|
|
|
107
110
|
fastify.addHook("preHandler", async (request, reply) => {
|
|
108
111
|
const pathname = request.raw.url || request.url || "/";
|
|
@@ -147,6 +150,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
|
|
|
147
150
|
}
|
|
148
151
|
|
|
149
152
|
request.user = actorResolution.actor;
|
|
153
|
+
request.secondFactorAt = actorResolution.secondFactorAt;
|
|
150
154
|
request.workspace = null;
|
|
151
155
|
request.membership = null;
|
|
152
156
|
request.permissions = [];
|
|
@@ -226,6 +230,21 @@ function authPolicyPlugin(deps = {}, options = {}) {
|
|
|
226
230
|
throw createError(403, "Forbidden.", { code: "auth.policy.permissionDenied" });
|
|
227
231
|
}
|
|
228
232
|
}
|
|
233
|
+
|
|
234
|
+
if (meta.secondFactor && !isSecondFactorMet(actorResolution.secondFactorAt, meta.secondFactor, Date.now())) {
|
|
235
|
+
onPolicyDenied({
|
|
236
|
+
reason: AUTH_POLICY_DENY_REASONS.SECOND_FACTOR_REQUIRED,
|
|
237
|
+
statusCode: 403,
|
|
238
|
+
request,
|
|
239
|
+
meta,
|
|
240
|
+
actor: actorResolution.actor,
|
|
241
|
+
context
|
|
242
|
+
});
|
|
243
|
+
throw createError(403, SECOND_FACTOR_REQUIRED.message, {
|
|
244
|
+
code: SECOND_FACTOR_REQUIRED.code,
|
|
245
|
+
params: secondFactorRequiredParams(meta.secondFactor)
|
|
246
|
+
});
|
|
247
|
+
}
|
|
229
248
|
});
|
|
230
249
|
};
|
|
231
250
|
}
|
|
@@ -20,7 +20,8 @@ const DEFAULT_AUTH_POLICY_META = Object.freeze({
|
|
|
20
20
|
ownerParam: null,
|
|
21
21
|
userField: "id",
|
|
22
22
|
ownerResolver: null,
|
|
23
|
-
csrfProtection: true
|
|
23
|
+
csrfProtection: true,
|
|
24
|
+
secondFactor: false
|
|
24
25
|
});
|
|
25
26
|
|
|
26
27
|
function resolveAuthPolicyMeta(input = {}) {
|
|
@@ -34,7 +35,9 @@ function resolveAuthPolicyMeta(input = {}) {
|
|
|
34
35
|
userField: source.userField || "id",
|
|
35
36
|
// readable-check: allow method-probe - data: a route's auth policy config may name an owner resolver
|
|
36
37
|
ownerResolver: typeof source.ownerResolver === "function" ? source.ownerResolver : null,
|
|
37
|
-
csrfProtection: source.csrfProtection !== false
|
|
38
|
+
csrfProtection: source.csrfProtection !== false,
|
|
39
|
+
// The route's second factor requirement, as the kernel router checked it: false, true or { maxAgeSeconds }.
|
|
40
|
+
secondFactor: source.secondFactor || false
|
|
38
41
|
};
|
|
39
42
|
}
|
|
40
43
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { defineFeature } from "@jskit-ai/kernel/server/features";
|
|
2
2
|
import { createAuthActions } from "../actions/authActions.js";
|
|
3
|
+
import { createSecondFactorActions } from "../actions/secondFactorActions.js";
|
|
3
4
|
|
|
4
5
|
// Without an auth provider installed there is no auth.service, so no auth actions.
|
|
5
6
|
const NO_AUTH_ACTIONS = Object.freeze([]);
|
|
@@ -11,7 +12,9 @@ const AuthFeature = defineFeature({
|
|
|
11
12
|
authService: "auth.service"
|
|
12
13
|
},
|
|
13
14
|
actions({ authService }) {
|
|
14
|
-
return authService
|
|
15
|
+
return authService
|
|
16
|
+
? Object.freeze([...createAuthActions({ authService }), ...createSecondFactorActions({ authService })])
|
|
17
|
+
: NO_AUTH_ACTIONS;
|
|
15
18
|
}
|
|
16
19
|
});
|
|
17
20
|
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
+
import { SECOND_FACTOR_REQUIRED } from "../shared/authSecondFactor.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Whether a session's second factor meets a requirement: true asks for one
|
|
6
|
+
* proved at any time in the session, `{ maxAgeSeconds }` for one proved within
|
|
7
|
+
* that many seconds of now.
|
|
8
|
+
* @param {string} secondFactorAt When the session last proved its second factor, as ISO text, or "" when it has not.
|
|
9
|
+
* @param {true | { maxAgeSeconds: number }} requirement
|
|
10
|
+
* @param {number} now
|
|
11
|
+
*/
|
|
12
|
+
function isSecondFactorMet(secondFactorAt, requirement, now) {
|
|
13
|
+
const provedAt = Date.parse(secondFactorAt || "");
|
|
14
|
+
if (!Number.isFinite(provedAt)) {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
return requirement === true || now - provedAt <= requirement.maxAgeSeconds * 1000;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The refusal's params: the age a proof may have, when the requirement names one.
|
|
22
|
+
* @param {true | { maxAgeSeconds: number }} requirement
|
|
23
|
+
*/
|
|
24
|
+
function secondFactorRequiredParams(requirement) {
|
|
25
|
+
return requirement === true ? {} : { maxAgeSeconds: requirement.maxAgeSeconds };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Refuses a signed-in request whose session has not proved its second factor
|
|
30
|
+
* as the requirement asks, with 403 `auth.secondFactor.required`, the refusal
|
|
31
|
+
* a route's `secondFactor` option gives. For an action whose requirement
|
|
32
|
+
* depends on more than its route, such as the actor's role. The auth policy
|
|
33
|
+
* sets `request.secondFactorAt` on every route that signs its caller in; a
|
|
34
|
+
* call without a request, as from the server's own code, has no session to
|
|
35
|
+
* prove it and is refused.
|
|
36
|
+
* @param {{ secondFactorAt?: string } | null} request The action's `resolveRequest(context)`.
|
|
37
|
+
* @param {true | { maxAgeSeconds: number }} requirement
|
|
38
|
+
*/
|
|
39
|
+
function requireSecondFactor(request, requirement) {
|
|
40
|
+
const valid = requirement === true || (Number.isInteger(requirement?.maxAgeSeconds) && requirement.maxAgeSeconds > 0);
|
|
41
|
+
if (!valid) {
|
|
42
|
+
throw new TypeError("requireSecondFactor() takes true or { maxAgeSeconds } with a positive integer.");
|
|
43
|
+
}
|
|
44
|
+
if (!isSecondFactorMet(request ? request.secondFactorAt : "", requirement, Date.now())) {
|
|
45
|
+
throw new AppError(403, SECOND_FACTOR_REQUIRED.message, {
|
|
46
|
+
code: SECOND_FACTOR_REQUIRED.code,
|
|
47
|
+
params: secondFactorRequiredParams(requirement)
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export {
|
|
53
|
+
isSecondFactorMet,
|
|
54
|
+
requireSecondFactor,
|
|
55
|
+
secondFactorRequiredParams
|
|
56
|
+
};
|
package/src/server/types.js
CHANGED
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
* @property {object | null} [session] The session to write with writeSessionCookies(), or null.
|
|
16
16
|
* @property {boolean} [clearSession] True when the request's session cookies should be cleared.
|
|
17
17
|
* @property {boolean} [transientFailure] True when authentication could not be decided at this time.
|
|
18
|
+
* @property {string} [secondFactorAt] When the request's session last proved its second factor, as ISO text, or ""
|
|
19
|
+
* when it has not; the auth policy compares it with a route's `secondFactor`.
|
|
18
20
|
* @property {boolean} [refreshRequired] True when the session must be refreshed first, which a caller
|
|
19
21
|
* that asked for no refresh (`refreshSession: false`), such as a realtime socket, cannot do.
|
|
20
22
|
*/
|
|
@@ -57,6 +59,48 @@
|
|
|
57
59
|
* Answers true when the actor may receive the event.
|
|
58
60
|
*/
|
|
59
61
|
|
|
62
|
+
/**
|
|
63
|
+
* A proof of the second factor: an authenticator's current code, or one of
|
|
64
|
+
* the recovery codes; exactly one of the two.
|
|
65
|
+
* @typedef {{ code?: string, recoveryCode?: string }} AuthSecondFactorProof
|
|
66
|
+
*/
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The signed-in person's second factor: whether an authenticator is set up and
|
|
70
|
+
* since when, how many recovery codes are left, and when the request's session
|
|
71
|
+
* last proved it (null when it has not).
|
|
72
|
+
* @typedef {object} AuthSecondFactorStatus
|
|
73
|
+
* @property {boolean} enrolled
|
|
74
|
+
* @property {string | null} enrolledAt
|
|
75
|
+
* @property {number} recoveryCodesLeft
|
|
76
|
+
* @property {string | null} verifiedAt
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* A proof the provider accepted: when, by which kind of code, and how many
|
|
81
|
+
* recovery codes are left.
|
|
82
|
+
* @typedef {object} AuthSecondFactorVerification
|
|
83
|
+
* @property {string} verifiedAt
|
|
84
|
+
* @property {"code" | "recoveryCode"} method
|
|
85
|
+
* @property {number} recoveryCodesLeft
|
|
86
|
+
*/
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* New recovery codes, shown once, and when the session proved its second
|
|
90
|
+
* factor to get them.
|
|
91
|
+
* @typedef {{ recoveryCodes: string[], verifiedAt: string }} AuthSecondFactorRecoveryCodes
|
|
92
|
+
*/
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A started authenticator setup: its secret in base32, shown once, and the
|
|
96
|
+
* otpauth:// address an authenticator app reads from a QR code.
|
|
97
|
+
* @typedef {object} AuthSecondFactorSetup
|
|
98
|
+
* @property {string} secret
|
|
99
|
+
* @property {string} otpauthUrl
|
|
100
|
+
* @property {string} issuer
|
|
101
|
+
* @property {string} accountName
|
|
102
|
+
*/
|
|
103
|
+
|
|
60
104
|
/**
|
|
61
105
|
* What logout() answers: the provider signed the session out, and whether the
|
|
62
106
|
* caller should clear the request's session cookies.
|
|
@@ -103,6 +147,22 @@
|
|
|
103
147
|
* @property {(request: object, input: object) => Promise<object>} unlinkProvider
|
|
104
148
|
* @property {(request: object) => Promise<object>} signOutOtherSessions
|
|
105
149
|
* @property {(input: object, request: object | null) => Promise<object>} devLoginAs
|
|
150
|
+
* @property {(request: object) => Promise<AuthSecondFactorStatus>} getSecondFactorStatus
|
|
151
|
+
* @property {(request: object) => Promise<AuthSecondFactorSetup>} startSecondFactorSetup Starts setting up an
|
|
152
|
+
* authenticator for the signed-in person, replacing a setup they have not confirmed.
|
|
153
|
+
* @property {(request: object, input: { code: string }) => Promise<AuthSecondFactorRecoveryCodes>} confirmSecondFactorSetup
|
|
154
|
+
* Confirms the setup with a first code, answers its recovery codes once, and marks the request's session as having
|
|
155
|
+
* proved its second factor.
|
|
156
|
+
* @property {(request: object, input: AuthSecondFactorProof) => Promise<AuthSecondFactorVerification>} verifySecondFactor
|
|
157
|
+
* Marks the request's session as having proved its second factor.
|
|
158
|
+
* @property {(request: object, input: AuthSecondFactorProof) => Promise<AuthSecondFactorRecoveryCodes>}
|
|
159
|
+
* replaceSecondFactorRecoveryCodes
|
|
160
|
+
* @property {(request: object, input: AuthSecondFactorProof) => Promise<{ ok: true }>} removeSecondFactor
|
|
161
|
+
* @property {(input: { userIds: string[] }) => Promise<{ userId: string, enrolledAt: string }[]>} listSecondFactors
|
|
162
|
+
* The given accounts (provider user ids) that have an authenticator set up: for an application's own screens.
|
|
163
|
+
* @property {(input: { userId: string, byUserId: string }) => Promise<{ reset: boolean }>} resetSecondFactor
|
|
164
|
+
* Removes an account's authenticator and recovery codes for the application, which decides who may: for an owner
|
|
165
|
+
* whose staff lost their authenticator. `byUserId` names who reset it, for the audit event.
|
|
106
166
|
* @property {(reply: object, result: object) => void} [writeOAuthStartCookies] Keeps the state of an OAuth sign-in that oauthStart() began.
|
|
107
167
|
* @property {(reply: object) => void} [clearOAuthStartCookies]
|
|
108
168
|
* @property {(request: object, options?: { everywhere?: boolean }) => Promise<any>} [logoutEverywhere]
|
|
@@ -27,7 +27,15 @@ const AUTH_OPERATION_FEATURES = Object.freeze({
|
|
|
27
27
|
startProviderLink: "providerLinking.start",
|
|
28
28
|
unlinkProvider: "providerLinking.unlink",
|
|
29
29
|
signOutOtherSessions: "signOutOtherSessions",
|
|
30
|
-
devLoginAs: "devLoginAs"
|
|
30
|
+
devLoginAs: "devLoginAs",
|
|
31
|
+
getSecondFactorStatus: "secondFactor",
|
|
32
|
+
startSecondFactorSetup: "secondFactor",
|
|
33
|
+
confirmSecondFactorSetup: "secondFactor",
|
|
34
|
+
verifySecondFactor: "secondFactor",
|
|
35
|
+
replaceSecondFactorRecoveryCodes: "secondFactor",
|
|
36
|
+
removeSecondFactor: "secondFactor",
|
|
37
|
+
listSecondFactors: "secondFactor",
|
|
38
|
+
resetSecondFactor: "secondFactor"
|
|
31
39
|
});
|
|
32
40
|
|
|
33
41
|
function normalizeBoolean(value, fallback = false) {
|
|
@@ -157,7 +165,9 @@ function normalizeAuthCapabilities(value = {}) {
|
|
|
157
165
|
securityStatus: normalizeBoolean(featuresSource.securityStatus),
|
|
158
166
|
signOutOtherSessions: normalizeBoolean(featuresSource.signOutOtherSessions),
|
|
159
167
|
appProfileProjection: normalizeBoolean(featuresSource.appProfileProjection),
|
|
160
|
-
devLoginAs: normalizeBoolean(featuresSource.devLoginAs)
|
|
168
|
+
devLoginAs: normalizeBoolean(featuresSource.devLoginAs),
|
|
169
|
+
// Authenticator codes (TOTP) and recovery codes as a second factor, which routes and actions may ask for.
|
|
170
|
+
secondFactor: normalizeBoolean(featuresSource.secondFactor)
|
|
161
171
|
})
|
|
162
172
|
});
|
|
163
173
|
}
|
package/src/shared/authPaths.js
CHANGED
|
@@ -12,7 +12,12 @@ const AUTH_PATHS = Object.freeze({
|
|
|
12
12
|
PASSWORD_RESET: "/api/password/reset",
|
|
13
13
|
DEV_LOGIN_AS: "/api/dev-auth/login-as",
|
|
14
14
|
LOGOUT: "/api/logout",
|
|
15
|
-
SESSION: "/api/session"
|
|
15
|
+
SESSION: "/api/session",
|
|
16
|
+
SECOND_FACTOR: "/api/second-factor",
|
|
17
|
+
SECOND_FACTOR_SETUP: "/api/second-factor/setup",
|
|
18
|
+
SECOND_FACTOR_SETUP_CONFIRM: "/api/second-factor/setup/confirm",
|
|
19
|
+
SECOND_FACTOR_VERIFY: "/api/second-factor/verify",
|
|
20
|
+
SECOND_FACTOR_RECOVERY_CODES: "/api/second-factor/recovery-codes"
|
|
16
21
|
});
|
|
17
22
|
|
|
18
23
|
function buildAuthOauthStartPath(provider) {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// The refusal of a request whose session has not proved its second factor as its route or action asks: 403, with
|
|
2
|
+
// `params.maxAgeSeconds` when it asks for a proof that recent.
|
|
3
|
+
const SECOND_FACTOR_REQUIRED = Object.freeze({
|
|
4
|
+
code: "auth.secondFactor.required",
|
|
5
|
+
message: "Confirm it's you with a code from your authenticator app."
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Whether an error is that refusal: the server's own, or the one a client's request received.
|
|
10
|
+
* @param {{ status?: number, code?: string | null } | null | undefined} error
|
|
11
|
+
*/
|
|
12
|
+
function isSecondFactorRequired(error) {
|
|
13
|
+
return error?.status === 403 && error?.code === SECOND_FACTOR_REQUIRED.code;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export { SECOND_FACTOR_REQUIRED, isSecondFactorRequired };
|
|
@@ -88,7 +88,12 @@ function normalizeAuthSecurityStatus(value = {}) {
|
|
|
88
88
|
});
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
|
|
91
|
+
/**
|
|
92
|
+
* @param {object} authMethodsStatus
|
|
93
|
+
* @param {{ actions?: object, mfa?: { status: string, enrolled: boolean, methods: string[] } }} [options] `mfa`, when
|
|
94
|
+
* the provider has second factors, says whether the account has one set up.
|
|
95
|
+
*/
|
|
96
|
+
function buildSecurityStatusFromAuthMethodsStatus(authMethodsStatus, { actions = {}, mfa } = {}) {
|
|
92
97
|
const source = authMethodsStatus && typeof authMethodsStatus === "object" ? authMethodsStatus : {};
|
|
93
98
|
return normalizeAuthSecurityStatus({
|
|
94
99
|
authMethods: Array.isArray(source.methods) ? source.methods : [],
|
|
@@ -96,7 +101,8 @@ function buildSecurityStatusFromAuthMethodsStatus(authMethodsStatus, { actions =
|
|
|
96
101
|
minimumEnabledMethods: source.minimumEnabledMethods,
|
|
97
102
|
enabledMethodsCount: source.enabledMethodsCount
|
|
98
103
|
},
|
|
99
|
-
actions
|
|
104
|
+
actions,
|
|
105
|
+
mfa
|
|
100
106
|
});
|
|
101
107
|
}
|
|
102
108
|
|
|
@@ -357,7 +357,8 @@ const authCapabilitiesFeaturesOutputSchema = createSchema({
|
|
|
357
357
|
securityStatus: { type: "boolean", required: true },
|
|
358
358
|
signOutOtherSessions: { type: "boolean", required: true },
|
|
359
359
|
appProfileProjection: { type: "boolean", required: true },
|
|
360
|
-
devLoginAs: { type: "boolean", required: true }
|
|
360
|
+
devLoginAs: { type: "boolean", required: true },
|
|
361
|
+
secondFactor: { type: "boolean", required: true }
|
|
361
362
|
});
|
|
362
363
|
|
|
363
364
|
const authCapabilitiesOutputSchema = createSchema({
|
|
@@ -470,6 +471,7 @@ const AUTH_FIELD_MESSAGES = deepFreeze({
|
|
|
470
471
|
otpTokenHashInvalid: { code: "auth.validation.otpTokenHashInvalid", message: "One-time token hash is invalid." },
|
|
471
472
|
otpTypeUnsupported: { code: "auth.validation.otpTypeUnsupported", message: "Only email OTP verification is supported." },
|
|
472
473
|
recoveryCodeInvalid: { code: "auth.validation.recoveryCodeInvalid", message: "Recovery code is invalid." },
|
|
474
|
+
secondFactorCodeRequired: { code: "auth.validation.secondFactorCodeRequired", message: "Enter the code from your authenticator app." },
|
|
473
475
|
recoveryTokenHashInvalid: {
|
|
474
476
|
code: "auth.validation.recoveryTokenHashInvalid",
|
|
475
477
|
message: "Recovery token hash is invalid."
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createSchema } from "json-rest-schema";
|
|
2
|
+
import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
|
|
3
|
+
import { AUTH_FIELD_MESSAGES, createCommandMessages, okOutputValidator } from "./authCommandValidators.js";
|
|
4
|
+
|
|
5
|
+
// The second factor's commands: reading it, setting up an authenticator, proving a code, and replacing its recovery
|
|
6
|
+
// codes or removing it with a proof. A code is an authenticator's six digits, which a person may type with spaces; a
|
|
7
|
+
// recovery code is ten letters and digits, which they may type with a hyphen.
|
|
8
|
+
const SECOND_FACTOR_CODE_MAX_LENGTH = 16;
|
|
9
|
+
const RECOVERY_CODE_MAX_LENGTH = 32;
|
|
10
|
+
|
|
11
|
+
const secondFactorCodeField = deepFreeze({ type: "string", minLength: 1, maxLength: SECOND_FACTOR_CODE_MAX_LENGTH });
|
|
12
|
+
const recoveryCodeField = deepFreeze({ type: "string", minLength: 1, maxLength: RECOVERY_CODE_MAX_LENGTH });
|
|
13
|
+
const isoTextField = deepFreeze({ type: "string", minLength: 1, maxLength: 64 });
|
|
14
|
+
|
|
15
|
+
const SECOND_FACTOR_CODE_MESSAGES = createCommandMessages({
|
|
16
|
+
fields: {
|
|
17
|
+
code: {
|
|
18
|
+
required: AUTH_FIELD_MESSAGES.secondFactorCodeRequired,
|
|
19
|
+
default: AUTH_FIELD_MESSAGES.secondFactorCodeRequired
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// A proof is a code or a recovery code; the provider refuses one that gives neither or both.
|
|
25
|
+
const SECOND_FACTOR_PROOF_MESSAGES = createCommandMessages({
|
|
26
|
+
fields: {
|
|
27
|
+
code: {
|
|
28
|
+
default: AUTH_FIELD_MESSAGES.secondFactorCodeRequired
|
|
29
|
+
},
|
|
30
|
+
recoveryCode: {
|
|
31
|
+
default: AUTH_FIELD_MESSAGES.recoveryCodeInvalid
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const secondFactorCodeBodyValidator = deepFreeze({
|
|
37
|
+
schema: createSchema({
|
|
38
|
+
code: { ...secondFactorCodeField, required: true }
|
|
39
|
+
}),
|
|
40
|
+
mode: "create",
|
|
41
|
+
messages: SECOND_FACTOR_CODE_MESSAGES
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const secondFactorProofBodyValidator = deepFreeze({
|
|
45
|
+
schema: createSchema({
|
|
46
|
+
code: { ...secondFactorCodeField, required: false },
|
|
47
|
+
recoveryCode: { ...recoveryCodeField, required: false }
|
|
48
|
+
}),
|
|
49
|
+
mode: "create",
|
|
50
|
+
messages: SECOND_FACTOR_PROOF_MESSAGES
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const secondFactorStatusOutputValidator = deepFreeze({
|
|
54
|
+
schema: createSchema({
|
|
55
|
+
enrolled: { type: "boolean", required: true },
|
|
56
|
+
enrolledAt: { ...isoTextField, required: true, nullable: true },
|
|
57
|
+
recoveryCodesLeft: { type: "integer", required: true, min: 0 },
|
|
58
|
+
// When the request's session last proved its second factor.
|
|
59
|
+
verifiedAt: { ...isoTextField, required: true, nullable: true }
|
|
60
|
+
}),
|
|
61
|
+
mode: "replace"
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const secondFactorSetupOutputValidator = deepFreeze({
|
|
65
|
+
schema: createSchema({
|
|
66
|
+
// The authenticator's secret in base32, shown once for a person to type; otpauthUrl carries it for a QR code.
|
|
67
|
+
secret: { type: "string", required: true, minLength: 16, maxLength: 128 },
|
|
68
|
+
otpauthUrl: { type: "string", required: true, minLength: 1, maxLength: 1024 },
|
|
69
|
+
issuer: { type: "string", required: true, minLength: 1, maxLength: 255 },
|
|
70
|
+
accountName: { type: "string", required: true, minLength: 1, maxLength: 320 }
|
|
71
|
+
}),
|
|
72
|
+
mode: "replace"
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// New recovery codes, shown once: only their hashes are kept.
|
|
76
|
+
const secondFactorRecoveryCodesOutputValidator = deepFreeze({
|
|
77
|
+
schema: createSchema({
|
|
78
|
+
recoveryCodes: { type: "array", required: true, items: { type: "string", minLength: 1, maxLength: RECOVERY_CODE_MAX_LENGTH } },
|
|
79
|
+
verifiedAt: { ...isoTextField, required: true }
|
|
80
|
+
}),
|
|
81
|
+
mode: "replace"
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const secondFactorVerifyOutputValidator = deepFreeze({
|
|
85
|
+
schema: createSchema({
|
|
86
|
+
verifiedAt: { ...isoTextField, required: true },
|
|
87
|
+
method: { type: "string", required: true, enum: ["code", "recoveryCode"] },
|
|
88
|
+
recoveryCodesLeft: { type: "integer", required: true, min: 0 }
|
|
89
|
+
}),
|
|
90
|
+
mode: "replace"
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const READ_INVALIDATES = Object.freeze(["auth.secondFactor.read"]);
|
|
94
|
+
|
|
95
|
+
const authSecondFactorReadCommand = deepFreeze({
|
|
96
|
+
command: "auth.secondFactor.read",
|
|
97
|
+
operation: {
|
|
98
|
+
method: "GET",
|
|
99
|
+
response: secondFactorStatusOutputValidator,
|
|
100
|
+
messages: createCommandMessages(),
|
|
101
|
+
idempotent: true,
|
|
102
|
+
invalidates: []
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
const authSecondFactorSetupStartCommand = deepFreeze({
|
|
107
|
+
command: "auth.secondFactor.setup.start",
|
|
108
|
+
operation: {
|
|
109
|
+
method: "POST",
|
|
110
|
+
response: secondFactorSetupOutputValidator,
|
|
111
|
+
messages: createCommandMessages(),
|
|
112
|
+
idempotent: false,
|
|
113
|
+
invalidates: READ_INVALIDATES
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const authSecondFactorSetupConfirmCommand = deepFreeze({
|
|
118
|
+
command: "auth.secondFactor.setup.confirm",
|
|
119
|
+
operation: {
|
|
120
|
+
method: "POST",
|
|
121
|
+
body: secondFactorCodeBodyValidator,
|
|
122
|
+
response: secondFactorRecoveryCodesOutputValidator,
|
|
123
|
+
messages: SECOND_FACTOR_CODE_MESSAGES,
|
|
124
|
+
idempotent: false,
|
|
125
|
+
invalidates: READ_INVALIDATES
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const authSecondFactorVerifyCommand = deepFreeze({
|
|
130
|
+
command: "auth.secondFactor.verify",
|
|
131
|
+
operation: {
|
|
132
|
+
method: "POST",
|
|
133
|
+
body: secondFactorProofBodyValidator,
|
|
134
|
+
response: secondFactorVerifyOutputValidator,
|
|
135
|
+
messages: SECOND_FACTOR_PROOF_MESSAGES,
|
|
136
|
+
idempotent: false,
|
|
137
|
+
invalidates: READ_INVALIDATES
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
const authSecondFactorRecoveryCodesReplaceCommand = deepFreeze({
|
|
142
|
+
command: "auth.secondFactor.recoveryCodes.replace",
|
|
143
|
+
operation: {
|
|
144
|
+
method: "POST",
|
|
145
|
+
body: secondFactorProofBodyValidator,
|
|
146
|
+
response: secondFactorRecoveryCodesOutputValidator,
|
|
147
|
+
messages: SECOND_FACTOR_PROOF_MESSAGES,
|
|
148
|
+
idempotent: false,
|
|
149
|
+
invalidates: READ_INVALIDATES
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
const authSecondFactorRemoveCommand = deepFreeze({
|
|
154
|
+
command: "auth.secondFactor.remove",
|
|
155
|
+
operation: {
|
|
156
|
+
method: "DELETE",
|
|
157
|
+
body: secondFactorProofBodyValidator,
|
|
158
|
+
response: okOutputValidator,
|
|
159
|
+
messages: SECOND_FACTOR_PROOF_MESSAGES,
|
|
160
|
+
idempotent: false,
|
|
161
|
+
invalidates: READ_INVALIDATES
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
export {
|
|
166
|
+
authSecondFactorReadCommand,
|
|
167
|
+
authSecondFactorRecoveryCodesReplaceCommand,
|
|
168
|
+
authSecondFactorRemoveCommand,
|
|
169
|
+
authSecondFactorSetupConfirmCommand,
|
|
170
|
+
authSecondFactorSetupStartCommand,
|
|
171
|
+
authSecondFactorVerifyCommand
|
|
172
|
+
};
|
|
@@ -12,3 +12,11 @@ export { authPasswordRecoveryCompleteCommand } from "./authPasswordRecoveryCompl
|
|
|
12
12
|
export { authPasswordResetCommand } from "./authPasswordResetCommand.js";
|
|
13
13
|
export { authLogoutCommand } from "./authLogoutCommand.js";
|
|
14
14
|
export { authSessionReadCommand } from "./authSessionReadCommand.js";
|
|
15
|
+
export {
|
|
16
|
+
authSecondFactorReadCommand,
|
|
17
|
+
authSecondFactorRecoveryCodesReplaceCommand,
|
|
18
|
+
authSecondFactorRemoveCommand,
|
|
19
|
+
authSecondFactorSetupConfirmCommand,
|
|
20
|
+
authSecondFactorSetupStartCommand,
|
|
21
|
+
authSecondFactorVerifyCommand
|
|
22
|
+
} from "./authSecondFactorCommands.js";
|
package/src/shared/index.js
CHANGED
|
@@ -8,6 +8,7 @@ export {
|
|
|
8
8
|
resolveAuthDeniedLoginMessage
|
|
9
9
|
} from "./authDenied.js";
|
|
10
10
|
export { AUTH_PATHS, buildAuthOauthStartPath } from "./authPaths.js";
|
|
11
|
+
export { SECOND_FACTOR_REQUIRED, isSecondFactorRequired } from "./authSecondFactor.js";
|
|
11
12
|
export {
|
|
12
13
|
AUTH_PASSWORD_RECOVERY_DELIVERIES,
|
|
13
14
|
AUTH_OPERATION_FEATURES,
|
package/test/authActions.test.js
CHANGED
|
@@ -5,6 +5,7 @@ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
|
|
|
5
5
|
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
6
6
|
import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
7
7
|
import { createAuthActions } from "../src/server/actions/authActions.js";
|
|
8
|
+
import { createSecondFactorActions } from "../src/server/actions/secondFactorActions.js";
|
|
8
9
|
import { AuthFeature } from "../src/server/providers/AuthFeature.js";
|
|
9
10
|
|
|
10
11
|
test("auth logout action delegates directly to the selected auth service", async () => {
|
|
@@ -40,6 +41,44 @@ test("shared dev login-as action passes the trusted request to auth.service", as
|
|
|
40
41
|
assert.deepEqual(received, { input, request });
|
|
41
42
|
});
|
|
42
43
|
|
|
44
|
+
test("second factor actions hand the request's own session and the input to auth.service", async () => {
|
|
45
|
+
const calls = [];
|
|
46
|
+
const record = (name) => async (...args) => {
|
|
47
|
+
calls.push([name, ...args]);
|
|
48
|
+
return { name };
|
|
49
|
+
};
|
|
50
|
+
const authService = {
|
|
51
|
+
getSecondFactorStatus: record("getSecondFactorStatus"),
|
|
52
|
+
startSecondFactorSetup: record("startSecondFactorSetup"),
|
|
53
|
+
confirmSecondFactorSetup: record("confirmSecondFactorSetup"),
|
|
54
|
+
verifySecondFactor: record("verifySecondFactor"),
|
|
55
|
+
replaceSecondFactorRecoveryCodes: record("replaceSecondFactorRecoveryCodes"),
|
|
56
|
+
removeSecondFactor: record("removeSecondFactor")
|
|
57
|
+
};
|
|
58
|
+
const request = { id: "request-1" };
|
|
59
|
+
const actions = createSecondFactorActions({ authService });
|
|
60
|
+
assert.deepEqual(actions.map((action) => [action.id, action.kind, action.permission]), [
|
|
61
|
+
["auth.secondFactor.read", "query", { require: "authenticated" }],
|
|
62
|
+
["auth.secondFactor.setup.start", "command", { require: "authenticated" }],
|
|
63
|
+
["auth.secondFactor.setup.confirm", "command", { require: "authenticated" }],
|
|
64
|
+
["auth.secondFactor.verify", "command", { require: "authenticated" }],
|
|
65
|
+
["auth.secondFactor.recoveryCodes.replace", "command", { require: "authenticated" }],
|
|
66
|
+
["auth.secondFactor.remove", "command", { require: "authenticated" }]
|
|
67
|
+
]);
|
|
68
|
+
assert.equal(actions.some((action) => action.channels.includes("automation")), false, "codes never reach automation");
|
|
69
|
+
for (const action of actions) {
|
|
70
|
+
await action.execute({ code: "123456" }, { requestMeta: { request } });
|
|
71
|
+
}
|
|
72
|
+
assert.deepEqual(calls, [
|
|
73
|
+
["getSecondFactorStatus", request],
|
|
74
|
+
["startSecondFactorSetup", request],
|
|
75
|
+
["confirmSecondFactorSetup", request, { code: "123456" }],
|
|
76
|
+
["verifySecondFactor", request, { code: "123456" }],
|
|
77
|
+
["replaceSecondFactorRecoveryCodes", request, { code: "123456" }],
|
|
78
|
+
["removeSecondFactor", request, { code: "123456" }]
|
|
79
|
+
]);
|
|
80
|
+
});
|
|
81
|
+
|
|
43
82
|
test("AuthFeature contributes actions only when auth.service exists", async () => {
|
|
44
83
|
let actions = null;
|
|
45
84
|
const SelectedAuthProvider = defineProvider({
|
|
@@ -72,6 +111,7 @@ test("AuthFeature contributes actions only when auth.service exists", async () =
|
|
|
72
111
|
});
|
|
73
112
|
await runtime.start();
|
|
74
113
|
assert.equal(actions.listDefinitions().some((definition) => definition.id === "auth.login.password"), true);
|
|
114
|
+
assert.equal(actions.listDefinitions().some((definition) => definition.id === "auth.secondFactor.verify"), true);
|
|
75
115
|
assert.deepEqual(actions.getDefinition("auth.session.read").surfaces, ["*"]);
|
|
76
116
|
|
|
77
117
|
let publicActions = null;
|
|
@@ -98,6 +98,26 @@ test("normalizeAuthCapabilities returns one provider-neutral feature shape", ()
|
|
|
98
98
|
);
|
|
99
99
|
});
|
|
100
100
|
|
|
101
|
+
test("the second factor is a capability of its own, which every second factor operation needs", () => {
|
|
102
|
+
const without = normalizeAuthCapabilities({ features: { password: { login: true } } });
|
|
103
|
+
const withSecondFactor = normalizeAuthCapabilities({ features: { secondFactor: true } });
|
|
104
|
+
assert.equal(without.features.secondFactor, false);
|
|
105
|
+
assert.equal(withSecondFactor.features.secondFactor, true);
|
|
106
|
+
for (const operation of [
|
|
107
|
+
"getSecondFactorStatus",
|
|
108
|
+
"startSecondFactorSetup",
|
|
109
|
+
"confirmSecondFactorSetup",
|
|
110
|
+
"verifySecondFactor",
|
|
111
|
+
"replaceSecondFactorRecoveryCodes",
|
|
112
|
+
"removeSecondFactor",
|
|
113
|
+
"listSecondFactors",
|
|
114
|
+
"resetSecondFactor"
|
|
115
|
+
]) {
|
|
116
|
+
assert.equal(isAuthOperationSupported(without, operation), false, operation);
|
|
117
|
+
assert.equal(isAuthOperationSupported(withSecondFactor, operation), true, operation);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
101
121
|
test("normalizeAuthActor builds the canonical actor", () => {
|
|
102
122
|
const actor = normalizeAuthActor({
|
|
103
123
|
provider: "supabase",
|
|
@@ -15,6 +15,14 @@ import { authPasswordResetCommand } from "../src/shared/commands/authPasswordRes
|
|
|
15
15
|
import { authLogoutCommand } from "../src/shared/commands/authLogoutCommand.js";
|
|
16
16
|
import { authSessionReadCommand } from "../src/shared/commands/authSessionReadCommand.js";
|
|
17
17
|
import { authDevLoginAsCommand } from "../src/shared/commands/authDevLoginAsCommand.js";
|
|
18
|
+
import {
|
|
19
|
+
authSecondFactorReadCommand,
|
|
20
|
+
authSecondFactorRecoveryCodesReplaceCommand,
|
|
21
|
+
authSecondFactorRemoveCommand,
|
|
22
|
+
authSecondFactorSetupConfirmCommand,
|
|
23
|
+
authSecondFactorSetupStartCommand,
|
|
24
|
+
authSecondFactorVerifyCommand
|
|
25
|
+
} from "../src/shared/commands/authSecondFactorCommands.js";
|
|
18
26
|
import { catalogMessage, formatMessage, mergeCatalogs, messageKeyForCode } from "@jskit-ai/kernel/shared/i18n";
|
|
19
27
|
import kernelEnglish from "@jskit-ai/kernel/locales/en.json" with { type: "json" };
|
|
20
28
|
import authEnglish from "../locales/en.json" with { type: "json" };
|
|
@@ -33,7 +41,13 @@ test("auth commands expose canonical operation validator messages", () => {
|
|
|
33
41
|
authPasswordRecoveryCompleteCommand,
|
|
34
42
|
authPasswordResetCommand,
|
|
35
43
|
authLogoutCommand,
|
|
36
|
-
authSessionReadCommand
|
|
44
|
+
authSessionReadCommand,
|
|
45
|
+
authSecondFactorReadCommand,
|
|
46
|
+
authSecondFactorSetupStartCommand,
|
|
47
|
+
authSecondFactorSetupConfirmCommand,
|
|
48
|
+
authSecondFactorVerifyCommand,
|
|
49
|
+
authSecondFactorRecoveryCodesReplaceCommand,
|
|
50
|
+
authSecondFactorRemoveCommand
|
|
37
51
|
};
|
|
38
52
|
|
|
39
53
|
for (const [label, command] of Object.entries(commands)) {
|
|
@@ -67,7 +81,13 @@ test("every auth command message is coded and its English renders from the catal
|
|
|
67
81
|
authPasswordResetCommand,
|
|
68
82
|
authLogoutCommand,
|
|
69
83
|
authSessionReadCommand,
|
|
70
|
-
authDevLoginAsCommand
|
|
84
|
+
authDevLoginAsCommand,
|
|
85
|
+
authSecondFactorReadCommand,
|
|
86
|
+
authSecondFactorSetupStartCommand,
|
|
87
|
+
authSecondFactorSetupConfirmCommand,
|
|
88
|
+
authSecondFactorVerifyCommand,
|
|
89
|
+
authSecondFactorRecoveryCodesReplaceCommand,
|
|
90
|
+
authSecondFactorRemoveCommand
|
|
71
91
|
];
|
|
72
92
|
const sources = commands.flatMap((command) => [
|
|
73
93
|
[`${command.command}.messages`, command.operation.messages],
|
|
@@ -146,6 +166,18 @@ test("registration takes the first account's setup code and confirmation takes i
|
|
|
146
166
|
assert.deepEqual(Object.keys(confirmBody.create({ token: "code", password: "" }).errors), ["password"]);
|
|
147
167
|
});
|
|
148
168
|
|
|
169
|
+
test("confirming an authenticator takes its code, and a proof takes a code or a recovery code", () => {
|
|
170
|
+
const confirmBody = authSecondFactorSetupConfirmCommand.operation.body.schema;
|
|
171
|
+
assert.deepEqual(confirmBody.create({ code: "123 456" }).validatedObject, { code: "123 456" });
|
|
172
|
+
assert.deepEqual(Object.keys(confirmBody.create({}).errors), ["code"]);
|
|
173
|
+
const proofBody = authSecondFactorVerifyCommand.operation.body.schema;
|
|
174
|
+
assert.deepEqual(proofBody.create({ code: "123456" }).validatedObject, { code: "123456" });
|
|
175
|
+
assert.deepEqual(proofBody.create({ recoveryCode: "abcde-fghjk" }).validatedObject, { recoveryCode: "abcde-fghjk" });
|
|
176
|
+
assert.deepEqual(Object.keys(proofBody.create({ code: "1".repeat(17) }).errors), ["code"]);
|
|
177
|
+
assert.deepEqual(Object.keys(proofBody.create({ recoveryCode: "x".repeat(33) }).errors), ["recoveryCode"]);
|
|
178
|
+
assert.equal(authSecondFactorRemoveCommand.operation.body, authSecondFactorVerifyCommand.operation.body);
|
|
179
|
+
});
|
|
180
|
+
|
|
149
181
|
test("auth session and oauth start commands expose explicit nested response schemas", () => {
|
|
150
182
|
const sessionResponseSchema = resolveSchemaTransportSchemaDefinition(
|
|
151
183
|
authSessionReadCommand.operation.response,
|
package/test/routeMeta.test.js
CHANGED
|
@@ -14,7 +14,8 @@ test("withAuthPolicy applies stable defaults", () => {
|
|
|
14
14
|
ownerParam: null,
|
|
15
15
|
userField: "id",
|
|
16
16
|
ownerResolver: null,
|
|
17
|
-
csrfProtection: true
|
|
17
|
+
csrfProtection: true,
|
|
18
|
+
secondFactor: false
|
|
18
19
|
}
|
|
19
20
|
});
|
|
20
21
|
});
|
|
@@ -46,7 +47,8 @@ test("mergeAuthPolicy preserves existing config fields and adds auth policy defa
|
|
|
46
47
|
ownerParam: null,
|
|
47
48
|
userField: "id",
|
|
48
49
|
ownerResolver: null,
|
|
49
|
-
csrfProtection: true
|
|
50
|
+
csrfProtection: true,
|
|
51
|
+
secondFactor: false
|
|
50
52
|
});
|
|
51
53
|
});
|
|
52
54
|
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { createFakeFastifyPolicyRuntime } from "../../../tooling/testUtils/fakeFastify.mjs";
|
|
4
|
+
import { authPolicyPlugin } from "../src/server/lib/index.js";
|
|
5
|
+
import { requireSecondFactor } from "../src/server/secondFactor.js";
|
|
6
|
+
|
|
7
|
+
const NOW = Date.parse("2026-11-13T10:00:00.000Z");
|
|
8
|
+
const minutesAgo = (minutes) => new Date(NOW - minutes * 60_000).toISOString();
|
|
9
|
+
const REQUIRED = Object.freeze({
|
|
10
|
+
status: 403,
|
|
11
|
+
code: "auth.secondFactor.required",
|
|
12
|
+
message: "Confirm it's you with a code from your authenticator app."
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
/** The auth policy over one signed-in session whose second factor time a test sets. */
|
|
16
|
+
async function startPolicy({ hasPermission = () => true } = {}) {
|
|
17
|
+
const { fastify, state } = createFakeFastifyPolicyRuntime();
|
|
18
|
+
const denied = [];
|
|
19
|
+
let secondFactorAt = "";
|
|
20
|
+
await authPolicyPlugin({
|
|
21
|
+
async resolveActor() {
|
|
22
|
+
return { authenticated: true, actor: { id: 7 }, secondFactorAt, transientFailure: false };
|
|
23
|
+
},
|
|
24
|
+
hasPermission,
|
|
25
|
+
onPolicyDenied(event) {
|
|
26
|
+
denied.push(event.reason);
|
|
27
|
+
}
|
|
28
|
+
})(fastify);
|
|
29
|
+
return {
|
|
30
|
+
state,
|
|
31
|
+
denied,
|
|
32
|
+
provedAt(value) {
|
|
33
|
+
secondFactorAt = value;
|
|
34
|
+
},
|
|
35
|
+
async request(config) {
|
|
36
|
+
const request = { method: "POST", raw: { url: "/api/console/action" }, headers: {}, params: {}, routeOptions: { config: { authPolicy: "required", ...config } } };
|
|
37
|
+
await state.preHandler(request, {});
|
|
38
|
+
return request;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
test("a route that asks for a second factor refuses a session that has not proved one", async (t) => {
|
|
44
|
+
t.mock.timers.enable({ apis: ["Date"], now: NOW });
|
|
45
|
+
const policy = await startPolicy();
|
|
46
|
+
assert.equal(policy.state.requestDecorators.has("secondFactorAt"), true);
|
|
47
|
+
|
|
48
|
+
await assert.rejects(policy.request({ secondFactor: true }), { ...REQUIRED, params: {} });
|
|
49
|
+
assert.deepEqual(policy.denied, ["second_factor_required"]);
|
|
50
|
+
assert.equal((await policy.request({})).secondFactorAt, "", "a route without the option lets the session through");
|
|
51
|
+
|
|
52
|
+
policy.provedAt(minutesAgo(90));
|
|
53
|
+
assert.equal((await policy.request({ secondFactor: true })).secondFactorAt, minutesAgo(90), "any time in the session will do");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("a dangerous action asks for a second factor proved within its max age", async (t) => {
|
|
57
|
+
t.mock.timers.enable({ apis: ["Date"], now: NOW });
|
|
58
|
+
const policy = await startPolicy();
|
|
59
|
+
const freshCode = { secondFactor: { maxAgeSeconds: 300 } };
|
|
60
|
+
|
|
61
|
+
policy.provedAt(minutesAgo(6));
|
|
62
|
+
await assert.rejects(policy.request(freshCode), { ...REQUIRED, params: { maxAgeSeconds: 300 } });
|
|
63
|
+
policy.provedAt(minutesAgo(5));
|
|
64
|
+
await policy.request(freshCode);
|
|
65
|
+
policy.provedAt(minutesAgo(1));
|
|
66
|
+
await policy.request(freshCode);
|
|
67
|
+
policy.provedAt("not a time");
|
|
68
|
+
await assert.rejects(policy.request(freshCode), REQUIRED);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("a caller without the route's permission is refused for that, not asked for a code", async () => {
|
|
72
|
+
const policy = await startPolicy({ hasPermission: () => false });
|
|
73
|
+
await assert.rejects(policy.request({ permission: "console.manage", secondFactor: true }), {
|
|
74
|
+
status: 403,
|
|
75
|
+
code: "auth.policy.permissionDenied"
|
|
76
|
+
});
|
|
77
|
+
assert.deepEqual(policy.denied, ["forbidden_permission"]);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("requireSecondFactor refuses an action whose session has not proved its second factor as asked", (t) => {
|
|
81
|
+
t.mock.timers.enable({ apis: ["Date"], now: NOW });
|
|
82
|
+
assert.throws(() => requireSecondFactor({ secondFactorAt: "" }, true), { ...REQUIRED, params: {} });
|
|
83
|
+
assert.throws(() => requireSecondFactor({}, true), REQUIRED);
|
|
84
|
+
assert.throws(() => requireSecondFactor(null, true), REQUIRED, "a call without a request has no session to prove it");
|
|
85
|
+
assert.throws(() => requireSecondFactor({ secondFactorAt: minutesAgo(10) }, { maxAgeSeconds: 300 }), {
|
|
86
|
+
...REQUIRED,
|
|
87
|
+
params: { maxAgeSeconds: 300 }
|
|
88
|
+
});
|
|
89
|
+
requireSecondFactor({ secondFactorAt: minutesAgo(10) }, true);
|
|
90
|
+
requireSecondFactor({ secondFactorAt: minutesAgo(1) }, { maxAgeSeconds: 300 });
|
|
91
|
+
for (const requirement of [false, undefined, { maxAgeSeconds: 0 }, { maxAgeSeconds: "300" }]) {
|
|
92
|
+
assert.throws(() => requireSecondFactor({ secondFactorAt: minutesAgo(1) }, requirement), TypeError);
|
|
93
|
+
}
|
|
94
|
+
});
|