@eaccess/auth 0.1.19 → 0.1.21

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/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Request, Response, NextFunction } from 'express';
2
2
  import { Pool } from 'pg';
3
+ import { IncomingMessage } from 'http';
3
4
 
4
5
  interface OAuthProviderConfig {
5
6
  clientId: string;
@@ -55,6 +56,7 @@ interface AuthConfig {
55
56
  google?: GoogleProviderConfig;
56
57
  azure?: AzureProviderConfig;
57
58
  };
59
+ githubUserAgent?: string;
58
60
  twoFactor?: {
59
61
  enabled?: boolean;
60
62
  requireForOAuth?: boolean;
@@ -118,6 +120,10 @@ interface AuthRemember {
118
120
  token: string;
119
121
  expires: Date;
120
122
  }
123
+ interface AuthenticateRequestResult {
124
+ account: AuthAccount | null;
125
+ source: "session" | "remember" | null;
126
+ }
121
127
  interface AuthReset {
122
128
  id: number;
123
129
  account_id: number;
@@ -598,6 +604,7 @@ interface AuthContext {
598
604
  }
599
605
  declare function createAuthContext(config: AuthConfig): AuthContext;
600
606
 
607
+ declare function authenticateRequest(config: AuthConfig, req: IncomingMessage, sessionMiddleware?: (req: any, res: any, next: () => void) => void): Promise<AuthenticateRequestResult>;
601
608
  declare function createUser(config: AuthConfig, credentials: {
602
609
  email: string;
603
610
  password: string;
@@ -653,6 +660,7 @@ declare function forceLogoutForUserBy(config: AuthConfig, identifier: {
653
660
  }>;
654
661
 
655
662
  declare const authFunctions_addRoleForUserBy: typeof addRoleForUserBy;
663
+ declare const authFunctions_authenticateRequest: typeof authenticateRequest;
656
664
  declare const authFunctions_changePasswordForUserBy: typeof changePasswordForUserBy;
657
665
  declare const authFunctions_confirmResetPassword: typeof confirmResetPassword;
658
666
  declare const authFunctions_createUser: typeof createUser;
@@ -666,7 +674,7 @@ declare const authFunctions_resetPassword: typeof resetPassword;
666
674
  declare const authFunctions_setStatusForUserBy: typeof setStatusForUserBy;
667
675
  declare const authFunctions_userExistsByEmail: typeof userExistsByEmail;
668
676
  declare namespace authFunctions {
669
- export { authFunctions_addRoleForUserBy as addRoleForUserBy, authFunctions_changePasswordForUserBy as changePasswordForUserBy, authFunctions_confirmResetPassword as confirmResetPassword, authFunctions_createUser as createUser, authFunctions_deleteUserBy as deleteUserBy, authFunctions_forceLogoutForUserBy as forceLogoutForUserBy, authFunctions_hasRoleForUserBy as hasRoleForUserBy, authFunctions_initiatePasswordResetForUserBy as initiatePasswordResetForUserBy, authFunctions_register as register, authFunctions_removeRoleForUserBy as removeRoleForUserBy, authFunctions_resetPassword as resetPassword, authFunctions_setStatusForUserBy as setStatusForUserBy, authFunctions_userExistsByEmail as userExistsByEmail };
677
+ export { authFunctions_addRoleForUserBy as addRoleForUserBy, authFunctions_authenticateRequest as authenticateRequest, authFunctions_changePasswordForUserBy as changePasswordForUserBy, authFunctions_confirmResetPassword as confirmResetPassword, authFunctions_createUser as createUser, authFunctions_deleteUserBy as deleteUserBy, authFunctions_forceLogoutForUserBy as forceLogoutForUserBy, authFunctions_hasRoleForUserBy as hasRoleForUserBy, authFunctions_initiatePasswordResetForUserBy as initiatePasswordResetForUserBy, authFunctions_register as register, authFunctions_removeRoleForUserBy as removeRoleForUserBy, authFunctions_resetPassword as resetPassword, authFunctions_setStatusForUserBy as setStatusForUserBy, authFunctions_userExistsByEmail as userExistsByEmail };
670
678
  }
671
679
 
672
680
  type UserIdentifier = {
@@ -1167,7 +1175,7 @@ declare abstract class BaseOAuthProvider implements OAuthProvider {
1167
1175
  protected processOAuthLogin(userData: OAuthUserData, req: Request): Promise<OAuthCallbackResult>;
1168
1176
  protected abstract getProviderName(): string;
1169
1177
  protected exchangeCodeForToken(code: string, tokenUrl: string): Promise<string>;
1170
- protected fetchUserFromAPI(accessToken: string, apiUrl: string): Promise<any>;
1178
+ protected fetchUserFromAPI(accessToken: string, apiUrl: string, headers?: Record<string, string>): Promise<any>;
1171
1179
  }
1172
1180
 
1173
1181
  declare class GitHubProvider extends BaseOAuthProvider {
@@ -1192,4 +1200,4 @@ declare class AzureProvider extends BaseOAuthProvider {
1192
1200
  protected exchangeCodeForToken(code: string, tokenUrl: string): Promise<string>;
1193
1201
  }
1194
1202
 
1195
- export { ActivityLogger, type AuthAccount, type AuthActivity, AuthActivityAction, type AuthActivityActionType, type AuthConfig, type AuthConfirmation, type AuthContext, AuthError, type AuthManager$1 as AuthManager, type AuthProvider, type AuthRemember, type AuthReset, AuthRole, type AuthSession, AuthStatus, AzureProvider, type AzureProviderConfig, BaseOAuthProvider, ConfirmationExpiredError, ConfirmationNotFoundError, EmailNotVerifiedError, EmailTakenError, GitHubProvider, type GitHubProviderConfig, GoogleProvider, type GoogleProviderConfig, InvalidBackupCodeError, InvalidEmailError, InvalidPasswordError, InvalidTokenError, InvalidTwoFactorCodeError, type OAuthCallbackResult, type OAuthProvider, type OAuthProviderConfig, type OAuthUserData, OtpProvider, ResetDisabledError, ResetExpiredError, ResetNotFoundError, SecondFactorRequiredError, type TokenCallback, TooManyResetsError, TotpProvider, TwoFactorAlreadyEnabledError, type TwoFactorChallenge, TwoFactorExpiredError, TwoFactorManager, TwoFactorMechanism, type TwoFactorMethod, TwoFactorNotSetupError, TwoFactorSetupIncompleteError, type TwoFactorSetupResult, type TwoFactorToken, type UserIdentifier, UserInactiveError, UserNotFoundError, UserNotLoggedInError, addRoleForUserBy, addRoleToUser, authFunctions, changePasswordForUserBy, cleanupExpiredTokens, confirmResetPassword, createAuthContext, createAuthMiddleware, createAuthTables, createUser, deleteUserBy, dropAuthTables, forceLogoutForUserBy, getAuthTableStats, getUserRoles, hasRoleForUserBy, initiatePasswordResetForUserBy, isValidEmail, register, removeRoleForUserBy, removeRoleFromUser, resetPassword, setStatusForUserBy, setUserRoles, userExistsByEmail, validateEmail };
1203
+ export { ActivityLogger, type AuthAccount, type AuthActivity, AuthActivityAction, type AuthActivityActionType, type AuthConfig, type AuthConfirmation, type AuthContext, AuthError, type AuthManager$1 as AuthManager, type AuthProvider, type AuthRemember, type AuthReset, AuthRole, type AuthSession, AuthStatus, type AuthenticateRequestResult, AzureProvider, type AzureProviderConfig, BaseOAuthProvider, ConfirmationExpiredError, ConfirmationNotFoundError, EmailNotVerifiedError, EmailTakenError, GitHubProvider, type GitHubProviderConfig, GoogleProvider, type GoogleProviderConfig, InvalidBackupCodeError, InvalidEmailError, InvalidPasswordError, InvalidTokenError, InvalidTwoFactorCodeError, type OAuthCallbackResult, type OAuthProvider, type OAuthProviderConfig, type OAuthUserData, OtpProvider, ResetDisabledError, ResetExpiredError, ResetNotFoundError, SecondFactorRequiredError, type TokenCallback, TooManyResetsError, TotpProvider, TwoFactorAlreadyEnabledError, type TwoFactorChallenge, TwoFactorExpiredError, TwoFactorManager, TwoFactorMechanism, type TwoFactorMethod, TwoFactorNotSetupError, TwoFactorSetupIncompleteError, type TwoFactorSetupResult, type TwoFactorToken, type UserIdentifier, UserInactiveError, UserNotFoundError, UserNotLoggedInError, addRoleForUserBy, addRoleToUser, authFunctions, authenticateRequest, changePasswordForUserBy, cleanupExpiredTokens, confirmResetPassword, createAuthContext, createAuthMiddleware, createAuthTables, createUser, deleteUserBy, dropAuthTables, forceLogoutForUserBy, getAuthTableStats, getUserRoles, hasRoleForUserBy, initiatePasswordResetForUserBy, isValidEmail, register, removeRoleForUserBy, removeRoleFromUser, resetPassword, setStatusForUserBy, setUserRoles, userExistsByEmail, validateEmail };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Request, Response, NextFunction } from 'express';
2
2
  import { Pool } from 'pg';
3
+ import { IncomingMessage } from 'http';
3
4
 
4
5
  interface OAuthProviderConfig {
5
6
  clientId: string;
@@ -55,6 +56,7 @@ interface AuthConfig {
55
56
  google?: GoogleProviderConfig;
56
57
  azure?: AzureProviderConfig;
57
58
  };
59
+ githubUserAgent?: string;
58
60
  twoFactor?: {
59
61
  enabled?: boolean;
60
62
  requireForOAuth?: boolean;
@@ -118,6 +120,10 @@ interface AuthRemember {
118
120
  token: string;
119
121
  expires: Date;
120
122
  }
123
+ interface AuthenticateRequestResult {
124
+ account: AuthAccount | null;
125
+ source: "session" | "remember" | null;
126
+ }
121
127
  interface AuthReset {
122
128
  id: number;
123
129
  account_id: number;
@@ -598,6 +604,7 @@ interface AuthContext {
598
604
  }
599
605
  declare function createAuthContext(config: AuthConfig): AuthContext;
600
606
 
607
+ declare function authenticateRequest(config: AuthConfig, req: IncomingMessage, sessionMiddleware?: (req: any, res: any, next: () => void) => void): Promise<AuthenticateRequestResult>;
601
608
  declare function createUser(config: AuthConfig, credentials: {
602
609
  email: string;
603
610
  password: string;
@@ -653,6 +660,7 @@ declare function forceLogoutForUserBy(config: AuthConfig, identifier: {
653
660
  }>;
654
661
 
655
662
  declare const authFunctions_addRoleForUserBy: typeof addRoleForUserBy;
663
+ declare const authFunctions_authenticateRequest: typeof authenticateRequest;
656
664
  declare const authFunctions_changePasswordForUserBy: typeof changePasswordForUserBy;
657
665
  declare const authFunctions_confirmResetPassword: typeof confirmResetPassword;
658
666
  declare const authFunctions_createUser: typeof createUser;
@@ -666,7 +674,7 @@ declare const authFunctions_resetPassword: typeof resetPassword;
666
674
  declare const authFunctions_setStatusForUserBy: typeof setStatusForUserBy;
667
675
  declare const authFunctions_userExistsByEmail: typeof userExistsByEmail;
668
676
  declare namespace authFunctions {
669
- export { authFunctions_addRoleForUserBy as addRoleForUserBy, authFunctions_changePasswordForUserBy as changePasswordForUserBy, authFunctions_confirmResetPassword as confirmResetPassword, authFunctions_createUser as createUser, authFunctions_deleteUserBy as deleteUserBy, authFunctions_forceLogoutForUserBy as forceLogoutForUserBy, authFunctions_hasRoleForUserBy as hasRoleForUserBy, authFunctions_initiatePasswordResetForUserBy as initiatePasswordResetForUserBy, authFunctions_register as register, authFunctions_removeRoleForUserBy as removeRoleForUserBy, authFunctions_resetPassword as resetPassword, authFunctions_setStatusForUserBy as setStatusForUserBy, authFunctions_userExistsByEmail as userExistsByEmail };
677
+ export { authFunctions_addRoleForUserBy as addRoleForUserBy, authFunctions_authenticateRequest as authenticateRequest, authFunctions_changePasswordForUserBy as changePasswordForUserBy, authFunctions_confirmResetPassword as confirmResetPassword, authFunctions_createUser as createUser, authFunctions_deleteUserBy as deleteUserBy, authFunctions_forceLogoutForUserBy as forceLogoutForUserBy, authFunctions_hasRoleForUserBy as hasRoleForUserBy, authFunctions_initiatePasswordResetForUserBy as initiatePasswordResetForUserBy, authFunctions_register as register, authFunctions_removeRoleForUserBy as removeRoleForUserBy, authFunctions_resetPassword as resetPassword, authFunctions_setStatusForUserBy as setStatusForUserBy, authFunctions_userExistsByEmail as userExistsByEmail };
670
678
  }
671
679
 
672
680
  type UserIdentifier = {
@@ -1167,7 +1175,7 @@ declare abstract class BaseOAuthProvider implements OAuthProvider {
1167
1175
  protected processOAuthLogin(userData: OAuthUserData, req: Request): Promise<OAuthCallbackResult>;
1168
1176
  protected abstract getProviderName(): string;
1169
1177
  protected exchangeCodeForToken(code: string, tokenUrl: string): Promise<string>;
1170
- protected fetchUserFromAPI(accessToken: string, apiUrl: string): Promise<any>;
1178
+ protected fetchUserFromAPI(accessToken: string, apiUrl: string, headers?: Record<string, string>): Promise<any>;
1171
1179
  }
1172
1180
 
1173
1181
  declare class GitHubProvider extends BaseOAuthProvider {
@@ -1192,4 +1200,4 @@ declare class AzureProvider extends BaseOAuthProvider {
1192
1200
  protected exchangeCodeForToken(code: string, tokenUrl: string): Promise<string>;
1193
1201
  }
1194
1202
 
1195
- export { ActivityLogger, type AuthAccount, type AuthActivity, AuthActivityAction, type AuthActivityActionType, type AuthConfig, type AuthConfirmation, type AuthContext, AuthError, type AuthManager$1 as AuthManager, type AuthProvider, type AuthRemember, type AuthReset, AuthRole, type AuthSession, AuthStatus, AzureProvider, type AzureProviderConfig, BaseOAuthProvider, ConfirmationExpiredError, ConfirmationNotFoundError, EmailNotVerifiedError, EmailTakenError, GitHubProvider, type GitHubProviderConfig, GoogleProvider, type GoogleProviderConfig, InvalidBackupCodeError, InvalidEmailError, InvalidPasswordError, InvalidTokenError, InvalidTwoFactorCodeError, type OAuthCallbackResult, type OAuthProvider, type OAuthProviderConfig, type OAuthUserData, OtpProvider, ResetDisabledError, ResetExpiredError, ResetNotFoundError, SecondFactorRequiredError, type TokenCallback, TooManyResetsError, TotpProvider, TwoFactorAlreadyEnabledError, type TwoFactorChallenge, TwoFactorExpiredError, TwoFactorManager, TwoFactorMechanism, type TwoFactorMethod, TwoFactorNotSetupError, TwoFactorSetupIncompleteError, type TwoFactorSetupResult, type TwoFactorToken, type UserIdentifier, UserInactiveError, UserNotFoundError, UserNotLoggedInError, addRoleForUserBy, addRoleToUser, authFunctions, changePasswordForUserBy, cleanupExpiredTokens, confirmResetPassword, createAuthContext, createAuthMiddleware, createAuthTables, createUser, deleteUserBy, dropAuthTables, forceLogoutForUserBy, getAuthTableStats, getUserRoles, hasRoleForUserBy, initiatePasswordResetForUserBy, isValidEmail, register, removeRoleForUserBy, removeRoleFromUser, resetPassword, setStatusForUserBy, setUserRoles, userExistsByEmail, validateEmail };
1203
+ export { ActivityLogger, type AuthAccount, type AuthActivity, AuthActivityAction, type AuthActivityActionType, type AuthConfig, type AuthConfirmation, type AuthContext, AuthError, type AuthManager$1 as AuthManager, type AuthProvider, type AuthRemember, type AuthReset, AuthRole, type AuthSession, AuthStatus, type AuthenticateRequestResult, AzureProvider, type AzureProviderConfig, BaseOAuthProvider, ConfirmationExpiredError, ConfirmationNotFoundError, EmailNotVerifiedError, EmailTakenError, GitHubProvider, type GitHubProviderConfig, GoogleProvider, type GoogleProviderConfig, InvalidBackupCodeError, InvalidEmailError, InvalidPasswordError, InvalidTokenError, InvalidTwoFactorCodeError, type OAuthCallbackResult, type OAuthProvider, type OAuthProviderConfig, type OAuthUserData, OtpProvider, ResetDisabledError, ResetExpiredError, ResetNotFoundError, SecondFactorRequiredError, type TokenCallback, TooManyResetsError, TotpProvider, TwoFactorAlreadyEnabledError, type TwoFactorChallenge, TwoFactorExpiredError, TwoFactorManager, TwoFactorMechanism, type TwoFactorMethod, TwoFactorNotSetupError, TwoFactorSetupIncompleteError, type TwoFactorSetupResult, type TwoFactorToken, type UserIdentifier, UserInactiveError, UserNotFoundError, UserNotLoggedInError, addRoleForUserBy, addRoleToUser, authFunctions, authenticateRequest, changePasswordForUserBy, cleanupExpiredTokens, confirmResetPassword, createAuthContext, createAuthMiddleware, createAuthTables, createUser, deleteUserBy, dropAuthTables, forceLogoutForUserBy, getAuthTableStats, getUserRoles, hasRoleForUserBy, initiatePasswordResetForUserBy, isValidEmail, register, removeRoleForUserBy, removeRoleFromUser, resetPassword, setStatusForUserBy, setUserRoles, userExistsByEmail, validateEmail };
package/dist/index.js CHANGED
@@ -696,11 +696,12 @@ var BaseOAuthProvider = class {
696
696
  }
697
697
  return data.access_token;
698
698
  }
699
- async fetchUserFromAPI(accessToken, apiUrl) {
699
+ async fetchUserFromAPI(accessToken, apiUrl, headers = {}) {
700
700
  const response = await fetch(apiUrl, {
701
701
  headers: {
702
702
  Authorization: `Bearer ${accessToken}`,
703
- Accept: "application/json"
703
+ Accept: "application/json",
704
+ ...headers
704
705
  }
705
706
  });
706
707
  if (!response.ok) {
@@ -731,14 +732,24 @@ var GitHubProvider = class extends BaseOAuthProvider {
731
732
  throw new Error("No authorization code provided");
732
733
  }
733
734
  const accessToken = await this.exchangeCodeForToken(code, "https://github.com/login/oauth/access_token");
734
- const [user, emails] = await Promise.all([this.fetchUserFromAPI(accessToken, "https://api.github.com/user"), this.fetchUserFromAPI(accessToken, "https://api.github.com/user/emails")]);
735
- const primaryEmail = Array.isArray(emails) ? emails.find((email) => email.primary)?.email : null;
736
- if (!primaryEmail) {
737
- throw new Error("No primary email found in GitHub account");
735
+ const apiHeaders = {
736
+ Accept: "application/vnd.github+json",
737
+ "User-Agent": this.authConfig.githubUserAgent || "EasyAccess",
738
+ "X-GitHub-Api-Version": "2022-11-28"
739
+ };
740
+ const [user, emails] = await Promise.all([
741
+ this.fetchUserFromAPI(accessToken, "https://api.github.com/user", apiHeaders),
742
+ this.fetchUserFromAPI(accessToken, "https://api.github.com/user/emails", apiHeaders)
743
+ ]);
744
+ const verifiedEmails = Array.isArray(emails) ? emails.filter((email) => email.verified) : [];
745
+ const primaryEmail = verifiedEmails.find((email) => email.primary)?.email;
746
+ const fallbackEmail = primaryEmail || verifiedEmails[0]?.email;
747
+ if (!fallbackEmail) {
748
+ throw new Error("No verified email found in GitHub account");
738
749
  }
739
750
  return {
740
751
  id: user.id.toString(),
741
- email: primaryEmail,
752
+ email: fallbackEmail,
742
753
  username: user.login,
743
754
  name: user.name || user.login,
744
755
  avatar: user.avatar_url
@@ -1371,6 +1382,7 @@ var TwoFactorManager = class {
1371
1382
  var auth_functions_exports = {};
1372
1383
  __export(auth_functions_exports, {
1373
1384
  addRoleForUserBy: () => addRoleForUserBy,
1385
+ authenticateRequest: () => authenticateRequest,
1374
1386
  changePasswordForUserBy: () => changePasswordForUserBy,
1375
1387
  confirmResetPassword: () => confirmResetPassword,
1376
1388
  createUser: () => createUser,
@@ -1386,6 +1398,48 @@ __export(auth_functions_exports, {
1386
1398
  });
1387
1399
  import { hash as hash3 } from "@prsm/hash";
1388
1400
  import ms2 from "@prsm/ms";
1401
+ function parseCookies(cookieHeader) {
1402
+ const cookies = {};
1403
+ if (!cookieHeader) return cookies;
1404
+ for (const pair of cookieHeader.split(";")) {
1405
+ const idx = pair.indexOf("=");
1406
+ if (idx === -1) continue;
1407
+ const key = pair.slice(0, idx).trim();
1408
+ const value = pair.slice(idx + 1).trim();
1409
+ if (key) cookies[key] = decodeURIComponent(value);
1410
+ }
1411
+ return cookies;
1412
+ }
1413
+ async function authenticateRequest(config, req, sessionMiddleware) {
1414
+ const queries = new AuthQueries(config);
1415
+ if (sessionMiddleware) {
1416
+ await new Promise((resolve) => {
1417
+ sessionMiddleware(req, {}, resolve);
1418
+ });
1419
+ }
1420
+ const session = req.session;
1421
+ if (session?.auth?.loggedIn && session.auth.accountId) {
1422
+ const account2 = await queries.findAccountById(session.auth.accountId);
1423
+ if (account2 && account2.status === AuthStatus.Normal) {
1424
+ return { account: account2, source: "session" };
1425
+ }
1426
+ }
1427
+ const cookies = parseCookies(req.headers.cookie || "");
1428
+ const cookieName = config.rememberCookieName || "remember_token";
1429
+ const token = cookies[cookieName];
1430
+ if (!token) {
1431
+ return { account: null, source: null };
1432
+ }
1433
+ const remember = await queries.findRememberToken(token);
1434
+ if (!remember || /* @__PURE__ */ new Date() > remember.expires) {
1435
+ return { account: null, source: null };
1436
+ }
1437
+ const account = await queries.findAccountById(remember.account_id);
1438
+ if (!account || account.status !== AuthStatus.Normal) {
1439
+ return { account: null, source: null };
1440
+ }
1441
+ return { account, source: "remember" };
1442
+ }
1389
1443
  function validatePassword(password, config) {
1390
1444
  const minLength = config.minPasswordLength || 8;
1391
1445
  const maxLength = config.maxPasswordLength || 64;
@@ -2704,6 +2758,7 @@ export {
2704
2758
  addRoleForUserBy,
2705
2759
  addRoleToUser,
2706
2760
  auth_functions_exports as authFunctions,
2761
+ authenticateRequest,
2707
2762
  changePasswordForUserBy,
2708
2763
  cleanupExpiredTokens,
2709
2764
  confirmResetPassword,