@oxyhq/core 20.0.0 → 20.1.0

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.
@@ -0,0 +1,746 @@
1
+ /**
2
+ * User-token authentication security regression tests
3
+ *
4
+ * Locks in the fix for the `oxy.auth()` authentication bypass.
5
+ *
6
+ * `auth()` decodes the bearer JWT with `jwtDecode`, which does NOT verify a
7
+ * signature — deliberately, since third-party backends mounting this middleware
8
+ * do not hold the Oxy signing secret. Every claim is therefore attacker
9
+ * controlled, and the middleware previously trusted two of them anyway:
10
+ *
11
+ * 1. **Session-less tokens were trusted outright.** When the payload carried
12
+ * no `sessionId`, the middleware skipped the network entirely and did:
13
+ *
14
+ * req.userId = userId; // straight from the claim
15
+ * req.user = { id: userId } as User;
16
+ *
17
+ * Anyone could authenticate as anyone on every Oxy backend mounting
18
+ * `oxy.auth()` / `createOxyAuthMiddleware()` by hand-rolling a JWT with a
19
+ * `userId` claim, a future `exp`, and a garbage signature. Victim ids are
20
+ * public (`GET /profiles/username/:handle`).
21
+ *
22
+ * 2. **The session path trusted the claimed user id.** `GET
23
+ * /session/validate/:sessionId` is UNAUTHENTICATED and returns whichever
24
+ * user owns the session id it is handed; it does not bind the bearer
25
+ * token. `auth()` then set `req.userId` from the JWT claim rather than
26
+ * from the validated session, so a caller holding ANY live session id —
27
+ * their own, for instance — could pair it with a forged `userId` and be
28
+ * trusted as that user. `authSocket()` already cross-checked this; the
29
+ * HTTP middleware did not.
30
+ *
31
+ * Both are now closed: a user token MUST carry a `sessionId`, and `req.userId`
32
+ * comes off the validated session, never off the token.
33
+ *
34
+ * There is nothing legitimate to preserve on the session-less path: every user
35
+ * access token the Oxy API issues carries a `sessionId`
36
+ * (`packages/api/src/utils/sessionUtils.ts`, `generateSessionTokens`, which is
37
+ * the only user-token mint site — the OAuth code exchange routes through it
38
+ * too). The `pre-authentication token shapes` block below covers the class of
39
+ * signed-but-session-less token that must never resolve to a logged-in
40
+ * identity, using the two shapes the API used to mint before they were removed.
41
+ *
42
+ * These tests exercise a real `OxyServices` instance with `validateSession`
43
+ * stubbed, so the middleware's own logic runs end to end without the network.
44
+ */
45
+
46
+ import crypto from 'node:crypto';
47
+ import { OxyServices } from '../../OxyServices';
48
+ import type { User } from '../../models/interfaces';
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Helpers
52
+ // ---------------------------------------------------------------------------
53
+
54
+ interface UserTokenClaims {
55
+ userId?: unknown;
56
+ id?: unknown;
57
+ sessionId?: unknown;
58
+ exp?: number;
59
+ iat?: number;
60
+ [key: string]: unknown;
61
+ }
62
+
63
+ const b64url = (input: Buffer | string): string => {
64
+ const buf = typeof input === 'string' ? Buffer.from(input, 'utf8') : input;
65
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
66
+ };
67
+
68
+ const ONE_HOUR_FROM_NOW = (): number => Math.floor(Date.now() / 1000) + 3600;
69
+
70
+ /** A JWT whose signature is invented. Structurally valid, cryptographically worthless. */
71
+ const forgeToken = (
72
+ claims: UserTokenClaims,
73
+ signature = 'AAAAcompletely-invented-signature',
74
+ ): string => {
75
+ const header = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
76
+ const payload = b64url(
77
+ JSON.stringify({ iat: Math.floor(Date.now() / 1000), exp: ONE_HOUR_FROM_NOW(), ...claims }),
78
+ );
79
+ return `${header}.${payload}.${signature}`;
80
+ };
81
+
82
+ /** An `alg: none` JWT — the classic unsigned-token attack. */
83
+ const forgeAlgNoneToken = (claims: UserTokenClaims): string => {
84
+ const header = b64url(JSON.stringify({ alg: 'none', typ: 'JWT' }));
85
+ const payload = b64url(
86
+ JSON.stringify({ iat: Math.floor(Date.now() / 1000), exp: ONE_HOUR_FROM_NOW(), ...claims }),
87
+ );
88
+ return `${header}.${payload}.`;
89
+ };
90
+
91
+ /**
92
+ * A genuinely HS256-signed token, byte-identical in shape to what
93
+ * `jsonwebtoken.sign()` produces in the API. The middleware never checks this
94
+ * signature for user tokens — security comes from the session round-trip — but
95
+ * signing the fixtures keeps them honest about what production sends, and
96
+ * proves the refusal is not merely "the signature looked wrong".
97
+ */
98
+ const signToken = (claims: UserTokenClaims, secret: string): string => {
99
+ const header = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
100
+ const payload = b64url(
101
+ JSON.stringify({
102
+ iat: Math.floor(Date.now() / 1000),
103
+ exp: ONE_HOUR_FROM_NOW(),
104
+ type: 'access',
105
+ deviceId: 'device-1',
106
+ ...claims,
107
+ }),
108
+ );
109
+ const signature = crypto
110
+ .createHmac('sha256', secret)
111
+ .update(`${header}.${payload}`)
112
+ .digest('base64')
113
+ .replace(/\+/g, '-')
114
+ .replace(/\//g, '_')
115
+ .replace(/=+$/, '');
116
+ return `${header}.${payload}.${signature}`;
117
+ };
118
+
119
+ interface MockReq {
120
+ method: string;
121
+ path: string;
122
+ headers: Record<string, string>;
123
+ query: Record<string, string>;
124
+ userId?: string | null;
125
+ user?: unknown;
126
+ accessToken?: string;
127
+ sessionId?: string | null;
128
+ serviceApp?: unknown;
129
+ serviceActingAs?: unknown;
130
+ }
131
+
132
+ interface MockRes {
133
+ statusCode: number;
134
+ body: unknown;
135
+ headersSent: boolean;
136
+ status(code: number): MockRes;
137
+ json(body: unknown): MockRes;
138
+ }
139
+
140
+ const makeReq = (overrides: Partial<MockReq> = {}): MockReq => ({
141
+ method: 'GET',
142
+ path: '/api/whoami',
143
+ headers: {},
144
+ query: {},
145
+ ...overrides,
146
+ });
147
+
148
+ const makeRes = (): MockRes => ({
149
+ statusCode: 0,
150
+ body: undefined,
151
+ headersSent: false,
152
+ status(code: number) {
153
+ this.statusCode = code;
154
+ return this;
155
+ },
156
+ json(body: unknown) {
157
+ this.body = body;
158
+ this.headersSent = true;
159
+ return this;
160
+ },
161
+ });
162
+
163
+ /** Run the middleware against the loose Express shape it declares internally. */
164
+ const run = async (
165
+ middleware: ReturnType<OxyServices['auth']>,
166
+ req: MockReq,
167
+ res: MockRes,
168
+ next: jest.Mock,
169
+ ): Promise<void> => {
170
+ await middleware(req as unknown as never, res as unknown as never, next as unknown as never);
171
+ };
172
+
173
+ const VICTIM_ID = '507f1f77bcf86cd799439011';
174
+ const ATTACKER_ID = '507f1f77bcf86cd799439022';
175
+ const ACCESS_TOKEN_SECRET = 'test-access-token-secret-not-production';
176
+
177
+ const asUser = (id: string): User => ({ id }) as User;
178
+
179
+ const validSessionFor = (user: User) => ({
180
+ valid: true as const,
181
+ expiresAt: new Date(Date.now() + 3600_000).toISOString(),
182
+ lastActivity: new Date().toISOString(),
183
+ user,
184
+ });
185
+
186
+ // ---------------------------------------------------------------------------
187
+ // Hole 1 — session-less user tokens must never authenticate
188
+ // ---------------------------------------------------------------------------
189
+
190
+ describe('user tokens without a sessionId are refused', () => {
191
+ let oxy: OxyServices;
192
+ let validateSpy: jest.SpyInstance;
193
+
194
+ beforeEach(() => {
195
+ oxy = new OxyServices({ baseURL: 'http://test.invalid' });
196
+ // Any call here would mean the middleware went to the network on a path
197
+ // that must be decided locally. Assertions below check it never happens.
198
+ validateSpy = jest.spyOn(oxy, 'validateSession');
199
+ });
200
+
201
+ afterEach(() => {
202
+ jest.restoreAllMocks();
203
+ });
204
+
205
+ it('rejects a forged token whose signature is garbage', async () => {
206
+ const req = makeReq({
207
+ headers: { authorization: `Bearer ${forgeToken({ userId: VICTIM_ID })}` },
208
+ });
209
+ const res = makeRes();
210
+ const next = jest.fn();
211
+
212
+ await run(oxy.auth(), req, res, next);
213
+
214
+ expect(next).not.toHaveBeenCalled();
215
+ expect(res.statusCode).toBe(401);
216
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
217
+ expect(req.userId).toBeUndefined();
218
+ expect(req.user).toBeUndefined();
219
+ expect(req.accessToken).toBeUndefined();
220
+ expect(validateSpy).not.toHaveBeenCalled();
221
+ });
222
+
223
+ it('rejects a token with an empty signature segment', async () => {
224
+ const req = makeReq({
225
+ headers: { authorization: `Bearer ${forgeToken({ userId: VICTIM_ID }, '')}` },
226
+ });
227
+ const res = makeRes();
228
+ const next = jest.fn();
229
+
230
+ await run(oxy.auth(), req, res, next);
231
+
232
+ expect(next).not.toHaveBeenCalled();
233
+ expect(res.statusCode).toBe(401);
234
+ expect(req.userId).toBeUndefined();
235
+ });
236
+
237
+ it('rejects an alg:none token', async () => {
238
+ const req = makeReq({
239
+ headers: { authorization: `Bearer ${forgeAlgNoneToken({ userId: VICTIM_ID })}` },
240
+ });
241
+ const res = makeRes();
242
+ const next = jest.fn();
243
+
244
+ await run(oxy.auth(), req, res, next);
245
+
246
+ expect(next).not.toHaveBeenCalled();
247
+ expect(res.statusCode).toBe(401);
248
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
249
+ expect(req.userId).toBeUndefined();
250
+ });
251
+
252
+ it('rejects a session-less token that carries the id claim instead of userId', async () => {
253
+ const req = makeReq({ headers: { authorization: `Bearer ${forgeToken({ id: VICTIM_ID })}` } });
254
+ const res = makeRes();
255
+ const next = jest.fn();
256
+
257
+ await run(oxy.auth(), req, res, next);
258
+
259
+ expect(next).not.toHaveBeenCalled();
260
+ expect(res.statusCode).toBe(401);
261
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
262
+ expect(req.userId).toBeUndefined();
263
+ });
264
+
265
+ it('rejects a genuinely signed session-less token, so the refusal is not about the signature', async () => {
266
+ const token = signToken({ userId: VICTIM_ID }, ACCESS_TOKEN_SECRET);
267
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
268
+ const res = makeRes();
269
+ const next = jest.fn();
270
+
271
+ await run(oxy.auth(), req, res, next);
272
+
273
+ expect(next).not.toHaveBeenCalled();
274
+ expect(res.statusCode).toBe(401);
275
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
276
+ expect(req.userId).toBeUndefined();
277
+ });
278
+
279
+ it('treats a non-string sessionId claim as no session at all', async () => {
280
+ // A decoded payload is attacker-supplied JSON: `sessionId` can be an
281
+ // object, and a truthiness check would have let it through into URL
282
+ // construction.
283
+ const req = makeReq({
284
+ headers: {
285
+ authorization: `Bearer ${forgeToken({ userId: VICTIM_ID, sessionId: { toString: 'x' } })}`,
286
+ },
287
+ });
288
+ const res = makeRes();
289
+ const next = jest.fn();
290
+
291
+ await run(oxy.auth(), req, res, next);
292
+
293
+ expect(next).not.toHaveBeenCalled();
294
+ expect(res.statusCode).toBe(401);
295
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
296
+ expect(validateSpy).not.toHaveBeenCalled();
297
+ });
298
+
299
+ it('treats an empty-string sessionId claim as no session at all', async () => {
300
+ const req = makeReq({
301
+ headers: { authorization: `Bearer ${forgeToken({ userId: VICTIM_ID, sessionId: '' })}` },
302
+ });
303
+ const res = makeRes();
304
+ const next = jest.fn();
305
+
306
+ await run(oxy.auth(), req, res, next);
307
+
308
+ expect(next).not.toHaveBeenCalled();
309
+ expect(res.statusCode).toBe(401);
310
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
311
+ expect(validateSpy).not.toHaveBeenCalled();
312
+ });
313
+
314
+ it('never loads a user profile for a session-less token, even with loadUser', async () => {
315
+ const getCurrentUserSpy = jest.spyOn(oxy, 'getCurrentUser');
316
+ const req = makeReq({
317
+ headers: { authorization: `Bearer ${forgeToken({ userId: VICTIM_ID })}` },
318
+ });
319
+ const res = makeRes();
320
+ const next = jest.fn();
321
+
322
+ await run(oxy.auth({ loadUser: true }), req, res, next);
323
+
324
+ expect(next).not.toHaveBeenCalled();
325
+ expect(res.statusCode).toBe(401);
326
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
327
+ expect(req.userId).toBeUndefined();
328
+ expect(getCurrentUserSpy).not.toHaveBeenCalled();
329
+ });
330
+
331
+ it('treats a session-less token as anonymous under optional auth, never as the claimed user', async () => {
332
+ const req = makeReq({
333
+ headers: { authorization: `Bearer ${forgeToken({ userId: VICTIM_ID })}` },
334
+ });
335
+ const res = makeRes();
336
+ const next = jest.fn();
337
+
338
+ await run(oxy.auth({ optional: true }), req, res, next);
339
+
340
+ expect(next).toHaveBeenCalledTimes(1);
341
+ expect(res.headersSent).toBe(false);
342
+ expect(req.userId).toBeNull();
343
+ expect(req.user).toBeNull();
344
+ expect(req.accessToken).toBeUndefined();
345
+ });
346
+
347
+ it('does not admit a session-less token via the jwtSecret / service-token path', async () => {
348
+ // `jwtSecret` exists to verify SERVICE tokens. A user token must not gain
349
+ // anything by its presence, whether or not it is signed with that secret.
350
+ const token = signToken({ userId: VICTIM_ID }, ACCESS_TOKEN_SECRET);
351
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
352
+ const res = makeRes();
353
+ const next = jest.fn();
354
+
355
+ await run(oxy.auth({ jwtSecret: ACCESS_TOKEN_SECRET }), req, res, next);
356
+
357
+ expect(next).not.toHaveBeenCalled();
358
+ expect(res.statusCode).toBe(401);
359
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
360
+ expect(req.userId).toBeUndefined();
361
+ expect(req.serviceApp).toBeUndefined();
362
+ });
363
+
364
+ it('does not admit a session-less token via the X-Oxy-User-Id delegation header', async () => {
365
+ // Delegation is a SERVICE-token feature. The header must not turn a user
366
+ // token into an acting-as grant, nor reach the grant lookup at all.
367
+ const grantSpy = jest.spyOn(oxy, 'verifyServiceActingAs');
368
+ const req = makeReq({
369
+ headers: {
370
+ authorization: `Bearer ${forgeToken({ userId: ATTACKER_ID })}`,
371
+ 'x-oxy-user-id': VICTIM_ID,
372
+ },
373
+ });
374
+ const res = makeRes();
375
+ const next = jest.fn();
376
+
377
+ await run(oxy.auth({ jwtSecret: ACCESS_TOKEN_SECRET }), req, res, next);
378
+
379
+ expect(next).not.toHaveBeenCalled();
380
+ expect(res.statusCode).toBe(401);
381
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
382
+ expect(req.userId).toBeUndefined();
383
+ expect(req.serviceActingAs).toBeUndefined();
384
+ expect(grantSpy).not.toHaveBeenCalled();
385
+ });
386
+
387
+ it('reports SESSION_REQUIRED through a custom onError handler', async () => {
388
+ const onError = jest.fn();
389
+ const req = makeReq({
390
+ headers: { authorization: `Bearer ${forgeToken({ userId: VICTIM_ID })}` },
391
+ });
392
+ const res = makeRes();
393
+ const next = jest.fn();
394
+
395
+ await run(oxy.auth({ onError }), req, res, next);
396
+
397
+ expect(next).not.toHaveBeenCalled();
398
+ expect(res.headersSent).toBe(false);
399
+ expect(onError).toHaveBeenCalledWith(
400
+ expect.objectContaining({ code: 'SESSION_REQUIRED', status: 401 }),
401
+ );
402
+ });
403
+ });
404
+
405
+ // ---------------------------------------------------------------------------
406
+ // The pre-authentication token class
407
+ // ---------------------------------------------------------------------------
408
+
409
+ describe('pre-authentication token shapes never resolve to a logged-in identity', () => {
410
+ let oxy: OxyServices;
411
+
412
+ beforeEach(() => {
413
+ oxy = new OxyServices({ baseURL: 'http://test.invalid' });
414
+ });
415
+
416
+ afterEach(() => {
417
+ jest.restoreAllMocks();
418
+ });
419
+
420
+ /**
421
+ * These two shapes were minted by `controllers/session.controller.ts` and
422
+ * signed with `ACCESS_TOKEN_SECRET`, carrying `userId` and no `sessionId`.
423
+ * Both were issued BEFORE authentication completed — one between the password
424
+ * step and the second factor, one to a caller proving only that they had
425
+ * received a recovery code — and the old middleware accepted either as the
426
+ * fully signed-in user.
427
+ *
428
+ * The password / 2FA / recovery backend was removed in `8bfdd965`, so neither
429
+ * token exists on `main` today. They stay here as the regression fixtures for
430
+ * the CLASS: any future signed, session-less, pre-authentication token must
431
+ * be refused by construction rather than by nobody happening to mint one.
432
+ */
433
+ it('refuses the 2FA-challenge shape (signed, userId, no sessionId)', async () => {
434
+ const loginToken = signToken(
435
+ { userId: VICTIM_ID, purpose: '2fa_challenge' },
436
+ ACCESS_TOKEN_SECRET,
437
+ );
438
+ const req = makeReq({ headers: { authorization: `Bearer ${loginToken}` } });
439
+ const res = makeRes();
440
+ const next = jest.fn();
441
+
442
+ await run(oxy.auth(), req, res, next);
443
+
444
+ expect(next).not.toHaveBeenCalled();
445
+ expect(res.statusCode).toBe(401);
446
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
447
+ expect(req.userId).toBeUndefined();
448
+ });
449
+
450
+ it('refuses the account-recovery shape (signed, userId, no sessionId)', async () => {
451
+ const recoveryToken = signToken(
452
+ { type: 'recovery', recoveryId: 'rec-1', userId: VICTIM_ID },
453
+ ACCESS_TOKEN_SECRET,
454
+ );
455
+ const req = makeReq({ headers: { authorization: `Bearer ${recoveryToken}` } });
456
+ const res = makeRes();
457
+ const next = jest.fn();
458
+
459
+ await run(oxy.auth(), req, res, next);
460
+
461
+ expect(next).not.toHaveBeenCalled();
462
+ expect(res.statusCode).toBe(401);
463
+ expect(res.body).toMatchObject({ code: 'SESSION_REQUIRED' });
464
+ expect(req.userId).toBeUndefined();
465
+ });
466
+ });
467
+
468
+ // ---------------------------------------------------------------------------
469
+ // Hole 2 — the identity must come from the validated session, not the claim
470
+ // ---------------------------------------------------------------------------
471
+
472
+ describe('session-backed user tokens bind identity to the validated session', () => {
473
+ let oxy: OxyServices;
474
+
475
+ beforeEach(() => {
476
+ oxy = new OxyServices({ baseURL: 'http://test.invalid' });
477
+ });
478
+
479
+ afterEach(() => {
480
+ jest.restoreAllMocks();
481
+ });
482
+
483
+ it('rejects a token pairing a live session with a forged userId claim', async () => {
484
+ // The attacker holds their OWN valid session and swaps the userId claim.
485
+ // `/session/validate/:id` is unauthenticated, so obtaining a live session
486
+ // id is not the hard part — binding it to an identity is.
487
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue(validSessionFor(asUser(ATTACKER_ID)));
488
+
489
+ const token = forgeToken({ userId: VICTIM_ID, sessionId: 'attacker-session' });
490
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
491
+ const res = makeRes();
492
+ const next = jest.fn();
493
+
494
+ await run(oxy.auth(), req, res, next);
495
+
496
+ expect(next).not.toHaveBeenCalled();
497
+ expect(res.statusCode).toBe(401);
498
+ expect(res.body).toMatchObject({ code: 'SESSION_USER_MISMATCH' });
499
+ expect(req.userId).toBeUndefined();
500
+ expect(req.user).toBeUndefined();
501
+ expect(req.accessToken).toBeUndefined();
502
+ });
503
+
504
+ it('rejects a session whose validation returns no user', async () => {
505
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue({
506
+ valid: true,
507
+ expiresAt: new Date(Date.now() + 3600_000).toISOString(),
508
+ lastActivity: new Date().toISOString(),
509
+ } as unknown as Awaited<ReturnType<OxyServices['validateSession']>>);
510
+
511
+ const token = forgeToken({ userId: VICTIM_ID, sessionId: 'session-1' });
512
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
513
+ const res = makeRes();
514
+ const next = jest.fn();
515
+
516
+ await run(oxy.auth(), req, res, next);
517
+
518
+ expect(next).not.toHaveBeenCalled();
519
+ expect(res.statusCode).toBe(401);
520
+ expect(res.body).toMatchObject({ code: 'INVALID_SESSION' });
521
+ expect(req.userId).toBeUndefined();
522
+ });
523
+
524
+ it('rejects a session whose user carries no usable id', async () => {
525
+ jest
526
+ .spyOn(oxy, 'validateSession')
527
+ .mockResolvedValue(validSessionFor({ username: 'ghost' } as unknown as User));
528
+
529
+ const token = forgeToken({ userId: VICTIM_ID, sessionId: 'session-1' });
530
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
531
+ const res = makeRes();
532
+ const next = jest.fn();
533
+
534
+ await run(oxy.auth(), req, res, next);
535
+
536
+ expect(next).not.toHaveBeenCalled();
537
+ expect(res.statusCode).toBe(401);
538
+ expect(res.body).toMatchObject({ code: 'INVALID_SESSION' });
539
+ expect(req.userId).toBeUndefined();
540
+ });
541
+
542
+ it('accepts a matching session and takes the id from the server, not the token', async () => {
543
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue(validSessionFor(asUser(VICTIM_ID)));
544
+
545
+ const token = signToken({ userId: VICTIM_ID, sessionId: 'session-1' }, ACCESS_TOKEN_SECRET);
546
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
547
+ const res = makeRes();
548
+ const next = jest.fn();
549
+
550
+ await run(oxy.auth(), req, res, next);
551
+
552
+ expect(next).toHaveBeenCalledTimes(1);
553
+ expect(res.headersSent).toBe(false);
554
+ expect(req.userId).toBe(VICTIM_ID);
555
+ expect(req.sessionId).toBe('session-1');
556
+ expect(req.accessToken).toBe(token);
557
+ expect(req.user).toEqual({ id: VICTIM_ID });
558
+ });
559
+
560
+ it('accepts a session identified by the raw Mongo _id shape', async () => {
561
+ jest
562
+ .spyOn(oxy, 'validateSession')
563
+ .mockResolvedValue(validSessionFor({ _id: VICTIM_ID } as unknown as User));
564
+
565
+ const token = signToken({ userId: VICTIM_ID, sessionId: 'session-1' }, ACCESS_TOKEN_SECRET);
566
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
567
+ const res = makeRes();
568
+ const next = jest.fn();
569
+
570
+ await run(oxy.auth(), req, res, next);
571
+
572
+ expect(next).toHaveBeenCalledTimes(1);
573
+ expect(req.userId).toBe(VICTIM_ID);
574
+ });
575
+
576
+ it('attaches the full validated profile when loadUser is set, with no extra round-trip', async () => {
577
+ const fullUser = {
578
+ id: VICTIM_ID,
579
+ username: 'victim',
580
+ email: 'victim@example.com',
581
+ } as User;
582
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue(validSessionFor(fullUser));
583
+ const getCurrentUserSpy = jest.spyOn(oxy, 'getCurrentUser');
584
+
585
+ const token = signToken({ userId: VICTIM_ID, sessionId: 'session-1' }, ACCESS_TOKEN_SECRET);
586
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
587
+ const res = makeRes();
588
+ const next = jest.fn();
589
+
590
+ await run(oxy.auth({ loadUser: true }), req, res, next);
591
+
592
+ expect(next).toHaveBeenCalledTimes(1);
593
+ expect(req.user).toEqual(fullUser);
594
+ expect(getCurrentUserSpy).not.toHaveBeenCalled();
595
+ });
596
+
597
+ it('rejects an invalid session', async () => {
598
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue({
599
+ valid: false,
600
+ } as unknown as Awaited<ReturnType<OxyServices['validateSession']>>);
601
+
602
+ const token = signToken({ userId: VICTIM_ID, sessionId: 'revoked' }, ACCESS_TOKEN_SECRET);
603
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
604
+ const res = makeRes();
605
+ const next = jest.fn();
606
+
607
+ await run(oxy.auth(), req, res, next);
608
+
609
+ expect(next).not.toHaveBeenCalled();
610
+ expect(res.statusCode).toBe(401);
611
+ expect(res.body).toMatchObject({ code: 'INVALID_SESSION' });
612
+ });
613
+
614
+ it('rejects when session validation throws', async () => {
615
+ jest.spyOn(oxy, 'validateSession').mockRejectedValue(new Error('session not found'));
616
+
617
+ const token = signToken({ userId: VICTIM_ID, sessionId: 'nope' }, ACCESS_TOKEN_SECRET);
618
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
619
+ const res = makeRes();
620
+ const next = jest.fn();
621
+
622
+ await run(oxy.auth(), req, res, next);
623
+
624
+ expect(next).not.toHaveBeenCalled();
625
+ expect(res.statusCode).toBe(401);
626
+ expect(res.body).toMatchObject({ code: 'SESSION_VALIDATION_ERROR' });
627
+ expect(req.userId).toBeUndefined();
628
+ });
629
+
630
+ it('rejects an expired token before any session round-trip', async () => {
631
+ const validateSpy = jest.spyOn(oxy, 'validateSession');
632
+ const token = forgeToken({
633
+ userId: VICTIM_ID,
634
+ sessionId: 'session-1',
635
+ exp: Math.floor(Date.now() / 1000) - 1,
636
+ });
637
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
638
+ const res = makeRes();
639
+ const next = jest.fn();
640
+
641
+ await run(oxy.auth(), req, res, next);
642
+
643
+ expect(next).not.toHaveBeenCalled();
644
+ expect(res.statusCode).toBe(401);
645
+ expect(res.body).toMatchObject({ code: 'TOKEN_EXPIRED' });
646
+ expect(validateSpy).not.toHaveBeenCalled();
647
+ });
648
+
649
+ it('falls back to anonymous, not to the claim, when optional auth hits a mismatch', async () => {
650
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue(validSessionFor(asUser(ATTACKER_ID)));
651
+
652
+ const token = forgeToken({ userId: VICTIM_ID, sessionId: 'attacker-session' });
653
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
654
+ const res = makeRes();
655
+ const next = jest.fn();
656
+
657
+ await run(oxy.auth({ optional: true }), req, res, next);
658
+
659
+ expect(next).toHaveBeenCalledTimes(1);
660
+ expect(res.headersSent).toBe(false);
661
+ expect(req.userId).toBeNull();
662
+ expect(req.user).toBeNull();
663
+ });
664
+
665
+ it('never logs the token or the decoded payload when refusing a mismatch', async () => {
666
+ // The warn on this path names ids (public) and nothing else.
667
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
668
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue(validSessionFor(asUser(ATTACKER_ID)));
669
+
670
+ const token = forgeToken({ userId: VICTIM_ID, sessionId: 'attacker-session' });
671
+ const req = makeReq({ headers: { authorization: `Bearer ${token}` } });
672
+ const res = makeRes();
673
+ const next = jest.fn();
674
+
675
+ await run(oxy.auth(), req, res, next);
676
+
677
+ const logged = warnSpy.mock.calls.map((call) => JSON.stringify(call)).join('\n');
678
+ expect(logged).not.toContain(token);
679
+ expect(logged).not.toContain('attacker-session');
680
+ });
681
+ });
682
+
683
+ // ---------------------------------------------------------------------------
684
+ // Socket auth keeps the same contract
685
+ // ---------------------------------------------------------------------------
686
+
687
+ describe('authSocket keeps refusing session-less tokens', () => {
688
+ let oxy: OxyServices;
689
+
690
+ beforeEach(() => {
691
+ oxy = new OxyServices({ baseURL: 'http://test.invalid' });
692
+ });
693
+
694
+ afterEach(() => {
695
+ jest.restoreAllMocks();
696
+ });
697
+
698
+ interface MockSocket {
699
+ handshake: { auth: { token?: string } };
700
+ data?: Record<string, unknown>;
701
+ user?: { id: string; userId: string; sessionId?: string | null };
702
+ }
703
+
704
+ const runSocket = async (socket: MockSocket, next: jest.Mock): Promise<void> => {
705
+ await oxy.authSocket()(socket as unknown as never, next as unknown as never);
706
+ };
707
+
708
+ it('refuses a session-less token', async () => {
709
+ const validateSpy = jest.spyOn(oxy, 'validateSession');
710
+ const next = jest.fn();
711
+
712
+ await runSocket({ handshake: { auth: { token: forgeToken({ userId: VICTIM_ID }) } } }, next);
713
+
714
+ expect(next).toHaveBeenCalledWith(expect.objectContaining({ message: 'Session required' }));
715
+ expect(validateSpy).not.toHaveBeenCalled();
716
+ });
717
+
718
+ it('refuses a live session paired with a forged userId claim', async () => {
719
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue(validSessionFor(asUser(ATTACKER_ID)));
720
+ const next = jest.fn();
721
+ const socket: MockSocket = {
722
+ handshake: { auth: { token: forgeToken({ userId: VICTIM_ID, sessionId: 'attacker-session' }) } },
723
+ };
724
+
725
+ await runSocket(socket, next);
726
+
727
+ expect(next).toHaveBeenCalledWith(expect.objectContaining({ message: 'Session user mismatch' }));
728
+ expect(socket.user).toBeUndefined();
729
+ });
730
+
731
+ it('accepts a matching session', async () => {
732
+ jest.spyOn(oxy, 'validateSession').mockResolvedValue(validSessionFor(asUser(VICTIM_ID)));
733
+ const next = jest.fn();
734
+ const socket: MockSocket = {
735
+ handshake: {
736
+ auth: { token: signToken({ userId: VICTIM_ID, sessionId: 'session-1' }, ACCESS_TOKEN_SECRET) },
737
+ },
738
+ };
739
+
740
+ await runSocket(socket, next);
741
+
742
+ expect(next).toHaveBeenCalledWith();
743
+ expect(socket.user).toEqual({ id: VICTIM_ID, userId: VICTIM_ID, sessionId: 'session-1' });
744
+ expect(socket.data?.sessionId).toBe('session-1');
745
+ });
746
+ });