@luckystack/login 0.1.7 → 0.1.9

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/CHANGELOG.md CHANGED
@@ -1,14 +1,14 @@
1
- # Changelog
2
-
3
- All notable changes to `@luckystack/login` are documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
- ## [Unreleased]
9
-
10
- ## [0.1.0]
11
-
12
- ### Added
13
-
14
- - Initial public release as part of the LuckyStack package split.
1
+ # Changelog
2
+
3
+ All notable changes to `@luckystack/login` are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0]
11
+
12
+ ### Added
13
+
14
+ - Initial public release as part of the LuckyStack package split.
package/CLAUDE.md CHANGED
@@ -138,7 +138,7 @@ All config keys live on `ProjectConfig` (from `@luckystack/core`). Resolved at c
138
138
  | `FACEBOOK_CLIENT_ID` / `FACEBOOK_CLIENT_SECRET` | `facebookProvider` | OAuth app credentials. |
139
139
  | `MICROSOFT_CLIENT_ID` / `MICROSOFT_CLIENT_SECRET` | `microsoftProvider` | OAuth app credentials. |
140
140
  | `MICROSOFT_TENANT_ID` | `microsoftProvider` (optional) | Single-tenant Azure AD. Defaults to `'common'`. |
141
- | `DNS` | All OAuth `callbackUrl` builders | Base URL prepended to `/auth/callback/<provider>`. |
141
+ | (callback origin) | All OAuth `callbackUrl` builders | The `callbackUrl` is the BACKEND origin + `/auth/callback/<provider>`. The scaffold derives it in `config.ts` (`oauthCallbackBase`: dev `http://localhost:80`, prod the public domain). No `DNS` env var — that was removed in 0.1.5. |
142
142
  | `BCRYPT_ROUNDS` | `auth.bcryptRounds` | Surfaced through project config; salt rounds for credentials hashing. |
143
143
 
144
144
  > Env-key set without the matching package installed = hard boot crash (see peer-dep guard policy). `@luckystack/email` is the optional case — login lazy-imports it and gracefully fails when `forgotPassword !== 'framework'`.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Mathijs van Melick
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mathijs van Melick
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -57,12 +57,12 @@ registerOAuthProviders([
57
57
  googleProvider({
58
58
  clientId: process.env.GOOGLE_CLIENT_ID,
59
59
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
60
- callbackUrl: `${process.env.DNS}/auth/callback/google`,
60
+ callbackUrl: `http://localhost:80/auth/callback/google`,
61
61
  }),
62
62
  githubProvider({
63
63
  clientId: process.env.GITHUB_CLIENT_ID,
64
64
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
65
- callbackUrl: `${process.env.DNS}/auth/callback/github`,
65
+ callbackUrl: `http://localhost:80/auth/callback/github`,
66
66
  }),
67
67
  ]);
68
68
  ```
@@ -77,7 +77,7 @@ Every helper accepts the base shape plus optional overrides for self-hosted inst
77
77
  | --- | --- | --- | --- |
78
78
  | `clientId` | all | — | Required. The OAuth app's client identifier. |
79
79
  | `clientSecret` | all | — | Required. The OAuth app's client secret. |
80
- | `callbackUrl` | all | — | Required. Must match the URL registered with the provider, normally `${DNS}/auth/callback/<name>`. |
80
+ | `callbackUrl` | all | — | Required. Must match the URL registered with the provider — your BACKEND origin + `/auth/callback/<name>` (dev `http://localhost:80/auth/callback/<name>`, prod `https://your-domain.com/auth/callback/<name>`). |
81
81
  | `endpoints?.authorizationURL` | all | provider-default | GitHub Enterprise host, Microsoft custom-tenant authorize URL, internal auth proxy, etc. |
82
82
  | `endpoints?.tokenExchangeURL` | all | provider-default | Same use cases as `authorizationURL`. |
83
83
  | `endpoints?.userInfoURL` | all | provider-default | Self-hosted GitHub Enterprise / Microsoft Graph mirror, etc. |
