@oxyhq/core 21.0.0 → 21.0.1

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.
Files changed (57) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/HttpService.js +47 -8
  3. package/dist/cjs/i18n/locales/en-US.json +7 -2
  4. package/dist/cjs/i18n/locales/es-ES.json +7 -2
  5. package/dist/cjs/i18n/locales/locales/en-US.json +7 -2
  6. package/dist/cjs/i18n/locales/locales/es-ES.json +7 -2
  7. package/dist/cjs/index.js +8 -1
  8. package/dist/cjs/inference/OxyInferenceClient.js +330 -0
  9. package/dist/cjs/mixins/OxyServices.accounts.js +5 -72
  10. package/dist/cjs/mixins/OxyServices.inference.js +59 -0
  11. package/dist/cjs/mixins/OxyServices.utility.js +18 -6
  12. package/dist/cjs/mixins/index.js +6 -0
  13. package/dist/cjs/server/auth.js +76 -0
  14. package/dist/cjs/server/index.js +5 -1
  15. package/dist/esm/.tsbuildinfo +1 -1
  16. package/dist/esm/HttpService.js +47 -8
  17. package/dist/esm/i18n/locales/en-US.json +7 -2
  18. package/dist/esm/i18n/locales/es-ES.json +7 -2
  19. package/dist/esm/i18n/locales/locales/en-US.json +7 -2
  20. package/dist/esm/i18n/locales/locales/es-ES.json +7 -2
  21. package/dist/esm/index.js +4 -0
  22. package/dist/esm/inference/OxyInferenceClient.js +325 -0
  23. package/dist/esm/mixins/OxyServices.accounts.js +5 -72
  24. package/dist/esm/mixins/OxyServices.inference.js +56 -0
  25. package/dist/esm/mixins/OxyServices.utility.js +18 -6
  26. package/dist/esm/mixins/index.js +6 -0
  27. package/dist/esm/server/auth.js +72 -0
  28. package/dist/esm/server/index.js +1 -1
  29. package/dist/types/.tsbuildinfo +1 -1
  30. package/dist/types/HttpService.d.ts +39 -1
  31. package/dist/types/index.d.ts +3 -1
  32. package/dist/types/inference/OxyInferenceClient.d.ts +324 -0
  33. package/dist/types/mixins/OxyServices.accounts.d.ts +73 -95
  34. package/dist/types/mixins/OxyServices.inference.d.ts +95 -0
  35. package/dist/types/mixins/OxyServices.utility.d.ts +44 -13
  36. package/dist/types/mixins/index.d.ts +2 -1
  37. package/dist/types/server/auth.d.ts +80 -0
  38. package/dist/types/server/index.d.ts +2 -2
  39. package/package.json +2 -2
  40. package/src/HttpService.ts +50 -10
  41. package/src/__tests__/httpServiceUnwrapEnvelope.test.ts +115 -0
  42. package/src/i18n/locales/en-US.json +7 -2
  43. package/src/i18n/locales/es-ES.json +7 -2
  44. package/src/index.ts +19 -7
  45. package/src/inference/OxyInferenceClient.ts +590 -0
  46. package/src/inference/__tests__/OxyInferenceClient.test.ts +383 -0
  47. package/src/mixins/OxyServices.accounts.ts +75 -176
  48. package/src/mixins/OxyServices.inference.ts +57 -0
  49. package/src/mixins/OxyServices.utility.ts +58 -14
  50. package/src/mixins/__tests__/accounts.test.ts +57 -102
  51. package/src/mixins/__tests__/inferenceFactory.test.ts +58 -0
  52. package/src/mixins/__tests__/serviceAuth.test.ts +2 -0
  53. package/src/mixins/index.ts +8 -0
  54. package/src/server/__tests__/serviceTokenAttribution.test.ts +396 -0
  55. package/src/server/auth.ts +118 -0
  56. package/src/server/index.ts +6 -0
  57. package/src/session/__tests__/accountDialogShape.test.ts +118 -0
