@jskit-ai/auth-provider-local-core 0.2.1 → 0.2.2

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.
@@ -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
  }
@@ -297,6 +312,16 @@ function createLocalAuthService({
297
312
  const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isProduction);
298
313
  const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isProduction);
299
314
  const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isProduction);
315
+ const OAUTH_ATTEMPT_COOKIE = hostOnlyCookieName(OAUTH_ATTEMPT_COOKIE_NAME, isProduction);
316
+ const oauthProviders = Array.isArray(config.oauthProviders) ? config.oauthProviders : [];
317
+ const oauthProvidersById = new Map(oauthProviders.map((provider) => [provider.id, provider]));
318
+ const oauthEnabled = oauthProviders.length > 0;
319
+ if (oauthEnabled && !config.appPublicUrl) {
320
+ throw new Error("Local auth OAuth sign-in requires config.appPublicUrl.");
321
+ }
322
+ const oauthRedirectUri = oauthEnabled ? `${config.appPublicUrl.replace(/\/$/u, "")}${OAUTH_REDIRECT_PATH}` : "";
323
+ const appOrigin = oauthEnabled ? new URL(config.appPublicUrl).origin : "";
324
+ const oauthClients = createOAuthClients({ logger: config.logger });
300
325
  const devAuth = config.devAuth || resolveDevAuthPolicy({
301
326
  nodeEnv: config.nodeEnv
302
327
  });