@@ -91,7 +91,7 @@ Example — self-hosted GitHub Enterprise:
91
91
  githubProvider({
92
92
  clientId: process.env.GITHUB_CLIENT_ID,
93
93
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
94
- callbackUrl: `${process.env.DNS}/auth/callback/github`,
94
+ callbackUrl: `http://localhost:80/auth/callback/github`,
95
95
  endpoints: {
96
96
  authorizationURL: 'https://github.acme.example/login/oauth/authorize',
97
97
  tokenExchangeURL: 'https://github.acme.example/login/oauth/access_token',
@@ -106,7 +106,7 @@ Example — single-tenant Microsoft Entra ID:
106
106
  microsoftProvider({
107
107
  clientId: process.env.MICROSOFT_CLIENT_ID,
108
108
  clientSecret: process.env.MICROSOFT_CLIENT_SECRET,
109
- callbackUrl: `${process.env.DNS}/auth/callback/microsoft`,
109
+ callbackUrl: `http://localhost:80/auth/callback/microsoft`,
110
110
  tenant: process.env.MICROSOFT_TENANT_ID, // 'common' for any tenant; UUID for a single tenant.
111
111
  apiVersion: 'v2.0', // OAuth endpoint version
112
112
  graphApiVersion: 'v1.0', // Graph endpoint version
package/dist/index.d.ts CHANGED
@@ -137,8 +137,20 @@ declare module '@luckystack/core' {
137
137
  * @param token - The session token (unique identifier)
138
138
  * @param data - The session data to store
139
139
  * @param newUser - If true, this is a new login (triggers single-session enforcement)
140
+ * @param options.supersedeToken - A token belonging to the SAME browser that is
141
+ * being replaced by this login (e.g. re-login while already signed in). It is
142
+ * excluded from single-session enforcement so the user's current device is not
143
+ * kicked by its own new session. The caller is responsible for deleting it
144
+ * afterwards (use `deleteSession(supersedeToken, { skipSocketLogout: true })`).
140
145
  */
141
- declare const saveSession: (token: string, data: BaseSessionLayout, newUser?: boolean) => Promise<void>;
146
+ declare const saveSession: (token: string, data: BaseSessionLayout, newUser?: boolean, options?: {
147
+ supersedeToken?: string;
148
+ }) => Promise<{
149
+ ok: true;
150
+ } | {
151
+ ok: false;
152
+ errorCode: string;
153
+ }>;
142
154
  /**
143
155
  * Retrieve a user session through the active session adapter.
144
156
  *
@@ -151,9 +163,16 @@ declare const getSession: (token: string | null) => Promise<BaseSessionLayout |
151
163
  * clients.
152
164
  *
153
165
  * @param token - The session token to delete
166
+ * @param options.skipSocketLogout - When true, the session data + active-token
167
+ * tracking are cleaned up and the pre/post delete hooks still fire, but NO
168
+ * `logout` is emitted to sockets in the token's room. Use this when the SAME
169
+ * browser is replacing its session (re-login): emitting a logout would bounce
170
+ * that browser to the login page and null its brand-new session.
154
171
  * @returns true if successful
155
172
  */
156
- declare const deleteSession: (token: string) => Promise<boolean>;
173
+ declare const deleteSession: (token: string, options?: {
174
+ skipSocketLogout?: boolean;
175
+ }) => Promise<boolean>;
157
176
  /**
158
177
  * Get all active sessions (admin utility). Returns empty when the active
159
178
  * adapter doesn't implement enumeration (signed-JWT-stateless, log-only).
@@ -283,6 +302,8 @@ declare const registerWithCredentials: ({ email, password, name, confirmPassword
283
302
  declare const loginWithCredentialsCore: ({ email, password }: {
284
303
  email: string;
285
304
  password: string;
305
+ }, options?: {
306
+ supersedeToken?: string;
286
307
  }) => Promise<{
287
308
  status: boolean;
288
309
  reason: string;
@@ -299,7 +320,9 @@ declare const loginWithCredentialsCore: ({ email, password }: {
299
320
  newToken: string;
300
321
  session: BaseSessionLayout;
301
322
  }>;
302
- declare const loginWithCredentials: (params: paramsType) => Promise<{
323
+ declare const loginWithCredentials: (params: paramsType, options?: {
324
+ supersedeToken?: string;
325
+ }) => Promise<{
303
326
  status: false;
304
327
  reason: string;
305
328
  } | {
@@ -330,6 +353,7 @@ interface OAuthCallbackResult {
330
353
  }
331
354
  declare const loginCallback: (pathname: string, req: IncomingMessage, _res: ServerResponse, options?: {
332
355
  defaultRedirectUrl?: string;
356
+ supersedeToken?: string;
333
357
  }) => Promise<OAuthCallbackResult | false>;
334
358
 
335
359
  declare const logout: ({ token, socket, userId, skipSessionDelete }: {
package/dist/index.js CHANGED
@@ -169,8 +169,8 @@ var init_session = __esm({
169
169
  const parsed = JSON.parse(value);
170
170
  return isSessionLayout(parsed) ? parsed : null;
171
171
  };
172
- saveSession = async (token, data, newUser) => {
173
- const [error] = await tryCatch3(async () => {
172
+ saveSession = async (token, data, newUser, options) => {
173
+ const [error, outcome] = await tryCatch3(async () => {
174
174
  const adapter = getSessionAdapter();
175
175
  if (newUser) {
176
176
  const preSessionCreateResult = await dispatchHook2("preSessionCreate", {
@@ -180,7 +180,7 @@ var init_session = __esm({
180
180
  });
181
181
  if (preSessionCreateResult.stopped) {
182
182
  getLogger2().warn(`session create aborted by preSessionCreate hook`, { errorCode: preSessionCreateResult.signal.errorCode });
183
- return;
183
+ return { ok: false, errorCode: preSessionCreateResult.signal.errorCode || "api.internalServerError" };
184
184
  }
185
185
  }
186
186
  data.csrfToken ??= randomBytes(getCsrfConfig().tokenLength).toString("hex");
@@ -192,13 +192,15 @@ var init_session = __esm({
192
192
  }
193
193
  const { getIoInstance } = await import("@luckystack/core");
194
194
  const io = getIoInstance();
195
- if (!io) return;
195
+ if (!io) return { ok: true };
196
196
  if (newUser && userId) {
197
197
  const sessionCfg = getProjectConfig().session;
198
198
  const effectivePerUser = sessionCfg.allowMultiple ? "multiple" : sessionCfg.perUser;
199
199
  const cap = sessionCfg.maxConcurrentPerUser;
200
200
  const allTokens = await adapter.listActive(userId);
201
- const previousTokens = allTokens.filter((t) => t !== token);
201
+ const previousTokens = allTokens.filter(
202
+ (t) => t !== token && t !== options?.supersedeToken
203
+ );
202
204
  let tokensToKick = [];
203
205
  if (effectivePerUser === "single") {
204
206
  tokensToKick = previousTokens;
@@ -237,10 +239,13 @@ var init_session = __esm({
237
239
  if (newUser) {
238
240
  await dispatchHook2("postSessionCreate", { token, user: data, persistent: !getProjectConfig().session.basedToken });
239
241
  }
242
+ return { ok: true };
240
243
  }, void 0, { fn: "saveSession", token });
241
244
  if (error) {
242
245
  getLogger2().error("saveSession failed", error, { token });
246
+ return { ok: false, errorCode: "api.internalServerError" };
243
247
  }
248
+ return outcome ?? { ok: false, errorCode: "api.internalServerError" };
244
249
  };
245
250
  getSession = async (token) => {
246
251
  if (!token) return null;
@@ -274,7 +279,7 @@ var init_session = __esm({
274
279
  }
275
280
  return value;
276
281
  };
277
- deleteSession = async (token) => {
282
+ deleteSession = async (token, options) => {
278
283
  if (process.env.LUCKYSTACK_TRACE_SESSION_DELETES === "1") {
279
284
  getLogger2().warn("[session] deleteSession invoked", {
280
285
  tokenPrefix: token.slice(0, 8),
@@ -296,7 +301,7 @@ var init_session = __esm({
296
301
  if (raw && resolvedUserId) {
297
302
  const { getIoInstance } = await import("@luckystack/core");
298
303
  const ioInstance = getIoInstance();
299
- if (ioInstance) {
304
+ if (ioInstance && !options?.skipSocketLogout) {
300
305
  const { logout: logout2 } = await Promise.resolve().then(() => (init_logout(), logout_exports));
301
306
  const sockets = ioInstance.sockets.adapter.rooms.get(token);
302
307
  if (sockets) {
@@ -968,7 +973,7 @@ var registerWithCredentials = async ({
968
973
  session: sanitizeUserForSession(createNewUserResponse)
969
974
  };
970
975
  };
971
- var loginWithCredentialsCore = async ({ email, password }) => {
976
+ var loginWithCredentialsCore = async ({ email, password }, options) => {
972
977
  const preLoginResult = await dispatchHook3("preLogin", { email, provider: "credentials" });
973
978
  if (preLoginResult.stopped) {
974
979
  return { status: false, reason: preLoginResult.signal.errorCode };
@@ -1004,14 +1009,17 @@ var loginWithCredentialsCore = async ({ email, password }) => {
1004
1009
  if (existsSync(filePath)) {
1005
1010
  newUser.avatar = `${newUser.id}.webp`;
1006
1011
  }
1007
- await saveSession(newToken, newUser, true);
1012
+ const saved = await saveSession(newToken, newUser, true, { supersedeToken: options?.supersedeToken });
1013
+ if (!saved.ok) {
1014
+ return { status: false, reason: saved.errorCode };
1015
+ }
1008
1016
  await dispatchHook3("postLogin", { userId: newUser.id, provider: "credentials", isNewUser: false, token: newToken });
1009
1017
  if (isDevMode()) {
1010
1018
  getLogger3().debug(`credentials login success for user ${newUser.id}`);
1011
1019
  }
1012
1020
  return { status: true, reason: "login.loggedIn", newToken, session: newUser };
1013
1021
  };
1014
- var loginWithCredentials = async (params) => {
1022
+ var loginWithCredentials = async (params, options) => {
1015
1023
  const creds = normalizeCredentials(params);
1016
1024
  if (isDevMode()) {
1017
1025
  getLogger3().debug(`credentials auth attempt for ${creds.email || "unknown-email"}`);
@@ -1026,7 +1034,7 @@ var loginWithCredentials = async (params) => {
1026
1034
  confirmPassword: creds.confirmPassword
1027
1035
  });
1028
1036
  }
1029
- return loginWithCredentialsCore({ email: creds.email, password: creds.password });
1037
+ return loginWithCredentialsCore({ email: creds.email, password: creds.password }, options);
1030
1038
  };
1031
1039
  var isAllowedRedirectUrl = (url) => {
1032
1040
  if (!URL.canParse(url, "http://placeholder")) return false;
@@ -1249,7 +1257,11 @@ var loginCallback = async (pathname, req, _res, options = {}) => {
1249
1257
  Object.assign(resolved.user, extra);
1250
1258
  }
1251
1259
  }
1252
- await saveSession(newToken, resolved.user, true);
1260
+ const saved = await saveSession(newToken, resolved.user, true, { supersedeToken: options.supersedeToken });
1261
+ if (!saved.ok) {
1262
+ getLogger3().error(`[oauth:${providerName}] saveSession failed \u2014 aborting callback`, { errorCode: saved.errorCode });
1263
+ return false;
1264
+ }
1253
1265
  if (resolved.isNewUser) {
1254
1266
  await dispatchHook3("postRegister", { userId: resolved.user.id, provider: providerName });
1255
1267
  }