@oxyhq/services 5.9.3 → 5.9.5

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.
@@ -154,6 +154,187 @@ class OxyServices {
154
154
  throw this.handleError(error);
155
155
  }
156
156
  }
157
+
158
+ /**
159
+ * Simple Express.js authentication middleware
160
+ *
161
+ * Built-in authentication middleware that validates JWT tokens and adds user data to requests.
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * // Basic usage - just add it to your routes
166
+ * app.use('/api/protected', oxyServices.auth());
167
+ *
168
+ * // With debug logging
169
+ * app.use('/api/protected', oxyServices.auth({ debug: true }));
170
+ *
171
+ * // With custom error handling
172
+ * app.use('/api/protected', oxyServices.auth({
173
+ * onError: (error) => console.error('Auth failed:', error)
174
+ * }));
175
+ *
176
+ * // Load full user data
177
+ * app.use('/api/protected', oxyServices.auth({ loadUser: true }));
178
+ * ```
179
+ *
180
+ * @param options Optional configuration
181
+ * @param options.debug Enable debug logging (default: false)
182
+ * @param options.onError Custom error handler
183
+ * @param options.loadUser Load full user data (default: false for performance)
184
+ * @param options.session Use session-based validation (default: false)
185
+ * @returns Express middleware function
186
+ */
187
+ auth(options = {}) {
188
+ const {
189
+ debug = false,
190
+ onError,
191
+ loadUser = false,
192
+ session = false
193
+ } = options;
194
+ return (req, res, next) => {
195
+ try {
196
+ // Extract token from Authorization header
197
+ const authHeader = req.headers['authorization'];
198
+ const token = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
199
+ if (debug) {
200
+ console.log(`🔐 Auth: Processing ${req.method} ${req.path}`);
201
+ console.log(`🔐 Auth: Token present: ${!!token}`);
202
+ }
203
+ if (!token) {
204
+ const error = {
205
+ message: 'Access token required',
206
+ code: 'MISSING_TOKEN',
207
+ status: 401
208
+ };
209
+ if (debug) console.log(`❌ Auth: Missing token`);
210
+ if (onError) return onError(error);
211
+ return res.status(401).json(error);
212
+ }
213
+
214
+ // Decode and validate token
215
+ let decoded;
216
+ try {
217
+ decoded = (0, _jwtDecode.jwtDecode)(token);
218
+ if (debug) {
219
+ console.log(`🔐 Auth: Token decoded, User ID: ${decoded.userId || decoded.id}`);
220
+ }
221
+ } catch (decodeError) {
222
+ const error = {
223
+ message: 'Invalid token format',
224
+ code: 'INVALID_TOKEN_FORMAT',
225
+ status: 403
226
+ };
227
+ if (debug) console.log(`❌ Auth: Token decode failed`);
228
+ if (onError) return onError(error);
229
+ return res.status(403).json(error);
230
+ }
231
+ const userId = decoded.userId || decoded.id;
232
+ if (!userId) {
233
+ const error = {
234
+ message: 'Token missing user ID',
235
+ code: 'INVALID_TOKEN_PAYLOAD',
236
+ status: 403
237
+ };
238
+ if (debug) console.log(`❌ Auth: Token missing user ID`);
239
+ if (onError) return onError(error);
240
+ return res.status(403).json(error);
241
+ }
242
+
243
+ // Check token expiration
244
+ if (decoded.exp && decoded.exp < Math.floor(Date.now() / 1000)) {
245
+ const error = {
246
+ message: 'Token expired',
247
+ code: 'TOKEN_EXPIRED',
248
+ status: 403
249
+ };
250
+ if (debug) console.log(`❌ Auth: Token expired`);
251
+ if (onError) return onError(error);
252
+ return res.status(403).json(error);
253
+ }
254
+
255
+ // Session-based validation if requested
256
+ if (session && decoded.sessionId) {
257
+ if (debug) console.log(`🔐 Auth: Validating session ${decoded.sessionId}`);
258
+ this.client.get(`/session/validate/${decoded.sessionId}`).then(sessionRes => {
259
+ const sessionData = sessionRes.data;
260
+ if (!sessionData.valid) {
261
+ const error = {
262
+ message: 'Invalid session',
263
+ code: 'INVALID_SESSION',
264
+ status: 403
265
+ };
266
+ if (debug) console.log(`❌ Auth: Session validation failed`);
267
+ if (onError) return onError(error);
268
+ return res.status(403).json(error);
269
+ }
270
+ if (debug) console.log(`✅ Auth: Session validation successful`);
271
+
272
+ // Continue with user data loading
273
+ this.loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError);
274
+ }).catch(sessionError => {
275
+ const error = {
276
+ message: 'Session validation failed',
277
+ code: 'SESSION_VALIDATION_ERROR',
278
+ status: 403
279
+ };
280
+ if (debug) console.log(`❌ Auth: Session validation error`);
281
+ if (onError) return onError(error);
282
+ return res.status(403).json(error);
283
+ });
284
+ return; // Exit early, will continue in promise chain
285
+ }
286
+
287
+ // No session validation needed, continue directly
288
+ this.loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError);
289
+ } catch (error) {
290
+ const apiError = this.handleError(error);
291
+ if (debug) {
292
+ console.log(`❌ Auth: Unexpected error:`, apiError);
293
+ }
294
+ if (onError) return onError(apiError);
295
+ return res.status(apiError.status || 500).json(apiError);
296
+ }
297
+ };
298
+ }
299
+
300
+ /**
301
+ * Helper method to load user data and continue middleware chain
302
+ */
303
+ loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError) {
304
+ // Set request properties
305
+ req.userId = userId;
306
+ req.accessToken = req.headers['authorization']?.substring(7) || null;
307
+
308
+ // Load user data if requested
309
+ if (loadUser) {
310
+ this.client.get(`/users/${userId}`).then(userRes => {
311
+ req.user = userRes.data;
312
+ if (debug) {
313
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
314
+ }
315
+ next();
316
+ }).catch(userError => {
317
+ // If user loading fails, just use minimal user data
318
+ req.user = {
319
+ id: userId
320
+ };
321
+ if (debug) {
322
+ console.log(`⚠️ Auth: Failed to load user data, using minimal data`);
323
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
324
+ }
325
+ next();
326
+ });
327
+ } else {
328
+ // Use minimal user data for performance
329
+ req.user = {
330
+ id: userId
331
+ };
332
+ if (debug) {
333
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
334
+ }
335
+ next();
336
+ }
337
+ }
157
338
  }