@@ -331,14 +356,14 @@ function createLocalAuthService({
331
356
  login: false
332
357
  },
333
358
  oauthLogin: {
334
- enabled: false,
335
- providers: []
359
+ enabled: oauthEnabled,
360
+ providers: oauthProviders.map(({ id, label }) => ({ id, label }))
336
361
  },
337
362
  emailConfirmation: false,
338
363
  profileUpdate: true,
339
364
  providerLinking: {
340
- start: false,
341
- unlink: false
365
+ start: oauthEnabled,
366
+ unlink: oauthEnabled
342
367
  },
343
368
  securityStatus: true,
344
369
  signOutOtherSessions: true,
@@ -440,7 +465,7 @@ function createLocalAuthService({
440
465
  const password = String(input.password || "");
441
466
  return backend.withTransaction(async (tx) => {
442
467
  const user = await tx.users.findByEmail(email);
443
- if (!user || user.disabled || !(await passwords.verifyPassword(password, user.password))) {
468
+ if (!user || user.disabled || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
444
469
  throw createAuthError(AUTH_TEXTS.invalidCredentials);
445
470
  }
446
471
  const session = await createSessionForUser(tx, user);
@@ -757,38 +782,251 @@ function createLocalAuthService({
757
782
  });
758
783
  }
759
784
 
760
- async function getSecurityStatus(request) {
761
- const authResult = await authenticateRequest(request);
762
- if (authResult.authenticated !== true) {
763
- throw createAuthError(AUTH_TEXTS.sessionRequired);
764
- }
785
+ async function securityStatusForUser(userId) {
786
+ const { user, identities } = await backend.withTransaction(async (tx) => ({
787
+ user: await tx.users.findById(userId),
788
+ identities: oauthEnabled ? await tx.identities.listForUser(userId) : []
789
+ }));
790
+ const passwordSet = hasPassword(user);
791
+ // Identities of a provider the app no longer configures cannot sign in.
792
+ const linkedProviders = new Set(identities.map((identity) => identity.provider).filter((id) => oauthProvidersById.has(id)));
793
+ const signInMethodCount = (passwordSet ? 1 : 0) + linkedProviders.size;
794
+ const methods = [
795
+ {
796
+ id: "password",
797
+ kind: "password",
798
+ provider: "email",
799
+ label: "Password",
800
+ configured: passwordSet,
801
+ enabled: passwordSet,
802
+ canDisable: false,
803
+ supportsSecretUpdate: true,
804
+ requiresCurrentPassword: false
805
+ },
806
+ // canEnable links the provider and canDisable unlinks it, as for Supabase.
807
+ ...oauthProviders.map((provider) => {
808
+ const linked = linkedProviders.has(provider.id);
809
+ return {
810
+ id: buildOAuthMethodId(provider.id),
811
+ kind: AUTH_METHOD_KIND_OAUTH,
812
+ provider: provider.id,
813
+ label: provider.label,
814
+ configured: linked,
815
+ enabled: linked,
816
+ canEnable: !linked,
817
+ canDisable: linked && signInMethodCount > 1,
818
+ supportsSecretUpdate: false,
819
+ requiresCurrentPassword: false
820
+ };
821
+ })
822
+ ];
765
823
  return buildSecurityStatusFromAuthMethodsStatus(
766
824
  {
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
- ],
825
+ methods,
780
826
  minimumEnabledMethods: 1,
781
- enabledMethodsCount: 1
827
+ enabledMethodsCount: signInMethodCount
782
828
  },
783
829
  {
784
830
  actions: {
785
- changePassword: true,
786
- signOutOtherSessions: true
831
+ changePassword: passwordSet,
832
+ signOutOtherSessions: true,
833
+ linkProvider: oauthEnabled,
834
+ unlinkProvider: oauthEnabled
787
835
  }
788
836
  }
789
837
  );
790
838
  }
791
839
 
840
+ async function requireNormalSessionUserId(request) {
841
+ const authResult = await authenticateRequest(request);
842
+ if (authResult.authenticated !== true || authResult.sessionPurpose !== "normal") {
843
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
844
+ }
845
+ return authResult.actor.providerUserId;
846
+ }
847
+
848
+ async function getSecurityStatus(request) {
849
+ const authResult = await authenticateRequest(request);
850
+ if (authResult.authenticated !== true) {
851
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
852
+ }
853
+ return securityStatusForUser(authResult.actor.providerUserId);
854
+ }
855
+
856
+ function requireOAuthProvider(value) {
857
+ const provider = oauthProvidersById.get(String(value || "").trim().toLowerCase());
858
+ if (!provider) {
859
+ throw new AppError(400, "This sign-in provider is not available.", { code: "auth.local.oauth.providerInvalid" });
860
+ }
861
+ return provider;
862
+ }
863
+
864
+ // The attempt (state, nonce, PKCE verifier) is stored server-side under the
865
+ // hash of a random key that only the starting browser holds in a cookie.
866
+ async function beginOAuthAttempt(provider, { intent, userId = "", returnTo }) {
867
+ const browserKey = randomToken(32);
868
+ const attempt = {
869
+ browserKeyHash: sha256Base64url(browserKey),
870
+ provider: provider.id,
871
+ intent,
872
+ userId,
873
+ state: randomToken(32),
874
+ nonce: randomToken(32),
875
+ codeVerifier: randomToken(32),
876
+ returnTo: normalizeReturnToPath(returnTo, { fallback: "/", allowedOrigins: [appOrigin] }),
877
+ expiresAt: isoFromNow(OAUTH_ATTEMPT_TTL_SECONDS)
878
+ };
879
+ const url = await oauthClients.authorizationUrl(provider, { ...attempt, redirectUri: oauthRedirectUri });
880
+ await backend.withTransaction(async (tx) => {
881
+ await tx.oauthAttempts.deleteExpired(new Date().toISOString());
882
+ await tx.oauthAttempts.create(attempt);
883
+ });
884
+ return { provider: provider.id, returnTo: attempt.returnTo, url, attempt: browserKey };
885
+ }
886
+
887
+ async function oauthStart(input = {}) {
888
+ return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "login", returnTo: input.returnTo });
889
+ }
890
+
891
+ async function startProviderLink(request, input = {}) {
892
+ const userId = await requireNormalSessionUserId(request);
893
+ return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "link", userId, returnTo: input.returnTo });
894
+ }
895
+
896
+ function writeOAuthStartCookies(reply, result) {
897
+ if (reply && result?.attempt) {
898
+ reply.setCookie(OAUTH_ATTEMPT_COOKIE, result.attempt, cookieOptions(isProduction, OAUTH_ATTEMPT_TTL_SECONDS));
899
+ }
900
+ }
901
+
902
+ function clearOAuthStartCookies(reply) {
903
+ if (reply) {
904
+ reply.clearCookie(OAUTH_ATTEMPT_COOKIE, cookieOptions(isProduction, 0));
905
+ }
906
+ }
907
+
908
+ // Subject first, then a verified email that matches an existing user, then a
909
+ // new user created like register; profile sync then provisions it as usual.
910
+ async function signInWithOAuthIdentity(identity) {
911
+ const result = await backend.withTransaction(async (tx) => {
912
+ const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
913
+ let user = linked ? await tx.users.findById(linked.userId) : await tx.users.findByEmail(identity.email);
914
+ const registered = !linked && !user;
915
+ if (registered) {
916
+ user = await tx.users.create({
917
+ id: createId("usr"),
918
+ email: identity.email,
919
+ displayName: normalizeDisplayName(identity.name, identity.email),
920
+ password: NO_PASSWORD
921
+ });
922
+ }
923
+ if (!user || user.disabled) {
924
+ throw new AppError(401, "This account can't sign in.", { code: "auth.local.oauth.accountUnavailable" });
925
+ }
926
+ if (!linked) {
927
+ await tx.identities.create({
928
+ userId: user.id,
929
+ provider: identity.provider,
930
+ providerSubject: identity.providerSubject,
931
+ email: identity.email
932
+ });
933
+ }
934
+ return { user, registered, session: await createSessionForUser(tx, user) };
935
+ });
936
+ return {
937
+ ...(await buildAuthPayload({ user: result.user, session: result.session, profileProjector })),
938
+ registered: result.registered
939
+ };
940
+ }
941
+
942
+ async function linkOAuthIdentity(request, attempt, identity, provider) {
943
+ const authResult = await authenticateRequest(request);
944
+ if (authResult.authenticated !== true || authResult.actor.providerUserId !== attempt.userId) {
945
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
946
+ }
947
+ const user = await backend.withTransaction(async (tx) => {
948
+ const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
949
+ if (linked && linked.userId !== attempt.userId) {
950
+ throw new AppError(409, `This ${provider.label} account is already linked to another account.`, {
951
+ code: "auth.local.oauth.identityTaken",
952
+ params: { provider: provider.label }
953
+ });
954
+ }
955
+ if (!linked) {
956
+ await tx.identities.create({
957
+ userId: attempt.userId,
958
+ provider: identity.provider,
959
+ providerSubject: identity.providerSubject,
960
+ email: identity.email
961
+ });
962
+ }
963
+ return tx.users.findById(attempt.userId);
964
+ });
965
+ return buildAuthPayload({ user, session: null, profileProjector });
966
+ }
967
+
968
+ async function oauthComplete(input = {}, request = null) {
969
+ const errorCode = String(input.error || input.error_code || "").trim();
970
+ if (errorCode) {
971
+ throw errorCode === "access_denied"
972
+ ? new AppError(401, "Sign-in was cancelled.", { code: "auth.local.oauth.cancelled" })
973
+ : new AppError(401, "Sign-in was not completed. Start again.", { code: "auth.local.oauth.incomplete" });
974
+ }
975
+ const browserKey = String(safeRequestCookies(request)[OAUTH_ATTEMPT_COOKIE] || "").trim();
976
+ // Taking an attempt deletes it, so each one completes at most once.
977
+ const attempt = browserKey
978
+ ? await backend.withTransaction((tx) => tx.oauthAttempts.take(sha256Base64url(browserKey)))
979
+ : null;
980
+ const state = String(input.state || "");
981
+ // The provider is the one this attempt started with, whatever the callback names.
982
+ const provider = attempt ? oauthProvidersById.get(attempt.provider) : null;
983
+ if (!provider || isExpiredIso(attempt.expiresAt) || !state || state !== attempt.state) {
984
+ throw new AppError(400, "This sign-in took too long or started in another browser. Start again.", {
985
+ code: "auth.local.oauth.expired"
986
+ });
987
+ }
988
+ const code = String(input.code || "").trim();
989
+ if (!code) {
990
+ throw new AppError(400, "OAuth code is required.", { code: "auth.local.oauth.codeRequired" });
991
+ }
992
+ const callbackUrl = new URL(oauthRedirectUri);
993
+ callbackUrl.searchParams.set("code", code);
994
+ callbackUrl.searchParams.set("state", state);
995
+ if (input.iss) {
996
+ callbackUrl.searchParams.set("iss", String(input.iss));
997
+ }
998
+ const identity = await oauthClients.verifiedIdentity(provider, { callbackUrl, attempt });
999
+ const result = attempt.intent === "link"
1000
+ ? await linkOAuthIdentity(request, attempt, identity, provider)
1001
+ : await signInWithOAuthIdentity(identity);
1002
+ return { ...result, provider: provider.id, returnTo: attempt.returnTo };
1003
+ }
1004
+
1005
+ async function unlinkProvider(request, input = {}) {
1006
+ const userId = await requireNormalSessionUserId(request);
1007
+ const provider = requireOAuthProvider(input.provider);
1008
+ await backend.withTransaction(async (tx) => {
1009
+ const user = await tx.users.findById(userId);
1010
+ const identities = await tx.identities.listForUser(userId);
1011
+ if (!identities.some((identity) => identity.provider === provider.id)) {
1012
+ throw new AppError(404, `${provider.label} is not linked to this account.`, {
1013
+ code: "auth.local.oauth.notLinked",
1014
+ params: { provider: provider.label }
1015
+ });
1016
+ }
1017
+ const otherMethodRemains = hasPassword(user) || identities.some(
1018
+ (identity) => identity.provider !== provider.id && oauthProvidersById.has(identity.provider)
1019
+ );
1020
+ if (!otherMethodRemains) {
1021
+ throw new AppError(409, "Add a password or link another sign-in method before removing this one.", {
1022
+ code: "auth.local.oauth.lastMethod"
1023
+ });
1024
+ }
1025
+ await tx.identities.deleteForUser(userId, provider.id);
1026
+ });
1027
+ return { securityStatus: await securityStatusForUser(userId) };
1028
+ }
1029
+
792
1030
  async function signOutOtherSessions(request) {
793
1031
  const authResult = await authenticateRequest(request);
794
1032
  if (authResult.authenticated !== true) {
@@ -837,12 +1075,10 @@ function createLocalAuthService({
837
1075
  verifyOtpLogin() {
838
1076
  return throwUnsupportedAuthOperation("verifyOtpLogin");
839
1077
  },
840
- oauthStart() {
841
- return throwUnsupportedAuthOperation("oauthStart");
842
- },
843
- oauthComplete() {
844
- return throwUnsupportedAuthOperation("oauthComplete");
845
- },
1078
+ writeOAuthStartCookies,
1079
+ clearOAuthStartCookies,
1080
+ oauthStart,
1081
+ oauthComplete,
846
1082
  requestPasswordReset,
847
1083
  completePasswordRecovery,
848
1084
  resetPassword,
@@ -852,12 +1088,8 @@ function createLocalAuthService({
852
1088
  setPasswordSignInEnabled() {
853
1089
  return throwUnsupportedAuthOperation("setPasswordSignInEnabled");
854
1090
  },
855
- startProviderLink() {
856
- return throwUnsupportedAuthOperation("startProviderLink");
857
- },
858
- unlinkProvider() {
859
- return throwUnsupportedAuthOperation("unlinkProvider");
860
- },
1091
+ startProviderLink,
1092
+ unlinkProvider,
861
1093
  signOutOtherSessions,
862
1094
  logout
863
1095
  });
@@ -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
- function resolveAppPublicUrl(env, { recoverySender }) {
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 when local auth email recovery is configured.");
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 when local auth email recovery is configured.");
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