pico-auth 0.0.27 → 0.0.28

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.
@@ -49,6 +49,6 @@ declare module "core/auth" {
49
49
  export const mfaEnabled: (login: string, userProvider: UserProvider) => Promise<any>;
50
50
  }
51
51
  declare module "pico-auth" {
52
- export { mfaRegister, mfaVerify, mfaEnabled, authenticate } from "core/auth";
53
- export type { UserProvider, ImpersonateProvider, JWTSpecs } from "core/auth";
52
+ export { mfaRegister, mfaVerify, mfaEnabled, authenticate, authenticateWithScratchCard } from "core/auth";
53
+ export type { UserProvider, ImpersonateProvider, JWTSpecs, ScratchCardProvider, BaseUser } from "core/auth";
54
54
  }
@@ -83,6 +83,53 @@ const authenticate = async (login, password, mfaToken, impersonateEntity, userPr
83
83
  throw new Error(`Failed authentication attempt ${login}`);
84
84
  }
85
85
  };
86
+ /**
87
+ * Allows to login using scratch card. As scratch card may provide a different user to log in to
88
+ * it also allows to impersonate someone using scratch card.
89
+ * @param requesterLogin
90
+ * @param cardCode
91
+ * @param userProvider
92
+ * @param scratchCardProvider
93
+ * @param jwtSpecs
94
+ * @returns
95
+ */
96
+ const authenticateWithScratchCard = async (requesterLogin, cardCode, userProvider, scratchCardProvider, jwtSpecs) => {
97
+ let user = await userProvider.getUser(requesterLogin);
98
+ if (user.blocked)
99
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Blocked)`);
100
+ try {
101
+ let targetUser;
102
+ try {
103
+ targetUser = await scratchCardProvider.consume(user, cardCode);
104
+ }
105
+ catch (error) {
106
+ // on any error we assume that it was a failed attempt
107
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Consume Failed)`);
108
+ }
109
+ if (!targetUser)
110
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Consume Failed)`);
111
+ // also check if the target user is not blocked
112
+ if (targetUser.blocked)
113
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Blocked as Target)`);
114
+ // ok so we will use targetUser as a user that will be actually logged in
115
+ // in impersonation scenario targetUser may be different then the user.
116
+ let clearedUser = userProvider.getSafeUser ? await userProvider.getSafeUser(targetUser) : targetUser;
117
+ clearedUser = userProvider.getUserPostAuthenticate ? await userProvider.getUserPostAuthenticate(clearedUser) : clearedUser;
118
+ let jwtSecretKey = jwtSpecs.secretKey;
119
+ let data = {
120
+ time: Date.now(),
121
+ user: clearedUser
122
+ };
123
+ // const token = jwt.sign(data, jwtSecretKey, {expiresIn: process.env.JWT_EXPIRY_TIME});
124
+ const token = jwt.sign(data, jwtSecretKey, { expiresIn: jwtSpecs.expiryTimeMs });
125
+ console.info(`Card authentication success. Requester:${requesterLogin} Target:${targetUser.id}`);
126
+ return token;
127
+ }
128
+ catch (error) {
129
+ // on any error we assume that it was a failed attempt
130
+ throw new Error(`Failed card authentication attempt ${requesterLogin}`);
131
+ }
132
+ };
86
133
  /**
87
134
  * Will prepare user for MFA activation. Next step is to call verify with token generated in MFA app by the user.
88
135
  */
@@ -157,4 +204,4 @@ const mfaEnabled = async (login, userProvider) => {
157
204
  return (mfaInfo === null || mfaInfo === void 0 ? void 0 : mfaInfo.enabled) || false;
158
205
  };
159
206
 