158
339
  exports.OxyServices = OxyServices;
159
340
  //# sourceMappingURL=OxyServices.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_axios","_interopRequireDefault","require","_jwtDecode","_errorUtils","e","__esModule","default","OxyServices","accessToken","refreshToken","constructor","config","client","axios","create","baseURL","timeout","setupInterceptors","interceptors","request","use","req","decoded","jwtDecode","currentTime","Math","floor","Date","now","exp","sessionId","res","get","data","refreshError","clearTokens","headers","Authorization","error","getBaseURL","defaults","setTokens","getCurrentUserId","userId","id","hasAccessToken","validate","valid","getClient","handleError","handleHttpError","healthCheck","exports"],"sourceRoot":"../../../src","sources":["core/OxyServices.ts"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,UAAA,GAAAD,OAAA;AAEA,IAAAE,WAAA,GAAAF,OAAA;AAAsD,SAAAD,uBAAAI,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAQtD;AACA;AACA;AACA;AACA;AACA;AACO,MAAMG,WAAW,CAAC;EAEfC,WAAW,GAAkB,IAAI;EACjCC,YAAY,GAAkB,IAAI;;EAE1C;AACF;AACA;AACA;EACEC,WAAWA,CAACC,MAAiB,EAAE;IAC7B,IAAI,CAACC,MAAM,GAAGC,cAAK,CAACC,MAAM,CAAC;MACzBC,OAAO,EAAEJ,MAAM,CAACI,OAAO;MACvBC,OAAO,EAAE,KAAK,CAAC;IACjB,CAAC,CAAC;IAEF,IAAI,CAACC,iBAAiB,CAAC,CAAC;EAC1B;;EAEA;AACF;AACA;EACUA,iBAAiBA,CAAA,EAAS;IAChC;IACA,IAAI,CAACL,MAAM,CAACM,YAAY,CAACC,OAAO,CAACC,GAAG,CAAC,MAAOC,GAA+B,IAAK;MAC9E,IAAI,CAAC,IAAI,CAACb,WAAW,EAAE;QACrB,OAAOa,GAAG;MACZ;;MAEA;MACA,IAAI;QACF,MAAMC,OAAO,GAAG,IAAAC,oBAAS,EAAa,IAAI,CAACf,WAAW,CAAC;QACvD,MAAMgB,WAAW,GAAGC,IAAI,CAACC,KAAK,CAACC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC;;QAEjD;QACA,IAAIN,OAAO,CAACO,GAAG,GAAGL,WAAW,GAAG,EAAE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CAAC,OAAON,KAAK,EAAE;MACd,OAAO,IAAI;IACb;EACF;;EAEA;AACF;AACA;EACUO,cAAcA,CAAA,EAAY;IAChC,OAAO,CAAC,CAAC,IAAI,CAACrC,WAAW;EAC3B;;EAEA;AACF;AACA;EACE,MAAMsC,QAAQA,CAAA,EAAqB;IACjC,IAAI,CAAC,IAAI,CAACD,cAAc,CAAC,CAAC,EAAE;MAC1B,OAAO,KAAK;IACd;IAEA,IAAI;MACF,MAAMd,GAAG,GAAG,MAAM,IAAI,CAACnB,MAAM,CAACoB,GAAG,CAAC,gBAAgB,CAAC;MACnD,OAAOD,GAAG,CAACE,IAAI,CAACc,KAAK,KAAK,IAAI;IAChC,CAAC,CAAC,OAAOT,KAAK,EAAE;MACd,OAAO,KAAK;IACd;EACF;;EAEA;AACF;AACA;EACYU,SAASA,CAAA,EAAkB;IACnC,OAAO,IAAI,CAACpC,MAAM;EACpB;;EAEA;AACF;AACA;EACYqC,WAAWA,CAACX,KAAU,EAAY;IAC1C,OAAO,IAAAY,2BAAe,EAACZ,KAAK,CAAC;EAC/B;;EAEA;AACF;AACA;EACE,MAAMa,WAAWA,CAAA,EAKd;IACD,IAAI;MACF,MAAMpB,GAAG,GAAG,MAAM,IAAI,CAACnB,MAAM,CAACoB,GAAG,CAAC,SAAS,CAAC;MAC5C,OAAOD,GAAG,CAACE,IAAI;IACjB,CAAC,CAAC,OAAOK,KAAK,EAAE;MACd,MAAM,IAAI,CAACW,WAAW,CAACX,KAAK,CAAC;IAC/B;EACF;AACF;AAACc,OAAA,CAAA7C,WAAA,GAAAA,WAAA","ignoreList":[]}