@@ -17,9 +17,6 @@ import type { User } from '../../models/interfaces';
17
17
  import type {
18
18
  AccountNode,
19
19
  AccountMember,
20
- AccountCredential,
21
- AccountCredentialWithSecret,
22
- RotateAccountCredentialResult,
23
20
  Application,
24
21
  ApplicationCredential,
25
22
  ApplicationCredentialWithSecret,
@@ -62,20 +59,6 @@ const accountNodeFixture: AccountNode = {
62
59
  childCount: 2,
63
60
  };
64
61
 
65
- const credentialFixture: AccountCredential = {
66
- _id: 'cred1',
67
- accountId: 'acc1',
68
- name: 'bot-prod',
69
- publicKey: 'oxy_dk_abc',
70
- type: 'service',
71
- environment: 'production',
72
- scopes: ['user:read'],
73
- status: 'active',
74
- createdByUserId: 'u1',
75
- createdAt: '2026-06-29T00:00:00.000Z',
76
- updatedAt: '2026-06-29T00:00:00.000Z',
77
- };
78
-
79
62
  const appFixture: Application = {
80
63
  _id: 'app1',
81
64
  name: 'Mention',
@@ -476,91 +459,6 @@ describe('OxyServices.accounts', () => {
476
459
  });
477
460
  });
478
461
 
479
- describe('listAccountCredentials', () => {
480
- it('unwraps the `credentials` array and caches the read', async () => {
481
- makeRequestSpy.mockResolvedValue({ credentials: [credentialFixture] });
482
-
483
- const result = await oxy.listAccountCredentials('acc1');
484
-
485
- expect(result).toEqual([credentialFixture]);
486
- expect(makeRequestSpy).toHaveBeenCalledWith(
487
- 'GET',
488
- '/accounts/acc1/credentials',
489
- undefined,
490
- expect.objectContaining({ cache: true }),
491
- );
492
- });
493
-
494
- it('returns an empty array when `credentials` is absent', async () => {
495
- makeRequestSpy.mockResolvedValue({});
496
- expect(await oxy.listAccountCredentials('acc1')).toEqual([]);
497
- });
498
- });
499
-
500
- describe('createAccountCredential', () => {
501
- it('posts the config, returns the secret result, and busts the credentials cache', async () => {
502
- const created: AccountCredentialWithSecret = {
503
- credential: credentialFixture,
504
- secret: 'sk_once',
505
- };
506
- makeRequestSpy.mockResolvedValue(created);
507
-
508
- const result = await oxy.createAccountCredential('acc1', {
509
- name: 'bot-prod',
510
- environment: 'production',
511
- });
512
-
513
- expect(result).toEqual(created);
514
- expect(makeRequestSpy).toHaveBeenCalledWith(
515
- 'POST',
516
- '/accounts/acc1/credentials',
517
- { name: 'bot-prod', environment: 'production' },
518
- expect.objectContaining({ cache: false }),
519
- );
520
- expect(clearEntrySpy).toHaveBeenCalledWith('GET:/accounts/acc1/credentials');
521
- });
522
- });
523
-
524
- describe('rotateAccountCredential', () => {
525
- it('posts to /rotate, encodes ids, returns the audit result, and busts credentials', async () => {
526
- const rotated: RotateAccountCredentialResult = {
527
- credential: { ...credentialFixture, _id: 'cred2' },
528
- secret: 'sk_new',
529
- rotatedFrom: 'cred1',
530
- graceExpiresAt: '2026-07-06T00:00:00.000Z',
531
- };
532
- makeRequestSpy.mockResolvedValue(rotated);
533
-
534
- const result = await oxy.rotateAccountCredential('acc1', 'cred 1');
535
-
536
- expect(result).toEqual(rotated);
537
- expect(makeRequestSpy).toHaveBeenCalledWith(
538
- 'POST',
539
- '/accounts/acc1/credentials/cred%201/rotate',
540
- undefined,
541
- expect.objectContaining({ cache: false }),
542
- );
543
- expect(clearEntrySpy).toHaveBeenCalledWith('GET:/accounts/acc1/credentials');
544
- });
545
- });
546
-
547
- describe('revokeAccountCredential', () => {
548
- it('deletes the credential and busts the credentials cache', async () => {
549
- makeRequestSpy.mockResolvedValue({ success: true });
550
-
551
- const result = await oxy.revokeAccountCredential('acc1', 'cred1');
552
-
553
- expect(result).toEqual({ success: true });
554
- expect(makeRequestSpy).toHaveBeenCalledWith(
555
- 'DELETE',
556
- '/accounts/acc1/credentials/cred1',
557
- undefined,
558
- expect.objectContaining({ cache: false }),
559
- );
560
- expect(clearEntrySpy).toHaveBeenCalledWith('GET:/accounts/acc1/credentials');
561
- });
562
- });
563
-
564
462
  describe('createApp', () => {
565
463
  it('posts the payload, unwraps `application`, and busts every app list', async () => {
566
464
  makeRequestSpy.mockResolvedValue({ application: appFixture });
@@ -678,6 +576,39 @@ describe('OxyServices.accounts', () => {
678
576
  );
679
577
  expect(clearEntrySpy).toHaveBeenCalledWith('GET:/applications/app1/credentials');
680
578
  });
579
+
580
+ it("forwards a machine credential's expiresInSeconds and its one-time token", async () => {
581
+ // A `machine` credential's material arrives in `token`, never `secret` —
582
+ // a surface rendering "the secret" must not silently print an API key.
583
+ const created: ApplicationCredentialWithSecret = {
584
+ credential: { ...appCredentialFixture, type: 'machine', tokenPrefix: 'oxy_sk_0123456789abcdef' },
585
+ secret: null,
586
+ token: 'oxy_sk_0123456789abcdef_' + 'a'.repeat(64),
587
+ };
588
+ makeRequestSpy.mockResolvedValue(created);
589
+
590
+ const result = await oxy.createAppCredential('app1', {
591
+ name: 'ci-runner',
592
+ type: 'machine',
593
+ environment: 'production',
594
+ scopes: ['inference:invoke'],
595
+ expiresInSeconds: 86_400,
596
+ });
597
+
598
+ expect(result.token).toBe(created.token);
599
+ expect(makeRequestSpy).toHaveBeenCalledWith(
600
+ 'POST',
601
+ '/applications/app1/credentials',
602
+ {
603
+ name: 'ci-runner',
604
+ type: 'machine',
605
+ environment: 'production',
606
+ scopes: ['inference:invoke'],
607
+ expiresInSeconds: 86_400,
608
+ },
609
+ expect.objectContaining({ cache: false }),
610
+ );
611
+ });
681
612
  });
682
613
 
683
614
  describe('rotateAppCredential', () => {
@@ -701,6 +632,30 @@ describe('OxyServices.accounts', () => {
701
632
  );
702
633
  expect(clearEntrySpy).toHaveBeenCalledWith('GET:/applications/app1/credentials');
703
634
  });
635
+
636
+ it('forwards an opt-in rotation grace window', async () => {
637
+ // Omitting it (the case above) sends `undefined`, and the server then
638
+ // revokes the superseded machine token immediately. Sending it must reach
639
+ // the body, or a caller asking for zero-downtime rotation would silently
640
+ // get the instant-revoke behaviour instead.
641
+ const rotated: RotateApplicationCredentialResult = {
642
+ credential: { ...appCredentialFixture, _id: 'appcred2', type: 'machine' },
643
+ secret: null,
644
+ token: 'oxy_sk_fedcba9876543210_' + 'b'.repeat(64),
645
+ rotatedFrom: 'appcred1',
646
+ graceExpiresAt: '2026-08-17T00:00:00.000Z',
647
+ };
648
+ makeRequestSpy.mockResolvedValue(rotated);
649
+
650
+ await oxy.rotateAppCredential('app1', 'appcred1', { graceSeconds: 3600 });
651
+
652
+ expect(makeRequestSpy).toHaveBeenCalledWith(
653
+ 'POST',
654
+ '/applications/app1/credentials/appcred1/rotate',
655
+ { graceSeconds: 3600 },
656
+ expect.objectContaining({ cache: false }),
657
+ );
658
+ });
704
659
  });