160
- export { authenticate, mfaEnabled, mfaRegister, mfaVerify };
207
+ export { authenticate, authenticateWithScratchCard, mfaEnabled, mfaRegister, mfaVerify };
@@ -1 +1 @@
1
- const speakeasy=require("speakeasy"),qrcode=require("qrcode"),md5=require("md5"),jwt=require("jsonwebtoken"),authenticate=async(e,t,a,r,s,o,i)=>{var n;let c=await s.getUser(e);const l=s.userSecretPath?c[s.userSecretPath]:c.mfa,d=s.userPasswordPath?c[s.userPasswordPath]:c.password;if(null==l?void 0:l.enabled){if(!speakeasy.totp.verify({secret:null===(n=null==l?void 0:l.secret)||void 0===n?void 0:n.actual,encoding:"base32",token:a,window:1}))throw new Error(`Failed authentication attempt ${e} (MFA Enabled)`)}if(c.blocked)throw new Error(`Failed authentication attempt ${e} (Blocked)`);if(md5(t||"")==d){const e=r,t=c;if(e){let a=!1;if(e.startsWith("@")){if(a=a||await o.canImpersonate(c,e),!a)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);await o.impersonateOrg(c,e)}else{const r=await s.getUser(e);if(a=a||await o.canImpersonate(c,e),!a)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);c=r}console.info(`Impersonate success. From: ${t.login} into ${e}`)}let a=i.secretKey,n=s.getSafeUser?await s.getSafeUser(c):c;n=s.getUserPostAuthenticate?await s.getUserPostAuthenticate(n):n;let l={time:Date.now(),user:n};const d=jwt.sign(l,a,{expiresIn:i.expiryTimeMs});return console.log(`Successful login: ${c.id}`),d}throw new Error(`Failed authentication attempt ${e}`)},mfaRegister=async(e,t,a)=>new Promise(async(r,s)=>{let o=await a.getUser(t),i=a.userSecretPath?o[a.userSecretPath]:o.mfa;const n=speakeasy.generateSecret({name:`${e}: ${t}`});if(!i){i={secret:{temp:void 0,actual:void 0},enabled:!1};o[a.userSecretPath?a.userSecretPath:"mfa"]=i}i.secret.temp=n.base32,i.secret.actual=void 0,await a.putUser(o),qrcode.toDataURL(n.otpauth_url,(e,t)=>{if(e)throw new Error("Error generating QR code");r({qr_code:t,secret:n.base32})})}),mfaVerify=async(e,t,a)=>{var r,s;const o=t;let i=await a.getUser(e);const n=a.userSecretPath?i[a.userSecretPath]:i.mfa;return speakeasy.totp.verify({secret:null===(r=null==n?void 0:n.secret)||void 0===r?void 0:r.temp,encoding:"base32",token:o})?(n.secret.actual=null===(s=null==n?void 0:n.secret)||void 0===s?void 0:s.temp,n.enabled=!0,await a.putUser(i),!0):(console.log(`Failed mfa verification for ${e}`),!1)},mfaEnabled=async(e,t)=>{let a=await t.getUser(e);const r=t.userSecretPath?a[t.userSecretPath]:a.mfa;return(null==r?void 0:r.enabled)||!1};export{authenticate,mfaEnabled,mfaRegister,mfaVerify};
1
+ const speakeasy=require("speakeasy"),qrcode=require("qrcode"),md5=require("md5"),jwt=require("jsonwebtoken"),authenticate=async(e,t,a,r,i,o,s)=>{var n;let c=await i.getUser(e);const l=i.userSecretPath?c[i.userSecretPath]:c.mfa,d=i.userPasswordPath?c[i.userPasswordPath]:c.password;if(null==l?void 0:l.enabled){if(!speakeasy.totp.verify({secret:null===(n=null==l?void 0:l.secret)||void 0===n?void 0:n.actual,encoding:"base32",token:a,window:1}))throw new Error(`Failed authentication attempt ${e} (MFA Enabled)`)}if(c.blocked)throw new Error(`Failed authentication attempt ${e} (Blocked)`);if(md5(t||"")==d){const e=r,t=c;if(e){let a=!1;if(e.startsWith("@")){if(a=a||await o.canImpersonate(c,e),!a)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);await o.impersonateOrg(c,e)}else{const r=await i.getUser(e);if(a=a||await o.canImpersonate(c,e),!a)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);c=r}console.info(`Impersonate success. From: ${t.login} into ${e}`)}let a=s.secretKey,n=i.getSafeUser?await i.getSafeUser(c):c;n=i.getUserPostAuthenticate?await i.getUserPostAuthenticate(n):n;let l={time:Date.now(),user:n};const d=jwt.sign(l,a,{expiresIn:s.expiryTimeMs});return console.log(`Successful login: ${c.id}`),d}throw new Error(`Failed authentication attempt ${e}`)},authenticateWithScratchCard=async(e,t,a,r,i)=>{let o=await a.getUser(e);if(o.blocked)throw new Error(`Failed card authentication attempt ${e} (Blocked)`);try{let s;try{s=await r.consume(o,t)}catch(t){throw new Error(`Failed card authentication attempt ${e} (Consume Failed)`)}if(!s)throw new Error(`Failed card authentication attempt ${e} (Consume Failed)`);if(s.blocked)throw new Error(`Failed card authentication attempt ${e} (Blocked as Target)`);let n=a.getSafeUser?await a.getSafeUser(s):s;n=a.getUserPostAuthenticate?await a.getUserPostAuthenticate(n):n;let c=i.secretKey,l={time:Date.now(),user:n};const d=jwt.sign(l,c,{expiresIn:i.expiryTimeMs});return console.info(`Card authentication success. Requester:${e} Target:${s.id}`),d}catch(t){throw new Error(`Failed card authentication attempt ${e}`)}},mfaRegister=async(e,t,a)=>new Promise(async(r,i)=>{let o=await a.getUser(t),s=a.userSecretPath?o[a.userSecretPath]:o.mfa;const n=speakeasy.generateSecret({name:`${e}: ${t}`});if(!s){s={secret:{temp:void 0,actual:void 0},enabled:!1};o[a.userSecretPath?a.userSecretPath:"mfa"]=s}s.secret.temp=n.base32,s.secret.actual=void 0,await a.putUser(o),qrcode.toDataURL(n.otpauth_url,(e,t)=>{if(e)throw new Error("Error generating QR code");r({qr_code:t,secret:n.base32})})}),mfaVerify=async(e,t,a)=>{var r,i;const o=t;let s=await a.getUser(e);const n=a.userSecretPath?s[a.userSecretPath]:s.mfa;return speakeasy.totp.verify({secret:null===(r=null==n?void 0:n.secret)||void 0===r?void 0:r.temp,encoding:"base32",token:o})?(n.secret.actual=null===(i=null==n?void 0:n.secret)||void 0===i?void 0:i.temp,n.enabled=!0,await a.putUser(s),!0):(console.log(`Failed mfa verification for ${e}`),!1)},mfaEnabled=async(e,t)=>{let a=await t.getUser(e);const r=t.userSecretPath?a[t.userSecretPath]:a.mfa;return(null==r?void 0:r.enabled)||!1};export{authenticate,authenticateWithScratchCard,mfaEnabled,mfaRegister,mfaVerify};
@@ -89,6 +89,53 @@
89
89
  throw new Error(`Failed authentication attempt ${login}`);