1
+ {"version":3,"names":["_axios","_interopRequireDefault","require","_jwtDecode","_errorUtils","e","__esModule","default","OxyServices","accessToken","refreshToken","constructor","config","client","axios","create","baseURL","timeout","setupInterceptors","interceptors","request","use","req","decoded","jwtDecode","currentTime","Math","floor","Date","now","exp","sessionId","res","get","data","refreshError","clearTokens","headers","Authorization","error","getBaseURL","defaults","setTokens","getCurrentUserId","userId","id","hasAccessToken","validate","valid","getClient","handleError","handleHttpError","healthCheck","auth","options","debug","onError","loadUser","session","next","authHeader","token","startsWith","substring","console","log","method","path","message","code","status","json","decodeError","then","sessionRes","sessionData","loadUserDataAndContinue","catch","sessionError","apiError","userRes","user","userError","exports"],"sourceRoot":"../../../src","sources":["core/OxyServices.ts"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,UAAA,GAAAD,OAAA;AAEA,IAAAE,WAAA,GAAAF,OAAA;AAAsD,SAAAD,uBAAAI,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAQtD;AACA;AACA;AACA;AACA;AACA;AACO,MAAMG,WAAW,CAAC;EAEfC,WAAW,GAAkB,IAAI;EACjCC,YAAY,GAAkB,IAAI;;EAE1C;AACF;AACA;AACA;EACEC,WAAWA,CAACC,MAAiB,EAAE;IAC7B,IAAI,CAACC,MAAM,GAAGC,cAAK,CAACC,MAAM,CAAC;MACzBC,OAAO,EAAEJ,MAAM,CAACI,OAAO;MACvBC,OAAO,EAAE,KAAK,CAAC;IACjB,CAAC,CAAC;IAEF,IAAI,CAACC,iBAAiB,CAAC,CAAC;EAC1B;;EAEA;AACF;AACA;EACUA,iBAAiBA,CAAA,EAAS;IAChC;IACA,IAAI,CAACL,MAAM,CAACM,YAAY,CAACC,OAAO,CAACC,GAAG,CAAC,MAAOC,GAA+B,IAAK;MAC9E,IAAI,CAAC,IAAI,CAACb,WAAW,EAAE;QACrB,OAAOa,GAAG;MACZ;;MAEA;MACA,IAAI;QACF,MAAMC,OAAO,GAAG,IAAAC,oBAAS,EAAa,IAAI,CAACf,WAAW,CAAC;QACvD,MAAMgB,WAAW,GAAGC,IAAI,CAACC,KAAK,CAACC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC;;QAEjD;QACA,IAAIN,OAAO,CAACO,GAAG,G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AAG,CAAC,uDAAuD,CAAC;UACpED,OAAO,CAACC,GAAG,CAAC,8CAA8CrB,MAAM,EAAE,CAAC;QACrE;QAEAe,IAAI,CAAC,CAAC;MACR,CAAC,CAAC;IACN,CAAC,MAAM;MACL;MACArC,GAAG,CAAC2D,IAAI,GAAG;QAAEpC,EAAE,EAAED;MAAO,CAAS;MAEjC,IAAIW,KAAK,EAAE;QACTS,OAAO,CAACC,GAAG,CAAC,8CAA8CrB,MAAM,EAAE,CAAC;MACrE;MAEAe,IAAI,CAAC,CAAC;IACR;EACF;AACF;AAACwB,OAAA,CAAA3E,WAAA,GAAAA,WAAA","ignoreList":[]}
@@ -149,5 +149,186 @@ export class OxyServices {
149
149
  throw this.handleError(error);
150
150
  }
151
151
  }
152
+
153
+ /**
154
+ * Simple Express.js authentication middleware
155
+ *
156
+ * Built-in authentication middleware that validates JWT tokens and adds user data to requests.
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * // Basic usage - just add it to your routes
161
+ * app.use('/api/protected', oxyServices.auth());
162
+ *
163
+ * // With debug logging
164
+ * app.use('/api/protected', oxyServices.auth({ debug: true }));
165
+ *
166
+ * // With custom error handling
167
+ * app.use('/api/protected', oxyServices.auth({
168
+ * onError: (error) => console.error('Auth failed:', error)
169
+ * }));
170
+ *
171
+ * // Load full user data
172
+ * app.use('/api/protected', oxyServices.auth({ loadUser: true }));
173
+ * ```
174
+ *
175
+ * @param options Optional configuration
176
+ * @param options.debug Enable debug logging (default: false)
177
+ * @param options.onError Custom error handler
178
+ * @param options.loadUser Load full user data (default: false for performance)
179
+ * @param options.session Use session-based validation (default: false)
180
+ * @returns Express middleware function
181
+ */
182
+ auth(options = {}) {
183
+ const {
184
+ debug = false,
185
+ onError,
186
+ loadUser = false,
187
+ session = false
188
+ } = options;
189
+ return (req, res, next) => {
190
+ try {
191
+ // Extract token from Authorization header
192
+ const authHeader = req.headers['authorization'];
193
+ const token = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
194
+ if (debug) {
195
+ console.log(`🔐 Auth: Processing ${req.method} ${req.path}`);
196
+ console.log(`🔐 Auth: Token present: ${!!token}`);
197
+ }
198
+ if (!token) {
199
+ const error = {
200
+ message: 'Access token required',
201
+ code: 'MISSING_TOKEN',
202
+ status: 401
203
+ };
204
+ if (debug) console.log(`❌ Auth: Missing token`);
205
+ if (onError) return onError(error);
206
+ return res.status(401).json(error);
207
+ }
208
+
209
+ // Decode and validate token
210
+ let decoded;
211
+ try {
212
+ decoded = jwtDecode(token);
213
+ if (debug) {
214
+ console.log(`🔐 Auth: Token decoded, User ID: ${decoded.userId || decoded.id}`);
215
+ }
216
+ } catch (decodeError) {
217
+ const error = {
218
+ message: 'Invalid token format',
219
+ code: 'INVALID_TOKEN_FORMAT',
220
+ status: 403
221
+ };
222
+ if (debug) console.log(`❌ Auth: Token decode failed`);
223
+ if (onError) return onError(error);
224
+ return res.status(403).json(error);
225
+ }
226
+ const userId = decoded.userId || decoded.id;
227
+ if (!userId) {
228
+ const error = {
229
+ message: 'Token missing user ID',
230
+ code: 'INVALID_TOKEN_PAYLOAD',
231
+ status: 403
232
+ };
233
+ if (debug) console.log(`❌ Auth: Token missing user ID`);
234
+ if (onError) return onError(error);
235
+ return res.status(403).json(error);
236
+ }
237
+
238
+ // Check token expiration
239
+ if (decoded.exp && decoded.exp < Math.floor(Date.now() / 1000)) {
240
+ const error = {
241
+ message: 'Token expired',
242
+ code: 'TOKEN_EXPIRED',
243
+ status: 403
244
+ };
245
+ if (debug) console.log(`❌ Auth: Token expired`);
246
+ if (onError) return onError(error);
247
+ return res.status(403).json(error);
248
+ }
249
+
250
+ // Session-based validation if requested
251
+ if (session && decoded.sessionId) {
252
+ if (debug) console.log(`🔐 Auth: Validating session ${decoded.sessionId}`);
253
+ this.client.get(`/session/validate/${decoded.sessionId}`).then(sessionRes => {
254
+ const sessionData = sessionRes.data;
255
+ if (!sessionData.valid) {
256
+ const error = {
257
+ message: 'Invalid session',
258
+ code: 'INVALID_SESSION',
259
+ status: 403
260
+ };
261
+ if (debug) console.log(`❌ Auth: Session validation failed`);
262
+ if (onError) return onError(error);
263
+ return res.status(403).json(error);
264
+ }
265
+ if (debug) console.log(`✅ Auth: Session validation successful`);
266
+
267
+ // Continue with user data loading
268
+ this.loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError);
269
+ }).catch(sessionError => {
270
+ const error = {
271
+ message: 'Session validation failed',
272
+ code: 'SESSION_VALIDATION_ERROR',
273
+ status: 403
274
+ };
275
+ if (debug) console.log(`❌ Auth: Session validation error`);
276
+ if (onError) return onError(error);
277
+ return res.status(403).json(error);
278
+ });
279
+ return; // Exit early, will continue in promise chain
280
+ }
281
+
282
+ // No session validation needed, continue directly
283
+ this.loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError);
284
+ } catch (error) {
285
+ const apiError = this.handleError(error);
286
+ if (debug) {
287
+ console.log(`❌ Auth: Unexpected error:`, apiError);
288
+ }
289
+ if (onError) return onError(apiError);
290
+ return res.status(apiError.status || 500).json(apiError);
291
+ }
292
+ };
293
+ }
294
+
295
+ /**
296
+ * Helper method to load user data and continue middleware chain
297
+ */
298
+ loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError) {
299
+ // Set request properties
300
+ req.userId = userId;
301
+ req.accessToken = req.headers['authorization']?.substring(7) || null;
302
+
303
+ // Load user data if requested
304
+ if (loadUser) {
305
+ this.client.get(`/users/${userId}`).then(userRes => {
306
+ req.user = userRes.data;
307
+ if (debug) {
308
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
309
+ }
310
+ next();
311
+ }).catch(userError => {
312
+ // If user loading fails, just use minimal user data
313
+ req.user = {
314
+ id: userId
315
+ };
316
+ if (debug) {
317
+ console.log(`⚠️ Auth: Failed to load user data, using minimal data`);
318
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
319
+ }
320
+ next();
321
+ });
322
+ } else {
323
+ // Use minimal user data for performance
324
+ req.user = {
325
+ id: userId
326
+ };
327
+ if (debug) {
328
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
329
+ }
330
+ next();
331
+ }
332
+ }
152
333
  }
