@jskit-ai/auth-provider-local-core 0.2.4 → 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
|
@@ -1,345 +1,43 @@
|
|
|
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
1
|
import { normalizeAuthCapabilities } from "@jskit-ai/auth-core/shared/authCapabilities";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { normalizeAuthActor, normalizeAuthResult } from "@jskit-ai/auth-core/server/authActor";
|
|
10
|
-
import {
|
|
11
|
-
assertDevAuthPolicy,
|
|
12
|
-
ensureDevAuthExchangeAvailable,
|
|
13
|
-
ensureDevAuthRuntimeAvailable,
|
|
14
|
-
resolveDevAuthPolicy
|
|
15
|
-
} from "@jskit-ai/auth-core/server/devAuth";
|
|
16
|
-
import { hostOnlyCookieName, normalizeEmail, normalizeReturnToPath } from "@jskit-ai/auth-core/server/utils";
|
|
2
|
+
import { isDevAuthBootstrapEnabled } from "@jskit-ai/auth-core/server/devAuth";
|
|
3
|
+
import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
17
4
|
import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
createAuthError
|
|
23
|
-
} from "@jskit-ai/auth-core/server/authTexts";
|
|
24
|
-
import { createOAuthClients } from "./oauth.js";
|
|
5
|
+
import { createLocalAccounts } from "./accounts.js";
|
|
6
|
+
import { PROVIDER_ID } from "./authPayloads.js";
|
|
7
|
+
import { createLocalOAuthFlows } from "./oauthFlows.js";
|
|
8
|
+
import { createLocalPasswordFlows } from "./passwordFlows.js";
|
|
25
9
|
import { normalizePasswordStrategy } from "./passwords.js";
|
|
26
|
-
import {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
function nowSeconds() {
|
|
45
|
-
return Math.floor(Date.now() / 1000);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function isoFromNow(seconds) {
|
|
49
|
-
return new Date(Date.now() + seconds * 1000).toISOString();
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function isExpiredIso(value) {
|
|
53
|
-
return Date.parse(String(value || "")) <= Date.now();
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function isNormalSession(session) {
|
|
57
|
-
return (session?.purpose || "normal") === "normal";
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function isDevAuthSession(session) {
|
|
61
|
-
return session?.purpose === DEV_AUTH_SESSION_PURPOSE;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function isAuthenticatingSession(session) {
|
|
65
|
-
return isNormalSession(session) || isDevAuthSession(session);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
function normalizeDisplayName(value, email) {
|
|
69
|
-
const displayName = String(value || "").trim();
|
|
70
|
-
if (displayName) {
|
|
71
|
-
return displayName;
|
|
72
|
-
}
|
|
73
|
-
return email.split("@")[0] || "User";
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// Accounts created through a provider store NO_PASSWORD; any other stored
|
|
77
|
-
// record, in whatever format the password strategy uses, is a password.
|
|
78
|
-
function hasPassword(user) {
|
|
79
|
-
const record = user?.password;
|
|
80
|
-
return record && typeof record === "object" ? Boolean(record.hash) : Boolean(record);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function createId(prefix) {
|
|
84
|
-
return `${prefix}_${randomToken(18)}`;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function safeRequestCookies(request) {
|
|
88
|
-
return request && request.cookies && typeof request.cookies === "object" ? request.cookies : {};
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function unauthenticatedAuthResult(clearSession = false) {
|
|
92
|
-
return {
|
|
93
|
-
authenticated: false,
|
|
94
|
-
clearSession: Boolean(clearSession),
|
|
95
|
-
session: null,
|
|
96
|
-
transientFailure: false
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function cookieOptions(isProduction, maxAge) {
|
|
101
|
-
return {
|
|
102
|
-
path: "/",
|
|
103
|
-
httpOnly: true,
|
|
104
|
-
sameSite: "lax",
|
|
105
|
-
secure: isProduction,
|
|
106
|
-
maxAge
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function clearCookieOptions(isProduction) {
|
|
111
|
-
return [
|
|
112
|
-
{ path: "/", httpOnly: true, sameSite: "lax", secure: isProduction, maxAge: 0 },
|
|
113
|
-
{ path: "/api", httpOnly: true, sameSite: "lax", secure: isProduction, maxAge: 0 }
|
|
114
|
-
];
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
function buildProfile(user) {
|
|
118
|
-
return {
|
|
119
|
-
id: user.id,
|
|
120
|
-
authProvider: PROVIDER_ID,
|
|
121
|
-
authProviderUserSid: user.id,
|
|
122
|
-
email: user.email,
|
|
123
|
-
displayName: user.displayName,
|
|
124
|
-
profileSource: "auth-provider"
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function buildActor(user, profile = null) {
|
|
129
|
-
const profileSource = profile ? "users" : "auth-provider";
|
|
130
|
-
return normalizeAuthActor({
|
|
131
|
-
provider: PROVIDER_ID,
|
|
132
|
-
providerUserId: user.id,
|
|
133
|
-
email: user.email,
|
|
134
|
-
displayName: user.displayName,
|
|
135
|
-
appUserId: profile?.id || null,
|
|
136
|
-
profileSource
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function buildAuthResult({ user, session, appProfile = null }) {
|
|
141
|
-
return normalizeAuthResult({
|
|
142
|
-
actor: buildActor(user, appProfile),
|
|
143
|
-
session
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function requireProfileResult(profile, methodName) {
|
|
148
|
-
if (!profile || typeof profile !== "object") {
|
|
149
|
-
throw new Error(`auth.profile.projector.${methodName}() must return a profile object.`);
|
|
150
|
-
}
|
|
151
|
-
return profile;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
async function buildAuthPayload({ user, session, profileProjector, profileOptions = {} }) {
|
|
155
|
-
const appProfile = profileProjector
|
|
156
|
-
? requireProfileResult(
|
|
157
|
-
await profileProjector.syncIdentityProfile(buildProfile(user), profileOptions),
|
|
158
|
-
"syncIdentityProfile"
|
|
159
|
-
)
|
|
160
|
-
: null;
|
|
161
|
-
return buildAuthResult({ user, session, appProfile });
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
async function findExistingAppProfile(user, profileProjector) {
|
|
165
|
-
if (!profileProjector) {
|
|
166
|
-
return null;
|
|
167
|
-
}
|
|
168
|
-
if (typeof profileProjector.findByIdentity !== "function") {
|
|
169
|
-
throw new Error(
|
|
170
|
-
"auth.profile.projector.findByIdentity() is required for dev auth impersonation and profile lookups without sync."
|
|
171
|
-
);
|
|
172
|
-
}
|
|
173
|
-
const profile = await profileProjector.findByIdentity(buildProfile(user));
|
|
174
|
-
return profile ? requireProfileResult(profile, "findByIdentity") : null;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// A dev session, or a caller that asks only who is signed in (syncProfile:
|
|
178
|
-
// false), reads the existing app profile instead of synchronizing it.
|
|
179
|
-
async function buildSessionAuthPayload({ devAuth, profileProjector, request, session, user, syncProfile = true }) {
|
|
180
|
-
const devSession = isDevAuthSession(session);
|
|
181
|
-
if (!devSession && syncProfile) {
|
|
182
|
-
return buildAuthPayload({ user, session: null, profileProjector });
|
|
183
|
-
}
|
|
184
|
-
if (devSession) {
|
|
185
|
-
try {
|
|
186
|
-
ensureDevAuthRuntimeAvailable(devAuth, request);
|
|
187
|
-
} catch {
|
|
188
|
-
return null;
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
const appProfile = await findExistingAppProfile(user, profileProjector);
|
|
192
|
-
return profileProjector && !appProfile
|
|
193
|
-
? null
|
|
194
|
-
: buildAuthResult({ user, session: null, appProfile });
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function buildAccessToken({ user, session, secret, ttlSeconds = ACCESS_TTL_SECONDS }) {
|
|
198
|
-
const issuedAt = nowSeconds();
|
|
199
|
-
return signToken(
|
|
200
|
-
{
|
|
201
|
-
iss: "jskit-auth-local",
|
|
202
|
-
aud: "authenticated",
|
|
203
|
-
sub: user.id,
|
|
204
|
-
sid: session.id,
|
|
205
|
-
purpose: session.purpose || "normal",
|
|
206
|
-
email: user.email,
|
|
207
|
-
iat: issuedAt,
|
|
208
|
-
exp: issuedAt + ttlSeconds,
|
|
209
|
-
jti: randomToken(12)
|
|
210
|
-
},
|
|
211
|
-
secret
|
|
212
|
-
);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function buildSessionPayload({ user, session, refreshToken, secret }) {
|
|
216
|
-
const accessToken = buildAccessToken({ user, session, secret });
|
|
217
|
-
return {
|
|
218
|
-
access_token: accessToken,
|
|
219
|
-
refresh_token: refreshToken,
|
|
220
|
-
expires_in: ACCESS_TTL_SECONDS,
|
|
221
|
-
token_type: "bearer",
|
|
222
|
-
purpose: session.purpose || "normal"
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function validatePasswordInput(password) {
|
|
227
|
-
const normalizedPassword = String(password || "");
|
|
228
|
-
if (
|
|
229
|
-
normalizedPassword.length < AUTH_PASSWORD_MIN_LENGTH ||
|
|
230
|
-
normalizedPassword.length > AUTH_PASSWORD_MAX_LENGTH
|
|
231
|
-
) {
|
|
232
|
-
const params = { min: AUTH_PASSWORD_MIN_LENGTH };
|
|
233
|
-
throw new AppError(400, "Password must be at least 8 characters.", {
|
|
234
|
-
code: "auth.local.password.tooShort",
|
|
235
|
-
params,
|
|
236
|
-
details: {
|
|
237
|
-
fieldErrors: {
|
|
238
|
-
password: "Password must be at least 8 characters."
|
|
239
|
-
},
|
|
240
|
-
fieldErrorCodes: {
|
|
241
|
-
password: { code: "auth.local.password.tooShort", params }
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
function validateEmailInput(email) {
|
|
249
|
-
const normalized = normalizeEmail(email);
|
|
250
|
-
if (!normalized || !normalized.includes("@")) {
|
|
251
|
-
throw new AppError(400, "Enter a valid email address.", {
|
|
252
|
-
code: "auth.local.email.invalid",
|
|
253
|
-
details: {
|
|
254
|
-
fieldErrors: {
|
|
255
|
-
email: "Enter a valid email address."
|
|
256
|
-
},
|
|
257
|
-
fieldErrorCodes: {
|
|
258
|
-
email: { code: "auth.local.email.invalid", params: {} }
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
return normalized;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// fields: { field: AUTH_TEXTS entry }; the error says the first field's text.
|
|
267
|
-
function devLoginAsValidationError(fields = {}) {
|
|
268
|
-
const [first = AUTH_TEXTS.devUserRequired] = Object.values(fields);
|
|
269
|
-
return createAuthError(first, {
|
|
270
|
-
details: authFieldErrorDetails(fields)
|
|
271
|
-
});
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
function devLoginAsUserNotFound({ email = "", userId = "" } = {}) {
|
|
275
|
-
return devLoginAsValidationError({
|
|
276
|
-
...(userId ? { userId: AUTH_TEXTS.devUserNotFound } : {}),
|
|
277
|
-
...(email ? { email: AUTH_TEXTS.devUserNotFound } : {})
|
|
278
|
-
});
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
function normalizeInvitationInput(value = null) {
|
|
282
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
283
|
-
return null;
|
|
284
|
-
}
|
|
285
|
-
const token = String(value.token || value.inviteToken || "").trim();
|
|
286
|
-
if (!token) {
|
|
287
|
-
return null;
|
|
288
|
-
}
|
|
289
|
-
return {
|
|
290
|
-
token,
|
|
291
|
-
source: String(value.source || "workspace-invite").trim() || "workspace-invite"
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
|
-
|
|
10
|
+
import { createLocalSecurityStatus } from "./securityStatus.js";
|
|
11
|
+
import { createLocalSessions } from "./sessions.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The `auth.service` of local auth, from the collaborators its provider
|
|
15
|
+
* resolved once.
|
|
16
|
+
* @param {object} dependencies
|
|
17
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
18
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
19
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
|
|
20
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
21
|
+
* @param {import("../types.js").AuthLocalPasswordStrategy} dependencies.passwordStrategy The
|
|
22
|
+
* `auth.local.password-strategy`, or scryptPasswordStrategy.
|
|
23
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector The
|
|
24
|
+
* `auth.profile.projector`, or noAppProfiles.
|
|
25
|
+
* @param {import("../types.js").AuthLocalRecoverySender} dependencies.recoverySender The
|
|
26
|
+
* `auth.local.recovery-sender`, or one made by createLoggedRecoverySender.
|
|
27
|
+
*/
|
|
295
28
|
function createLocalAuthService({
|
|
296
29
|
backend,
|
|
297
30
|
config,
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
31
|
+
invitationContextResolver,
|
|
32
|
+
logger,
|
|
33
|
+
passwordStrategy,
|
|
34
|
+
profileProjector,
|
|
35
|
+
recoverySender
|
|
302
36
|
}) {
|
|
303
|
-
if (!backend || typeof backend.withTransaction !== "function") {
|
|
304
|
-
throw new Error("Local auth requires auth.local.backend with withTransaction().");
|
|
305
|
-
}
|
|
306
|
-
if (!config?.sessionSecret) {
|
|
307
|
-
throw new Error("Local auth requires a session secret.");
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
if (recoverySender !== null && typeof recoverySender !== "function") {
|
|
311
|
-
throw new Error("auth.local.recovery-sender must be a function.");
|
|
312
|
-
}
|
|
313
|
-
|
|
314
37
|
const passwords = normalizePasswordStrategy(passwordStrategy);
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
const
|
|
318
|
-
const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isProduction);
|
|
319
|
-
const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isProduction);
|
|
320
|
-
const OAUTH_ATTEMPT_COOKIE = hostOnlyCookieName(OAUTH_ATTEMPT_COOKIE_NAME, isProduction);
|
|
321
|
-
const oauthProviders = Array.isArray(config.oauthProviders) ? config.oauthProviders : [];
|
|
322
|
-
const oauthProvidersById = new Map(oauthProviders.map((provider) => [provider.id, provider]));
|
|
323
|
-
const oauthEnabled = oauthProviders.length > 0;
|
|
324
|
-
if (oauthEnabled && !config.appPublicUrl) {
|
|
325
|
-
throw new Error("Local auth OAuth sign-in requires config.appPublicUrl.");
|
|
326
|
-
}
|
|
327
|
-
const oauthRedirectUri = oauthEnabled ? `${config.appPublicUrl.replace(/\/$/u, "")}${OAUTH_REDIRECT_PATH}` : "";
|
|
328
|
-
const appOrigin = oauthEnabled ? new URL(config.appPublicUrl).origin : "";
|
|
329
|
-
const oauthClients = createOAuthClients({ logger: config.logger });
|
|
330
|
-
const devAuth = config.devAuth || resolveDevAuthPolicy({
|
|
331
|
-
nodeEnv: config.nodeEnv
|
|
332
|
-
});
|
|
333
|
-
assertDevAuthPolicy(devAuth);
|
|
334
|
-
const profileProjectionEnabled = typeof profileProjector?.syncIdentityProfile === "function";
|
|
335
|
-
const recoveryDelivery = recoverySender
|
|
336
|
-
? "email"
|
|
337
|
-
: isProduction
|
|
338
|
-
? "disabled"
|
|
339
|
-
: config.recoveryDevOutput === "response"
|
|
340
|
-
? "dev-response"
|
|
341
|
-
: "dev-log";
|
|
342
|
-
const recoveryEnabled = recoveryDelivery !== "disabled";
|
|
38
|
+
const oauthProvidersById = new Map(config.oauthProviders.map((provider) => [provider.id, provider]));
|
|
39
|
+
const { oauthEnabled, recoveryEnabled } = config;
|
|
40
|
+
const appProfileProjection = profileProjector !== noAppProfiles;
|
|
343
41
|
const capabilities = normalizeAuthCapabilities({
|
|
344
42
|
provider: {
|
|
345
43
|
id: PROVIDER_ID,
|
|
@@ -355,14 +53,14 @@ function createLocalAuthService({
|
|
|
355
53
|
passwordRecovery: {
|
|
356
54
|
request: recoveryEnabled,
|
|
357
55
|
complete: recoveryEnabled,
|
|
358
|
-
delivery: recoveryDelivery
|
|
56
|
+
delivery: config.recoveryDelivery
|
|
359
57
|
},
|
|
360
58
|
otp: {
|
|
361
59
|
login: false
|
|
362
60
|
},
|
|
363
61
|
oauthLogin: {
|
|
364
62
|
enabled: oauthEnabled,
|
|
365
|
-
providers: oauthProviders.map(({ id, label }) => ({ id, label }))
|
|
63
|
+
providers: config.oauthProviders.map(({ id, label }) => ({ id, label }))
|
|
366
64
|
},
|
|
367
65
|
emailConfirmation: false,
|
|
368
66
|
profileUpdate: true,
|
|
@@ -372,733 +70,90 @@ function createLocalAuthService({
|
|
|
372
70
|
},
|
|
373
71
|
securityStatus: true,
|
|
374
72
|
signOutOtherSessions: true,
|
|
375
|
-
appProfileProjection
|
|
376
|
-
devLoginAs:
|
|
73
|
+
appProfileProjection,
|
|
74
|
+
devLoginAs: isDevAuthBootstrapEnabled(config.devAuth)
|
|
377
75
|
}
|
|
378
76
|
});
|
|
379
77
|
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
return {
|
|
409
|
-
user,
|
|
410
|
-
session
|
|
411
|
-
};
|
|
412
|
-
});
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
async function resolveProfileOptionsForRegistration(input = {}, { email } = {}) {
|
|
416
|
-
const invitation = normalizeInvitationInput(input.invitation);
|
|
417
|
-
if (!invitation) {
|
|
418
|
-
return {};
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
let resolvedInvitation = invitation;
|
|
422
|
-
if (invitationContextResolver && typeof invitationContextResolver.resolveInvitationContext === "function") {
|
|
423
|
-
resolvedInvitation = await invitationContextResolver.resolveInvitationContext({
|
|
424
|
-
...invitation,
|
|
425
|
-
email
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
return {
|
|
430
|
-
source: resolvedInvitation?.source || "workspace-invite",
|
|
431
|
-
invitation: resolvedInvitation
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
async function register(input = {}) {
|
|
436
|
-
const email = validateEmailInput(input.email);
|
|
437
|
-
validatePasswordInput(input.password);
|
|
438
|
-
const displayName = normalizeDisplayName(input.displayName, email);
|
|
439
|
-
const profileOptions = await resolveProfileOptionsForRegistration(input, { email });
|
|
440
|
-
const password = await passwords.hashPassword(input.password);
|
|
441
|
-
const result = await backend.withTransaction(async (tx) => {
|
|
442
|
-
const existing = await tx.users.findByEmail(email);
|
|
443
|
-
if (existing) {
|
|
444
|
-
throw new AppError(409, "An account already exists for this email.", { code: "auth.local.register.emailTaken" });
|
|
445
|
-
}
|
|
446
|
-
const user = await tx.users.create({
|
|
447
|
-
id: createId("usr"),
|
|
448
|
-
email,
|
|
449
|
-
displayName,
|
|
450
|
-
password
|
|
451
|
-
});
|
|
452
|
-
return {
|
|
453
|
-
user,
|
|
454
|
-
session: await createSessionForUser(tx, user)
|
|
455
|
-
};
|
|
456
|
-
});
|
|
457
|
-
return {
|
|
458
|
-
...(await buildAuthPayload({
|
|
459
|
-
user: result.user,
|
|
460
|
-
session: result.session,
|
|
461
|
-
profileProjector,
|
|
462
|
-
profileOptions
|
|
463
|
-
})),
|
|
464
|
-
requiresEmailConfirmation: false
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
async function login(input = {}) {
|
|
469
|
-
const email = validateEmailInput(input.email);
|
|
470
|
-
const password = String(input.password || "");
|
|
471
|
-
return backend.withTransaction(async (tx) => {
|
|
472
|
-
const user = await tx.users.findByEmail(email);
|
|
473
|
-
if (!user || user.disabled || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
|
|
474
|
-
throw createAuthError(AUTH_TEXTS.invalidCredentials);
|
|
475
|
-
}
|
|
476
|
-
const session = await createSessionForUser(tx, user);
|
|
477
|
-
return buildAuthPayload({ user, session, profileProjector });
|
|
478
|
-
});
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
function isDevAuthBootstrapEnabled() {
|
|
482
|
-
return devAuth.enabled === true && devAuth.isProduction !== true;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
async function devLoginAs(request, input = {}) {
|
|
486
|
-
ensureDevAuthExchangeAvailable(devAuth, request);
|
|
487
|
-
const userId = String(input?.userId || "").trim();
|
|
488
|
-
const email = normalizeEmail(input?.email || "");
|
|
489
|
-
if (!userId && !email) {
|
|
490
|
-
throw devLoginAsValidationError({
|
|
491
|
-
userId: AUTH_TEXTS.devUserRequired,
|
|
492
|
-
email: AUTH_TEXTS.devUserRequired
|
|
493
|
-
});
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
return backend.withTransaction(async (tx) => {
|
|
497
|
-
let user = userId ? await tx.users.findById(userId) : null;
|
|
498
|
-
if (!user && email) {
|
|
499
|
-
user = await tx.users.findByEmail(email);
|
|
500
|
-
}
|
|
501
|
-
if (!user || user.disabled) {
|
|
502
|
-
throw devLoginAsUserNotFound({ email, userId });
|
|
503
|
-
}
|
|
504
|
-
const appProfile = await findExistingAppProfile(user, profileProjector);
|
|
505
|
-
if (profileProjector && !appProfile) {
|
|
506
|
-
throw devLoginAsUserNotFound({ email, userId });
|
|
507
|
-
}
|
|
508
|
-
const session = await createSessionForUser(tx, user, {
|
|
509
|
-
purpose: DEV_AUTH_SESSION_PURPOSE
|
|
510
|
-
});
|
|
511
|
-
return buildAuthResult({ user, session, appProfile });
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
async function authenticateRequest(request, { syncProfile = true } = {}) {
|
|
516
|
-
const cookies = safeRequestCookies(request);
|
|
517
|
-
const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
|
|
518
|
-
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
519
|
-
|
|
520
|
-
if (accessToken) {
|
|
521
|
-
const payload = verifySignedToken(accessToken, config.sessionSecret);
|
|
522
|
-
if (payload?.sid && payload?.sub) {
|
|
523
|
-
const resolved = await backend.withTransaction(async (tx) => {
|
|
524
|
-
const session = await tx.sessions.findById(String(payload.sid));
|
|
525
|
-
if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
|
|
526
|
-
return null;
|
|
527
|
-
}
|
|
528
|
-
const user = await tx.users.findById(String(payload.sub));
|
|
529
|
-
if (!user || user.disabled) {
|
|
530
|
-
return null;
|
|
531
|
-
}
|
|
532
|
-
return { user, session };
|
|
533
|
-
});
|
|
534
|
-
if (resolved && isAuthenticatingSession(resolved.session)) {
|
|
535
|
-
const authPayload = await buildSessionAuthPayload({
|
|
536
|
-
devAuth,
|
|
537
|
-
profileProjector,
|
|
538
|
-
request,
|
|
539
|
-
session: resolved.session,
|
|
540
|
-
user: resolved.user,
|
|
541
|
-
syncProfile
|
|
542
|
-
});
|
|
543
|
-
if (!authPayload) {
|
|
544
|
-
return unauthenticatedAuthResult(true);
|
|
545
|
-
}
|
|
546
|
-
return {
|
|
547
|
-
authenticated: true,
|
|
548
|
-
...authPayload,
|
|
549
|
-
session: null,
|
|
550
|
-
sessionPurpose: resolved.session.purpose || "normal",
|
|
551
|
-
clearSession: false,
|
|
552
|
-
transientFailure: false
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
if (!refreshToken) {
|
|
559
|
-
return unauthenticatedAuthResult(Boolean(accessToken));
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
const resolved = await resolveValidSessionByRefreshToken(refreshToken);
|
|
563
|
-
if (!resolved) {
|
|
564
|
-
return unauthenticatedAuthResult(true);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
if (!isAuthenticatingSession(resolved.session)) {
|
|
568
|
-
return unauthenticatedAuthResult();
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
const authPayload = await buildSessionAuthPayload({
|
|
572
|
-
devAuth,
|
|
573
|
-
profileProjector,
|
|
574
|
-
request,
|
|
575
|
-
session: resolved.session,
|
|
576
|
-
user: resolved.user,
|
|
577
|
-
syncProfile
|
|
578
|
-
});
|
|
579
|
-
if (!authPayload) {
|
|
580
|
-
return unauthenticatedAuthResult(true);
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
return {
|
|
584
|
-
authenticated: true,
|
|
585
|
-
...authPayload,
|
|
586
|
-
session: buildSessionPayload({
|
|
587
|
-
user: resolved.user,
|
|
588
|
-
session: resolved.session,
|
|
589
|
-
refreshToken,
|
|
590
|
-
secret: config.sessionSecret
|
|
591
|
-
}),
|
|
592
|
-
sessionPurpose: resolved.session.purpose || "normal",
|
|
593
|
-
clearSession: false,
|
|
594
|
-
transientFailure: false
|
|
595
|
-
};
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
function writeSessionCookies(reply, session) {
|
|
599
|
-
if (!reply || !session) {
|
|
600
|
-
return;
|
|
601
|
-
}
|
|
602
|
-
const accessToken = String(session.access_token || "");
|
|
603
|
-
const refreshToken = String(session.refresh_token || "");
|
|
604
|
-
const purpose = String(session.purpose || "normal");
|
|
605
|
-
const isRecoverySession = purpose === "recovery";
|
|
606
|
-
const accessMaxAge = Number(session.expires_in || ACCESS_TTL_SECONDS);
|
|
607
|
-
const refreshMaxAge = isRecoverySession ? accessMaxAge : REFRESH_TTL_SECONDS;
|
|
608
|
-
if (accessToken) {
|
|
609
|
-
reply.setCookie(
|
|
610
|
-
isRecoverySession ? RECOVERY_TOKEN_COOKIE : ACCESS_TOKEN_COOKIE,
|
|
611
|
-
accessToken,
|
|
612
|
-
cookieOptions(isProduction, accessMaxAge)
|
|
613
|
-
);
|
|
614
|
-
}
|
|
615
|
-
if (refreshToken) {
|
|
616
|
-
reply.setCookie(REFRESH_TOKEN_COOKIE, refreshToken, cookieOptions(isProduction, refreshMaxAge));
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
function clearSessionCookies(reply) {
|
|
621
|
-
if (!reply) {
|
|
622
|
-
return;
|
|
623
|
-
}
|
|
624
|
-
for (const options of clearCookieOptions(isProduction)) {
|
|
625
|
-
// A __Host- cookie only exists at Path=/.
|
|
626
|
-
if (options.path === "/" || !isProduction) {
|
|
627
|
-
reply.clearCookie(ACCESS_TOKEN_COOKIE, options);
|
|
628
|
-
reply.clearCookie(REFRESH_TOKEN_COOKIE, options);
|
|
629
|
-
reply.clearCookie(RECOVERY_TOKEN_COOKIE, options);
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
async function logout(request) {
|
|
635
|
-
const cookies = safeRequestCookies(request);
|
|
636
|
-
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
637
|
-
if (!refreshToken) {
|
|
638
|
-
return {
|
|
639
|
-
ok: true,
|
|
640
|
-
clearSession: true
|
|
641
|
-
};
|
|
642
|
-
}
|
|
643
|
-
await backend.withTransaction(async (tx) => {
|
|
644
|
-
const session = await tx.sessions.findByTokenHash(sha256Base64url(refreshToken));
|
|
645
|
-
if (session) {
|
|
646
|
-
await tx.sessions.revoke(session.id);
|
|
647
|
-
}
|
|
648
|
-
});
|
|
649
|
-
return {
|
|
650
|
-
ok: true,
|
|
651
|
-
clearSession: true
|
|
652
|
-
};
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
async function requestPasswordReset(input = {}) {
|
|
656
|
-
if (!recoveryEnabled) {
|
|
657
|
-
throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
|
|
658
|
-
}
|
|
659
|
-
const email = validateEmailInput(input.email);
|
|
660
|
-
let recoveryUrl = "";
|
|
661
|
-
await backend.withTransaction(async (tx) => {
|
|
662
|
-
const user = await tx.users.findByEmail(email);
|
|
663
|
-
if (!user || user.disabled) {
|
|
664
|
-
return;
|
|
665
|
-
}
|
|
666
|
-
const token = randomToken(32);
|
|
667
|
-
recoveryUrl = `${config.appPublicUrl.replace(/\/$/, "")}/auth/reset-password?token=${encodeURIComponent(token)}&type=recovery`;
|
|
668
|
-
await tx.recovery.create({
|
|
669
|
-
id: createId("rec"),
|
|
670
|
-
userId: user.id,
|
|
671
|
-
tokenHash: sha256Base64url(token),
|
|
672
|
-
expiresAt: isoFromNow(RECOVERY_TOKEN_TTL_SECONDS)
|
|
673
|
-
});
|
|
674
|
-
});
|
|
675
|
-
if (recoveryUrl) {
|
|
676
|
-
if (recoverySender) await recoverySender({ email, recoveryUrl });
|
|
677
|
-
if (!recoverySender && config.recoveryDevOutput === "log" && config.logger?.info) {
|
|
678
|
-
config.logger.info({ recoveryUrl, email }, "Local auth password recovery URL created.");
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
return {
|
|
682
|
-
ok: true,
|
|
683
|
-
message: "If an account exists for that email, password reset instructions have been sent.",
|
|
684
|
-
messageCode: "auth.local.recovery.requested",
|
|
685
|
-
messageParams: {},
|
|
686
|
-
...(recoveryUrl && !recoverySender && config.recoveryDevOutput === "response" ? { recoveryUrl } : {})
|
|
687
|
-
};
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
async function completePasswordRecovery(input = {}) {
|
|
691
|
-
if (!recoveryEnabled) {
|
|
692
|
-
throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
|
|
693
|
-
}
|
|
694
|
-
const token = String(input.code || input.token || "").trim();
|
|
695
|
-
const tokenHash = String(input.tokenHash || "").trim() || (token ? sha256Base64url(token) : "");
|
|
696
|
-
if (!tokenHash) {
|
|
697
|
-
throw createAuthError(AUTH_TEXTS.recoveryTokenRequired);
|
|
698
|
-
}
|
|
699
|
-
return backend.withTransaction(async (tx) => {
|
|
700
|
-
const recovery = await tx.recovery.findByTokenHash(tokenHash);
|
|
701
|
-
if (!recovery || recovery.usedAt || isExpiredIso(recovery.expiresAt)) {
|
|
702
|
-
throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
|
|
703
|
-
}
|
|
704
|
-
await tx.recovery.consume(recovery.id);
|
|
705
|
-
const user = await tx.users.findById(recovery.userId);
|
|
706
|
-
if (!user || user.disabled) {
|
|
707
|
-
throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
|
|
708
|
-
}
|
|
709
|
-
const session = await createSessionForUser(tx, user, {
|
|
710
|
-
purpose: "recovery",
|
|
711
|
-
ttlSeconds: RECOVERY_SESSION_TTL_SECONDS
|
|
712
|
-
});
|
|
713
|
-
return buildAuthPayload({ user, session, profileProjector });
|
|
714
|
-
});
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
async function resetPassword(request, input = {}) {
|
|
718
|
-
validatePasswordInput(input.password);
|
|
719
|
-
const cookies = safeRequestCookies(request);
|
|
720
|
-
const recoveryAccessToken = String(cookies[RECOVERY_TOKEN_COOKIE] || "").trim();
|
|
721
|
-
const payload = verifySignedToken(recoveryAccessToken, config.sessionSecret);
|
|
722
|
-
if (!payload?.sub || !payload?.sid) {
|
|
723
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
724
|
-
}
|
|
725
|
-
const password = await passwords.hashPassword(input.password);
|
|
726
|
-
await backend.withTransaction(async (tx) => {
|
|
727
|
-
const session = await tx.sessions.findById(String(payload.sid));
|
|
728
|
-
if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
|
|
729
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
730
|
-
}
|
|
731
|
-
if (session.purpose !== "recovery") {
|
|
732
|
-
throw new AppError(401, "Recovery session required.", { code: "auth.local.recovery.sessionRequired" });
|
|
733
|
-
}
|
|
734
|
-
await tx.users.updatePassword(String(payload.sub), password);
|
|
735
|
-
await tx.sessions.revokeForUser(String(payload.sub));
|
|
736
|
-
if (typeof tx.recovery.consumeForUser === "function") {
|
|
737
|
-
await tx.recovery.consumeForUser(String(payload.sub));
|
|
738
|
-
}
|
|
739
|
-
});
|
|
740
|
-
return {
|
|
741
|
-
ok: true,
|
|
742
|
-
...authMessageFields(AUTH_TEXTS.passwordUpdatedSignIn)
|
|
743
|
-
};
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
async function changePassword(request, input = {}) {
|
|
747
|
-
validatePasswordInput(input.newPassword);
|
|
748
|
-
const authResult = await authenticateRequest(request);
|
|
749
|
-
if (authResult.authenticated !== true || authResult.sessionPurpose !== "normal") {
|
|
750
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
const currentPassword = String(input.currentPassword || "");
|
|
754
|
-
const password = await passwords.hashPassword(input.newPassword);
|
|
755
|
-
await backend.withTransaction(async (tx) => {
|
|
756
|
-
const user = await tx.users.findById(authResult.actor.providerUserId);
|
|
757
|
-
if (!user || user.disabled) {
|
|
758
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
759
|
-
}
|
|
760
|
-
if (!(await passwords.verifyPassword(currentPassword, user.password))) {
|
|
761
|
-
throw new AppError(401, "Current password is invalid.", { code: "auth.local.password.currentInvalid" });
|
|
762
|
-
}
|
|
763
|
-
await tx.users.updatePassword(user.id, password);
|
|
764
|
-
});
|
|
765
|
-
|
|
766
|
-
return {
|
|
767
|
-
ok: true,
|
|
768
|
-
message: "Password updated.",
|
|
769
|
-
messageCode: "auth.local.password.changed",
|
|
770
|
-
messageParams: {}
|
|
771
|
-
};
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
async function updateDisplayName(request, input = {}) {
|
|
775
|
-
const authResult = await authenticateRequest(request);
|
|
776
|
-
if (authResult.authenticated !== true) {
|
|
777
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
778
|
-
}
|
|
779
|
-
const displayName = String(input.displayName || "").trim();
|
|
780
|
-
if (!displayName) {
|
|
781
|
-
throw createAuthError(AUTH_TEXTS.displayNameRequired);
|
|
782
|
-
}
|
|
783
|
-
return backend.withTransaction(async (tx) => {
|
|
784
|
-
const user = await tx.users.updateProfile(authResult.actor.providerUserId, { displayName });
|
|
785
|
-
if (!user) {
|
|
786
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
787
|
-
}
|
|
788
|
-
return buildAuthPayload({ user, session: null, profileProjector });
|
|
789
|
-
});
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
async function securityStatusForUser(userId) {
|
|
793
|
-
const { user, identities } = await backend.withTransaction(async (tx) => ({
|
|
794
|
-
user: await tx.users.findById(userId),
|
|
795
|
-
identities: oauthEnabled ? await tx.identities.listForUser(userId) : []
|
|
796
|
-
}));
|
|
797
|
-
const passwordSet = hasPassword(user);
|
|
798
|
-
// Identities of a provider the app no longer configures cannot sign in.
|
|
799
|
-
const linkedProviders = new Set(identities.map((identity) => identity.provider).filter((id) => oauthProvidersById.has(id)));
|
|
800
|
-
const signInMethodCount = (passwordSet ? 1 : 0) + linkedProviders.size;
|
|
801
|
-
const methods = [
|
|
802
|
-
{
|
|
803
|
-
id: "password",
|
|
804
|
-
kind: "password",
|
|
805
|
-
provider: "email",
|
|
806
|
-
label: "Password",
|
|
807
|
-
configured: passwordSet,
|
|
808
|
-
enabled: passwordSet,
|
|
809
|
-
canDisable: false,
|
|
810
|
-
supportsSecretUpdate: true,
|
|
811
|
-
requiresCurrentPassword: false
|
|
812
|
-
},
|
|
813
|
-
// canEnable links the provider and canDisable unlinks it, as for Supabase.
|
|
814
|
-
...oauthProviders.map((provider) => {
|
|
815
|
-
const linked = linkedProviders.has(provider.id);
|
|
816
|
-
return {
|
|
817
|
-
id: buildOAuthMethodId(provider.id),
|
|
818
|
-
kind: AUTH_METHOD_KIND_OAUTH,
|
|
819
|
-
provider: provider.id,
|
|
820
|
-
label: provider.label,
|
|
821
|
-
configured: linked,
|
|
822
|
-
enabled: linked,
|
|
823
|
-
canEnable: !linked,
|
|
824
|
-
canDisable: linked && signInMethodCount > 1,
|
|
825
|
-
supportsSecretUpdate: false,
|
|
826
|
-
requiresCurrentPassword: false
|
|
827
|
-
};
|
|
828
|
-
})
|
|
829
|
-
];
|
|
830
|
-
return buildSecurityStatusFromAuthMethodsStatus(
|
|
831
|
-
{
|
|
832
|
-
methods,
|
|
833
|
-
minimumEnabledMethods: 1,
|
|
834
|
-
enabledMethodsCount: signInMethodCount
|
|
835
|
-
},
|
|
836
|
-
{
|
|
837
|
-
actions: {
|
|
838
|
-
changePassword: passwordSet,
|
|
839
|
-
signOutOtherSessions: true,
|
|
840
|
-
linkProvider: oauthEnabled,
|
|
841
|
-
unlinkProvider: oauthEnabled
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
);
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
async function requireNormalSessionUserId(request) {
|
|
848
|
-
const authResult = await authenticateRequest(request);
|
|
849
|
-
if (authResult.authenticated !== true || authResult.sessionPurpose !== "normal") {
|
|
850
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
851
|
-
}
|
|
852
|
-
return authResult.actor.providerUserId;
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
async function getSecurityStatus(request) {
|
|
856
|
-
const authResult = await authenticateRequest(request);
|
|
857
|
-
if (authResult.authenticated !== true) {
|
|
858
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
859
|
-
}
|
|
860
|
-
return securityStatusForUser(authResult.actor.providerUserId);
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
function requireOAuthProvider(value) {
|
|
864
|
-
const provider = oauthProvidersById.get(String(value || "").trim().toLowerCase());
|
|
865
|
-
if (!provider) {
|
|
866
|
-
throw new AppError(400, "This sign-in provider is not available.", { code: "auth.local.oauth.providerInvalid" });
|
|
867
|
-
}
|
|
868
|
-
return provider;
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
// The attempt (state, nonce, PKCE verifier) is stored server-side under the
|
|
872
|
-
// hash of a random key that only the starting browser holds in a cookie.
|
|
873
|
-
async function beginOAuthAttempt(provider, { intent, userId = "", returnTo }) {
|
|
874
|
-
const browserKey = randomToken(32);
|
|
875
|
-
const attempt = {
|
|
876
|
-
browserKeyHash: sha256Base64url(browserKey),
|
|
877
|
-
provider: provider.id,
|
|
878
|
-
intent,
|
|
879
|
-
userId,
|
|
880
|
-
state: randomToken(32),
|
|
881
|
-
nonce: randomToken(32),
|
|
882
|
-
codeVerifier: randomToken(32),
|
|
883
|
-
returnTo: normalizeReturnToPath(returnTo, { fallback: "/", allowedOrigins: [appOrigin] }),
|
|
884
|
-
expiresAt: isoFromNow(OAUTH_ATTEMPT_TTL_SECONDS)
|
|
885
|
-
};
|
|
886
|
-
const url = await oauthClients.authorizationUrl(provider, { ...attempt, redirectUri: oauthRedirectUri });
|
|
887
|
-
await backend.withTransaction(async (tx) => {
|
|
888
|
-
await tx.oauthAttempts.deleteExpired(new Date().toISOString());
|
|
889
|
-
await tx.oauthAttempts.create(attempt);
|
|
890
|
-
});
|
|
891
|
-
return { provider: provider.id, returnTo: attempt.returnTo, url, attempt: browserKey };
|
|
892
|
-
}
|
|
893
|
-
|
|
894
|
-
async function oauthStart(input = {}) {
|
|
895
|
-
return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "login", returnTo: input.returnTo });
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
async function startProviderLink(request, input = {}) {
|
|
899
|
-
const userId = await requireNormalSessionUserId(request);
|
|
900
|
-
return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "link", userId, returnTo: input.returnTo });
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
function writeOAuthStartCookies(reply, result) {
|
|
904
|
-
if (reply && result?.attempt) {
|
|
905
|
-
reply.setCookie(OAUTH_ATTEMPT_COOKIE, result.attempt, cookieOptions(isProduction, OAUTH_ATTEMPT_TTL_SECONDS));
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
function clearOAuthStartCookies(reply) {
|
|
910
|
-
if (reply) {
|
|
911
|
-
reply.clearCookie(OAUTH_ATTEMPT_COOKIE, cookieOptions(isProduction, 0));
|
|
912
|
-
}
|
|
913
|
-
}
|
|
78
|
+
const sessions = createLocalSessions({ appProfileProjection, backend, config, profileProjector });
|
|
79
|
+
const accounts = createLocalAccounts({
|
|
80
|
+
appProfileProjection,
|
|
81
|
+
backend,
|
|
82
|
+
config,
|
|
83
|
+
invitationContextResolver,
|
|
84
|
+
passwords,
|
|
85
|
+
profileProjector,
|
|
86
|
+
sessions
|
|
87
|
+
});
|
|
88
|
+
const passwordFlows = createLocalPasswordFlows({
|
|
89
|
+
backend,
|
|
90
|
+
config,
|
|
91
|
+
passwords,
|
|
92
|
+
profileProjector,
|
|
93
|
+
recoverySender,
|
|
94
|
+
sessions
|
|
95
|
+
});
|
|
96
|
+
const securityStatus = createLocalSecurityStatus({ backend, config, oauthProvidersById, sessions });
|
|
97
|
+
const oauthFlows = createLocalOAuthFlows({
|
|
98
|
+
backend,
|
|
99
|
+
config,
|
|
100
|
+
logger,
|
|
101
|
+
oauthProvidersById,
|
|
102
|
+
profileProjector,
|
|
103
|
+
securityStatus,
|
|
104
|
+
sessions
|
|
105
|
+
});
|
|
914
106
|
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
async function signInWithOAuthIdentity(identity) {
|
|
918
|
-
const result = await backend.withTransaction(async (tx) => {
|
|
919
|
-
const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
|
|
920
|
-
let user = linked ? await tx.users.findById(linked.userId) : await tx.users.findByEmail(identity.email);
|
|
921
|
-
const registered = !linked && !user;
|
|
922
|
-
if (registered) {
|
|
923
|
-
user = await tx.users.create({
|
|
924
|
-
id: createId("usr"),
|
|
925
|
-
email: identity.email,
|
|
926
|
-
displayName: normalizeDisplayName(identity.name, identity.email),
|
|
927
|
-
password: NO_PASSWORD
|
|
928
|
-
});
|
|
929
|
-
}
|
|
930
|
-
if (!user || user.disabled) {
|
|
931
|
-
throw new AppError(401, "This account can't sign in.", { code: "auth.local.oauth.accountUnavailable" });
|
|
932
|
-
}
|
|
933
|
-
if (!linked) {
|
|
934
|
-
await tx.identities.create({
|
|
935
|
-
userId: user.id,
|
|
936
|
-
provider: identity.provider,
|
|
937
|
-
providerSubject: identity.providerSubject,
|
|
938
|
-
email: identity.email
|
|
939
|
-
});
|
|
940
|
-
}
|
|
941
|
-
return { user, registered, session: await createSessionForUser(tx, user) };
|
|
942
|
-
});
|
|
943
|
-
return {
|
|
944
|
-
...(await buildAuthPayload({ user: result.user, session: result.session, profileProjector })),
|
|
945
|
-
registered: result.registered
|
|
946
|
-
};
|
|
107
|
+
function getCapabilities() {
|
|
108
|
+
return capabilities;
|
|
947
109
|
}
|
|
948
110
|
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
if (authResult.authenticated !== true || authResult.actor.providerUserId !== attempt.userId) {
|
|
952
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
953
|
-
}
|
|
954
|
-
const user = await backend.withTransaction(async (tx) => {
|
|
955
|
-
const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
|
|
956
|
-
if (linked && linked.userId !== attempt.userId) {
|
|
957
|
-
throw new AppError(409, `This ${provider.label} account is already linked to another account.`, {
|
|
958
|
-
code: "auth.local.oauth.identityTaken",
|
|
959
|
-
params: { provider: provider.label }
|
|
960
|
-
});
|
|
961
|
-
}
|
|
962
|
-
if (!linked) {
|
|
963
|
-
await tx.identities.create({
|
|
964
|
-
userId: attempt.userId,
|
|
965
|
-
provider: identity.provider,
|
|
966
|
-
providerSubject: identity.providerSubject,
|
|
967
|
-
email: identity.email
|
|
968
|
-
});
|
|
969
|
-
}
|
|
970
|
-
return tx.users.findById(attempt.userId);
|
|
971
|
-
});
|
|
972
|
-
return buildAuthPayload({ user, session: null, profileProjector });
|
|
111
|
+
function resendRegisterConfirmation() {
|
|
112
|
+
return throwUnsupportedAuthOperation("resendRegisterConfirmation");
|
|
973
113
|
}
|
|
974
114
|
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
if (errorCode) {
|
|
978
|
-
throw errorCode === "access_denied"
|
|
979
|
-
? new AppError(401, "Sign-in was cancelled.", { code: "auth.local.oauth.cancelled" })
|
|
980
|
-
: new AppError(401, "Sign-in was not completed. Start again.", { code: "auth.local.oauth.incomplete" });
|
|
981
|
-
}
|
|
982
|
-
const browserKey = String(safeRequestCookies(request)[OAUTH_ATTEMPT_COOKIE] || "").trim();
|
|
983
|
-
// Taking an attempt deletes it, so each one completes at most once.
|
|
984
|
-
const attempt = browserKey
|
|
985
|
-
? await backend.withTransaction((tx) => tx.oauthAttempts.take(sha256Base64url(browserKey)))
|
|
986
|
-
: null;
|
|
987
|
-
const state = String(input.state || "");
|
|
988
|
-
// The provider is the one this attempt started with, whatever the callback names.
|
|
989
|
-
const provider = attempt ? oauthProvidersById.get(attempt.provider) : null;
|
|
990
|
-
if (!provider || isExpiredIso(attempt.expiresAt) || !state || state !== attempt.state) {
|
|
991
|
-
throw new AppError(400, "This sign-in took too long or started in another browser. Start again.", {
|
|
992
|
-
code: "auth.local.oauth.expired"
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
const code = String(input.code || "").trim();
|
|
996
|
-
if (!code) {
|
|
997
|
-
throw new AppError(400, "OAuth code is required.", { code: "auth.local.oauth.codeRequired" });
|
|
998
|
-
}
|
|
999
|
-
const callbackUrl = new URL(oauthRedirectUri);
|
|
1000
|
-
callbackUrl.searchParams.set("code", code);
|
|
1001
|
-
callbackUrl.searchParams.set("state", state);
|
|
1002
|
-
if (input.iss) {
|
|
1003
|
-
callbackUrl.searchParams.set("iss", String(input.iss));
|
|
1004
|
-
}
|
|
1005
|
-
const identity = await oauthClients.verifiedIdentity(provider, { callbackUrl, attempt });
|
|
1006
|
-
const result = attempt.intent === "link"
|
|
1007
|
-
? await linkOAuthIdentity(request, attempt, identity, provider)
|
|
1008
|
-
: await signInWithOAuthIdentity(identity);
|
|
1009
|
-
return { ...result, provider: provider.id, returnTo: attempt.returnTo };
|
|
115
|
+
function requestOtpLogin() {
|
|
116
|
+
return throwUnsupportedAuthOperation("requestOtpLogin");
|
|
1010
117
|
}
|
|
1011
118
|
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
const provider = requireOAuthProvider(input.provider);
|
|
1015
|
-
await backend.withTransaction(async (tx) => {
|
|
1016
|
-
const user = await tx.users.findById(userId);
|
|
1017
|
-
const identities = await tx.identities.listForUser(userId);
|
|
1018
|
-
if (!identities.some((identity) => identity.provider === provider.id)) {
|
|
1019
|
-
throw new AppError(404, `${provider.label} is not linked to this account.`, {
|
|
1020
|
-
code: "auth.local.oauth.notLinked",
|
|
1021
|
-
params: { provider: provider.label }
|
|
1022
|
-
});
|
|
1023
|
-
}
|
|
1024
|
-
const otherMethodRemains = hasPassword(user) || identities.some(
|
|
1025
|
-
(identity) => identity.provider !== provider.id && oauthProvidersById.has(identity.provider)
|
|
1026
|
-
);
|
|
1027
|
-
if (!otherMethodRemains) {
|
|
1028
|
-
throw new AppError(409, "Add a password or link another sign-in method before removing this one.", {
|
|
1029
|
-
code: "auth.local.oauth.lastMethod"
|
|
1030
|
-
});
|
|
1031
|
-
}
|
|
1032
|
-
await tx.identities.deleteForUser(userId, provider.id);
|
|
1033
|
-
});
|
|
1034
|
-
return { securityStatus: await securityStatusForUser(userId) };
|
|
119
|
+
function verifyOtpLogin() {
|
|
120
|
+
return throwUnsupportedAuthOperation("verifyOtpLogin");
|
|
1035
121
|
}
|
|
1036
122
|
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
if (authResult.authenticated !== true) {
|
|
1040
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
1041
|
-
}
|
|
1042
|
-
const cookies = safeRequestCookies(request);
|
|
1043
|
-
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
1044
|
-
const currentSession = refreshToken ? await resolveValidSessionByRefreshToken(refreshToken) : null;
|
|
1045
|
-
const count = await backend.withTransaction((tx) =>
|
|
1046
|
-
tx.sessions.revokeForUser(authResult.actor.providerUserId, {
|
|
1047
|
-
exceptSessionId: currentSession?.session?.id
|
|
1048
|
-
})
|
|
1049
|
-
);
|
|
1050
|
-
return {
|
|
1051
|
-
ok: true,
|
|
1052
|
-
revokedSessions: count
|
|
1053
|
-
};
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
function getCapabilities() {
|
|
1057
|
-
return capabilities;
|
|
123
|
+
function setPasswordSignInEnabled() {
|
|
124
|
+
return throwUnsupportedAuthOperation("setPasswordSignInEnabled");
|
|
1058
125
|
}
|
|
1059
126
|
|
|
1060
127
|
return Object.freeze({
|
|
1061
128
|
getCapabilities,
|
|
1062
|
-
isDevAuthBootstrapEnabled,
|
|
1063
|
-
devLoginAs,
|
|
1064
|
-
authenticateRequest,
|
|
1065
|
-
hasAccessTokenCookie
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
completePasswordRecovery,
|
|
1091
|
-
resetPassword,
|
|
1092
|
-
changePassword,
|
|
1093
|
-
updateDisplayName,
|
|
1094
|
-
getSecurityStatus,
|
|
1095
|
-
setPasswordSignInEnabled() {
|
|
1096
|
-
return throwUnsupportedAuthOperation("setPasswordSignInEnabled");
|
|
1097
|
-
},
|
|
1098
|
-
startProviderLink,
|
|
1099
|
-
unlinkProvider,
|
|
1100
|
-
signOutOtherSessions,
|
|
1101
|
-
logout
|
|
129
|
+
isDevAuthBootstrapEnabled: accounts.isDevAuthBootstrapEnabled,
|
|
130
|
+
devLoginAs: accounts.devLoginAs,
|
|
131
|
+
authenticateRequest: sessions.authenticateRequest,
|
|
132
|
+
hasAccessTokenCookie: sessions.hasAccessTokenCookie,
|
|
133
|
+
hasSessionCookie: sessions.hasSessionCookie,
|
|
134
|
+
writeSessionCookies: sessions.writeSessionCookies,
|
|
135
|
+
clearSessionCookies: sessions.clearSessionCookies,
|
|
136
|
+
register: accounts.register,
|
|
137
|
+
resendRegisterConfirmation,
|
|
138
|
+
login: accounts.login,
|
|
139
|
+
requestOtpLogin,
|
|
140
|
+
verifyOtpLogin,
|
|
141
|
+
writeOAuthStartCookies: oauthFlows.writeOAuthStartCookies,
|
|
142
|
+
clearOAuthStartCookies: oauthFlows.clearOAuthStartCookies,
|
|
143
|
+
oauthStart: oauthFlows.oauthStart,
|
|
144
|
+
oauthComplete: oauthFlows.oauthComplete,
|
|
145
|
+
requestPasswordReset: passwordFlows.requestPasswordReset,
|
|
146
|
+
completePasswordRecovery: passwordFlows.completePasswordRecovery,
|
|
147
|
+
resetPassword: passwordFlows.resetPassword,
|
|
148
|
+
changePassword: passwordFlows.changePassword,
|
|
149
|
+
updateDisplayName: accounts.updateDisplayName,
|
|
150
|
+
getSecurityStatus: securityStatus.getSecurityStatus,
|
|
151
|
+
// readable-check: allow setter-seam - not a slot: setPasswordSignInEnabled is an auth.service operation
|
|
152
|
+
setPasswordSignInEnabled,
|
|
153
|
+
startProviderLink: oauthFlows.startProviderLink,
|
|
154
|
+
unlinkProvider: oauthFlows.unlinkProvider,
|
|
155
|
+
signOutOtherSessions: sessions.signOutOtherSessions,
|
|
156
|
+
logout: sessions.logout
|
|
1102
157
|
});
|
|
1103
158
|
}
|
|
1104
159
|
|