@jskit-ai/auth-provider-local-core 0.2.5 → 0.2.7
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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "node --test --test-concurrency=1"
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
"exports": {
|
|
9
9
|
"./server/providers/AuthLocalProvider": "./src/server/providers/AuthLocalProvider.js",
|
|
10
10
|
"./server/lib/index": "./src/server/lib/index.js",
|
|
11
|
+
"./server/types": "./src/server/types.js",
|
|
11
12
|
"./locales/en.json": "./locales/en.json"
|
|
12
13
|
},
|
|
13
14
|
"dependencies": {
|
|
@@ -47,7 +48,11 @@
|
|
|
47
48
|
},
|
|
48
49
|
{
|
|
49
50
|
"subpath": "./server/lib/index",
|
|
50
|
-
"summary": "Exports local auth service, file backend
|
|
51
|
+
"summary": "Exports the local auth service and its configuration (createLocalAuthService, resolveLocalAuthConfig), the file backend, the password strategy helpers (scryptPasswordStrategy, normalizePasswordStrategy, hashPassword, verifyPassword), the logged recovery sender (createLoggedRecoverySender), and local auth register hook decorators. Google, Microsoft and GitHub sign-in turn on from AUTH_GOOGLE_*, AUTH_MICROSOFT_* and AUTH_GITHUB_* client id and secret pairs."
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"subpath": "./server/types",
|
|
55
|
+
"summary": "Types of the auth.local.backend contract (AuthLocalBackend) that every local auth backend implements, of the auth.local.password-strategy and auth.local.recovery-sender capabilities, and of the configuration, passwords and sessions local auth's modules share."
|
|
51
56
|
}
|
|
52
57
|
],
|
|
53
58
|
"extensionCapabilities": [
|
|
@@ -61,7 +66,7 @@
|
|
|
61
66
|
}
|
|
62
67
|
},
|
|
63
68
|
"peerDependencies": {
|
|
64
|
-
"@jskit-ai/auth-core": "0.2.
|
|
65
|
-
"@jskit-ai/kernel": "0.2.
|
|
69
|
+
"@jskit-ai/auth-core": "0.2.5",
|
|
70
|
+
"@jskit-ai/kernel": "0.2.5"
|
|
66
71
|
}
|
|
67
72
|
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
+
import {
|
|
3
|
+
AUTH_PASSWORD_MAX_LENGTH,
|
|
4
|
+
AUTH_PASSWORD_MIN_LENGTH
|
|
5
|
+
} from "@jskit-ai/auth-core/shared/authConstraints";
|
|
6
|
+
import { ensureDevAuthExchangeAvailable, isDevAuthBootstrapEnabled } from "@jskit-ai/auth-core/server/devAuth";
|
|
7
|
+
import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
|
|
8
|
+
import { AUTH_TEXTS, authFieldErrorDetails, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
9
|
+
import { DEV_AUTH_SESSION_PURPOSE, buildAuthPayload, buildAuthResult, findExistingAppProfile } from "./authPayloads.js";
|
|
10
|
+
import { createId } from "./tokens.js";
|
|
11
|
+
|
|
12
|
+
/** An account created through a provider has no password until recovery sets one. */
|
|
13
|
+
const NO_PASSWORD = Object.freeze({ algorithm: "", version: "", salt: "", hash: "" });
|
|
14
|
+
|
|
15
|
+
function normalizeDisplayName(value, email) {
|
|
16
|
+
const displayName = String(value || "").trim();
|
|
17
|
+
if (displayName) {
|
|
18
|
+
return displayName;
|
|
19
|
+
}
|
|
20
|
+
return email.split("@")[0] || "User";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Accounts created through a provider store NO_PASSWORD; any other stored
|
|
25
|
+
* record, in whatever format the password strategy uses, is a password.
|
|
26
|
+
*/
|
|
27
|
+
function hasPassword(user) {
|
|
28
|
+
const record = user?.password;
|
|
29
|
+
return record && typeof record === "object" ? Boolean(record.hash) : Boolean(record);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function validatePasswordInput(password) {
|
|
33
|
+
const normalizedPassword = String(password || "");
|
|
34
|
+
if (
|
|
35
|
+
normalizedPassword.length < AUTH_PASSWORD_MIN_LENGTH ||
|
|
36
|
+
normalizedPassword.length > AUTH_PASSWORD_MAX_LENGTH
|
|
37
|
+
) {
|
|
38
|
+
const params = { min: AUTH_PASSWORD_MIN_LENGTH };
|
|
39
|
+
throw new AppError(400, "Password must be at least 8 characters.", {
|
|
40
|
+
code: "auth.local.password.tooShort",
|
|
41
|
+
params,
|
|
42
|
+
details: {
|
|
43
|
+
fieldErrors: {
|
|
44
|
+
password: "Password must be at least 8 characters."
|
|
45
|
+
},
|
|
46
|
+
fieldErrorCodes: {
|
|
47
|
+
password: { code: "auth.local.password.tooShort", params }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function validateEmailInput(email) {
|
|
55
|
+
const normalized = normalizeEmail(email);
|
|
56
|
+
if (!normalized || !normalized.includes("@")) {
|
|
57
|
+
throw new AppError(400, "Enter a valid email address.", {
|
|
58
|
+
code: "auth.local.email.invalid",
|
|
59
|
+
details: {
|
|
60
|
+
fieldErrors: {
|
|
61
|
+
email: "Enter a valid email address."
|
|
62
|
+
},
|
|
63
|
+
fieldErrorCodes: {
|
|
64
|
+
email: { code: "auth.local.email.invalid", params: {} }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return normalized;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** fields: { field: AUTH_TEXTS entry }; the error says the first field's text. */
|
|
73
|
+
function devLoginAsValidationError(fields = {}) {
|
|
74
|
+
const [first = AUTH_TEXTS.devUserRequired] = Object.values(fields);
|
|
75
|
+
return createAuthError(first, {
|
|
76
|
+
details: authFieldErrorDetails(fields)
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function devLoginAsUserNotFound({ email = "", userId = "" } = {}) {
|
|
81
|
+
return devLoginAsValidationError({
|
|
82
|
+
...(userId ? { userId: AUTH_TEXTS.devUserNotFound } : {}),
|
|
83
|
+
...(email ? { email: AUTH_TEXTS.devUserNotFound } : {})
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function normalizeInvitationInput(value) {
|
|
88
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const token = String(value.token || value.inviteToken || "").trim();
|
|
92
|
+
if (!token) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
token,
|
|
97
|
+
source: String(value.source || "workspace-invite").trim() || "workspace-invite"
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The accounts of local auth: registering one, signing in with its password
|
|
103
|
+
* or as a dev user, and renaming it.
|
|
104
|
+
* @param {object} dependencies
|
|
105
|
+
* @param {boolean} dependencies.appProfileProjection True when the application keeps profiles.
|
|
106
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
107
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
108
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
|
|
109
|
+
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
110
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
111
|
+
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
112
|
+
*/
|
|
113
|
+
function createLocalAccounts({ appProfileProjection, backend, config, invitationContextResolver, passwords, profileProjector, sessions }) {
|
|
114
|
+
const { devAuth } = config;
|
|
115
|
+
|
|
116
|
+
async function resolveProfileOptionsForRegistration(input, email) {
|
|
117
|
+
const invitation = normalizeInvitationInput(input.invitation);
|
|
118
|
+
if (!invitation) {
|
|
119
|
+
return {};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const resolvedInvitation = await invitationContextResolver.resolveInvitationContext({ ...invitation, email });
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
source: resolvedInvitation?.source || "workspace-invite",
|
|
126
|
+
invitation: resolvedInvitation
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function register(input) {
|
|
131
|
+
const email = validateEmailInput(input.email);
|
|
132
|
+
validatePasswordInput(input.password);
|
|
133
|
+
const displayName = normalizeDisplayName(input.displayName, email);
|
|
134
|
+
const profileOptions = await resolveProfileOptionsForRegistration(input, email);
|
|
135
|
+
const password = await passwords.hashPassword(input.password);
|
|
136
|
+
const result = await backend.withTransaction(async (tx) => {
|
|
137
|
+
const existing = await tx.users.findByEmail(email);
|
|
138
|
+
if (existing) {
|
|
139
|
+
throw new AppError(409, "An account already exists for this email.", { code: "auth.local.register.emailTaken" });
|
|
140
|
+
}
|
|
141
|
+
const user = await tx.users.create({
|
|
142
|
+
id: createId("usr"),
|
|
143
|
+
email,
|
|
144
|
+
displayName,
|
|
145
|
+
password
|
|
146
|
+
});
|
|
147
|
+
return {
|
|
148
|
+
user,
|
|
149
|
+
session: await sessions.createSessionForUser(tx, user)
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
return {
|
|
153
|
+
...(await buildAuthPayload({
|
|
154
|
+
user: result.user,
|
|
155
|
+
session: result.session,
|
|
156
|
+
profileProjector,
|
|
157
|
+
profileOptions
|
|
158
|
+
})),
|
|
159
|
+
requiresEmailConfirmation: false
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function login(input) {
|
|
164
|
+
const email = validateEmailInput(input.email);
|
|
165
|
+
const password = String(input.password || "");
|
|
166
|
+
return backend.withTransaction(async (tx) => {
|
|
167
|
+
const user = await tx.users.findByEmail(email);
|
|
168
|
+
if (!user || user.disabled || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
|
|
169
|
+
throw createAuthError(AUTH_TEXTS.invalidCredentials);
|
|
170
|
+
}
|
|
171
|
+
const session = await sessions.createSessionForUser(tx, user);
|
|
172
|
+
return buildAuthPayload({ user, session, profileProjector });
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function devAuthBootstrapEnabled() {
|
|
177
|
+
return isDevAuthBootstrapEnabled(devAuth);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function devLoginAs(input, request) {
|
|
181
|
+
ensureDevAuthExchangeAvailable(devAuth, request);
|
|
182
|
+
const userId = String(input.userId || "").trim();
|
|
183
|
+
const email = normalizeEmail(input.email || "");
|
|
184
|
+
if (!userId && !email) {
|
|
185
|
+
throw devLoginAsValidationError({
|
|
186
|
+
userId: AUTH_TEXTS.devUserRequired,
|
|
187
|
+
email: AUTH_TEXTS.devUserRequired
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return backend.withTransaction(async (tx) => {
|
|
192
|
+
let user = userId ? await tx.users.findById(userId) : null;
|
|
193
|
+
if (!user && email) {
|
|
194
|
+
user = await tx.users.findByEmail(email);
|
|
195
|
+
}
|
|
196
|
+
if (!user || user.disabled) {
|
|
197
|
+
throw devLoginAsUserNotFound({ email, userId });
|
|
198
|
+
}
|
|
199
|
+
const appProfile = await findExistingAppProfile(user, profileProjector);
|
|
200
|
+
if (appProfileProjection && !appProfile) {
|
|
201
|
+
throw devLoginAsUserNotFound({ email, userId });
|
|
202
|
+
}
|
|
203
|
+
const session = await sessions.createSessionForUser(tx, user, {
|
|
204
|
+
purpose: DEV_AUTH_SESSION_PURPOSE
|
|
205
|
+
});
|
|
206
|
+
return buildAuthResult({ user, session, appProfile });
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function updateDisplayName(request, input) {
|
|
211
|
+
const authResult = await sessions.authenticateRequest(request);
|
|
212
|
+
if (authResult.authenticated !== true) {
|
|
213
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
214
|
+
}
|
|
215
|
+
const displayName = String(input.displayName || "").trim();
|
|
216
|
+
if (!displayName) {
|
|
217
|
+
throw createAuthError(AUTH_TEXTS.displayNameRequired);
|
|
218
|
+
}
|
|
219
|
+
return backend.withTransaction(async (tx) => {
|
|
220
|
+
const user = await tx.users.updateProfile(authResult.actor.providerUserId, { displayName });
|
|
221
|
+
if (!user) {
|
|
222
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
223
|
+
}
|
|
224
|
+
return buildAuthPayload({ user, session: null, profileProjector });
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return Object.freeze({
|
|
229
|
+
register,
|
|
230
|
+
login,
|
|
231
|
+
isDevAuthBootstrapEnabled: devAuthBootstrapEnabled,
|
|
232
|
+
devLoginAs,
|
|
233
|
+
updateDisplayName
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export {
|
|
238
|
+
NO_PASSWORD,
|
|
239
|
+
createLocalAccounts,
|
|
240
|
+
hasPassword,
|
|
241
|
+
normalizeDisplayName,
|
|
242
|
+
validateEmailInput,
|
|
243
|
+
validatePasswordInput
|
|
244
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { normalizeAuthActor, normalizeAuthResult } from "@jskit-ai/auth-core/server/authActor";
|
|
2
|
+
import { ensureDevAuthRuntimeAvailable } from "@jskit-ai/auth-core/server/devAuth";
|
|
3
|
+
|
|
4
|
+
const PROVIDER_ID = "local";
|
|
5
|
+
const DEV_AUTH_SESSION_PURPOSE = "dev-auth";
|
|
6
|
+
|
|
7
|
+
function isNormalSession(session) {
|
|
8
|
+
return (session?.purpose || "normal") === "normal";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function isDevAuthSession(session) {
|
|
12
|
+
return session?.purpose === DEV_AUTH_SESSION_PURPOSE;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isAuthenticatingSession(session) {
|
|
16
|
+
return isNormalSession(session) || isDevAuthSession(session);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function buildProfile(user) {
|
|
20
|
+
return {
|
|
21
|
+
id: user.id,
|
|
22
|
+
authProvider: PROVIDER_ID,
|
|
23
|
+
authProviderUserSid: user.id,
|
|
24
|
+
email: user.email,
|
|
25
|
+
displayName: user.displayName,
|
|
26
|
+
profileSource: "auth-provider"
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function buildActor(user, profile) {
|
|
31
|
+
const profileSource = profile ? "users" : "auth-provider";
|
|
32
|
+
return normalizeAuthActor({
|
|
33
|
+
provider: PROVIDER_ID,
|
|
34
|
+
providerUserId: user.id,
|
|
35
|
+
email: user.email,
|
|
36
|
+
displayName: user.displayName,
|
|
37
|
+
appUserId: profile?.id || null,
|
|
38
|
+
profileSource
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param {{ user: object, session: object | null, appProfile: object | null }} result */
|
|
43
|
+
function buildAuthResult({ user, session, appProfile }) {
|
|
44
|
+
return normalizeAuthResult({
|
|
45
|
+
actor: buildActor(user, appProfile),
|
|
46
|
+
session
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {object} input
|
|
52
|
+
* @param {object} input.user
|
|
53
|
+
* @param {object | null} input.session
|
|
54
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} input.profileProjector
|
|
55
|
+
* @param {object} [input.profileOptions]
|
|
56
|
+
*/
|
|
57
|
+
async function buildAuthPayload({ user, session, profileProjector, profileOptions = {} }) {
|
|
58
|
+
const appProfile = await profileProjector.syncIdentityProfile(buildProfile(user), profileOptions);
|
|
59
|
+
return buildAuthResult({ user, session, appProfile });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @param {object} user
|
|
64
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} profileProjector
|
|
65
|
+
*/
|
|
66
|
+
function findExistingAppProfile(user, profileProjector) {
|
|
67
|
+
return profileProjector.findByIdentity(buildProfile(user));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A dev session, or a caller that asks only who is signed in (syncProfile:
|
|
72
|
+
* false), reads the existing app profile instead of synchronizing it. When the
|
|
73
|
+
* application keeps profiles, a user without one is not signed in.
|
|
74
|
+
* @param {object} input
|
|
75
|
+
* @param {boolean} input.appProfileProjection True when the application keeps profiles.
|
|
76
|
+
* @param {object} input.devAuth
|
|
77
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} input.profileProjector
|
|
78
|
+
* @param {object} input.request
|
|
79
|
+
* @param {object} input.session
|
|
80
|
+
* @param {object} input.user
|
|
81
|
+
* @param {boolean} [input.syncProfile]
|
|
82
|
+
*/
|
|
83
|
+
async function buildSessionAuthPayload({ appProfileProjection, devAuth, profileProjector, request, session, user, syncProfile = true }) {
|
|
84
|
+
const devSession = isDevAuthSession(session);
|
|
85
|
+
if (!devSession && syncProfile) {
|
|
86
|
+
return buildAuthPayload({ user, session: null, profileProjector });
|
|
87
|
+
}
|
|
88
|
+
if (devSession) {
|
|
89
|
+
try {
|
|
90
|
+
ensureDevAuthRuntimeAvailable(devAuth, request);
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const appProfile = await findExistingAppProfile(user, profileProjector);
|
|
96
|
+
return appProfileProjection && !appProfile
|
|
97
|
+
? null
|
|
98
|
+
: buildAuthResult({ user, session: null, appProfile });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export {
|
|
102
|
+
DEV_AUTH_SESSION_PURPOSE,
|
|
103
|
+
PROVIDER_ID,
|
|
104
|
+
buildAuthPayload,
|
|
105
|
+
buildAuthResult,
|
|
106
|
+
buildSessionAuthPayload,
|
|
107
|
+
findExistingAppProfile,
|
|
108
|
+
isAuthenticatingSession
|
|
109
|
+
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { parseBooleanFlag } from "@jskit-ai/auth-core/server/booleanFlag";
|
|
2
|
+
import { assertDevAuthPolicy, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { resolveOAuthProviders } from "./oauth.js";
|
|
7
|
+
|
|
8
|
+
const DEFAULT_STORE_DIR = ".jskit/auth";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
12
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} appRoot
|
|
13
|
+
*/
|
|
14
|
+
function resolveStoreDir(env, appRoot) {
|
|
15
|
+
const configured = String(env.AUTH_LOCAL_STORE_DIR || DEFAULT_STORE_DIR).trim() || DEFAULT_STORE_DIR;
|
|
16
|
+
return path.resolve(appRoot, configured);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* AUTH_LOCAL_SESSION_SECRET, or outside production a secret kept in the store
|
|
21
|
+
* directory, generated on first use.
|
|
22
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
23
|
+
* @param {{ storeDir: string, isProduction: boolean }} options
|
|
24
|
+
*/
|
|
25
|
+
function resolveSessionSecret(env, { storeDir, isProduction }) {
|
|
26
|
+
const explicit = String(env.AUTH_LOCAL_SESSION_SECRET || "").trim();
|
|
27
|
+
if (explicit) return explicit;
|
|
28
|
+
if (isProduction) throw new Error("AUTH_LOCAL_SESSION_SECRET is required for local auth in production.");
|
|
29
|
+
|
|
30
|
+
const secretPath = path.join(storeDir, "session.secret");
|
|
31
|
+
try {
|
|
32
|
+
const existing = fs.readFileSync(secretPath, "utf8").trim();
|
|
33
|
+
if (existing) return existing;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (!error || error.code !== "ENOENT") throw error;
|
|
36
|
+
}
|
|
37
|
+
fs.mkdirSync(storeDir, { recursive: true, mode: 0o700 });
|
|
38
|
+
const generated = randomBytes(32).toString("base64url");
|
|
39
|
+
fs.writeFileSync(secretPath, `${generated}\n`, { mode: 0o600 });
|
|
40
|
+
return generated;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* APP_PUBLIC_URL, from which recovery links and OAuth redirect addresses are
|
|
45
|
+
* built. Email recovery and OAuth sign-in require it.
|
|
46
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
47
|
+
* @param {{ emailRecovery: boolean, oauthEnabled: boolean }} options
|
|
48
|
+
*/
|
|
49
|
+
function resolveAppPublicUrl(env, { emailRecovery, oauthEnabled }) {
|
|
50
|
+
const configured = String(env.APP_PUBLIC_URL || "").trim();
|
|
51
|
+
if (!configured) {
|
|
52
|
+
if (emailRecovery) throw new Error("APP_PUBLIC_URL is required when local auth email recovery is configured.");
|
|
53
|
+
if (oauthEnabled) throw new Error("APP_PUBLIC_URL is required when local auth OAuth sign-in is configured.");
|
|
54
|
+
return "http://localhost:5173";
|
|
55
|
+
}
|
|
56
|
+
let parsed;
|
|
57
|
+
try {
|
|
58
|
+
parsed = new URL(configured);
|
|
59
|
+
} catch {
|
|
60
|
+
throw new Error("APP_PUBLIC_URL must be a valid URL.");
|
|
61
|
+
}
|
|
62
|
+
if (!["http:", "https:"].includes(parsed.protocol)) {
|
|
63
|
+
throw new Error("APP_PUBLIC_URL must use http or https.");
|
|
64
|
+
}
|
|
65
|
+
return parsed.toString().replace(/\/$/u, "");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* How a password recovery link reaches the person: by email through the
|
|
70
|
+
* installed recovery sender; otherwise, outside production, in the log or in
|
|
71
|
+
* the response (AUTH_LOCAL_RECOVERY_DEV_OUTPUT=response). In production without
|
|
72
|
+
* a sender, recovery is disabled.
|
|
73
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
74
|
+
* @param {{ emailRecovery: boolean, isProduction: boolean }} options
|
|
75
|
+
* @returns {"email" | "disabled" | "dev-response" | "dev-log"}
|
|
76
|
+
*/
|
|
77
|
+
function resolveRecoveryDelivery(env, { emailRecovery, isProduction }) {
|
|
78
|
+
if (emailRecovery) return "email";
|
|
79
|
+
if (isProduction) return "disabled";
|
|
80
|
+
const devOutput = String(env.AUTH_LOCAL_RECOVERY_DEV_OUTPUT || "").trim().toLowerCase();
|
|
81
|
+
return devOutput === "response" ? "dev-response" : "dev-log";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The local auth configuration, resolved and checked once from the environment.
|
|
86
|
+
* Production is worked out once, by auth-core's dev auth policy, so local auth
|
|
87
|
+
* and its dev sign-in agree on it.
|
|
88
|
+
* @param {object} input
|
|
89
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} input.appRoot
|
|
90
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} input.env
|
|
91
|
+
* @param {boolean} input.fileBackend True when local auth keeps its records in files, because no
|
|
92
|
+
* `auth.local.backend` is installed.
|
|
93
|
+
* @param {boolean} input.emailRecovery True when an `auth.local.recovery-sender` is installed.
|
|
94
|
+
*/
|
|
95
|
+
function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery }) {
|
|
96
|
+
const devAuth = resolveDevAuthPolicyFromEnv(env);
|
|
97
|
+
const { isProduction } = devAuth;
|
|
98
|
+
const storeDir = resolveStoreDir(env, appRoot);
|
|
99
|
+
if (fileBackend && isProduction && !parseBooleanFlag(env.AUTH_LOCAL_FILE_PRODUCTION_ACK, false)) {
|
|
100
|
+
throw new Error("AUTH_LOCAL_FILE_PRODUCTION_ACK is required to use the local file auth backend in production.");
|
|
101
|
+
}
|
|
102
|
+
assertDevAuthPolicy(devAuth);
|
|
103
|
+
const oauthProviders = resolveOAuthProviders(env);
|
|
104
|
+
const oauthEnabled = oauthProviders.length > 0;
|
|
105
|
+
const recoveryDelivery = resolveRecoveryDelivery(env, { emailRecovery, isProduction });
|
|
106
|
+
return Object.freeze({
|
|
107
|
+
storeDir,
|
|
108
|
+
isProduction,
|
|
109
|
+
appPublicUrl: resolveAppPublicUrl(env, { emailRecovery, oauthEnabled }),
|
|
110
|
+
oauthProviders,
|
|
111
|
+
oauthEnabled,
|
|
112
|
+
sessionSecret: resolveSessionSecret(env, { storeDir, isProduction }),
|
|
113
|
+
recoveryDelivery,
|
|
114
|
+
recoveryEnabled: recoveryDelivery !== "disabled",
|
|
115
|
+
devAuth
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export { resolveLocalAuthConfig };
|
package/src/server/lib/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { createLocalAuthService } from "./service.js";
|
|
2
|
+
export { resolveLocalAuthConfig } from "./config.js";
|
|
3
|
+
export { createLoggedRecoverySender } from "./passwordFlows.js";
|
|
2
4
|
export { createLocalFileBackend } from "./fileBackend.js";
|
|
3
5
|
export {
|
|
4
6
|
LOCAL_AUTH_USER_REGISTERED_EVENT,
|
|
5
7
|
createLocalAuthRegisterHookDecorator
|
|
6
8
|
} from "./registerHookDecorator.js";
|
|
7
|
-
export { hashPassword, normalizePasswordStrategy, verifyPassword } from "./passwords.js";
|
|
9
|
+
export { hashPassword, normalizePasswordStrategy, scryptPasswordStrategy, verifyPassword } from "./passwords.js";
|
package/src/server/lib/oauth.js
CHANGED
|
@@ -44,7 +44,7 @@ function resolveOAuthProviders(env = {}) {
|
|
|
44
44
|
return Object.freeze(providers);
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
/** Errors that name a provider carry its label as the provider param. */
|
|
48
48
|
function signInError(statusCode, message, { code, provider = null }) {
|
|
49
49
|
return new AppError(statusCode, message, {
|
|
50
50
|
code,
|
|
@@ -110,8 +110,9 @@ const IDENTITY_READERS = Object.freeze({
|
|
|
110
110
|
/**
|
|
111
111
|
* The authorization-code (PKCE) client for each configured provider. Provider
|
|
112
112
|
* tokens are used once to learn who signed in and are never kept.
|
|
113
|
+
* @param {{ logger: import("@jskit-ai/kernel/server/types").RuntimeLogger }} dependencies
|
|
113
114
|
*/
|
|
114
|
-
function createOAuthClients({ logger
|
|
115
|
+
function createOAuthClients({ logger }) {
|
|
115
116
|
const configurations = new Map();
|
|
116
117
|
|
|
117
118
|
async function createConfiguration(provider) {
|
|
@@ -149,7 +150,7 @@ function createOAuthClients({ logger = null } = {}) {
|
|
|
149
150
|
if (!configurations.has(provider.id)) {
|
|
150
151
|
configurations.set(provider.id, createConfiguration(provider).catch((error) => {
|
|
151
152
|
configurations.delete(provider.id);
|
|
152
|
-
logger
|
|
153
|
+
logger.warn({ err: error, provider: provider.id }, "OAuth provider discovery failed.");
|
|
153
154
|
throw signInError(503, `${provider.label} can't be reached right now. Try again in a moment.`,
|
|
154
155
|
{ code: "auth.local.oauth.providerUnreachable", provider });
|
|
155
156
|
}));
|
|
@@ -184,7 +185,7 @@ function createOAuthClients({ logger = null } = {}) {
|
|
|
184
185
|
...(provider.issuer ? { expectedNonce: attempt.nonce, idTokenExpected: true } : {})
|
|
185
186
|
});
|
|
186
187
|
} catch (error) {
|
|
187
|
-
logger
|
|
188
|
+
logger.warn({ err: { name: error?.name, code: error?.code, message: error?.message }, provider: provider.id },
|
|
188
189
|
"OAuth sign-in was rejected.");
|
|
189
190
|
throw unverifiedSignIn();
|
|
190
191
|
}
|
|
@@ -201,7 +202,10 @@ function createOAuthClients({ logger = null } = {}) {
|
|
|
201
202
|
return { provider: provider.id, providerSubject: String(identity.subject), email, name: identity.name.slice(0, 160) };
|
|
202
203
|
}
|
|
203
204
|
|
|
204
|
-
return Object.freeze({
|
|
205
|
+
return Object.freeze({
|
|
206
|
+
authorizationUrl,
|
|
207
|
+
verifiedIdentity
|
|
208
|
+
});
|
|
205
209
|
}
|
|
206
210
|
|
|
207
211
|
export { createOAuthClients, resolveOAuthProviders };
|