153
334
  //# sourceMappingURL=OxyServices.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["axios","jwtDecode","handleHttpError","OxyServices","accessToken","refreshToken","constructor","config","client","create","baseURL","timeout","setupInterceptors","interceptors","request","use","req","decoded","currentTime","Math","floor","Date","now","exp","sessionId","res","get","data","refreshError","clearTokens","headers","Authorization","error","getBaseURL","defaults","setTokens","getCurrentUserId","userId","id","hasAccessToken","validate","valid","getClient","handleError","healthCheck"],"sourceRoot":"../../../src","sources":["core/OxyServices.ts"],"mappings":";;AAAA,OAAOA,KAAK,MAAqD,OAAO;AACxE,SAASC,SAAS,QAAQ,YAAY;AAEtC,SAASC,eAAe,QAAQ,qBAAqB;AAQrD;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,WAAW,CAAC;EAEfC,WAAW,GAAkB,IAAI;EACjCC,YAAY,GAAkB,IAAI;;EAE1C;AACF;AACA;AACA;EACEC,WAAWA,CAACC,MAAiB,EAAE;IAC7B,IAAI,CAACC,MAAM,GAAGR,KAAK,CAACS,MAAM,CAAC;MACzBC,OAAO,EAAEH,MAAM,CAACG,OAAO;MACvBC,OAAO,EAAE,KAAK,CAAC;IACjB,CAAC,CAAC;IAEF,IAAI,CAACC,iBAAiB,CAAC,CAAC;EAC1B;;EAEA;AACF;AACA;EACUA,iBAAiBA,CAAA,EAAS;IAChC;IACA,IAAI,CAACJ,MAAM,CAACK,YAAY,CAACC,OAAO,CAACC,GAAG,CAAC,MAAOC,GAA+B,IAAK;MAC9E,IAAI,CAAC,IAAI,CAACZ,WAAW,EAAE;QACrB,OAAOY,GAAG;MACZ;;MAEA;MACA,IAAI;QACF,MAAMC,OAAO,GAAGhB,SAAS,CAAa,IAAI,CAACG,WAAW,CAAC;QACvD,MAAMc,WAAW,GAAGC,IAAI,CAACC,KAAK,CAACC,IAAI,CAACC,GAAG,CAAC,CAAC,GAA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CAACoB,MAAM,IAAIpB,OAAO,CAACqB,EAAE,IAAI,IAAI;IAC7C,CAAC,CAAC,OAAON,KAAK,EAAE;MACd,OAAO,IAAI;IACb;EACF;;EAEA;AACF;AACA;EACUO,cAAcA,CAAA,EAAY;IAChC,OAAO,CAAC,CAAC,IAAI,CAACnC,WAAW;EAC3B;;EAEA;AACF;AACA;EACE,MAAMoC,QAAQA,CAAA,EAAqB;IACjC,IAAI,CAAC,IAAI,CAACD,cAAc,CAAC,CAAC,EAAE;MAC1B,OAAO,KAAK;IACd;IAEA,IAAI;MACF,MAAMd,GAAG,GAAG,MAAM,IAAI,CAACjB,MAAM,CAACkB,GAAG,CAAC,gBAAgB,CAAC;MACnD,OAAOD,GAAG,CAACE,IAAI,CAACc,KAAK,KAAK,IAAI;IAChC,CAAC,CAAC,OAAOT,KAAK,EAAE;MACd,OAAO,KAAK;IACd;EACF;;EAEA;AACF;AACA;EACYU,SAASA,CAAA,EAAkB;IACnC,OAAO,IAAI,CAAClC,MAAM;EACpB;;EAEA;AACF;AACA;EACYmC,WAAWA,CAACX,KAAU,EAAY;IAC1C,OAAO9B,eAAe,CAAC8B,KAAK,CAAC;EAC/B;;EAEA;AACF;AACA;EACE,MAAMY,WAAWA,CAAA,EAKd;IACD,IAAI;MACF,MAAMnB,GAAG,GAAG,MAAM,IAAI,CAACjB,MAAM,CAACkB,GAAG,CAAC,SAAS,CAAC;MAC5C,OAAOD,GAAG,CAACE,IAAI;IACjB,CAAC,CAAC,OAAOK,KAAK,EAAE;MACd,MAAM,IAAI,CAACW,WAAW,CAACX,KAAK,CAAC;IAC/B;EACF;AACF","ignoreList":[]}