90
90
  }
91
91
  };
92
+ /**
93
+ * Allows to login using scratch card. As scratch card may provide a different user to log in to
94
+ * it also allows to impersonate someone using scratch card.
95
+ * @param requesterLogin
96
+ * @param cardCode
97
+ * @param userProvider
98
+ * @param scratchCardProvider
99
+ * @param jwtSpecs
100
+ * @returns
101
+ */
102
+ const authenticateWithScratchCard = async (requesterLogin, cardCode, userProvider, scratchCardProvider, jwtSpecs) => {
103
+ let user = await userProvider.getUser(requesterLogin);
104
+ if (user.blocked)
105
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Blocked)`);
106
+ try {
107
+ let targetUser;
108
+ try {
109
+ targetUser = await scratchCardProvider.consume(user, cardCode);
110
+ }
111
+ catch (error) {
112
+ // on any error we assume that it was a failed attempt
113
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Consume Failed)`);
114
+ }
115
+ if (!targetUser)
116
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Consume Failed)`);
117
+ // also check if the target user is not blocked
118
+ if (targetUser.blocked)
119
+ throw new Error(`Failed card authentication attempt ${requesterLogin} (Blocked as Target)`);
120
+ // ok so we will use targetUser as a user that will be actually logged in
121
+ // in impersonation scenario targetUser may be different then the user.
122
+ let clearedUser = userProvider.getSafeUser ? await userProvider.getSafeUser(targetUser) : targetUser;
123
+ clearedUser = userProvider.getUserPostAuthenticate ? await userProvider.getUserPostAuthenticate(clearedUser) : clearedUser;
124
+ let jwtSecretKey = jwtSpecs.secretKey;
125
+ let data = {
126
+ time: Date.now(),
127
+ user: clearedUser
128
+ };
129
+ // const token = jwt.sign(data, jwtSecretKey, {expiresIn: process.env.JWT_EXPIRY_TIME});
130
+ const token = jwt.sign(data, jwtSecretKey, { expiresIn: jwtSpecs.expiryTimeMs });
131
+ console.info(`Card authentication success. Requester:${requesterLogin} Target:${targetUser.id}`);
132
+ return token;
133
+ }
134
+ catch (error) {
135
+ // on any error we assume that it was a failed attempt
136
+ throw new Error(`Failed card authentication attempt ${requesterLogin}`);
137
+ }
138
+ };
92
139
  /**
93
140
  * Will prepare user for MFA activation. Next step is to call verify with token generated in MFA app by the user.
94
141
  */
@@ -164,6 +211,7 @@
164
211
  };
165
212
 
166
213
  exports.authenticate = authenticate;
214
+ exports.authenticateWithScratchCard = authenticateWithScratchCard;
167
215
  exports.mfaEnabled = mfaEnabled;
168
216
  exports.mfaRegister = mfaRegister;
169
217
  exports.mfaVerify = mfaVerify;
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).picoAuth={})}(this,function(e){"use strict";const t=require("speakeasy"),r=require("qrcode"),a=require("md5"),o=require("jsonwebtoken");e.authenticate=async(e,r,i,s,n,c,l)=>{var u;let d=await n.getUser(e);const f=n.userSecretPath?d[n.userSecretPath]:d.mfa,m=n.userPasswordPath?d[n.userPasswordPath]:d.password;if(null==f?void 0:f.enabled){if(!t.totp.verify({secret:null===(u=null==f?void 0:f.secret)||void 0===u?void 0:u.actual,encoding:"base32",token:i,window:1}))throw new Error(`Failed authentication attempt ${e} (MFA Enabled)`)}if(d.blocked)throw new Error(`Failed authentication attempt ${e} (Blocked)`);if(a(r||"")==m){const e=s,t=d;if(e){let r=!1;if(e.startsWith("@")){if(r=r||await c.canImpersonate(d,e),!r)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);await c.impersonateOrg(d,e)}else{const a=await n.getUser(e);if(r=r||await c.canImpersonate(d,e),!r)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);d=a}console.info(`Impersonate success. From: ${t.login} into ${e}`)}let r=l.secretKey,a=n.getSafeUser?await n.getSafeUser(d):d;a=n.getUserPostAuthenticate?await n.getUserPostAuthenticate(a):a;let i={time:Date.now(),user:a};const u=o.sign(i,r,{expiresIn:l.expiryTimeMs});return console.log(`Successful login: ${d.id}`),u}throw new Error(`Failed authentication attempt ${e}`)},e.mfaEnabled=async(e,t)=>{let r=await t.getUser(e);const a=t.userSecretPath?r[t.userSecretPath]:r.mfa;return(null==a?void 0:a.enabled)||!1},e.mfaRegister=async(e,a,o)=>new Promise(async(i,s)=>{let n=await o.getUser(a),c=o.userSecretPath?n[o.userSecretPath]:n.mfa;const l=t.generateSecret({name:`${e}: ${a}`});if(!c){c={secret:{temp:void 0,actual:void 0},enabled:!1};n[o.userSecretPath?o.userSecretPath:"mfa"]=c}c.secret.temp=l.base32,c.secret.actual=void 0,await o.putUser(n),r.toDataURL(l.otpauth_url,(e,t)=>{if(e)throw new Error("Error generating QR code");i({qr_code:t,secret:l.base32})})}),e.mfaVerify=async(e,r,a)=>{var o,i;const s=r;let n=await a.getUser(e);const c=a.userSecretPath?n[a.userSecretPath]:n.mfa;return t.totp.verify({secret:null===(o=null==c?void 0:c.secret)||void 0===o?void 0:o.temp,encoding:"base32",token:s})?(c.secret.actual=null===(i=null==c?void 0:c.secret)||void 0===i?void 0:i.temp,c.enabled=!0,await a.putUser(n),!0):(console.log(`Failed mfa verification for ${e}`),!1)},Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).picoAuth={})}(this,function(e){"use strict";const t=require("speakeasy"),a=require("qrcode"),r=require("md5"),i=require("jsonwebtoken");e.authenticate=async(e,a,o,n,s,c,l)=>{var d;let u=await s.getUser(e);const f=s.userSecretPath?u[s.userSecretPath]:u.mfa,h=s.userPasswordPath?u[s.userPasswordPath]:u.password;if(null==f?void 0:f.enabled){if(!t.totp.verify({secret:null===(d=null==f?void 0:f.secret)||void 0===d?void 0:d.actual,encoding:"base32",token:o,window:1}))throw new Error(`Failed authentication attempt ${e} (MFA Enabled)`)}if(u.blocked)throw new Error(`Failed authentication attempt ${e} (Blocked)`);if(r(a||"")==h){const e=n,t=u;if(e){let a=!1;if(e.startsWith("@")){if(a=a||await c.canImpersonate(u,e),!a)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);await c.impersonateOrg(u,e)}else{const r=await s.getUser(e);if(a=a||await c.canImpersonate(u,e),!a)throw new Error(`Failed impersonate attempt. From: ${t.id} into ${e}`);u=r}console.info(`Impersonate success. From: ${t.login} into ${e}`)}let a=l.secretKey,r=s.getSafeUser?await s.getSafeUser(u):u;r=s.getUserPostAuthenticate?await s.getUserPostAuthenticate(r):r;let o={time:Date.now(),user:r};const d=i.sign(o,a,{expiresIn:l.expiryTimeMs});return console.log(`Successful login: ${u.id}`),d}throw new Error(`Failed authentication attempt ${e}`)},e.authenticateWithScratchCard=async(e,t,a,r,o)=>{let n=await a.getUser(e);if(n.blocked)throw new Error(`Failed card authentication attempt ${e} (Blocked)`);try{let s;try{s=await r.consume(n,t)}catch(t){throw new Error(`Failed card authentication attempt ${e} (Consume Failed)`)}if(!s)throw new Error(`Failed card authentication attempt ${e} (Consume Failed)`);if(s.blocked)throw new Error(`Failed card authentication attempt ${e} (Blocked as Target)`);let c=a.getSafeUser?await a.getSafeUser(s):s;c=a.getUserPostAuthenticate?await a.getUserPostAuthenticate(c):c;let l=o.secretKey,d={time:Date.now(),user:c};const u=i.sign(d,l,{expiresIn:o.expiryTimeMs});return console.info(`Card authentication success. Requester:${e} Target:${s.id}`),u}catch(t){throw new Error(`Failed card authentication attempt ${e}`)}},e.mfaEnabled=async(e,t)=>{let a=await t.getUser(e);const r=t.userSecretPath?a[t.userSecretPath]:a.mfa;return(null==r?void 0:r.enabled)||!1},e.mfaRegister=async(e,r,i)=>new Promise(async(o,n)=>{let s=await i.getUser(r),c=i.userSecretPath?s[i.userSecretPath]:s.mfa;const l=t.generateSecret({name:`${e}: ${r}`});if(!c){c={secret:{temp:void 0,actual:void 0},enabled:!1};s[i.userSecretPath?i.userSecretPath:"mfa"]=c}c.secret.temp=l.base32,c.secret.actual=void 0,await i.putUser(s),a.toDataURL(l.otpauth_url,(e,t)=>{if(e)throw new Error("Error generating QR code");o({qr_code:t,secret:l.base32})})}),e.mfaVerify=async(e,a,r)=>{var i,o;const n=a;let s=await r.getUser(e);const c=r.userSecretPath?s[r.userSecretPath]:s.mfa;return t.totp.verify({secret:null===(i=null==c?void 0:c.secret)||void 0===i?void 0:i.temp,encoding:"base32",token:n})?(c.secret.actual=null===(o=null==c?void 0:c.secret)||void 0===o?void 0:o.temp,c.enabled=!0,await r.putUser(s),!0):(console.log(`Failed mfa verification for ${e}`),!1)},Object.defineProperty(e,"__esModule",{value:!0})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pico-auth",
3
- "version": "0.0.27",
3
+ "version": "0.0.28",
4
4
  "description": "Minimal auth with user/pass, impersonation and mfa authentication",
5
5
  "main": "dist/pico-auth.umd.js",
6
6
  "types": "dist/pico-auth.d.ts",