705
660
 
706
661
  describe('revokeAppCredential', () => {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * `oxyServices.inference()` — the binding, which is the only thing this mixin
3
+ * does.
4
+ *
5
+ * Two properties matter and neither is visible from the client's own suite: the
6
+ * client must inherit THIS instance's base URL, and it must read the bearer
7
+ * LATE, so a token planted after construction is the one that gets sent. A
8
+ * factory that captured `getAccessToken()` eagerly would pass every test that
9
+ * signs in first and fail on the cold-boot ordering every app actually has.
10
+ *
11
+ * Driven through the real global `fetch`, spied — the factory takes no
12
+ * transport, so a test that built its own client would be asserting against a
13
+ * re-implementation of the thing under test rather than against it.
14
+ */
15
+
16
+ import { OxyServices } from '../../OxyServices';
17
+ import { OxyInferenceClient } from '../../inference/OxyInferenceClient';
18
+
19
+ describe('OxyServices.inference()', () => {
20
+ let fetchSpy: jest.SpyInstance;
21
+
22
+ beforeEach(() => {
23
+ fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValue(
24
+ new Response(JSON.stringify({ data: [], count: 0 }), {
25
+ status: 200,
26
+ headers: { 'Content-Type': 'application/json' },
27
+ }),
28
+ );
29
+ });
30
+
31
+ afterEach(() => {
32
+ fetchSpy.mockRestore();
33
+ });
34
+
35
+ it('returns one memoized client, so a consumer can hold it', () => {
36
+ const oxy = new OxyServices({ baseURL: 'http://test.invalid' });
37
+
38
+ const first = oxy.inference();
39
+ expect(first).toBeInstanceOf(OxyInferenceClient);
40
+ expect(oxy.inference()).toBe(first);
41
+ });
42
+
43
+ it('binds this instance base URL and reads the bearer at request time', async () => {
44
+ const oxy = new OxyServices({ baseURL: 'http://test.invalid' });
45
+ const client = oxy.inference();
46
+
47
+ // The token is planted AFTER the client exists — the cold-boot order.
48
+ oxy.setTokens('planted-later');
49
+ await client.listModels();
50
+
51
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
52
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
53
+ expect(String(url)).toBe('http://test.invalid/v1/models');
54
+ expect((init.headers as Record<string, string>)['Authorization']).toBe(
55
+ 'Bearer planted-later',
56
+ );
57
+ });
58
+ });
@@ -50,6 +50,7 @@ const signServiceToken = (claims: ServiceTokenClaims, secret: string): string =>
50
50
  aud: 'oxy-api',
51
51
  iss: 'oxy-auth',
52
52
  credentialId: 'cred-1',
53
+ ownerAccountId: 'owner-account-1',
53
54
  environment: 'production',
54
55
  ...claims,
55
56
  };
@@ -184,6 +185,7 @@ describe('C3: service-token acting-as enforcement', () => {
184
185
  appId: 'app-1',
185
186
  appName: 'trusted-service',
186
187
  credentialId: 'cred-1',
188
+ ownerAccountId: 'owner-account-1',
187
189
  scopes: ['user:read'],
188
190
  environment: 'production',
189
191
  });
@@ -33,6 +33,7 @@ import { OxyServicesChainsMixin } from './OxyServices.chains';
33
33
  import { OxyServicesNodesMixin } from './OxyServices.nodes';
34
34
  import { OxyServicesLinksMixin } from './OxyServices.links';
35
35
  import { OxyServicesFollowGraphMixin } from './OxyServices.followGraph';
36
+ import { OxyServicesInferenceMixin } from './OxyServices.inference';
36
37
  import { OxyServicesDeviceBootMixin } from './OxyServices.deviceBoot';
37
38
  import { OxyServicesDeviceTransferMixin } from './OxyServices.deviceTransfer';
38
39
 
@@ -72,6 +73,7 @@ type AllMixinInstances =
72
73
  & InstanceType<ReturnType<typeof OxyServicesNodesMixin<typeof OxyServicesBase>>>
73
74
  & InstanceType<ReturnType<typeof OxyServicesLinksMixin<typeof OxyServicesBase>>>
74
75
  & InstanceType<ReturnType<typeof OxyServicesFollowGraphMixin<typeof OxyServicesBase>>>
76
+ & InstanceType<ReturnType<typeof OxyServicesInferenceMixin<typeof OxyServicesBase>>>
75
77
  & InstanceType<ReturnType<typeof OxyServicesDeviceBootMixin<typeof OxyServicesBase>>>
76
78
  & InstanceType<ReturnType<typeof OxyServicesDeviceTransferMixin<typeof OxyServicesBase>>>
77
79
  & InstanceType<ReturnType<typeof OxyServicesUtilityMixin<typeof OxyServicesBase>>>;
@@ -156,6 +158,12 @@ const MIXIN_PIPELINE: MixinFunction[] = [
156
158
  // shared across applications, with per-application context on top.
157
159
  OxyServicesFollowGraphMixin,
158
160
 
161
+ // The inference model catalogue (#972). Reads only, and deliberately no
162
+ // request/stream/receipt methods — the public inference edge those would
163
+ // call is workstream 4 and does not exist yet. See
164
+ // `docs/inference/README.md` for what is and is not built.
165
+ OxyServicesInferenceMixin,
166
+
159
167
  // Device-first token mint: the client half of the zero-cookie transport
160
168
  // (`mintFromDeviceSecret` → `POST /session/device/token`).
161
169
  OxyServicesDeviceBootMixin,
@@ -0,0 +1,396 @@
1
+ /**
2
+ * Canonical request attribution for service tokens (ADR 0007, issue #972 §2.2).
3
+ *
4
+ * Two claims are under test, and they are different claims:
5
+ *
6
+ * 1. A VERIFIED service token names the whole attribution tuple locally —
7
+ * application, credential, owning account, environment and effective
8
+ * scopes — so a verifier with no database can say who is responsible.
9
+ * 2. A delegated `X-Oxy-User-Id` can never become that responsible party. It
10
+ * is visible exactly where delegation is meant to be visible
11
+ * (`req.userId`, `getOxyDelegatedUserId`) and nowhere else.
12
+ *
13
+ * Everything runs through the REAL `oxy.auth()` middleware with a real HMAC
14
+ * signature, so the assertions are about the shipped lane rather than a
15
+ * hand-built request object. The one exception is deliberate and marked: the
16
+ * tampering cases plant fields on an already-authenticated request to prove the
17
+ * billing resolver does not read them.
18
+ */
19
+
20
+ import crypto from 'node:crypto';
21
+ import { OxyServices } from '../../OxyServices';
22
+ import {
23
+ getOxyBillingPrincipal,
24
+ getOxyDelegatedUserId,
25
+ getOxyRequestAttribution,
26
+ getRequiredOxyBillingPrincipal,
27
+ getRequiredOxyUserId,
28
+ } from '../auth';
29
+ import type { Request } from 'express';
30
+
31
+ const SERVICE_SECRET = 'attribution-suite-secret-not-production';
32
+ const OWNER_ACCOUNT = 'account-owning-the-application';
33
+ const DELEGATED_USER = 'end-user-the-service-acts-for';
34
+
35
+ interface Claims {
36
+ [key: string]: unknown;
37
+ }
38
+
39
+ const b64url = (input: Buffer | string): string =>
40
+ (typeof input === 'string' ? Buffer.from(input, 'utf8') : input)
41
+ .toString('base64')
42
+ .replace(/\+/g, '-')
43
+ .replace(/\//g, '_')
44
+ .replace(/=+$/, '');
45
+
46
+ /** Sign an HS256 JWT byte-identically to `POST /auth/service-token`. */
47
+ function signServiceToken(claims: Claims = {}, secret = SERVICE_SECRET): string {
48
+ const now = Math.floor(Date.now() / 1000);
49
+ const payload: Claims = {
50
+ iat: now,
51
+ exp: now + 3600,
52
+ type: 'service',
53
+ aud: 'oxy-api',
54
+ iss: 'oxy-auth',
55
+ appId: 'app-1',
56
+ appName: 'relay',
57
+ credentialId: 'cred-1',
58
+ ownerAccountId: OWNER_ACCOUNT,
59
+ environment: 'production',
60
+ scopes: ['inference:invoke'],
61
+ ...claims,
62
+ };
63
+ const headerB64 = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
64
+ const payloadB64 = b64url(JSON.stringify(payload));
65
+ const signature = crypto
66
+ .createHmac('sha256', secret)
67
+ .update(`${headerB64}.${payloadB64}`)
68
+ .digest('base64')
69
+ .replace(/\+/g, '-')
70
+ .replace(/\//g, '_')
71
+ .replace(/=+$/, '');
72
+ return `${headerB64}.${payloadB64}.${signature}`;
73
+ }
74
+
75
+ interface MockReq {
76
+ method: string;
77
+ path: string;
78
+ headers: Record<string, string>;
79
+ query: Record<string, string>;
80
+ userId?: string | null;
81
+ user?: unknown;
82
+ serviceApp?: unknown;
83
+ serviceActingAs?: unknown;
84
+ accessToken?: string;
85
+ }
86
+
87
+ interface MockRes {
88
+ statusCode: number;
89
+ body: unknown;
90
+ headersSent: boolean;
91
+ status(code: number): MockRes;
92
+ json(body: unknown): MockRes;
93
+ }
94
+
95
+ const makeReq = (headers: Record<string, string> = {}): MockReq => ({
96
+ method: 'POST',
97
+ path: '/v1/responses',
98
+ headers,
99
+ query: {},
100
+ });
101
+
102
+ const makeRes = (): MockRes => ({
103
+ statusCode: 0,
104
+ body: undefined,
105
+ headersSent: false,
106
+ status(code: number) {
107
+ this.statusCode = code;
108
+ return this;
109
+ },
110
+ json(body: unknown) {
111
+ this.body = body;
112
+ this.headersSent = true;
113
+ return this;
114
+ },
115
+ });
116
+
117
+ /** Run `oxy.auth()` over a request and report what the middleware decided. */
118
+ async function authenticate(
119
+ oxy: OxyServices,
120
+ headers: Record<string, string>,
121
+ options: Parameters<OxyServices['auth']>[0] = { jwtSecret: SERVICE_SECRET },
122
+ ): Promise<{ req: MockReq; res: MockRes; nextCalled: boolean }> {
123
+ const req = makeReq(headers);
124
+ const res = makeRes();
125
+ const next = jest.fn();
126
+ const middleware = oxy.auth(options);
127
+ await middleware(req as unknown as never, res as unknown as never, next as unknown as never);
128
+ return { req, res, nextCalled: next.mock.calls.length > 0 };
129
+ }
130
+
131
+ /** `MockReq` is the structural subset the resolvers read; Express's own shape is irrelevant here. */
132
+ const asRequest = (req: MockReq): Request => req as unknown as Request;
133
+
134
+ let oxy: OxyServices;
135
+
136
+ beforeEach(() => {
137
+ oxy = new OxyServices({ baseURL: 'http://test.invalid' });
138
+ });
139
+
140
+ describe('a verified service token resolves the whole attribution tuple locally', () => {
141
+ it('names application, credential, owning account, environment and effective scopes', async () => {
142
+ const { req, nextCalled } = await authenticate(oxy, {
143
+ authorization: `Bearer ${signServiceToken()}`,
144
+ });
145
+
146
+ expect(nextCalled).toBe(true);
147
+ expect(getOxyBillingPrincipal(asRequest(req))).toEqual({
148
+ accountId: OWNER_ACCOUNT,
149
+ applicationId: 'app-1',
150
+ credentialId: 'cred-1',
151
+ environment: 'production',
152
+ scopes: ['inference:invoke'],
153
+ });
154
+ });
155
+
156
+ it('reports the effective scopes verbatim — nothing re-intersects them here', async () => {
157
+ // The mint already intersected credential ∩ application via the API's
158
+ // `intersectScopes`. If this side narrowed again it would be a second
159
+ // authority, and the two could disagree.
160
+ const token = signServiceToken({ scopes: ['inference:invoke', 'inference:models:read'] });
161
+ const { req } = await authenticate(oxy, { authorization: `Bearer ${token}` });
162
+
163
+ expect(getRequiredOxyBillingPrincipal(asRequest(req)).scopes).toEqual([
164
+ 'inference:invoke',
165
+ 'inference:models:read',
166
+ ]);
167
+ });
168
+
169
+ it('has no principal at all for an unauthenticated request', () => {
170
+ expect(getOxyBillingPrincipal(asRequest(makeReq()))).toBeNull();
171
+ expect(() => getRequiredOxyBillingPrincipal(asRequest(makeReq()))).toThrow(
172
+ 'no verified Oxy service principal',
173
+ );
174
+ });
175
+ });
176
+
177
+ describe('a delegated X-Oxy-User-Id is attribution, never the payer', () => {
178
+ it('leaves the billing account untouched while the delegated user stays visible', async () => {
179
+ jest
180
+ .spyOn(oxy, 'verifyServiceActingAs')
181
+ .mockResolvedValue({ authorized: true, scopes: ['user:read'] });
182
+
183
+ const { req, nextCalled } = await authenticate(oxy, {
184
+ authorization: `Bearer ${signServiceToken()}`,
185
+ 'x-oxy-user-id': DELEGATED_USER,
186
+ });
187
+
188
+ expect(nextCalled).toBe(true);
189
+
190
+ // The assertion that matters: who pays does not move.
191
+ const principal = getRequiredOxyBillingPrincipal(asRequest(req));
192
+ expect(principal.accountId).toBe(OWNER_ACCOUNT);
193
+ expect(principal.accountId).not.toBe(DELEGATED_USER);
194
+
195
+ // The POSITIVE CONTROL. Without it, a resolver that simply returned a
196
+ // constant would pass the line above. The delegated id must be visible
197
+ // exactly where delegation is supposed to be visible.
198
+ expect(getOxyDelegatedUserId(asRequest(req))).toBe(DELEGATED_USER);
199
+ expect(getRequiredOxyUserId(asRequest(req))).toBe(DELEGATED_USER);
200
+ expect(getOxyRequestAttribution(asRequest(req))).toEqual({
201
+ accountId: OWNER_ACCOUNT,
202
+ applicationId: 'app-1',
203
+ credentialId: 'cred-1',
204
+ environment: 'production',
205
+ scopes: ['inference:invoke'],
206
+ delegatedUserId: DELEGATED_USER,
207
+ });
208
+ });
209
+
210
+ it('resolves the SAME billing account with and without delegation', async () => {
211
+ jest
212
+ .spyOn(oxy, 'verifyServiceActingAs')
213
+ .mockResolvedValue({ authorized: true, scopes: ['user:read'] });
214
+
215
+ const withDelegation = await authenticate(oxy, {
216
+ authorization: `Bearer ${signServiceToken()}`,
217
+ 'x-oxy-user-id': DELEGATED_USER,
218
+ });
219
+ const withoutDelegation = await authenticate(oxy, {
220
+ authorization: `Bearer ${signServiceToken()}`,
221
+ });
222
+
223
+ // Restated as ADR 0007 states it: removing `userId` from a request must not
224
+ // change what any account is charged.
225
+ expect(getRequiredOxyBillingPrincipal(asRequest(withDelegation.req))).toEqual(
226
+ getRequiredOxyBillingPrincipal(asRequest(withoutDelegation.req)),
227
+ );
228
+ expect(getOxyDelegatedUserId(asRequest(withoutDelegation.req))).toBeNull();
229
+ expect(withoutDelegation.req.userId).toBeNull();
230
+ });
231
+
232
+ it('ignores a userId planted on an already-authenticated request', async () => {
233
+ const { req } = await authenticate(oxy, {
234
+ authorization: `Bearer ${signServiceToken()}`,
235
+ });
236
+
237
+ // Deliberate tampering AFTER authentication: this is the shape a downstream
238
+ // middleware bug takes. `getOxyBillingPrincipal` must read `serviceApp` and
239
+ // nothing else, so none of these can move the answer.
240
+ req.userId = DELEGATED_USER;
241
+ req.user = { id: DELEGATED_USER };
242
+ req.serviceActingAs = { userId: DELEGATED_USER, scopes: [] };
243
+
244
+ expect(getRequiredOxyBillingPrincipal(asRequest(req)).accountId).toBe(OWNER_ACCOUNT);
245
+ // Control: the planted fields ARE readable through the user-identity
246
+ // accessor, so the assertion above is about the resolver's inputs and not
247
+ // about the fields being unset.
248
+ expect(getRequiredOxyUserId(asRequest(req))).toBe(DELEGATED_USER);
249
+ });
250
+
251
+ it('does not put the delegated user anywhere on the service principal', async () => {
252
+ jest
253
+ .spyOn(oxy, 'verifyServiceActingAs')
254
+ .mockResolvedValue({ authorized: true, scopes: ['user:read'] });
255
+
256
+ const { req } = await authenticate(oxy, {
257
+ authorization: `Bearer ${signServiceToken()}`,
258
+ 'x-oxy-user-id': DELEGATED_USER,
259
+ });
260
+
261
+ // A field-name-agnostic sweep: no value of `req.serviceApp`, at any depth
262
+ // this object has, may equal the delegated id. A future field called
263
+ // `userId`/`subject`/`onBehalfOf` would fail here without anyone having to
264
+ // remember to extend the list above.
265
+ expect(JSON.stringify(req.serviceApp)).not.toContain(DELEGATED_USER);
266
+ });
267
+ });
268
+
269
+ describe('signature verification is mandatory before any claim is trusted', () => {
270
+ it('refuses a token signed with a different secret (401, no principal)', async () => {
271
+ const forged = signServiceToken({}, 'a-secret-the-issuer-never-used');
272
+ const { req, res, nextCalled } = await authenticate(oxy, {
273
+ authorization: `Bearer ${forged}`,
274
+ });
275
+
276
+ expect(nextCalled).toBe(false);
277
+ expect(res.statusCode).toBe(401);
278
+ expect(res.body).toMatchObject({ code: 'INVALID_SERVICE_TOKEN' });
279
+ expect(req.serviceApp).toBeUndefined();
280
+ expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
281
+ });
282
+
283
+ it('refuses a token whose payload was edited after signing', async () => {
284
+ // The attack the claim set invites: take a real token and rewrite
285
+ // `ownerAccountId` to somebody else's account. The signature covers the
286
+ // payload, so the edit must not survive.
287
+ const token = signServiceToken();
288
+ const [headerB64, , signatureB64] = token.split('.');
289
+ const tamperedPayload = b64url(
290
+ JSON.stringify({
291
+ iat: Math.floor(Date.now() / 1000),
292
+ exp: Math.floor(Date.now() / 1000) + 3600,
293
+ type: 'service',
294
+ aud: 'oxy-api',
295
+ iss: 'oxy-auth',
296
+ appId: 'app-1',
297
+ appName: 'relay',
298
+ credentialId: 'cred-1',
299
+ ownerAccountId: 'somebody-elses-account',
300
+ environment: 'production',
301
+ scopes: ['inference:invoke'],
302
+ }),
303
+ );
304
+ const { req, res, nextCalled } = await authenticate(oxy, {
305
+ authorization: `Bearer ${headerB64}.${tamperedPayload}.${signatureB64}`,
306
+ });
307
+
308
+ expect(nextCalled).toBe(false);
309
+ expect(res.statusCode).toBe(401);
310
+ expect(req.serviceApp).toBeUndefined();
311
+ });
312
+
313
+ it('refuses an UNSIGNED token (alg: none, empty signature segment)', async () => {
314
+ const headerB64 = b64url(JSON.stringify({ alg: 'none', typ: 'JWT' }));
315
+ const payloadB64 = b64url(
316
+ JSON.stringify({
317
+ type: 'service',
318
+ appId: 'app-1',
319
+ appName: 'relay',
320
+ credentialId: 'cred-1',
321
+ ownerAccountId: OWNER_ACCOUNT,
322
+ environment: 'production',
323
+ exp: Math.floor(Date.now() / 1000) + 3600,
324
+ aud: 'oxy-api',
325
+ iss: 'oxy-auth',
326
+ }),
327
+ );
328
+ const { req, res, nextCalled } = await authenticate(oxy, {
329
+ authorization: `Bearer ${headerB64}.${payloadB64}.`,
330
+ });
331
+
332
+ expect(nextCalled).toBe(false);
333
+ expect(res.statusCode).toBe(401);
334
+ expect(req.serviceApp).toBeUndefined();
335
+ });
336
+
337
+ it('refuses every service token when no verification secret is configured', async () => {
338
+ // The secure default: without a secret the middleware CANNOT verify, so it
339
+ // must not fall back to reading the decoded claims.
340
+ const { req, res, nextCalled } = await authenticate(
341
+ oxy,
342
+ { authorization: `Bearer ${signServiceToken()}` },
343
+ {},
344
+ );
345
+
346
+ expect(nextCalled).toBe(false);
347
+ expect(res.statusCode).toBe(403);
348
+ expect(res.body).toMatchObject({ code: 'SERVICE_TOKEN_NOT_CONFIGURED' });
349
+ expect(req.serviceApp).toBeUndefined();
350
+ expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
351
+ });
352
+
353
+ it('attaches no principal on the OPTIONAL lane either', async () => {
354
+ // `optional: true` degrades to anonymous rather than 401 — the thing that
355
+ // must not happen is degrading to an UNVERIFIED principal.
356
+ const forged = signServiceToken({}, 'wrong-secret');
357
+ const { req, nextCalled } = await authenticate(
358
+ oxy,
359
+ { authorization: `Bearer ${forged}` },
360
+ { jwtSecret: SERVICE_SECRET, optional: true },
361
+ );
362
+
363
+ expect(nextCalled).toBe(true);
364
+ expect(req.serviceApp).toBeUndefined();
365
+ expect(req.userId).toBeNull();
366
+ expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
367
+ });
368
+ });
369
+
370
+ describe('the owning account is a required claim', () => {
371
+ it.each([
372
+ ['absent', undefined],
373
+ ['empty', ''],
374
+ ['a number', 42],
375
+ ['null', null],
376
+ ])('refuses a signature-valid token whose ownerAccountId is %s', async (_label, value) => {
377
+ const token = signServiceToken({ ownerAccountId: value });
378
+ const { req, res, nextCalled } = await authenticate(oxy, {
379
+ authorization: `Bearer ${token}`,
380
+ });
381
+
382
+ expect(nextCalled).toBe(false);
383
+ expect(res.statusCode).toBe(401);
384
+ expect(res.body).toMatchObject({ code: 'INVALID_SERVICE_TOKEN' });
385
+ expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
386
+ });
387
+
388
+ it('accepts the same token once the claim is present — the control', async () => {
389
+ const { res, nextCalled } = await authenticate(oxy, {
390
+ authorization: `Bearer ${signServiceToken()}`,
391
+ });
392
+
393
+ expect(nextCalled).toBe(true);
394
+ expect(res.statusCode).toBe(0);
395
+ });
396
+ });