1
+ {"version":3,"names":["axios","jwtDecode","handleHttpError","OxyServices","accessToken","refreshToken","constructor","config","client","create","baseURL","timeout","setupInterceptors","interceptors","request","use","req","decoded","currentTime","Math","floor","Date","now","exp","sessionId","res","get","data","refreshError","clearTokens","headers","Authorization","error","getBaseURL","defaults","setTokens","getCurrentUserId","userId","id","hasAccessToken","validate","valid","getClient","handleError","healthCheck","auth","options","debug","onError","loadUser","session","next","authHeader","token","startsWith","substring","console","log","method","path","message","code","status","json","decodeError","then","sessionRes","sessionData","loadUserDataAndContinue","catch","sessionError","apiError","userRes","user","userError"],"sourceRoot":"../../../src","sources":["core/OxyServices.ts"],"mappings":";;AAAA,OAAOA,KAAK,MAAqD,OAAO;AACxE,SAASC,SAAS,QAAQ,YAAY;AAEtC,SAASC,eAAe,QAAQ,qBAAqB;AAQrD;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,WAAW,CAAC;EAEfC,WAAW,GAAkB,IAAI;EACjCC,YAAY,GAAkB,IAAI;;EAE1C;AACF;AACA;AACA;EACEC,WAAWA,CAACC,MAAiB,EAAE;IAC7B,IAAI,CAACC,MAAM,GAAGR,KAAK,CAACS,MAAM,CAAC;MACzBC,OAAO,EAAEH,MAAM,CAACG,OAAO;MACvBC,OAAO,EAAE,KAAK,CAAC;IACjB,CAAC,CAAC;IAEF,IAAI,CAACC,iBAAiB,CAAC,CAAC;EAC1B;;EAEA;AACF;AACA;EACUA,iBAAiBA,CAAA,EAAS;IAChC;IACA,IAAI,CAACJ,MAAM,CAACK,YAAY,CAACC,OAAO,CAACC,GAAG,CAAC,MAAOC,GAA+B,IAAK;MAC9E,IAAI,CAAC,IAAI,CAACZ,WAAW,EAAE;QACrB,OAAOY,GAAG;MACZ;;MAEA;MACA,IAAI;QACF,MAAMC,OAAO,GAAGhB,SAAS,CAAa,IAAI,CAACG,WAAW,CAAC;QACvD,MAAMc,WAAW,GAAGC,IAAI,CAACC,KAAK,CAACC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC;;QAEjD;QACA,IAAIL,OAAO,CAACM,GAAG,GAAGL,WAAW,GAAG,EAAE,EAAE;UAClC;UACA,IAAID,OAAO,CAACO,SAAS,EAAE;YACrB,IAAI;cACF,MAAMC,GAAG,GAAG,MAAM,IAAI,CAACjB,MAAM,CAACkB,GAAG,CAAC,kBA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,GAAG;QAAEnC,EAAE,EAAED;MAAO,CAAS;MAEjC,IAAIU,KAAK,EAAE;QACTS,OAAO,CAACC,GAAG,CAAC,8CAA8CpB,MAAM,EAAE,CAAC;MACrE;MAEAc,IAAI,CAAC,CAAC;IACR;EACF;AACF","ignoreList":[]}
@@ -60,5 +60,44 @@ export declare class OxyServices {
60
60
  timestamp?: string;
61
61
  [key: string]: any;
62
62
  }>;
