@jskit-ai/auth-provider-local-core 0.2.5 → 0.2.6
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/package.json +9 -4
- package/src/server/lib/accounts.js +244 -0
- package/src/server/lib/authPayloads.js +109 -0
- package/src/server/lib/config.js +119 -0
- package/src/server/lib/index.js +3 -1
- package/src/server/lib/oauth.js +9 -5
- package/src/server/lib/oauthFlows.js +221 -0
- package/src/server/lib/passwordFlows.js +158 -0
- package/src/server/lib/passwords.js +18 -16
- package/src/server/lib/registerHookDecorator.js +74 -53
- package/src/server/lib/securityStatus.js +86 -0
- package/src/server/lib/service.js +102 -1047
- package/src/server/lib/sessions.js +324 -0
- package/src/server/lib/tokens.js +13 -1
- package/src/server/providers/AuthLocalProvider.js +28 -81
- package/src/server/types.js +73 -0
- package/test/codedTexts.test.js +5 -10
- package/test/oauthSignIn.test.js +16 -6
- package/test/providerRuntime.test.js +50 -39
- package/test-support/localService.js +38 -0
- package/test-support/oauthHarness.js +15 -9
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
+
import { hostOnlyCookieName, normalizeReturnToPath } from "@jskit-ai/auth-core/server/utils";
|
|
3
|
+
import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
4
|
+
import { NO_PASSWORD, hasPassword, normalizeDisplayName } from "./accounts.js";
|
|
5
|
+
import { buildAuthPayload } from "./authPayloads.js";
|
|
6
|
+
import { createOAuthClients } from "./oauth.js";
|
|
7
|
+
import { cookieOptions, safeRequestCookies } from "./sessions.js";
|
|
8
|
+
import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url } from "./tokens.js";
|
|
9
|
+
|
|
10
|
+
const OAUTH_ATTEMPT_COOKIE_NAME = "jskit_local_oauth_attempt";
|
|
11
|
+
const OAUTH_ATTEMPT_TTL_SECONDS = 10 * 60;
|
|
12
|
+
/** Every provider returns to the login page, which completes a sign-in or a link. */
|
|
13
|
+
const OAUTH_REDIRECT_PATH = "/auth/login";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Signing in with a configured OAuth provider, and linking or unlinking one.
|
|
17
|
+
* @param {object} dependencies
|
|
18
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
19
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
20
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
21
|
+
* @param {Map<string, import("../types.js").AuthLocalOAuthProvider>} dependencies.oauthProvidersById
|
|
22
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
23
|
+
* @param {ReturnType<typeof import("./securityStatus.js").createLocalSecurityStatus>} dependencies.securityStatus
|
|
24
|
+
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
25
|
+
*/
|
|
26
|
+
function createLocalOAuthFlows({ backend, config, logger, oauthProvidersById, profileProjector, securityStatus, sessions }) {
|
|
27
|
+
const { isProduction, oauthEnabled } = config;
|
|
28
|
+
const OAUTH_ATTEMPT_COOKIE = hostOnlyCookieName(OAUTH_ATTEMPT_COOKIE_NAME, isProduction);
|
|
29
|
+
const oauthRedirectUri = oauthEnabled ? `${config.appPublicUrl.replace(/\/$/u, "")}${OAUTH_REDIRECT_PATH}` : "";
|
|
30
|
+
const appOrigin = oauthEnabled ? new URL(config.appPublicUrl).origin : "";
|
|
31
|
+
const oauthClients = createOAuthClients({ logger });
|
|
32
|
+
|
|
33
|
+
function requireOAuthProvider(value) {
|
|
34
|
+
const provider = oauthProvidersById.get(String(value || "").trim().toLowerCase());
|
|
35
|
+
if (!provider) {
|
|
36
|
+
throw new AppError(400, "This sign-in provider is not available.", { code: "auth.local.oauth.providerInvalid" });
|
|
37
|
+
}
|
|
38
|
+
return provider;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The attempt (state, nonce, PKCE verifier) is stored server-side under the
|
|
43
|
+
* hash of a random key that only the starting browser holds in a cookie.
|
|
44
|
+
*/
|
|
45
|
+
async function beginOAuthAttempt(provider, { intent, userId = "", returnTo }) {
|
|
46
|
+
const browserKey = randomToken(32);
|
|
47
|
+
const attempt = {
|
|
48
|
+
browserKeyHash: sha256Base64url(browserKey),
|
|
49
|
+
provider: provider.id,
|
|
50
|
+
intent,
|
|
51
|
+
userId,
|
|
52
|
+
state: randomToken(32),
|
|
53
|
+
nonce: randomToken(32),
|
|
54
|
+
codeVerifier: randomToken(32),
|
|
55
|
+
returnTo: normalizeReturnToPath(returnTo, { fallback: "/", allowedOrigins: [appOrigin] }),
|
|
56
|
+
expiresAt: isoFromNow(OAUTH_ATTEMPT_TTL_SECONDS)
|
|
57
|
+
};
|
|
58
|
+
const url = await oauthClients.authorizationUrl(provider, { ...attempt, redirectUri: oauthRedirectUri });
|
|
59
|
+
await backend.withTransaction(async (tx) => {
|
|
60
|
+
await tx.oauthAttempts.deleteExpired(new Date().toISOString());
|
|
61
|
+
await tx.oauthAttempts.create(attempt);
|
|
62
|
+
});
|
|
63
|
+
return { provider: provider.id, returnTo: attempt.returnTo, url, attempt: browserKey };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function oauthStart(input) {
|
|
67
|
+
return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "login", returnTo: input.returnTo });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function startProviderLink(request, input) {
|
|
71
|
+
const userId = await sessions.requireNormalSessionUserId(request);
|
|
72
|
+
return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "link", userId, returnTo: input.returnTo });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function writeOAuthStartCookies(reply, result) {
|
|
76
|
+
if (reply && result?.attempt) {
|
|
77
|
+
reply.setCookie(OAUTH_ATTEMPT_COOKIE, result.attempt, cookieOptions(isProduction, OAUTH_ATTEMPT_TTL_SECONDS));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function clearOAuthStartCookies(reply) {
|
|
82
|
+
if (reply) {
|
|
83
|
+
reply.clearCookie(OAUTH_ATTEMPT_COOKIE, cookieOptions(isProduction, 0));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Subject first, then a verified email that matches an existing user, then a
|
|
89
|
+
* new user created like register; profile sync then provisions it as usual.
|
|
90
|
+
*/
|
|
91
|
+
async function signInWithOAuthIdentity(identity) {
|
|
92
|
+
const result = await backend.withTransaction(async (tx) => {
|
|
93
|
+
const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
|
|
94
|
+
let user = linked ? await tx.users.findById(linked.userId) : await tx.users.findByEmail(identity.email);
|
|
95
|
+
const registered = !linked && !user;
|
|
96
|
+
if (registered) {
|
|
97
|
+
user = await tx.users.create({
|
|
98
|
+
id: createId("usr"),
|
|
99
|
+
email: identity.email,
|
|
100
|
+
displayName: normalizeDisplayName(identity.name, identity.email),
|
|
101
|
+
password: NO_PASSWORD
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (!user || user.disabled) {
|
|
105
|
+
throw new AppError(401, "This account can't sign in.", { code: "auth.local.oauth.accountUnavailable" });
|
|
106
|
+
}
|
|
107
|
+
if (!linked) {
|
|
108
|
+
await tx.identities.create({
|
|
109
|
+
userId: user.id,
|
|
110
|
+
provider: identity.provider,
|
|
111
|
+
providerSubject: identity.providerSubject,
|
|
112
|
+
email: identity.email
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return { user, registered, session: await sessions.createSessionForUser(tx, user) };
|
|
116
|
+
});
|
|
117
|
+
return {
|
|
118
|
+
...(await buildAuthPayload({ user: result.user, session: result.session, profileProjector })),
|
|
119
|
+
registered: result.registered
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function linkOAuthIdentity(request, attempt, identity, provider) {
|
|
124
|
+
const authResult = await sessions.authenticateRequest(request);
|
|
125
|
+
if (authResult.authenticated !== true || authResult.actor.providerUserId !== attempt.userId) {
|
|
126
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
127
|
+
}
|
|
128
|
+
const user = await backend.withTransaction(async (tx) => {
|
|
129
|
+
const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
|
|
130
|
+
if (linked && linked.userId !== attempt.userId) {
|
|
131
|
+
throw new AppError(409, `This ${provider.label} account is already linked to another account.`, {
|
|
132
|
+
code: "auth.local.oauth.identityTaken",
|
|
133
|
+
params: { provider: provider.label }
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (!linked) {
|
|
137
|
+
await tx.identities.create({
|
|
138
|
+
userId: attempt.userId,
|
|
139
|
+
provider: identity.provider,
|
|
140
|
+
providerSubject: identity.providerSubject,
|
|
141
|
+
email: identity.email
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
return tx.users.findById(attempt.userId);
|
|
145
|
+
});
|
|
146
|
+
return buildAuthPayload({ user, session: null, profileProjector });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function oauthComplete(input, request) {
|
|
150
|
+
const errorCode = String(input.error || input.error_code || "").trim();
|
|
151
|
+
if (errorCode) {
|
|
152
|
+
throw errorCode === "access_denied"
|
|
153
|
+
? new AppError(401, "Sign-in was cancelled.", { code: "auth.local.oauth.cancelled" })
|
|
154
|
+
: new AppError(401, "Sign-in was not completed. Start again.", { code: "auth.local.oauth.incomplete" });
|
|
155
|
+
}
|
|
156
|
+
const browserKey = String(safeRequestCookies(request)[OAUTH_ATTEMPT_COOKIE] || "").trim();
|
|
157
|
+
// Taking an attempt deletes it, so each one completes at most once.
|
|
158
|
+
const attempt = browserKey
|
|
159
|
+
? await backend.withTransaction((tx) => tx.oauthAttempts.take(sha256Base64url(browserKey)))
|
|
160
|
+
: null;
|
|
161
|
+
const state = String(input.state || "");
|
|
162
|
+
// The provider is the one this attempt started with, whatever the callback names.
|
|
163
|
+
const provider = attempt ? oauthProvidersById.get(attempt.provider) : null;
|
|
164
|
+
if (!provider || isExpiredIso(attempt.expiresAt) || !state || state !== attempt.state) {
|
|
165
|
+
throw new AppError(400, "This sign-in took too long or started in another browser. Start again.", {
|
|
166
|
+
code: "auth.local.oauth.expired"
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
const code = String(input.code || "").trim();
|
|
170
|
+
if (!code) {
|
|
171
|
+
throw new AppError(400, "OAuth code is required.", { code: "auth.local.oauth.codeRequired" });
|
|
172
|
+
}
|
|
173
|
+
const callbackUrl = new URL(oauthRedirectUri);
|
|
174
|
+
callbackUrl.searchParams.set("code", code);
|
|
175
|
+
callbackUrl.searchParams.set("state", state);
|
|
176
|
+
if (input.iss) {
|
|
177
|
+
callbackUrl.searchParams.set("iss", String(input.iss));
|
|
178
|
+
}
|
|
179
|
+
const identity = await oauthClients.verifiedIdentity(provider, { callbackUrl, attempt });
|
|
180
|
+
const result = attempt.intent === "link"
|
|
181
|
+
? await linkOAuthIdentity(request, attempt, identity, provider)
|
|
182
|
+
: await signInWithOAuthIdentity(identity);
|
|
183
|
+
return { ...result, provider: provider.id, returnTo: attempt.returnTo };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function unlinkProvider(request, input) {
|
|
187
|
+
const userId = await sessions.requireNormalSessionUserId(request);
|
|
188
|
+
const provider = requireOAuthProvider(input.provider);
|
|
189
|
+
await backend.withTransaction(async (tx) => {
|
|
190
|
+
const user = await tx.users.findById(userId);
|
|
191
|
+
const identities = await tx.identities.listForUser(userId);
|
|
192
|
+
if (!identities.some((identity) => identity.provider === provider.id)) {
|
|
193
|
+
throw new AppError(404, `${provider.label} is not linked to this account.`, {
|
|
194
|
+
code: "auth.local.oauth.notLinked",
|
|
195
|
+
params: { provider: provider.label }
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const otherMethodRemains = hasPassword(user) || identities.some(
|
|
199
|
+
(identity) => identity.provider !== provider.id && oauthProvidersById.has(identity.provider)
|
|
200
|
+
);
|
|
201
|
+
if (!otherMethodRemains) {
|
|
202
|
+
throw new AppError(409, "Add a password or link another sign-in method before removing this one.", {
|
|
203
|
+
code: "auth.local.oauth.lastMethod"
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
await tx.identities.deleteForUser(userId, provider.id);
|
|
207
|
+
});
|
|
208
|
+
return { securityStatus: await securityStatus.securityStatusForUser(userId) };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return Object.freeze({
|
|
212
|
+
oauthStart,
|
|
213
|
+
startProviderLink,
|
|
214
|
+
writeOAuthStartCookies,
|
|
215
|
+
clearOAuthStartCookies,
|
|
216
|
+
oauthComplete,
|
|
217
|
+
unlinkProvider
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export { createLocalOAuthFlows };
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
+
import { AUTH_TEXTS, authMessageFields, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
3
|
+
import { validateEmailInput, validatePasswordInput } from "./accounts.js";
|
|
4
|
+
import { buildAuthPayload } from "./authPayloads.js";
|
|
5
|
+
import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url, verifySignedToken } from "./tokens.js";
|
|
6
|
+
|
|
7
|
+
const RECOVERY_SESSION_TTL_SECONDS = 15 * 60;
|
|
8
|
+
const RECOVERY_TOKEN_TTL_SECONDS = 60 * 60;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The `auth.local.recovery-sender` default when no feature provides one: outside
|
|
12
|
+
* production, local auth logs each recovery link instead of emailing it.
|
|
13
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
|
|
14
|
+
* @returns {import("../types.js").AuthLocalRecoverySender}
|
|
15
|
+
*/
|
|
16
|
+
function createLoggedRecoverySender(logger) {
|
|
17
|
+
return async function logRecoveryLink({ email, recoveryUrl }) {
|
|
18
|
+
logger.info({ recoveryUrl, email }, "Local auth password recovery URL created.");
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Changing a password, and recovering one: a recovery link opens a short
|
|
24
|
+
* recovery session, which can only set a new password.
|
|
25
|
+
* @param {object} dependencies
|
|
26
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
27
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
28
|
+
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
29
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
30
|
+
* @param {import("../types.js").AuthLocalRecoverySender} dependencies.recoverySender Sends each recovery
|
|
31
|
+
* link, except when the configuration returns it in the response.
|
|
32
|
+
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
33
|
+
*/
|
|
34
|
+
function createLocalPasswordFlows({ backend, config, passwords, profileProjector, recoverySender, sessions }) {
|
|
35
|
+
const { recoveryEnabled } = config;
|
|
36
|
+
const recoveryInResponse = config.recoveryDelivery === "dev-response";
|
|
37
|
+
|
|
38
|
+
async function requestPasswordReset(input) {
|
|
39
|
+
if (!recoveryEnabled) {
|
|
40
|
+
throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
|
|
41
|
+
}
|
|
42
|
+
const email = validateEmailInput(input.email);
|
|
43
|
+
let recoveryUrl = "";
|
|
44
|
+
await backend.withTransaction(async (tx) => {
|
|
45
|
+
const user = await tx.users.findByEmail(email);
|
|
46
|
+
if (!user || user.disabled) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const token = randomToken(32);
|
|
50
|
+
recoveryUrl = `${config.appPublicUrl.replace(/\/$/, "")}/auth/reset-password?token=${encodeURIComponent(token)}&type=recovery`;
|
|
51
|
+
await tx.recovery.create({
|
|
52
|
+
id: createId("rec"),
|
|
53
|
+
userId: user.id,
|
|
54
|
+
tokenHash: sha256Base64url(token),
|
|
55
|
+
expiresAt: isoFromNow(RECOVERY_TOKEN_TTL_SECONDS)
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
if (recoveryUrl && !recoveryInResponse) {
|
|
59
|
+
await recoverySender({ email, recoveryUrl });
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
ok: true,
|
|
63
|
+
message: "If an account exists for that email, password reset instructions have been sent.",
|
|
64
|
+
messageCode: "auth.local.recovery.requested",
|
|
65
|
+
messageParams: {},
|
|
66
|
+
...(recoveryUrl && recoveryInResponse ? { recoveryUrl } : {})
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function completePasswordRecovery(input) {
|
|
71
|
+
if (!recoveryEnabled) {
|
|
72
|
+
throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
|
|
73
|
+
}
|
|
74
|
+
const token = String(input.code || input.token || "").trim();
|
|
75
|
+
const tokenHash = String(input.tokenHash || "").trim() || (token ? sha256Base64url(token) : "");
|
|
76
|
+
if (!tokenHash) {
|
|
77
|
+
throw createAuthError(AUTH_TEXTS.recoveryTokenRequired);
|
|
78
|
+
}
|
|
79
|
+
return backend.withTransaction(async (tx) => {
|
|
80
|
+
const recovery = await tx.recovery.findByTokenHash(tokenHash);
|
|
81
|
+
if (!recovery || recovery.usedAt || isExpiredIso(recovery.expiresAt)) {
|
|
82
|
+
throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
|
|
83
|
+
}
|
|
84
|
+
await tx.recovery.consume(recovery.id);
|
|
85
|
+
const user = await tx.users.findById(recovery.userId);
|
|
86
|
+
if (!user || user.disabled) {
|
|
87
|
+
throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
|
|
88
|
+
}
|
|
89
|
+
const session = await sessions.createSessionForUser(tx, user, {
|
|
90
|
+
purpose: "recovery",
|
|
91
|
+
ttlSeconds: RECOVERY_SESSION_TTL_SECONDS
|
|
92
|
+
});
|
|
93
|
+
return buildAuthPayload({ user, session, profileProjector });
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function resetPassword(input, request) {
|
|
98
|
+
validatePasswordInput(input.password);
|
|
99
|
+
const payload = verifySignedToken(sessions.readRecoveryAccessToken(request), config.sessionSecret);
|
|
100
|
+
if (!payload?.sub || !payload?.sid) {
|
|
101
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
102
|
+
}
|
|
103
|
+
const password = await passwords.hashPassword(input.password);
|
|
104
|
+
await backend.withTransaction(async (tx) => {
|
|
105
|
+
const session = await tx.sessions.findById(String(payload.sid));
|
|
106
|
+
if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
|
|
107
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
108
|
+
}
|
|
109
|
+
if (session.purpose !== "recovery") {
|
|
110
|
+
throw new AppError(401, "Recovery session required.", { code: "auth.local.recovery.sessionRequired" });
|
|
111
|
+
}
|
|
112
|
+
await tx.users.updatePassword(String(payload.sub), password);
|
|
113
|
+
await tx.sessions.revokeForUser(String(payload.sub));
|
|
114
|
+
await tx.recovery.consumeForUser(String(payload.sub));
|
|
115
|
+
});
|
|
116
|
+
return {
|
|
117
|
+
ok: true,
|
|
118
|
+
...authMessageFields(AUTH_TEXTS.passwordUpdatedSignIn)
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function changePassword(request, input) {
|
|
123
|
+
validatePasswordInput(input.newPassword);
|
|
124
|
+
const authResult = await sessions.authenticateRequest(request);
|
|
125
|
+
if (authResult.authenticated !== true || authResult.sessionPurpose !== "normal") {
|
|
126
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const currentPassword = String(input.currentPassword || "");
|
|
130
|
+
const password = await passwords.hashPassword(input.newPassword);
|
|
131
|
+
await backend.withTransaction(async (tx) => {
|
|
132
|
+
const user = await tx.users.findById(authResult.actor.providerUserId);
|
|
133
|
+
if (!user || user.disabled) {
|
|
134
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
135
|
+
}
|
|
136
|
+
if (!(await passwords.verifyPassword(currentPassword, user.password))) {
|
|
137
|
+
throw new AppError(401, "Current password is invalid.", { code: "auth.local.password.currentInvalid" });
|
|
138
|
+
}
|
|
139
|
+
await tx.users.updatePassword(user.id, password);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
ok: true,
|
|
144
|
+
message: "Password updated.",
|
|
145
|
+
messageCode: "auth.local.password.changed",
|
|
146
|
+
messageParams: {}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return Object.freeze({
|
|
151
|
+
requestPasswordReset,
|
|
152
|
+
completePasswordRecovery,
|
|
153
|
+
resetPassword,
|
|
154
|
+
changePassword
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export { createLocalPasswordFlows, createLoggedRecoverySender };
|
|
@@ -41,28 +41,30 @@ async function verifyPassword(password, record) {
|
|
|
41
41
|
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
}
|
|
44
|
+
/**
|
|
45
|
+
* The `auth.local.password-strategy` default when no feature provides one:
|
|
46
|
+
* scrypt records.
|
|
47
|
+
* @type {import("../types.js").AuthLocalPasswordStrategy}
|
|
48
|
+
*/
|
|
49
|
+
const scryptPasswordStrategy = Object.freeze({ hashPassword, verifyPassword });
|
|
51
50
|
|
|
52
|
-
|
|
51
|
+
/**
|
|
52
|
+
* The password operations local auth uses: the strategy's own, with scrypt for
|
|
53
|
+
* an operation it leaves out.
|
|
54
|
+
* @param {import("../types.js").AuthLocalPasswordStrategy} strategy
|
|
55
|
+
*/
|
|
56
|
+
function normalizePasswordStrategy(strategy) {
|
|
57
|
+
// readable-check: allow method-probe - input validation: the password strategy an application installs
|
|
58
|
+
if (!strategy || typeof strategy !== "object" || Array.isArray(strategy)) {
|
|
53
59
|
throw new TypeError("Local auth password strategy must be an object.");
|
|
54
60
|
}
|
|
55
61
|
|
|
56
|
-
const strategyHashPassword =
|
|
57
|
-
|
|
58
|
-
: strategy.hashPassword;
|
|
59
|
-
const strategyVerifyPassword = typeof strategy.verifyPassword === "undefined"
|
|
60
|
-
? verifyPassword
|
|
61
|
-
: strategy.verifyPassword;
|
|
62
|
-
|
|
62
|
+
const { hashPassword: strategyHashPassword = hashPassword, verifyPassword: strategyVerifyPassword = verifyPassword } = strategy;
|
|
63
|
+
// readable-check: allow method-probe - input validation: the password strategy an application installs
|
|
63
64
|
if (typeof strategyHashPassword !== "function") {
|
|
64
65
|
throw new TypeError("Local auth password strategy hashPassword must be a function.");
|
|
65
66
|
}
|
|
67
|
+
// readable-check: allow method-probe - input validation: the password strategy an application installs
|
|
66
68
|
if (typeof strategyVerifyPassword !== "function") {
|
|
67
69
|
throw new TypeError("Local auth password strategy verifyPassword must be a function.");
|
|
68
70
|
}
|
|
@@ -77,4 +79,4 @@ function normalizePasswordStrategy(strategy = null) {
|
|
|
77
79
|
});
|
|
78
80
|
}
|
|
79
81
|
|
|
80
|
-
export { hashPassword,
|
|
82
|
+
export { hashPassword, normalizePasswordStrategy, scryptPasswordStrategy, verifyPassword };
|
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
const LOCAL_AUTH_USER_REGISTERED_EVENT = "auth.local.user.registered";
|
|
2
2
|
|
|
3
3
|
function assertBlockingMode(hook) {
|
|
4
|
-
if (typeof hook
|
|
4
|
+
if (typeof hook.blocking !== "boolean") {
|
|
5
5
|
throw new TypeError("Local auth register hooks must set blocking to true or false.");
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* @param {LocalAuthRegisterHook} hook
|
|
11
|
+
*/
|
|
12
|
+
function normalizeRegisterHook(hook) {
|
|
10
13
|
if (!hook || typeof hook !== "object" || Array.isArray(hook)) {
|
|
11
|
-
|
|
14
|
+
throw new TypeError("createLocalAuthRegisterHookDecorator requires a hook object.");
|
|
12
15
|
}
|
|
13
16
|
assertBlockingMode(hook);
|
|
17
|
+
// readable-check: allow method-probe - input validation: the hook an application passes
|
|
14
18
|
if (typeof hook.handle !== "function") {
|
|
15
19
|
throw new TypeError("Local auth register hook handle must be a function.");
|
|
16
20
|
}
|
|
@@ -21,27 +25,41 @@ function normalizeRegisterHook(hook = null) {
|
|
|
21
25
|
});
|
|
22
26
|
}
|
|
23
27
|
|
|
24
|
-
|
|
28
|
+
/**
|
|
29
|
+
* What an application's register hook is: `blocking` hooks run before register
|
|
30
|
+
* answers, and their errors fail it; the others run after, and their errors are
|
|
31
|
+
* logged.
|
|
32
|
+
* @typedef {object} LocalAuthRegisterHook
|
|
33
|
+
* @property {string} [hookId]
|
|
34
|
+
* @property {boolean} blocking
|
|
35
|
+
* @property {(payload: { event: string, actor: object, authResult: object }) => unknown} handle
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} failure
|
|
40
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} failure.logger
|
|
41
|
+
* @param {{ hookId: string }} failure.hook
|
|
42
|
+
* @param {unknown} failure.error
|
|
43
|
+
*/
|
|
44
|
+
function logNonBlockingHookFailure({ logger, hook, error }) {
|
|
25
45
|
const payload = {
|
|
26
46
|
err: error,
|
|
27
|
-
hook: hook
|
|
47
|
+
hook: hook.hookId,
|
|
28
48
|
event: LOCAL_AUTH_USER_REGISTERED_EVENT
|
|
29
49
|
};
|
|
30
|
-
|
|
31
|
-
logger.warn(payload, "Non-blocking local auth register hook failed.");
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
console.warn("Non-blocking local auth register hook failed.", payload);
|
|
50
|
+
logger.warn(payload, "Non-blocking local auth register hook failed.");
|
|
35
51
|
}
|
|
36
52
|
|
|
53
|
+
/**
|
|
54
|
+
* @param {object} run
|
|
55
|
+
* @param {{ hookId: string, blocking: boolean, handle: LocalAuthRegisterHook["handle"] }} run.hook
|
|
56
|
+
* @param {object} run.result The answer of register, or of an oauthComplete that registered the user.
|
|
57
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} run.logger
|
|
58
|
+
*/
|
|
37
59
|
async function runRegisterHook({ hook, result, logger }) {
|
|
38
|
-
if (!hook) {
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
60
|
const payload = Object.freeze({
|
|
43
61
|
event: LOCAL_AUTH_USER_REGISTERED_EVENT,
|
|
44
|
-
actor: result
|
|
62
|
+
actor: result.actor,
|
|
45
63
|
authResult: result
|
|
46
64
|
});
|
|
47
65
|
|
|
@@ -55,50 +73,53 @@ async function runRegisterHook({ hook, result, logger }) {
|
|
|
55
73
|
.catch((error) => logNonBlockingHookFailure({ logger, hook, error }));
|
|
56
74
|
}
|
|
57
75
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
76
|
+
/**
|
|
77
|
+
* An auth service decorator that runs an application's hook for each user
|
|
78
|
+
* that registers, by password or by a first OAuth sign-in.
|
|
79
|
+
* @param {object} options
|
|
80
|
+
* @param {string} [options.decoratorId]
|
|
81
|
+
* @param {number} [options.order]
|
|
82
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} options.logger Reports a failed non-blocking hook.
|
|
83
|
+
* @param {LocalAuthRegisterHook} options.hook
|
|
84
|
+
*/
|
|
85
|
+
function createLocalAuthRegisterHookDecorator({ decoratorId = "auth.local.registerHook", order = 0, logger, hook }) {
|
|
64
86
|
const registerHook = normalizeRegisterHook(hook);
|
|
65
|
-
|
|
66
|
-
if (
|
|
67
|
-
throw new TypeError("createLocalAuthRegisterHookDecorator requires a
|
|
87
|
+
// readable-check: allow method-probe - input validation: the logger an application passes
|
|
88
|
+
if (typeof logger?.warn !== "function") {
|
|
89
|
+
throw new TypeError("createLocalAuthRegisterHookDecorator requires a logger.");
|
|
68
90
|
}
|
|
69
91
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
92
|
+
/** @param {import("@jskit-ai/auth-core/server/types").AuthService} authService */
|
|
93
|
+
function decorateAuthService(authService) {
|
|
94
|
+
return Object.freeze(
|
|
95
|
+
Object.defineProperties(Object.create(authService), {
|
|
96
|
+
register: {
|
|
97
|
+
enumerable: true,
|
|
98
|
+
value: async function register(input) {
|
|
99
|
+
const result = await authService.register(input);
|
|
100
|
+
await runRegisterHook({ hook: registerHook, result, logger });
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
// A first sign-in through a provider creates the user the way register does.
|
|
105
|
+
oauthComplete: {
|
|
106
|
+
enumerable: true,
|
|
107
|
+
value: async function oauthComplete(input, request) {
|
|
108
|
+
const result = await authService.oauthComplete(input, request);
|
|
109
|
+
if (result.registered === true) {
|
|
84
110
|
await runRegisterHook({ hook: registerHook, result, logger });
|
|
85
|
-
return result;
|
|
86
|
-
}
|
|
87
|
-
},
|
|
88
|
-
// A first sign-in through a provider creates the user the way register does.
|
|
89
|
-
oauthComplete: {
|
|
90
|
-
enumerable: true,
|
|
91
|
-
value: async function oauthComplete(input = {}, request = null) {
|
|
92
|
-
const result = await authService.oauthComplete(input, request);
|
|
93
|
-
if (result?.registered === true) {
|
|
94
|
-
await runRegisterHook({ hook: registerHook, result, logger });
|
|
95
|
-
}
|
|
96
|
-
return result;
|
|
97
111
|
}
|
|
112
|
+
return result;
|
|
98
113
|
}
|
|
99
|
-
}
|
|
100
|
-
)
|
|
101
|
-
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return Object.freeze({
|
|
120
|
+
decoratorId: String(decoratorId),
|
|
121
|
+
order: Number.isFinite(order) ? Number(order) : 0,
|
|
122
|
+
decorateAuthService
|
|
102
123
|
});
|
|
103
124
|
}
|
|
104
125
|
|