@jskit-ai/auth-provider-local-core 0.2.1 → 0.2.3
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/locales/en.json +15 -0
- package/package.json +6 -3
- package/src/server/lib/fileBackend.js +160 -2
- package/src/server/lib/oauth.js +207 -0
- package/src/server/lib/registerHookDecorator.js +19 -6
- package/src/server/lib/service.js +288 -49
- package/src/server/providers/AuthLocalProvider.js +9 -4
- package/test/oauthSignIn.test.js +359 -0
- package/test/providerRuntime.test.js +48 -0
- package/test-support/oauthHarness.js +167 -0
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
AUTH_PASSWORD_MIN_LENGTH
|
|
5
5
|
} from "@jskit-ai/auth-core/shared/authConstraints";
|
|
6
6
|
import { normalizeAuthCapabilities } from "@jskit-ai/auth-core/shared/authCapabilities";
|
|
7
|
+
import { AUTH_METHOD_KIND_OAUTH, buildOAuthMethodId } from "@jskit-ai/auth-core/shared/authMethods";
|
|
7
8
|
import { buildSecurityStatusFromAuthMethodsStatus } from "@jskit-ai/auth-core/shared/authSecurityStatus";
|
|
8
9
|
import { normalizeAuthActor, normalizeAuthResult } from "@jskit-ai/auth-core/server/authActor";
|
|
9
10
|
import {
|
|
@@ -12,7 +13,7 @@ import {
|
|
|
12
13
|
ensureDevAuthRuntimeAvailable,
|
|
13
14
|
resolveDevAuthPolicy
|
|
14
15
|
} from "@jskit-ai/auth-core/server/devAuth";
|
|
15
|
-
import { hostOnlyCookieName, normalizeEmail } from "@jskit-ai/auth-core/server/utils";
|
|
16
|
+
import { hostOnlyCookieName, normalizeEmail, normalizeReturnToPath } from "@jskit-ai/auth-core/server/utils";
|
|
16
17
|
import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
|
|
17
18
|
import {
|
|
18
19
|
AUTH_TEXTS,
|
|
@@ -20,18 +21,25 @@ import {
|
|
|
20
21
|
authMessageFields,
|
|
21
22
|
createAuthError
|
|
22
23
|
} from "@jskit-ai/auth-core/server/authTexts";
|
|
24
|
+
import { createOAuthClients } from "./oauth.js";
|
|
23
25
|
import { normalizePasswordStrategy } from "./passwords.js";
|
|
24
26
|
import { randomToken, sha256Base64url, signToken, verifySignedToken } from "./tokens.js";
|
|
25
27
|
|
|
26
28
|
const ACCESS_TOKEN_COOKIE_NAME = "jskit_local_access_token";
|
|
27
29
|
const REFRESH_TOKEN_COOKIE_NAME = "jskit_local_refresh_token";
|
|
28
30
|
const RECOVERY_TOKEN_COOKIE_NAME = "jskit_local_recovery_token";
|
|
31
|
+
const OAUTH_ATTEMPT_COOKIE_NAME = "jskit_local_oauth_attempt";
|
|
29
32
|
const PROVIDER_ID = "local";
|
|
30
33
|
const DEV_AUTH_SESSION_PURPOSE = "dev-auth";
|
|
31
34
|
const ACCESS_TTL_SECONDS = 15 * 60;
|
|
32
35
|
const REFRESH_TTL_SECONDS = 60 * 60 * 24 * 30;
|
|
33
36
|
const RECOVERY_SESSION_TTL_SECONDS = 15 * 60;
|
|
34
37
|
const RECOVERY_TOKEN_TTL_SECONDS = 60 * 60;
|
|
38
|
+
const OAUTH_ATTEMPT_TTL_SECONDS = 10 * 60;
|
|
39
|
+
// Every provider returns to the login page, which completes a sign-in or a link.
|
|
40
|
+
const OAUTH_REDIRECT_PATH = "/auth/login";
|
|
41
|
+
// An account created through a provider has no password until recovery sets one.
|
|
42
|
+
const NO_PASSWORD = Object.freeze({ algorithm: "", version: "", salt: "", hash: "" });
|
|
35
43
|
|
|
36
44
|
function nowSeconds() {
|
|
37
45
|
return Math.floor(Date.now() / 1000);
|
|
@@ -65,6 +73,13 @@ function normalizeDisplayName(value, email) {
|
|
|
65
73
|
return email.split("@")[0] || "User";
|
|
66
74
|
}
|
|
67
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
|
+
|
|
68
83
|
function createId(prefix) {
|
|
69
84
|
return `${prefix}_${randomToken(18)}`;
|
|
70
85
|
}
|
|
@@ -152,21 +167,26 @@ async function findExistingAppProfile(user, profileProjector) {
|
|
|
152
167
|
}
|
|
153
168
|
if (typeof profileProjector.findByIdentity !== "function") {
|
|
154
169
|
throw new Error(
|
|
155
|
-
"auth.profile.projector.findByIdentity() is required for dev auth impersonation."
|
|
170
|
+
"auth.profile.projector.findByIdentity() is required for dev auth impersonation and profile lookups without sync."
|
|
156
171
|
);
|
|
157
172
|
}
|
|
158
173
|
const profile = await profileProjector.findByIdentity(buildProfile(user));
|
|
159
174
|
return profile ? requireProfileResult(profile, "findByIdentity") : null;
|
|
160
175
|
}
|
|
161
176
|
|
|
162
|
-
|
|
163
|
-
|
|
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) {
|
|
164
182
|
return buildAuthPayload({ user, session: null, profileProjector });
|
|
165
183
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
184
|
+
if (devSession) {
|
|
185
|
+
try {
|
|
186
|
+
ensureDevAuthRuntimeAvailable(devAuth, request);
|
|
187
|
+
} catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
170
190
|
}
|
|
171
191
|
const appProfile = await findExistingAppProfile(user, profileProjector);
|
|
172
192
|
return profileProjector && !appProfile
|
|
@@ -297,6 +317,16 @@ function createLocalAuthService({
|
|
|
297
317
|
const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isProduction);
|
|
298
318
|
const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isProduction);
|
|
299
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 });
|
|
300
330
|
const devAuth = config.devAuth || resolveDevAuthPolicy({
|
|
301
331
|
nodeEnv: config.nodeEnv
|
|
302
332
|
});
|
|
@@ -331,14 +361,14 @@ function createLocalAuthService({
|
|
|
331
361
|
login: false
|
|
332
362
|
},
|
|
333
363
|
oauthLogin: {
|
|
334
|
-
enabled:
|
|
335
|
-
providers:
|
|
364
|
+
enabled: oauthEnabled,
|
|
365
|
+
providers: oauthProviders.map(({ id, label }) => ({ id, label }))
|
|
336
366
|
},
|
|
337
367
|
emailConfirmation: false,
|
|
338
368
|
profileUpdate: true,
|
|
339
369
|
providerLinking: {
|
|
340
|
-
start:
|
|
341
|
-
unlink:
|
|
370
|
+
start: oauthEnabled,
|
|
371
|
+
unlink: oauthEnabled
|
|
342
372
|
},
|
|
343
373
|
securityStatus: true,
|
|
344
374
|
signOutOtherSessions: true,
|
|
@@ -440,7 +470,7 @@ function createLocalAuthService({
|
|
|
440
470
|
const password = String(input.password || "");
|
|
441
471
|
return backend.withTransaction(async (tx) => {
|
|
442
472
|
const user = await tx.users.findByEmail(email);
|
|
443
|
-
if (!user || user.disabled || !(await passwords.verifyPassword(password, user.password))) {
|
|
473
|
+
if (!user || user.disabled || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
|
|
444
474
|
throw createAuthError(AUTH_TEXTS.invalidCredentials);
|
|
445
475
|
}
|
|
446
476
|
const session = await createSessionForUser(tx, user);
|
|
@@ -482,7 +512,7 @@ function createLocalAuthService({
|
|
|
482
512
|
});
|
|
483
513
|
}
|
|
484
514
|
|
|
485
|
-
async function authenticateRequest(request) {
|
|
515
|
+
async function authenticateRequest(request, { syncProfile = true } = {}) {
|
|
486
516
|
const cookies = safeRequestCookies(request);
|
|
487
517
|
const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
|
|
488
518
|
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
@@ -507,7 +537,8 @@ function createLocalAuthService({
|
|
|
507
537
|
profileProjector,
|
|
508
538
|
request,
|
|
509
539
|
session: resolved.session,
|
|
510
|
-
user: resolved.user
|
|
540
|
+
user: resolved.user,
|
|
541
|
+
syncProfile
|
|
511
542
|
});
|
|
512
543
|
if (!authPayload) {
|
|
513
544
|
return unauthenticatedAuthResult(true);
|
|
@@ -542,7 +573,8 @@ function createLocalAuthService({
|
|
|
542
573
|
profileProjector,
|
|
543
574
|
request,
|
|
544
575
|
session: resolved.session,
|
|
545
|
-
user: resolved.user
|
|
576
|
+
user: resolved.user,
|
|
577
|
+
syncProfile
|
|
546
578
|
});
|
|
547
579
|
if (!authPayload) {
|
|
548
580
|
return unauthenticatedAuthResult(true);
|
|
@@ -757,38 +789,251 @@ function createLocalAuthService({
|
|
|
757
789
|
});
|
|
758
790
|
}
|
|
759
791
|
|
|
760
|
-
async function
|
|
761
|
-
const
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
}
|
|
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
|
+
];
|
|
765
830
|
return buildSecurityStatusFromAuthMethodsStatus(
|
|
766
831
|
{
|
|
767
|
-
methods
|
|
768
|
-
{
|
|
769
|
-
id: "password",
|
|
770
|
-
kind: "password",
|
|
771
|
-
provider: "email",
|
|
772
|
-
label: "Password",
|
|
773
|
-
configured: true,
|
|
774
|
-
enabled: true,
|
|
775
|
-
canDisable: false,
|
|
776
|
-
supportsSecretUpdate: true,
|
|
777
|
-
requiresCurrentPassword: false
|
|
778
|
-
}
|
|
779
|
-
],
|
|
832
|
+
methods,
|
|
780
833
|
minimumEnabledMethods: 1,
|
|
781
|
-
enabledMethodsCount:
|
|
834
|
+
enabledMethodsCount: signInMethodCount
|
|
782
835
|
},
|
|
783
836
|
{
|
|
784
837
|
actions: {
|
|
785
|
-
changePassword:
|
|
786
|
-
signOutOtherSessions: true
|
|
838
|
+
changePassword: passwordSet,
|
|
839
|
+
signOutOtherSessions: true,
|
|
840
|
+
linkProvider: oauthEnabled,
|
|
841
|
+
unlinkProvider: oauthEnabled
|
|
787
842
|
}
|
|
788
843
|
}
|
|
789
844
|
);
|
|
790
845
|
}
|
|
791
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
|
+
}
|
|
914
|
+
|
|
915
|
+
// Subject first, then a verified email that matches an existing user, then a
|
|
916
|
+
// new user created like register; profile sync then provisions it as usual.
|
|
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
|
+
};
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
async function linkOAuthIdentity(request, attempt, identity, provider) {
|
|
950
|
+
const authResult = await authenticateRequest(request);
|
|
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 });
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
async function oauthComplete(input = {}, request = null) {
|
|
976
|
+
const errorCode = String(input.error || input.error_code || "").trim();
|
|
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 };
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
async function unlinkProvider(request, input = {}) {
|
|
1013
|
+
const userId = await requireNormalSessionUserId(request);
|
|
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) };
|
|
1035
|
+
}
|
|
1036
|
+
|
|
792
1037
|
async function signOutOtherSessions(request) {
|
|
793
1038
|
const authResult = await authenticateRequest(request);
|
|
794
1039
|
if (authResult.authenticated !== true) {
|
|
@@ -837,12 +1082,10 @@ function createLocalAuthService({
|
|
|
837
1082
|
verifyOtpLogin() {
|
|
838
1083
|
return throwUnsupportedAuthOperation("verifyOtpLogin");
|
|
839
1084
|
},
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
oauthComplete
|
|
844
|
-
return throwUnsupportedAuthOperation("oauthComplete");
|
|
845
|
-
},
|
|
1085
|
+
writeOAuthStartCookies,
|
|
1086
|
+
clearOAuthStartCookies,
|
|
1087
|
+
oauthStart,
|
|
1088
|
+
oauthComplete,
|
|
846
1089
|
requestPasswordReset,
|
|
847
1090
|
completePasswordRecovery,
|
|
848
1091
|
resetPassword,
|
|
@@ -852,12 +1095,8 @@ function createLocalAuthService({
|
|
|
852
1095
|
setPasswordSignInEnabled() {
|
|
853
1096
|
return throwUnsupportedAuthOperation("setPasswordSignInEnabled");
|
|
854
1097
|
},
|
|
855
|
-
startProviderLink
|
|
856
|
-
|
|
857
|
-
},
|
|
858
|
-
unlinkProvider() {
|
|
859
|
-
return throwUnsupportedAuthOperation("unlinkProvider");
|
|
860
|
-
},
|
|
1098
|
+
startProviderLink,
|
|
1099
|
+
unlinkProvider,
|
|
861
1100
|
signOutOtherSessions,
|
|
862
1101
|
logout
|
|
863
1102
|
});
|
|
@@ -9,6 +9,7 @@ import { randomBytes } from "node:crypto";
|
|
|
9
9
|
import fs from "node:fs";
|
|
10
10
|
import path from "node:path";
|
|
11
11
|
import { createLocalFileBackend } from "../lib/fileBackend.js";
|
|
12
|
+
import { resolveOAuthProviders } from "../lib/oauth.js";
|
|
12
13
|
import { createLocalAuthService } from "../lib/service.js";
|
|
13
14
|
|
|
14
15
|
const DEFAULT_STORE_DIR = ".jskit/auth";
|
|
@@ -35,20 +36,22 @@ function resolveSessionSecret(env, { storeDir, isProduction }) {
|
|
|
35
36
|
return generated;
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
|
|
39
|
+
// Recovery links and OAuth redirect addresses are built from APP_PUBLIC_URL.
|
|
40
|
+
function resolveAppPublicUrl(env, { recoverySender, oauthProviders }) {
|
|
39
41
|
const configured = String(env.APP_PUBLIC_URL || "").trim();
|
|
40
42
|
if (!configured) {
|
|
41
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.");
|
|
42
45
|
return "http://localhost:5173";
|
|
43
46
|
}
|
|
44
47
|
let parsed;
|
|
45
48
|
try {
|
|
46
49
|
parsed = new URL(configured);
|
|
47
50
|
} catch {
|
|
48
|
-
throw new Error("APP_PUBLIC_URL must be a valid URL
|
|
51
|
+
throw new Error("APP_PUBLIC_URL must be a valid URL.");
|
|
49
52
|
}
|
|
50
53
|
if (!["http:", "https:"].includes(parsed.protocol)) {
|
|
51
|
-
throw new Error("APP_PUBLIC_URL must use http or https
|
|
54
|
+
throw new Error("APP_PUBLIC_URL must use http or https.");
|
|
52
55
|
}
|
|
53
56
|
return parsed.toString().replace(/\/$/u, "");
|
|
54
57
|
}
|
|
@@ -62,11 +65,13 @@ function resolveConfig({ appRoot, backend, env, logger, recoverySender = null })
|
|
|
62
65
|
}
|
|
63
66
|
const devAuth = resolveDevAuthPolicyFromEnv(env);
|
|
64
67
|
assertDevAuthPolicy(devAuth);
|
|
68
|
+
const oauthProviders = resolveOAuthProviders(env);
|
|
65
69
|
return {
|
|
66
70
|
storeDir,
|
|
67
71
|
nodeEnv,
|
|
68
72
|
logger,
|
|
69
|
-
appPublicUrl: resolveAppPublicUrl(env, { recoverySender }),
|
|
73
|
+
appPublicUrl: resolveAppPublicUrl(env, { recoverySender, oauthProviders }),
|
|
74
|
+
oauthProviders,
|
|
70
75
|
sessionSecret: resolveSessionSecret(env, { storeDir, isProduction }),
|
|
71
76
|
recoveryDevOutput: String(env.AUTH_LOCAL_RECOVERY_DEV_OUTPUT || "log").trim().toLowerCase() || "log",
|
|
72
77
|
devAuth
|