63
+ /**
64
+ * Simple Express.js authentication middleware
65
+ *
66
+ * Built-in authentication middleware that validates JWT tokens and adds user data to requests.
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * // Basic usage - just add it to your routes
71
+ * app.use('/api/protected', oxyServices.auth());
72
+ *
73
+ * // With debug logging
74
+ * app.use('/api/protected', oxyServices.auth({ debug: true }));
75
+ *
76
+ * // With custom error handling
77
+ * app.use('/api/protected', oxyServices.auth({
78
+ * onError: (error) => console.error('Auth failed:', error)
79
+ * }));
80
+ *
81
+ * // Load full user data
82
+ * app.use('/api/protected', oxyServices.auth({ loadUser: true }));
83
+ * ```
84
+ *
85
+ * @param options Optional configuration
86
+ * @param options.debug Enable debug logging (default: false)
87
+ * @param options.onError Custom error handler
88
+ * @param options.loadUser Load full user data (default: false for performance)
89
+ * @param options.session Use session-based validation (default: false)
90
+ * @returns Express middleware function
91
+ */
92
+ auth(options?: {
93
+ debug?: boolean;
94
+ onError?: (error: ApiError) => any;
95
+ loadUser?: boolean;
96
+ session?: boolean;
97
+ }): (req: any, res: any, next: any) => any;
98
+ /**
99
+ * Helper method to load user data and continue middleware chain
100
+ */
101
+ private loadUserDataAndContinue;
63
102
  }
