@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
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
2
|
+
import { hostOnlyCookieName } from "@jskit-ai/auth-core/server/utils";
|
|
3
|
+
import { buildSessionAuthPayload, isAuthenticatingSession } from "./authPayloads.js";
|
|
4
|
+
import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url, signToken, verifySignedToken } from "./tokens.js";
|
|
5
|
+
|
|
6
|
+
const ACCESS_TOKEN_COOKIE_NAME = "jskit_local_access_token";
|
|
7
|
+
const REFRESH_TOKEN_COOKIE_NAME = "jskit_local_refresh_token";
|
|
8
|
+
const RECOVERY_TOKEN_COOKIE_NAME = "jskit_local_recovery_token";
|
|
9
|
+
const ACCESS_TTL_SECONDS = 15 * 60;
|
|
10
|
+
const REFRESH_TTL_SECONDS = 60 * 60 * 24 * 30;
|
|
11
|
+
|
|
12
|
+
function nowSeconds() {
|
|
13
|
+
return Math.floor(Date.now() / 1000);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function safeRequestCookies(request) {
|
|
17
|
+
return request && request.cookies && typeof request.cookies === "object" ? request.cookies : {};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function unauthenticatedAuthResult(clearSession = false) {
|
|
21
|
+
return {
|
|
22
|
+
authenticated: false,
|
|
23
|
+
clearSession: Boolean(clearSession),
|
|
24
|
+
session: null,
|
|
25
|
+
transientFailure: false
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function cookieOptions(isProduction, maxAge) {
|
|
30
|
+
return {
|
|
31
|
+
path: "/",
|
|
32
|
+
httpOnly: true,
|
|
33
|
+
sameSite: "lax",
|
|
34
|
+
secure: isProduction,
|
|
35
|
+
maxAge
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function clearCookieOptions(isProduction) {
|
|
40
|
+
return [
|
|
41
|
+
{ path: "/", httpOnly: true, sameSite: "lax", secure: isProduction, maxAge: 0 },
|
|
42
|
+
{ path: "/api", httpOnly: true, sameSite: "lax", secure: isProduction, maxAge: 0 }
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function buildAccessToken({ user, session, secret, ttlSeconds = ACCESS_TTL_SECONDS }) {
|
|
47
|
+
const issuedAt = nowSeconds();
|
|
48
|
+
return signToken(
|
|
49
|
+
{
|
|
50
|
+
iss: "jskit-auth-local",
|
|
51
|
+
aud: "authenticated",
|
|
52
|
+
sub: user.id,
|
|
53
|
+
sid: session.id,
|
|
54
|
+
purpose: session.purpose || "normal",
|
|
55
|
+
email: user.email,
|
|
56
|
+
iat: issuedAt,
|
|
57
|
+
exp: issuedAt + ttlSeconds,
|
|
58
|
+
jti: randomToken(12)
|
|
59
|
+
},
|
|
60
|
+
secret
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @param {{ user: object, session: object, refreshToken: string, secret: string }} input */
|
|
65
|
+
function buildSessionPayload({ user, session, refreshToken, secret }) {
|
|
66
|
+
const accessToken = buildAccessToken({ user, session, secret });
|
|
67
|
+
return {
|
|
68
|
+
access_token: accessToken,
|
|
69
|
+
refresh_token: refreshToken,
|
|
70
|
+
expires_in: ACCESS_TTL_SECONDS,
|
|
71
|
+
token_type: "bearer",
|
|
72
|
+
purpose: session.purpose || "normal"
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The sessions of local auth: creating one, authenticating a request from its
|
|
78
|
+
* cookies, writing and clearing those cookies, and revoking sessions.
|
|
79
|
+
* @param {object} dependencies
|
|
80
|
+
* @param {boolean} dependencies.appProfileProjection True when the application keeps profiles.
|
|
81
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
82
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
83
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
84
|
+
*/
|
|
85
|
+
function createLocalSessions({ appProfileProjection, backend, config, profileProjector }) {
|
|
86
|
+
const { devAuth, isProduction } = config;
|
|
87
|
+
// Production cookies are Secure, so they are also host-only __Host- cookies.
|
|
88
|
+
const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isProduction);
|
|
89
|
+
const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isProduction);
|
|
90
|
+
const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isProduction);
|
|
91
|
+
|
|
92
|
+
async function createSessionForUser(tx, user, { purpose = "normal", ttlSeconds = REFRESH_TTL_SECONDS } = {}) {
|
|
93
|
+
const refreshToken = randomToken(36);
|
|
94
|
+
const session = await tx.sessions.create({
|
|
95
|
+
id: createId("ses"),
|
|
96
|
+
userId: user.id,
|
|
97
|
+
tokenHash: sha256Base64url(refreshToken),
|
|
98
|
+
purpose,
|
|
99
|
+
expiresAt: isoFromNow(ttlSeconds)
|
|
100
|
+
});
|
|
101
|
+
return buildSessionPayload({
|
|
102
|
+
user,
|
|
103
|
+
session,
|
|
104
|
+
refreshToken,
|
|
105
|
+
secret: config.sessionSecret
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function resolveValidSessionByRefreshToken(refreshToken) {
|
|
110
|
+
const tokenHash = sha256Base64url(refreshToken);
|
|
111
|
+
return backend.withTransaction(async (tx) => {
|
|
112
|
+
const session = await tx.sessions.findByTokenHash(tokenHash);
|
|
113
|
+
if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
const user = await tx.users.findById(session.userId);
|
|
117
|
+
if (!user || user.disabled) {
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
user,
|
|
122
|
+
session
|
|
123
|
+
};
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function authenticateRequest(request, { syncProfile = true } = {}) {
|
|
128
|
+
const cookies = safeRequestCookies(request);
|
|
129
|
+
const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
|
|
130
|
+
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
131
|
+
|
|
132
|
+
if (accessToken) {
|
|
133
|
+
const payload = verifySignedToken(accessToken, config.sessionSecret);
|
|
134
|
+
if (payload?.sid && payload?.sub) {
|
|
135
|
+
const resolved = await backend.withTransaction(async (tx) => {
|
|
136
|
+
const session = await tx.sessions.findById(String(payload.sid));
|
|
137
|
+
if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
const user = await tx.users.findById(String(payload.sub));
|
|
141
|
+
if (!user || user.disabled) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
return { user, session };
|
|
145
|
+
});
|
|
146
|
+
if (resolved && isAuthenticatingSession(resolved.session)) {
|
|
147
|
+
const authPayload = await buildSessionAuthPayload({
|
|
148
|
+
appProfileProjection,
|
|
149
|
+
devAuth,
|
|
150
|
+
profileProjector,
|
|
151
|
+
request,
|
|
152
|
+
session: resolved.session,
|
|
153
|
+
user: resolved.user,
|
|
154
|
+
syncProfile
|
|
155
|
+
});
|
|
156
|
+
if (!authPayload) {
|
|
157
|
+
return unauthenticatedAuthResult(true);
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
authenticated: true,
|
|
161
|
+
...authPayload,
|
|
162
|
+
session: null,
|
|
163
|
+
sessionPurpose: resolved.session.purpose || "normal",
|
|
164
|
+
clearSession: false,
|
|
165
|
+
transientFailure: false
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (!refreshToken) {
|
|
172
|
+
return unauthenticatedAuthResult(Boolean(accessToken));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const resolved = await resolveValidSessionByRefreshToken(refreshToken);
|
|
176
|
+
if (!resolved) {
|
|
177
|
+
return unauthenticatedAuthResult(true);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (!isAuthenticatingSession(resolved.session)) {
|
|
181
|
+
return unauthenticatedAuthResult();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const authPayload = await buildSessionAuthPayload({
|
|
185
|
+
appProfileProjection,
|
|
186
|
+
devAuth,
|
|
187
|
+
profileProjector,
|
|
188
|
+
request,
|
|
189
|
+
session: resolved.session,
|
|
190
|
+
user: resolved.user,
|
|
191
|
+
syncProfile
|
|
192
|
+
});
|
|
193
|
+
if (!authPayload) {
|
|
194
|
+
return unauthenticatedAuthResult(true);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
authenticated: true,
|
|
199
|
+
...authPayload,
|
|
200
|
+
session: buildSessionPayload({
|
|
201
|
+
user: resolved.user,
|
|
202
|
+
session: resolved.session,
|
|
203
|
+
refreshToken,
|
|
204
|
+
secret: config.sessionSecret
|
|
205
|
+
}),
|
|
206
|
+
sessionPurpose: resolved.session.purpose || "normal",
|
|
207
|
+
clearSession: false,
|
|
208
|
+
transientFailure: false
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function requireNormalSessionUserId(request) {
|
|
213
|
+
const authResult = await authenticateRequest(request);
|
|
214
|
+
if (authResult.authenticated !== true || authResult.sessionPurpose !== "normal") {
|
|
215
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
216
|
+
}
|
|
217
|
+
return authResult.actor.providerUserId;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The access token of the request's recovery session, or "" when it has none. */
|
|
221
|
+
function readRecoveryAccessToken(request) {
|
|
222
|
+
return String(safeRequestCookies(request)[RECOVERY_TOKEN_COOKIE] || "").trim();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function hasAccessTokenCookie(request) {
|
|
226
|
+
return Boolean(safeRequestCookies(request)[ACCESS_TOKEN_COOKIE] || safeRequestCookies(request)[RECOVERY_TOKEN_COOKIE]);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function hasSessionCookie(request) {
|
|
230
|
+
const cookies = safeRequestCookies(request);
|
|
231
|
+
return Boolean(cookies[ACCESS_TOKEN_COOKIE] || cookies[REFRESH_TOKEN_COOKIE] || cookies[RECOVERY_TOKEN_COOKIE]);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function writeSessionCookies(reply, session) {
|
|
235
|
+
if (!reply || !session) {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const accessToken = String(session.access_token || "");
|
|
239
|
+
const refreshToken = String(session.refresh_token || "");
|
|
240
|
+
const purpose = String(session.purpose || "normal");
|
|
241
|
+
const isRecoverySession = purpose === "recovery";
|
|
242
|
+
const accessMaxAge = Number(session.expires_in || ACCESS_TTL_SECONDS);
|
|
243
|
+
const refreshMaxAge = isRecoverySession ? accessMaxAge : REFRESH_TTL_SECONDS;
|
|
244
|
+
if (accessToken) {
|
|
245
|
+
reply.setCookie(
|
|
246
|
+
isRecoverySession ? RECOVERY_TOKEN_COOKIE : ACCESS_TOKEN_COOKIE,
|
|
247
|
+
accessToken,
|
|
248
|
+
cookieOptions(isProduction, accessMaxAge)
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
if (refreshToken) {
|
|
252
|
+
reply.setCookie(REFRESH_TOKEN_COOKIE, refreshToken, cookieOptions(isProduction, refreshMaxAge));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function clearSessionCookies(reply) {
|
|
257
|
+
if (!reply) {
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
for (const options of clearCookieOptions(isProduction)) {
|
|
261
|
+
// A __Host- cookie only exists at Path=/.
|
|
262
|
+
if (options.path === "/" || !isProduction) {
|
|
263
|
+
reply.clearCookie(ACCESS_TOKEN_COOKIE, options);
|
|
264
|
+
reply.clearCookie(REFRESH_TOKEN_COOKIE, options);
|
|
265
|
+
reply.clearCookie(RECOVERY_TOKEN_COOKIE, options);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function logout(request) {
|
|
271
|
+
const cookies = safeRequestCookies(request);
|
|
272
|
+
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
273
|
+
if (!refreshToken) {
|
|
274
|
+
return {
|
|
275
|
+
ok: true,
|
|
276
|
+
clearSession: true
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
await backend.withTransaction(async (tx) => {
|
|
280
|
+
const session = await tx.sessions.findByTokenHash(sha256Base64url(refreshToken));
|
|
281
|
+
if (session) {
|
|
282
|
+
await tx.sessions.revoke(session.id);
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
return {
|
|
286
|
+
ok: true,
|
|
287
|
+
clearSession: true
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function signOutOtherSessions(request) {
|
|
292
|
+
const authResult = await authenticateRequest(request);
|
|
293
|
+
if (authResult.authenticated !== true) {
|
|
294
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
295
|
+
}
|
|
296
|
+
const cookies = safeRequestCookies(request);
|
|
297
|
+
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
298
|
+
const currentSession = refreshToken ? await resolveValidSessionByRefreshToken(refreshToken) : null;
|
|
299
|
+
const count = await backend.withTransaction((tx) =>
|
|
300
|
+
tx.sessions.revokeForUser(authResult.actor.providerUserId, {
|
|
301
|
+
exceptSessionId: currentSession?.session?.id
|
|
302
|
+
})
|
|
303
|
+
);
|
|
304
|
+
return {
|
|
305
|
+
ok: true,
|
|
306
|
+
revokedSessions: count
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
return Object.freeze({
|
|
311
|
+
createSessionForUser,
|
|
312
|
+
authenticateRequest,
|
|
313
|
+
requireNormalSessionUserId,
|
|
314
|
+
readRecoveryAccessToken,
|
|
315
|
+
hasAccessTokenCookie,
|
|
316
|
+
hasSessionCookie,
|
|
317
|
+
writeSessionCookies,
|
|
318
|
+
clearSessionCookies,
|
|
319
|
+
logout,
|
|
320
|
+
signOutOtherSessions
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export { cookieOptions, createLocalSessions, safeRequestCookies };
|
package/src/server/lib/tokens.js
CHANGED
|
@@ -54,4 +54,16 @@ function verifySignedToken(token, secret) {
|
|
|
54
54
|
return payload;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
function createId(prefix) {
|
|
58
|
+
return `${prefix}_${randomToken(18)}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isoFromNow(seconds) {
|
|
62
|
+
return new Date(Date.now() + seconds * 1000).toISOString();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function isExpiredIso(value) {
|
|
66
|
+
return Date.parse(String(value || "")) <= Date.now();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url, signToken, verifySignedToken };
|
|
@@ -1,83 +1,15 @@
|
|
|
1
|
-
import { parseBooleanFlag } from "@jskit-ai/auth-core/server/booleanFlag";
|
|
2
|
-
import { assertDevAuthPolicy, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
|
|
3
1
|
import {
|
|
4
2
|
attachDeferredAuthService,
|
|
5
3
|
createDeferredAuthService
|
|
6
4
|
} from "@jskit-ai/auth-core/server/deferredAuthService";
|
|
5
|
+
import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
7
6
|
import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
8
|
-
import {
|
|
9
|
-
import fs from "node:fs";
|
|
10
|
-
import path from "node:path";
|
|
7
|
+
import { resolveLocalAuthConfig } from "../lib/config.js";
|
|
11
8
|
import { createLocalFileBackend } from "../lib/fileBackend.js";
|
|
12
|
-
import {
|
|
9
|
+
import { createLoggedRecoverySender } from "../lib/passwordFlows.js";
|
|
10
|
+
import { scryptPasswordStrategy } from "../lib/passwords.js";
|
|
13
11
|
import { createLocalAuthService } from "../lib/service.js";
|
|
14
12
|
|
|
15
|
-
const DEFAULT_STORE_DIR = ".jskit/auth";
|
|
16
|
-
function resolveStoreDir(env, appRoot) {
|
|
17
|
-
const configured = String(env.AUTH_LOCAL_STORE_DIR || DEFAULT_STORE_DIR).trim() || DEFAULT_STORE_DIR;
|
|
18
|
-
return path.resolve(appRoot, configured);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function resolveSessionSecret(env, { storeDir, isProduction }) {
|
|
22
|
-
const explicit = String(env.AUTH_LOCAL_SESSION_SECRET || "").trim();
|
|
23
|
-
if (explicit) return explicit;
|
|
24
|
-
if (isProduction) throw new Error("AUTH_LOCAL_SESSION_SECRET is required for local auth in production.");
|
|
25
|
-
|
|
26
|
-
const secretPath = path.join(storeDir, "session.secret");
|
|
27
|
-
try {
|
|
28
|
-
const existing = fs.readFileSync(secretPath, "utf8").trim();
|
|
29
|
-
if (existing) return existing;
|
|
30
|
-
} catch (error) {
|
|
31
|
-
if (!error || error.code !== "ENOENT") throw error;
|
|
32
|
-
}
|
|
33
|
-
fs.mkdirSync(storeDir, { recursive: true, mode: 0o700 });
|
|
34
|
-
const generated = randomBytes(32).toString("base64url");
|
|
35
|
-
fs.writeFileSync(secretPath, `${generated}\n`, { mode: 0o600 });
|
|
36
|
-
return generated;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Recovery links and OAuth redirect addresses are built from APP_PUBLIC_URL.
|
|
40
|
-
function resolveAppPublicUrl(env, { recoverySender, oauthProviders }) {
|
|
41
|
-
const configured = String(env.APP_PUBLIC_URL || "").trim();
|
|
42
|
-
if (!configured) {
|
|
43
|
-
if (recoverySender) throw new Error("APP_PUBLIC_URL is required when local auth email recovery is configured.");
|
|
44
|
-
if (oauthProviders.length > 0) throw new Error("APP_PUBLIC_URL is required when local auth OAuth sign-in is configured.");
|
|
45
|
-
return "http://localhost:5173";
|
|
46
|
-
}
|
|
47
|
-
let parsed;
|
|
48
|
-
try {
|
|
49
|
-
parsed = new URL(configured);
|
|
50
|
-
} catch {
|
|
51
|
-
throw new Error("APP_PUBLIC_URL must be a valid URL.");
|
|
52
|
-
}
|
|
53
|
-
if (!["http:", "https:"].includes(parsed.protocol)) {
|
|
54
|
-
throw new Error("APP_PUBLIC_URL must use http or https.");
|
|
55
|
-
}
|
|
56
|
-
return parsed.toString().replace(/\/$/u, "");
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function resolveConfig({ appRoot, backend, env, logger, recoverySender = null }) {
|
|
60
|
-
const nodeEnv = String(env.NODE_ENV || "development").trim() || "development";
|
|
61
|
-
const isProduction = nodeEnv === "production";
|
|
62
|
-
const storeDir = resolveStoreDir(env, appRoot);
|
|
63
|
-
if (!backend && isProduction && !parseBooleanFlag(env.AUTH_LOCAL_FILE_PRODUCTION_ACK, false)) {
|
|
64
|
-
throw new Error("AUTH_LOCAL_FILE_PRODUCTION_ACK is required to use the local file auth backend in production.");
|
|
65
|
-
}
|
|
66
|
-
const devAuth = resolveDevAuthPolicyFromEnv(env);
|
|
67
|
-
assertDevAuthPolicy(devAuth);
|
|
68
|
-
const oauthProviders = resolveOAuthProviders(env);
|
|
69
|
-
return {
|
|
70
|
-
storeDir,
|
|
71
|
-
nodeEnv,
|
|
72
|
-
logger,
|
|
73
|
-
appPublicUrl: resolveAppPublicUrl(env, { recoverySender, oauthProviders }),
|
|
74
|
-
oauthProviders,
|
|
75
|
-
sessionSecret: resolveSessionSecret(env, { storeDir, isProduction }),
|
|
76
|
-
recoveryDevOutput: String(env.AUTH_LOCAL_RECOVERY_DEV_OUTPUT || "log").trim().toLowerCase() || "log",
|
|
77
|
-
devAuth
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
|
|
81
13
|
const AuthLocalProvider = defineProvider({
|
|
82
14
|
id: "auth.local",
|
|
83
15
|
requires: {
|
|
@@ -89,6 +21,7 @@ const AuthLocalProvider = defineProvider({
|
|
|
89
21
|
optional: {
|
|
90
22
|
backend: "auth.local.backend",
|
|
91
23
|
passwordStrategy: "auth.local.password-strategy",
|
|
24
|
+
profileProjector: "auth.profile.projector",
|
|
92
25
|
recoverySender: "auth.local.recovery-sender"
|
|
93
26
|
},
|
|
94
27
|
provides: {
|
|
@@ -97,19 +30,33 @@ const AuthLocalProvider = defineProvider({
|
|
|
97
30
|
setup() {
|
|
98
31
|
return { authService: createDeferredAuthService() };
|
|
99
32
|
},
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} dependencies
|
|
35
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} dependencies.appRoot
|
|
36
|
+
* @param {import("../types.js").AuthLocalBackend | null} dependencies.backend The `auth.local.backend`, when one is installed.
|
|
37
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
|
|
38
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthExtensions} dependencies.extensions
|
|
39
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
40
|
+
* @param {import("../types.js").AuthLocalPasswordStrategy | null} dependencies.passwordStrategy The `auth.local.password-strategy`, when one is installed.
|
|
41
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector | null} dependencies.profileProjector The `auth.profile.projector`, when one is installed.
|
|
42
|
+
* @param {import("../types.js").AuthLocalRecoverySender | null} dependencies.recoverySender The `auth.local.recovery-sender`, when one is installed.
|
|
43
|
+
*/
|
|
44
|
+
boot({ appRoot, backend, env, extensions, logger, passwordStrategy, profileProjector, recoverySender }, { outputs }) {
|
|
45
|
+
const fileBackend = backend === null;
|
|
46
|
+
const emailRecovery = recoverySender !== null;
|
|
47
|
+
const config = resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery });
|
|
103
48
|
const baseService = createLocalAuthService({
|
|
104
|
-
backend:
|
|
49
|
+
backend: fileBackend ? createLocalFileBackend({ storeDir: config.storeDir }) : backend,
|
|
105
50
|
config,
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
51
|
+
invitationContextResolver: extensions.resolveInvitationContextResolver(),
|
|
52
|
+
logger,
|
|
53
|
+
passwordStrategy: passwordStrategy ?? scryptPasswordStrategy,
|
|
54
|
+
profileProjector: profileProjector ?? noAppProfiles,
|
|
55
|
+
recoverySender: emailRecovery ? recoverySender : createLoggedRecoverySender(logger)
|
|
110
56
|
});
|
|
57
|
+
// readable-check: allow setter-seam - deferred until boot: auth.service is built after every setup has registered its auth extensions, and those setups already receive it
|
|
111
58
|
attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
|
|
112
59
|
}
|
|
113
60
|
});
|
|
114
61
|
|
|
115
|
-
export { AuthLocalProvider
|
|
62
|
+
export { AuthLocalProvider };
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The types of local auth's capabilities, for packages that provide one, and
|
|
2
|
+
// the types its modules share.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One transaction of a local auth backend. A find answers null when nothing
|
|
6
|
+
* matches; a bulk change answers how many records it changed.
|
|
7
|
+
* @typedef {object} AuthLocalBackendTransaction
|
|
8
|
+
* @property {{
|
|
9
|
+
* create(input: object): Promise<object>,
|
|
10
|
+
* findById(userId: string): Promise<object | null>,
|
|
11
|
+
* findByEmail(email: string): Promise<object | null>,
|
|
12
|
+
* updatePassword(userId: string, passwordRecord: object): Promise<object | null>,
|
|
13
|
+
* updateProfile(userId: string, updates: object): Promise<object | null>
|
|
14
|
+
* }} users
|
|
15
|
+
* @property {{
|
|
16
|
+
* create(input: object): Promise<object>,
|
|
17
|
+
* findById(sessionId: string): Promise<object | null>,
|
|
18
|
+
* findByTokenHash(tokenHash: string): Promise<object | null>,
|
|
19
|
+
* revoke(sessionId: string): Promise<object | null>,
|
|
20
|
+
* revokeForUser(userId: string, options?: object): Promise<number>
|
|
21
|
+
* }} sessions
|
|
22
|
+
* @property {{
|
|
23
|
+
* create(input: object): Promise<object>,
|
|
24
|
+
* findByTokenHash(tokenHash: string): Promise<object | null>,
|
|
25
|
+
* consume(tokenId: string): Promise<object | null>,
|
|
26
|
+
* consumeForUser(userId: string): Promise<number>
|
|
27
|
+
* }} recovery
|
|
28
|
+
* @property {{
|
|
29
|
+
* create(input: object): Promise<object>,
|
|
30
|
+
* findByProviderSubject(provider: string, providerSubject: string): Promise<object | null>,
|
|
31
|
+
* listForUser(userId: string): Promise<object[]>,
|
|
32
|
+
* deleteForUser(userId: string, provider: string): Promise<number>
|
|
33
|
+
* }} identities
|
|
34
|
+
* @property {{
|
|
35
|
+
* create(input: object): Promise<object>,
|
|
36
|
+
* take(browserKeyHash: string): Promise<object | null>,
|
|
37
|
+
* deleteExpired(now: string): Promise<number>
|
|
38
|
+
* }} oauthAttempts
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The `auth.local.backend` capability: where local auth keeps its users,
|
|
43
|
+
* sessions, recovery tokens, linked identities and OAuth attempts. Without
|
|
44
|
+
* one, local auth keeps them in files under AUTH_LOCAL_STORE_DIR;
|
|
45
|
+
* `@jskit-ai/auth-provider-local-db-core` provides one that keeps them in the
|
|
46
|
+
* database. Each backend implements this contract.
|
|
47
|
+
* @typedef {object} AuthLocalBackend
|
|
48
|
+
* @property {<T>(callback: (tx: AuthLocalBackendTransaction) => Promise<T>) => Promise<T>} withTransaction
|
|
49
|
+
* Runs the callback in one transaction and answers what it answered.
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The `auth.local.password-strategy` capability: how local auth hashes and
|
|
54
|
+
* checks passwords. A strategy may give only one of the two operations; local
|
|
55
|
+
* auth uses scrypt for the other.
|
|
56
|
+
* @typedef {object} AuthLocalPasswordStrategy
|
|
57
|
+
* @property {(password: string) => Promise<unknown>} [hashPassword] Answers the record to store.
|
|
58
|
+
* @property {(password: string, record: unknown) => Promise<boolean> | boolean} [verifyPassword]
|
|
59
|
+
* Answers true when the password matches the stored record.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The `auth.local.recovery-sender` capability: sends a password recovery link
|
|
64
|
+
* to the person it belongs to.
|
|
65
|
+
* @typedef {(delivery: { email: string, recoveryUrl: string }) => Promise<void>} AuthLocalRecoverySender
|
|
66
|
+
*/
|
|
67
|
+
|
|
68
|
+
/** @typedef {ReturnType<typeof import("./lib/config.js").resolveLocalAuthConfig>} AuthLocalConfig */
|
|
69
|
+
/** @typedef {AuthLocalConfig["oauthProviders"][number]} AuthLocalOAuthProvider */
|
|
70
|
+
/** @typedef {ReturnType<typeof import("./lib/passwords.js").normalizePasswordStrategy>} AuthLocalPasswords */
|
|
71
|
+
/** @typedef {ReturnType<typeof import("./lib/sessions.js").createLocalSessions>} AuthLocalSessions */
|
|
72
|
+
|
|
73
|
+
export {};
|
package/test/codedTexts.test.js
CHANGED
|
@@ -7,6 +7,7 @@ import { catalogMessage, formatMessage, mergeCatalogs, messageKeyForCode } from
|
|
|
7
7
|
import authCoreEnglish from "@jskit-ai/auth-core/locales/en.json" with { type: "json" };
|
|
8
8
|
import localEnglish from "../locales/en.json" with { type: "json" };
|
|
9
9
|
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
10
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
10
11
|
|
|
11
12
|
const english = mergeCatalogs(authCoreEnglish, localEnglish);
|
|
12
13
|
|
|
@@ -26,17 +27,11 @@ function assertCoded(error, code) {
|
|
|
26
27
|
return true;
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
async function createService(
|
|
30
|
+
async function createService(env = {}) {
|
|
30
31
|
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-coded-"));
|
|
31
32
|
return createLocalAuthService({
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
sessionSecret: "coded-texts-secret",
|
|
35
|
-
nodeEnv: "test",
|
|
36
|
-
appPublicUrl: "http://localhost:5173",
|
|
37
|
-
recoveryDevOutput: "response",
|
|
38
|
-
...config
|
|
39
|
-
}
|
|
33
|
+
...localServiceOptions({ env }),
|
|
34
|
+
backend: createLocalFileBackend({ storeDir })
|
|
40
35
|
});
|
|
41
36
|
}
|
|
42
37
|
|
|
@@ -58,7 +53,7 @@ test("local auth errors carry codes whose English is the thrown message", async
|
|
|
58
53
|
await assert.rejects(() => service.updateDisplayName({ cookies: {} }, { displayName: "Ada" }),
|
|
59
54
|
(error) => assertCoded(error, "auth.session.required"));
|
|
60
55
|
|
|
61
|
-
const disabled = await createService({
|
|
56
|
+
const disabled = await createService({ NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "log" });
|
|
62
57
|
await assert.rejects(() => disabled.requestPasswordReset({ email: "ada@example.com" }),
|
|
63
58
|
(error) => assertCoded(error, "auth.local.recovery.notConfigured"));
|
|
64
59
|
});
|
package/test/oauthSignIn.test.js
CHANGED
|
@@ -5,9 +5,11 @@ import path from "node:path";
|
|
|
5
5
|
import test from "node:test";
|
|
6
6
|
import { decodeJwt, generateKeyPair, SignJWT } from "jose";
|
|
7
7
|
import { createService as createProfileSyncService } from "../../users-core/src/server/common/services/authProfileSyncService.js";
|
|
8
|
+
import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
9
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
8
10
|
import { createLocalAuthRegisterHookDecorator, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
9
11
|
import { sha256Base64url } from "../src/server/lib/tokens.js";
|
|
10
|
-
import {
|
|
12
|
+
import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
11
13
|
import {
|
|
12
14
|
APP_URL,
|
|
13
15
|
ATTEMPT_COOKIE,
|
|
@@ -67,7 +69,7 @@ function createUsersProfileSync() {
|
|
|
67
69
|
return { profileProjector, profiles, provisioned };
|
|
68
70
|
}
|
|
69
71
|
|
|
70
|
-
async function googleSetup(t, { account, profileProjector =
|
|
72
|
+
async function googleSetup(t, { account, profileProjector = noAppProfiles } = {}) {
|
|
71
73
|
const issuer = await startOidcProvider({ account });
|
|
72
74
|
t.after(() => issuer.close());
|
|
73
75
|
const backend = await fileBackend();
|
|
@@ -96,6 +98,7 @@ test("a first Google sign-in creates the user like register, provisions it, and
|
|
|
96
98
|
const { issuer, backend, service: baseService } = await googleSetup(t, { profileProjector: usersSync.profileProjector });
|
|
97
99
|
const registered = [];
|
|
98
100
|
const service = createLocalAuthRegisterHookDecorator({
|
|
101
|
+
logger: silentLogger,
|
|
99
102
|
hook: { blocking: true, handle: (payload) => registered.push(payload.actor.email) }
|
|
100
103
|
}).decorateAuthService(baseService);
|
|
101
104
|
|
|
@@ -234,7 +237,8 @@ test("Microsoft accepts personal accounts and work accounts on a verified domain
|
|
|
234
237
|
st.after(() => issuer.close());
|
|
235
238
|
const service = createService({
|
|
236
239
|
backend: await fileBackend(),
|
|
237
|
-
oauthProviders: [oidcProviderEntry(issuer, { id: "microsoft", label: "Microsoft" })]
|
|
240
|
+
oauthProviders: [oidcProviderEntry(issuer, { id: "microsoft", label: "Microsoft" })],
|
|
241
|
+
profileProjector: noAppProfiles
|
|
238
242
|
});
|
|
239
243
|
tamperIdToken(st, issuer, claims);
|
|
240
244
|
const { input, request } = await approveAtProvider(service, { provider: "microsoft" });
|
|
@@ -252,7 +256,7 @@ test("GitHub signs in with the primary verified address and refuses an unverifie
|
|
|
252
256
|
const github = await startFakeGitHub();
|
|
253
257
|
t.after(() => github.close());
|
|
254
258
|
const backend = await fileBackend();
|
|
255
|
-
const service = createService({ backend, oauthProviders: [github.provider] });
|
|
259
|
+
const service = createService({ backend, oauthProviders: [github.provider], profileProjector: noAppProfiles });
|
|
256
260
|
|
|
257
261
|
const { started, input, request } = await approveAtProvider(service, { provider: "github" });
|
|
258
262
|
assert.equal(new URL(started.url).searchParams.get("scope"), "read:user user:email");
|
|
@@ -283,7 +287,8 @@ test("account settings link and unlink providers, never removing the last sign-i
|
|
|
283
287
|
});
|
|
284
288
|
const service = createService({
|
|
285
289
|
backend: await fileBackend(),
|
|
286
|
-
oauthProviders: [oidcProviderEntry(issuer), github.provider]
|
|
290
|
+
oauthProviders: [oidcProviderEntry(issuer), github.provider],
|
|
291
|
+
profileProjector: noAppProfiles
|
|
287
292
|
});
|
|
288
293
|
const methods = async (cookies) => Object.fromEntries((await service.getSecurityStatus({ cookies })).authMethods
|
|
289
294
|
.map((method) => [method.id, { enabled: method.enabled, canEnable: method.canEnable ?? false, canDisable: method.canDisable }]));
|
|
@@ -341,7 +346,12 @@ test("returnTo stays on the app's own origin", async (t) => {
|
|
|
341
346
|
|
|
342
347
|
test("a provider appears only when its client id and secret are both set", () => {
|
|
343
348
|
const base = { NODE_ENV: "test", AUTH_LOCAL_SESSION_SECRET: "secret", APP_PUBLIC_URL: APP_URL };
|
|
344
|
-
const config = (env) =>
|
|
349
|
+
const config = (env) => resolveLocalAuthConfig({
|
|
350
|
+
appRoot: os.tmpdir(),
|
|
351
|
+
env: { ...base, ...env },
|
|
352
|
+
fileBackend: false,
|
|
353
|
+
emailRecovery: false
|
|
354
|
+
});
|
|
345
355
|
|
|
346
356
|
assert.deepEqual(config({}).oauthProviders, []);
|
|
347
357
|
assert.deepEqual(config({
|