64
103
  //# sourceMappingURL=OxyServices.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"OxyServices.d.ts","sourceRoot":"","sources":["../../../src/core/OxyServices.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,aAAa,EAA8B,MAAM,OAAO,CAAC;AAEzE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,sBAAsB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,EAAE,SAAS;IAS7B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAqCzB;;OAEG;IACI,UAAU,IAAI,MAAM;IAI3B;;OAEG;IACI,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,YAAY,GAAE,MAAW,GAAG,IAAI;IAKtE;;OAEG;IACI,WAAW,IAAI,IAAI;IAK1B;;OAEG;IACI,gBAAgB,IAAI,MAAM,GAAG,IAAI;IAaxC;;OAEG;IACH,OAAO,CAAC,cAAc;IAItB;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC;IAalC;;OAEG;IACH,SAAS,CAAC,SAAS,IAAI,aAAa;IAIpC;;OAEG;IACH,SAAS,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,GAAG,QAAQ;IAI3C;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC;QAC3B,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KACnB,CAAC;IASF;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,IAAI,CAAC,OAAO,GAAE;QACZ,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,KAAK,GAAG,CAAC;QACnC,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,OAAO,CAAC,EAAE,OAAO,CAAC;KACd,IAGI,KAAK,GAAG,EAAE,KAAK,GAAG,EAAE,MAAM,GAAG;IAiIvC;;OAEG;IACH,OAAO,CAAC,uBAAuB;CA+ChC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxyhq/services",
3
- "version": "5.9.3",
3
+ "version": "5.9.5",
4
4
  "description": "Reusable OxyHQ module to handle authentication, user management, karma system, device-based session management and more 🚀",
5
5
  "main": "lib/commonjs/index.js",
6
6
  "module": "lib/module/index.js",
@@ -1,6 +1,6 @@
1
1
  import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
2
2
  import { jwtDecode } from 'jwt-decode';
3
- import { OxyConfig, ApiError } from '../models/interfaces';
3
+ import { OxyConfig, ApiError, User } from '../models/interfaces';
4
4
  import { handleHttpError } from '../utils/errorUtils';
5
5
 
6
6
  interface JwtPayload {
@@ -165,4 +165,221 @@ export class OxyServices {
165
165
  throw this.handleError(error);
166
166
  }
167
167
  }
168
+
169
+ /**
170
+ * Simple Express.js authentication middleware
171
+ *
172
+ * Built-in authentication middleware that validates JWT tokens and adds user data to requests.
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * // Basic usage - just add it to your routes
177
+ * app.use('/api/protected', oxyServices.auth());
178
+ *
179
+ * // With debug logging
180
+ * app.use('/api/protected', oxyServices.auth({ debug: true }));
181
+ *
182
+ * // With custom error handling
183
+ * app.use('/api/protected', oxyServices.auth({
184
+ * onError: (error) => console.error('Auth failed:', error)
185
+ * }));
186
+ *
187
+ * // Load full user data
188
+ * app.use('/api/protected', oxyServices.auth({ loadUser: true }));
189
+ * ```
190
+ *
191
+ * @param options Optional configuration
192
+ * @param options.debug Enable debug logging (default: false)
193
+ * @param options.onError Custom error handler
194
+ * @param options.loadUser Load full user data (default: false for performance)
195
+ * @param options.session Use session-based validation (default: false)
196
+ * @returns Express middleware function
197
+ */
198
+ auth(options: {
199
+ debug?: boolean;
200
+ onError?: (error: ApiError) => any;
201
+ loadUser?: boolean;
202
+ session?: boolean;
203
+ } = {}) {
204
+ const { debug = false, onError, loadUser = false, session = false } = options;
205
+
206
+ return (req: any, res: any, next: any) => {
207
+ try {
208
+ // Extract token from Authorization header
209
+ const authHeader = req.headers['authorization'];
210
+ const token = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
211
+
212
+ if (debug) {
213
+ console.log(`🔐 Auth: Processing ${req.method} ${req.path}`);
214
+ console.log(`🔐 Auth: Token present: ${!!token}`);
215
+ }
216
+
217
+ if (!token) {
218
+ const error = {
219
+ message: 'Access token required',
220
+ code: 'MISSING_TOKEN',
221
+ status: 401
222
+ };
223
+
224
+ if (debug) console.log(`❌ Auth: Missing token`);
225
+
226
+ if (onError) return onError(error);
227
+ return res.status(401).json(error);
228
+ }
229
+
230
+ // Decode and validate token
231
+ let decoded: JwtPayload;
232
+ try {
233
+ decoded = jwtDecode<JwtPayload>(token);
234
+
235
+ if (debug) {
236
+ console.log(`🔐 Auth: Token decoded, User ID: ${decoded.userId || decoded.id}`);
237
+ }
238
+ } catch (decodeError) {
239
+ const error = {
240
+ message: 'Invalid token format',
241
+ code: 'INVALID_TOKEN_FORMAT',
242
+ status: 403
243
+ };
244
+
245
+ if (debug) console.log(`❌ Auth: Token decode failed`);
246
+
247
+ if (onError) return onError(error);
248
+ return res.status(403).json(error);
249
+ }
250
+
251
+ const userId = decoded.userId || decoded.id;
252
+ if (!userId) {
253
+ const error = {
254
+ message: 'Token missing user ID',
255
+ code: 'INVALID_TOKEN_PAYLOAD',
256
+ status: 403
257
+ };
258
+
259
+ if (debug) console.log(`❌ Auth: Token missing user ID`);
260
+
261
+ if (onError) return onError(error);
262
+ return res.status(403).json(error);
263
+ }
264
+
265
+ // Check token expiration
266
+ if (decoded.exp && decoded.exp < Math.floor(Date.now() / 1000)) {
267
+ const error = {
268
+ message: 'Token expired',
269
+ code: 'TOKEN_EXPIRED',
270
+ status: 403
271
+ };
272
+
273
+ if (debug) console.log(`❌ Auth: Token expired`);
274
+
275
+ if (onError) return onError(error);
276
+ return res.status(403).json(error);
277
+ }
278
+
279
+ // Session-based validation if requested
280
+ if (session && decoded.sessionId) {
281
+ if (debug) console.log(`🔐 Auth: Validating session ${decoded.sessionId}`);
282
+
283
+ this.client.get(`/session/validate/${decoded.sessionId}`)
284
+ .then(sessionRes => {
285
+ const sessionData = sessionRes.data;
286
+
287
+ if (!sessionData.valid) {
288
+ const error = {
289
+ message: 'Invalid session',
290
+ code: 'INVALID_SESSION',
291
+ status: 403
292
+ };
293
+
294
+ if (debug) console.log(`❌ Auth: Session validation failed`);
295
+
296
+ if (onError) return onError(error);
297
+ return res.status(403).json(error);
298
+ }
299
+
300
+ if (debug) console.log(`✅ Auth: Session validation successful`);
301
+
302
+ // Continue with user data loading
303
+ this.loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError);
304
+ })
305
+ .catch(sessionError => {
306
+ const error = {
307
+ message: 'Session validation failed',
308
+ code: 'SESSION_VALIDATION_ERROR',
309
+ status: 403
310
+ };
311
+
312
+ if (debug) console.log(`❌ Auth: Session validation error`);
313
+
314
+ if (onError) return onError(error);
315
+ return res.status(403).json(error);
316
+ });
317
+ return; // Exit early, will continue in promise chain
318
+ }
319
+
320
+ // No session validation needed, continue directly
321
+ this.loadUserDataAndContinue(req, res, next, userId, loadUser, debug, onError);
322
+ } catch (error) {
323
+ const apiError = this.handleError(error);
324
+
325
+ if (debug) {
326
+ console.log(`❌ Auth: Unexpected error:`, apiError);
327
+ }
328
+
329
+ if (onError) return onError(apiError);
330
+ return res.status(apiError.status || 500).json(apiError);
331
+ }
332
+ };
333
+ }
334
+
335
+ /**
336
+ * Helper method to load user data and continue middleware chain
337
+ */
338
+ private loadUserDataAndContinue(
339
+ req: any,
340
+ res: any,
341
+ next: any,
342
+ userId: string,
343
+ loadUser: boolean,
344
+ debug: boolean,
345
+ onError?: (error: ApiError) => any
346
+ ): void {
347
+ // Set request properties
348
+ req.userId = userId;
349
+ req.accessToken = req.headers['authorization']?.substring(7) || null;
350
+
351
+ // Load user data if requested
352
+ if (loadUser) {
353
+ this.client.get(`/users/${userId}`)
354
+ .then(userRes => {
355
+ req.user = userRes.data;
356
+
357
+ if (debug) {
358
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
359
+ }
360
+
361
+ next();
362
+ })
363
+ .catch(userError => {
364
+ // If user loading fails, just use minimal user data
365
+ req.user = { id: userId } as User;
366
+
367
+ if (debug) {
368
+ console.log(`⚠️ Auth: Failed to load user data, using minimal data`);
369
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
370
+ }
371
+
372
+ next();
373
+ });
374
+ } else {
375
+ // Use minimal user data for performance
376
+ req.user = { id: userId } as User;
377
+
378
+ if (debug) {
379
+ console.log(`✅ Auth: Authentication successful for user ${userId}`);
380
+ }
381
+
382
+ next();
383
+ }
384
+ }
168
385
  }