@canton-network/wallet-gateway-remote 1.11.2 → 1.11.3

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 (65) hide show
  1. package/dist/auth/jwt-auth-service.d.ts +2 -1
  2. package/dist/auth/jwt-auth-service.d.ts.map +1 -1
  3. package/dist/auth/jwt-auth-service.js +47 -20
  4. package/dist/auth/jwt-auth-service.test.js +264 -58
  5. package/dist/user-api/controller.d.ts.map +1 -1
  6. package/dist/user-api/controller.js +9 -1
  7. package/dist/user-api/controller.test.js +28 -0
  8. package/dist/user-api/token-network-matching.d.ts.map +1 -1
  9. package/dist/user-api/token-network-matching.js +15 -1
  10. package/dist/user-api/token-network-matching.test.d.ts +2 -0
  11. package/dist/user-api/token-network-matching.test.d.ts.map +1 -0
  12. package/dist/user-api/token-network-matching.test.js +66 -0
  13. package/dist/web/frontend/404/index.html +2 -2
  14. package/dist/web/frontend/activities/index.html +2 -2
  15. package/dist/web/frontend/api-keys/add/index.html +15 -0
  16. package/dist/web/frontend/api-keys/index.html +15 -0
  17. package/dist/web/frontend/approve/index.html +2 -2
  18. package/dist/web/frontend/assets/{404-CPixqKLO.js → 404-Ds_FbOi_.js} +1 -1
  19. package/dist/web/frontend/assets/{activities-CVPKYW17.js → activities-DSP_NZCE.js} +1 -1
  20. package/dist/web/frontend/assets/addApiKey-Zv2CS3ub.js +92 -0
  21. package/dist/web/frontend/assets/{addIdentityProvider-nAJ-qcC5.js → addIdentityProvider-BqiC9u9A.js} +1 -1
  22. package/dist/web/frontend/assets/{addNetwork-BneU5JY2.js → addNetwork-B620CvC-.js} +2 -2
  23. package/dist/web/frontend/assets/{addParty-GstM-rQp.js → addParty-CSMZt930.js} +1 -1
  24. package/dist/web/frontend/assets/apiKeys-ohQpjexi.js +68 -0
  25. package/dist/web/frontend/assets/{approve-CWUpB-cM.js → approve-D5YmfGHz.js} +1 -1
  26. package/dist/web/frontend/assets/callback-Dk9tIdBj.js +7 -0
  27. package/dist/web/frontend/assets/{common-JTjsyB1o.js → common-BCDg7K0r.js} +2 -2
  28. package/dist/web/frontend/assets/{editParty-B-21AFFC.js → editParty-DX9X91dp.js} +2 -2
  29. package/dist/web/frontend/assets/{identityProviders-DFmAVYxV.js → identityProviders-C26I4FyE.js} +2 -2
  30. package/dist/web/frontend/assets/{index-BAXYVraq.js → index-BCECRB_Y.js} +1 -1
  31. package/dist/web/frontend/assets/{index-Dp1svjp8.js → index-DrEQVBtC.js} +1 -1
  32. package/dist/web/frontend/assets/{login-DuwXiFvJ.js → login-dmjNaK2x.js} +2 -2
  33. package/dist/web/frontend/assets/{networks-Bh4iCMzi.js → networks-CtFnklqS.js} +2 -2
  34. package/dist/web/frontend/assets/{reviewIdentityProvider-Bd7IWXao.js → reviewIdentityProvider-GBlomu4-.js} +2 -2
  35. package/dist/web/frontend/assets/{reviewNetwork-CPEZ1fzY.js → reviewNetwork-CWEgNcCg.js} +2 -2
  36. package/dist/web/frontend/assets/{settings-BUUAYz6_.js → settings-DSh9rqaO.js} +2 -2
  37. package/dist/web/frontend/assets/signMessage-CT2_Y1LA.js +79 -0
  38. package/dist/web/frontend/callback/index.html +2 -2
  39. package/dist/web/frontend/identity-providers/add/index.html +2 -2
  40. package/dist/web/frontend/identity-providers/index.html +2 -2
  41. package/dist/web/frontend/identity-providers/review/index.html +2 -2
  42. package/dist/web/frontend/index.html +1 -1
  43. package/dist/web/frontend/login/index.html +2 -2
  44. package/dist/web/frontend/networks/add/index.html +2 -2
  45. package/dist/web/frontend/networks/index.html +2 -2
  46. package/dist/web/frontend/networks/review/index.html +2 -2
  47. package/dist/web/frontend/parties/add/index.html +4 -4
  48. package/dist/web/frontend/parties/edit/index.html +4 -4
  49. package/dist/web/frontend/parties/index.html +2 -2
  50. package/dist/web/frontend/settings/index.html +2 -2
  51. package/dist/web/frontend/sign-message/index.html +16 -0
  52. package/dist/web/route-inputs.d.ts +3 -0
  53. package/dist/web/route-inputs.d.ts.map +1 -0
  54. package/dist/web/route-inputs.js +30 -0
  55. package/dist/web/route-inputs.test.d.ts +2 -0
  56. package/dist/web/route-inputs.test.d.ts.map +1 -0
  57. package/dist/web/route-inputs.test.js +30 -0
  58. package/package.json +24 -24
  59. package/dist/auth/jwt-unsafe-auth-service.d.ts +0 -11
  60. package/dist/auth/jwt-unsafe-auth-service.d.ts.map +0 -1
  61. package/dist/auth/jwt-unsafe-auth-service.js +0 -60
  62. package/dist/auth/jwt-unsafe-auth-service.test.d.ts +0 -2
  63. package/dist/auth/jwt-unsafe-auth-service.test.d.ts.map +0 -1
  64. package/dist/auth/jwt-unsafe-auth-service.test.js +0 -121
  65. package/dist/web/frontend/assets/callback-DX4EJbNv.js +0 -7
@@ -2,7 +2,8 @@ import { AuthService } from '@canton-network/core-wallet-auth';
2
2
  import { Store } from '@canton-network/core-wallet-store';
3
3
  import { Logger } from 'pino';
4
4
  /**
5
- * Creates an AuthService that verifies JWT tokens using a remote JWK set.
5
+ * Creates an AuthService that verifies JWT tokens, using a remote JWK set for
6
+ * oauth identity providers and the network's secret for self_signed ones.
6
7
  * @param store - The Store instance to access network configurations.
7
8
  * @param logger - Logger instance for logging debug and warning messages.
8
9
  * @returns An AuthService implementation that verifies JWT tokens.
@@ -1 +1 @@
1
- {"version":3,"file":"jwt-auth-service.d.ts","sourceRoot":"","sources":["../../src/auth/jwt-auth-service.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAoB,MAAM,kCAAkC,CAAA;AAChF,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAA;AAEzD,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAE7B;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,KAAK,EAAE,QAAQ,MAAM,KAAG,WAiI5D,CAAA"}
1
+ {"version":3,"file":"jwt-auth-service.d.ts","sourceRoot":"","sources":["../../src/auth/jwt-auth-service.ts"],"names":[],"mappings":"AAGA,OAAO,EAEH,WAAW,EAGd,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAA;AAOzD,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAgE7B;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,KAAK,EAAE,QAAQ,MAAM,KAAG,WA8G5D,CAAA"}
@@ -1,21 +1,58 @@
1
1
  // Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { resolveUserEmail } from '@canton-network/core-wallet-auth';
4
- import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
3
+ import { resolveUserEmail, } from '@canton-network/core-wallet-auth';
4
+ import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, jwtVerify, } from 'jose';
5
+ function getEmail(value) {
6
+ if (typeof value !== 'string' || value.length === 0) {
7
+ return undefined;
8
+ }
9
+ return value;
10
+ }
5
11
  /**
6
- * Creates an AuthService that verifies JWT tokens using a remote JWK set.
12
+ * Verifies a self-signed token against the secret of the network named by
13
+ * the `kid` header, and rejects it if that network belongs to another IDP.
14
+ */
15
+ async function verifySelfSignedToken(jwt, idp, store, logger) {
16
+ const { kid } = decodeProtectedHeader(jwt);
17
+ if (!kid) {
18
+ logger.warn('Self-signed JWT does not contain a kid header');
19
+ return undefined;
20
+ }
21
+ const network = await store.getNetworkForTokenVerification(kid);
22
+ if (!network || network.auth.method !== 'self_signed') {
23
+ logger.warn({ kid }, 'No self-signed network has this network id');
24
+ return undefined;
25
+ }
26
+ if (network.identityProviderId !== idp.id) {
27
+ logger.warn({ kid, networkId: network.id, idpId: idp.id }, 'JWT network id belongs to a different identity provider');
28
+ return undefined;
29
+ }
30
+ const auth = network.auth;
31
+ const { payload } = await jwtVerify(jwt, new TextEncoder().encode(auth.clientSecret), {
32
+ algorithms: ['HS256'],
33
+ issuer: idp.issuer,
34
+ audience: auth.audience,
35
+ });
36
+ if (!payload.sub) {
37
+ logger.warn('JWT does not contain a subject');
38
+ return undefined;
39
+ }
40
+ const email = getEmail(payload.email);
41
+ return {
42
+ userId: payload.sub,
43
+ accessToken: jwt,
44
+ ...(email ? { email } : {}),
45
+ };
46
+ }
47
+ /**
48
+ * Creates an AuthService that verifies JWT tokens, using a remote JWK set for
49
+ * oauth identity providers and the network's secret for self_signed ones.
7
50
  * @param store - The Store instance to access network configurations.
8
51
  * @param logger - Logger instance for logging debug and warning messages.
9
52
  * @returns An AuthService implementation that verifies JWT tokens.
10
53
  */
11
54
  export const jwtAuthService = (store, logger) => ({
12
55
  verifyToken: async (accessToken) => {
13
- const getEmail = (value) => {
14
- if (typeof value !== 'string' || value.length === 0) {
15
- return undefined;
16
- }
17
- return value;
18
- };
19
56
  if (!accessToken || !accessToken.startsWith('Bearer ')) {
20
57
  return undefined;
21
58
  }
@@ -39,17 +76,7 @@ export const jwtAuthService = (store, logger) => ({
39
76
  return undefined;
40
77
  }
41
78
  if (idp.type == 'self_signed') {
42
- const sub = decoded.sub;
43
- if (!sub) {
44
- logger.warn('JWT does not contain a subject');
45
- return undefined;
46
- }
47
- const email = getEmail(decoded.email);
48
- return {
49
- userId: sub,
50
- accessToken: jwt,
51
- ...(email ? { email } : {}),
52
- };
79
+ return await verifySelfSignedToken(jwt, idp, store, logger);
53
80
  }
54
81
  logger.debug({ idp }, 'Using IDP');
55
82
  const response = await fetch(idp.configUrl);
@@ -1,20 +1,18 @@
1
1
  // Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
3
+ import { vi, describe, it, expect, beforeAll, beforeEach, afterEach, } from 'vitest';
4
4
  import { getLogger } from '@logtape/logtape';
5
5
  import { pino } from 'pino';
6
6
  import { sink } from 'pino-test';
7
- import { SignJWT } from 'jose';
7
+ import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT, } from 'jose';
8
8
  import { StoreInternal } from '@canton-network/core-wallet-store-inmemory';
9
9
  import { jwtAuthService } from './jwt-auth-service.js';
10
- const mockJwtVerify = vi.hoisted(() => vi.fn());
11
- const mockCreateRemoteJWKSet = vi.hoisted(() => vi.fn(() => 'jwks'));
12
10
  const mockFetch = vi.hoisted(() => vi.fn());
11
+ const mockCreateRemoteJWKSet = vi.hoisted(() => vi.fn());
13
12
  vi.mock('jose', async (importOriginal) => {
14
13
  const actual = await importOriginal();
15
14
  return {
16
15
  ...actual,
17
- jwtVerify: mockJwtVerify,
18
16
  createRemoteJWKSet: mockCreateRemoteJWKSet,
19
17
  };
20
18
  });
@@ -23,14 +21,34 @@ const authContext = {
23
21
  accessToken: 'test-access-token',
24
22
  };
25
23
  const SELF_SIGNED_ISSUER = 'unsafe-auth';
24
+ const SELF_SIGNED_AUDIENCE = 'self-signed-audience';
25
+ const SELF_SIGNED_SECRET = 'test-secret';
26
+ const SELF_SIGNED_NETWORK_ID = 'network-self';
26
27
  const OAUTH_ISSUER = 'https://oauth.example.com';
27
- async function bearerToken(claims) {
28
+ const OAUTH_JWKS_URI = 'https://oauth.example.com/jwks';
29
+ const OAUTH_KEY_ID = 'oauth-test-key';
30
+ async function hs256BearerToken(claims, secret = SELF_SIGNED_SECRET, keyId = SELF_SIGNED_NETWORK_ID) {
28
31
  const jwt = await new SignJWT(claims)
29
- .setProtectedHeader({ alg: 'HS256' })
30
- .sign(new TextEncoder().encode('test-secret'));
32
+ .setProtectedHeader({
33
+ alg: 'HS256',
34
+ ...(keyId ? { kid: keyId } : {}),
35
+ })
36
+ .sign(new TextEncoder().encode(secret));
31
37
  return `Bearer ${jwt}`;
32
38
  }
33
- const createNetwork = (id, identityProviderId, audience = 'test-audience') => ({
39
+ function unsignedBearerToken(claims, keyId = SELF_SIGNED_NETWORK_ID) {
40
+ const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
41
+ const header = encode({ alg: 'none', typ: 'JWT', kid: keyId });
42
+ const payload = encode(claims);
43
+ return `Bearer ${header}.${payload}.`;
44
+ }
45
+ async function rs256BearerToken(claims, privateKey) {
46
+ const jwt = await new SignJWT(claims)
47
+ .setProtectedHeader({ alg: 'RS256', kid: OAUTH_KEY_ID })
48
+ .sign(privateKey);
49
+ return `Bearer ${jwt}`;
50
+ }
51
+ const createOAuthNetwork = (id, identityProviderId, audience = 'test-audience') => ({
34
52
  id,
35
53
  name: `Network ${id}`,
36
54
  synchronizerId: `${id}-sync`,
@@ -44,6 +62,22 @@ const createNetwork = (id, identityProviderId, audience = 'test-audience') => ({
44
62
  audience,
45
63
  },
46
64
  });
65
+ const createSelfSignedNetwork = (id, audience, clientSecret, identityProviderId = 'idp-self') => ({
66
+ id,
67
+ name: `Network ${id}`,
68
+ synchronizerId: `${id}-sync`,
69
+ identityProviderId,
70
+ description: `Test Network ${id}`,
71
+ ledgerApi: { baseUrl: `http://${id}` },
72
+ auth: {
73
+ method: 'self_signed',
74
+ issuer: SELF_SIGNED_ISSUER,
75
+ audience,
76
+ scope: 'openid',
77
+ clientId: 'cid',
78
+ clientSecret,
79
+ },
80
+ });
47
81
  describe('jwtAuthService', () => {
48
82
  let mockLogger;
49
83
  let store;
@@ -52,8 +86,7 @@ describe('jwtAuthService', () => {
52
86
  store = new StoreInternal({ idps: [], networks: [] }, getLogger('mock'), authContext);
53
87
  vi.stubGlobal('fetch', mockFetch);
54
88
  mockFetch.mockReset();
55
- mockJwtVerify.mockReset();
56
- mockCreateRemoteJWKSet.mockClear();
89
+ mockCreateRemoteJWKSet.mockReset();
57
90
  });
58
91
  afterEach(() => {
59
92
  vi.unstubAllGlobals();
@@ -69,7 +102,7 @@ describe('jwtAuthService', () => {
69
102
  });
70
103
  it('returns undefined when JWT has no issuer', async () => {
71
104
  const service = jwtAuthService(store, mockLogger);
72
- const token = await bearerToken({ sub: 'user-1', scope: 'openid' });
105
+ const token = await hs256BearerToken({ sub: 'user-1', scope: 'openid' });
73
106
  await expect(service.verifyToken(token)).resolves.toBeUndefined();
74
107
  });
75
108
  it('returns undefined when no identity provider matches issuer', async () => {
@@ -79,7 +112,7 @@ describe('jwtAuthService', () => {
79
112
  issuer: SELF_SIGNED_ISSUER,
80
113
  });
81
114
  const service = jwtAuthService(store, mockLogger);
82
- const token = await bearerToken({
115
+ const token = await hs256BearerToken({
83
116
  iss: 'unknown-issuer',
84
117
  sub: 'user-1',
85
118
  scope: 'openid',
@@ -93,7 +126,7 @@ describe('jwtAuthService', () => {
93
126
  issuer: SELF_SIGNED_ISSUER,
94
127
  });
95
128
  const service = jwtAuthService(store, mockLogger);
96
- const token = await bearerToken({
129
+ const token = await hs256BearerToken({
97
130
  iss: SELF_SIGNED_ISSUER,
98
131
  sub: 'user-1',
99
132
  });
@@ -108,10 +141,12 @@ describe('jwtAuthService', () => {
108
141
  });
109
142
  });
110
143
  it('returns auth context for a valid self-signed token', async () => {
144
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
111
145
  const service = jwtAuthService(store, mockLogger);
112
- const token = await bearerToken({
146
+ const token = await hs256BearerToken({
113
147
  iss: SELF_SIGNED_ISSUER,
114
148
  sub: 'user-1',
149
+ aud: SELF_SIGNED_AUDIENCE,
115
150
  scope: 'openid',
116
151
  });
117
152
  const result = await service.verifyToken(token);
@@ -121,20 +156,24 @@ describe('jwtAuthService', () => {
121
156
  });
122
157
  });
123
158
  it('accepts scp claim instead of scope', async () => {
159
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
124
160
  const service = jwtAuthService(store, mockLogger);
125
- const token = await bearerToken({
161
+ const token = await hs256BearerToken({
126
162
  iss: SELF_SIGNED_ISSUER,
127
163
  sub: 'user-1',
164
+ aud: SELF_SIGNED_AUDIENCE,
128
165
  scp: 'openid',
129
166
  });
130
167
  const result = await service.verifyToken(token);
131
168
  expect(result?.userId).toBe('user-1');
132
169
  });
133
170
  it('includes email when present in token', async () => {
171
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
134
172
  const service = jwtAuthService(store, mockLogger);
135
- const token = await bearerToken({
173
+ const token = await hs256BearerToken({
136
174
  iss: SELF_SIGNED_ISSUER,
137
175
  sub: 'user-1',
176
+ aud: SELF_SIGNED_AUDIENCE,
138
177
  scope: 'openid',
139
178
  email: 'user@example.com',
140
179
  });
@@ -145,17 +184,198 @@ describe('jwtAuthService', () => {
145
184
  email: 'user@example.com',
146
185
  });
147
186
  });
187
+ it('accepts a token whose audience is an array containing a matching network', async () => {
188
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
189
+ const service = jwtAuthService(store, mockLogger);
190
+ const token = await hs256BearerToken({
191
+ iss: SELF_SIGNED_ISSUER,
192
+ sub: 'user-1',
193
+ aud: ['other-audience', SELF_SIGNED_AUDIENCE],
194
+ scope: 'openid',
195
+ });
196
+ const result = await service.verifyToken(token);
197
+ expect(result?.userId).toBe('user-1');
198
+ });
148
199
  it('returns undefined when JWT has no subject', async () => {
200
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
201
+ const service = jwtAuthService(store, mockLogger);
202
+ const token = await hs256BearerToken({
203
+ iss: SELF_SIGNED_ISSUER,
204
+ aud: SELF_SIGNED_AUDIENCE,
205
+ scope: 'openid',
206
+ });
207
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
208
+ });
209
+ it('returns undefined when JWT has no key id', async () => {
210
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
211
+ const service = jwtAuthService(store, mockLogger);
212
+ const token = await hs256BearerToken({
213
+ iss: SELF_SIGNED_ISSUER,
214
+ sub: 'user-1',
215
+ aud: SELF_SIGNED_AUDIENCE,
216
+ scope: 'openid',
217
+ }, SELF_SIGNED_SECRET, null);
218
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
219
+ });
220
+ it('returns undefined when no network has the JWT network id', async () => {
221
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
222
+ const service = jwtAuthService(store, mockLogger);
223
+ const token = await hs256BearerToken({
224
+ iss: SELF_SIGNED_ISSUER,
225
+ sub: 'user-1',
226
+ aud: SELF_SIGNED_AUDIENCE,
227
+ scope: 'openid',
228
+ }, SELF_SIGNED_SECRET, 'unknown-network');
229
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
230
+ });
231
+ it('returns undefined when JWT has no audience', async () => {
232
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
233
+ const service = jwtAuthService(store, mockLogger);
234
+ const token = await hs256BearerToken({
235
+ iss: SELF_SIGNED_ISSUER,
236
+ sub: 'user-1',
237
+ scope: 'openid',
238
+ });
239
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
240
+ });
241
+ it('returns undefined when audience does not match any network', async () => {
242
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
243
+ const service = jwtAuthService(store, mockLogger);
244
+ const token = await hs256BearerToken({
245
+ iss: SELF_SIGNED_ISSUER,
246
+ sub: 'user-1',
247
+ aud: 'unknown-audience',
248
+ scope: 'openid',
249
+ });
250
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
251
+ });
252
+ it('returns undefined when the signature does not match any candidate secret', async () => {
253
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
254
+ const service = jwtAuthService(store, mockLogger);
255
+ const token = await hs256BearerToken({
256
+ iss: SELF_SIGNED_ISSUER,
257
+ sub: 'user-1',
258
+ aud: SELF_SIGNED_AUDIENCE,
259
+ scope: 'openid',
260
+ }, 'wrong-secret');
261
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
262
+ });
263
+ it('returns undefined when the token is expired', async () => {
264
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
149
265
  const service = jwtAuthService(store, mockLogger);
150
- const token = await bearerToken({
266
+ const token = await hs256BearerToken({
151
267
  iss: SELF_SIGNED_ISSUER,
268
+ sub: 'user-1',
269
+ aud: SELF_SIGNED_AUDIENCE,
152
270
  scope: 'openid',
271
+ exp: Math.floor(Date.now() / 1000) - 60,
153
272
  });
154
273
  await expect(service.verifyToken(token)).resolves.toBeUndefined();
155
274
  });
275
+ it('returns undefined when the kid network belongs to another identity provider', async () => {
276
+ await store.addIdp({
277
+ id: 'idp-other',
278
+ type: 'self_signed',
279
+ issuer: 'other-issuer',
280
+ });
281
+ await store.addNetwork(createSelfSignedNetwork('network-other', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET, 'idp-other'));
282
+ const service = jwtAuthService(store, mockLogger);
283
+ // Issuer resolves to idp-self, but the kid names a network owned
284
+ // by idp-other.
285
+ const token = await hs256BearerToken({
286
+ iss: SELF_SIGNED_ISSUER,
287
+ sub: 'user-1',
288
+ aud: SELF_SIGNED_AUDIENCE,
289
+ scope: 'openid',
290
+ }, SELF_SIGNED_SECRET, 'network-other');
291
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
292
+ });
293
+ it('returns undefined for an unsigned token using the none algorithm', async () => {
294
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
295
+ const service = jwtAuthService(store, mockLogger);
296
+ const token = unsignedBearerToken({
297
+ iss: SELF_SIGNED_ISSUER,
298
+ sub: 'user-1',
299
+ aud: SELF_SIGNED_AUDIENCE,
300
+ scope: 'openid',
301
+ });
302
+ await expect(service.verifyToken(token)).resolves.toBeUndefined();
303
+ });
304
+ it('returns undefined for an asymmetrically signed token', async () => {
305
+ await store.addNetwork(createSelfSignedNetwork('network-self', SELF_SIGNED_AUDIENCE, SELF_SIGNED_SECRET));
306
+ const { privateKey } = await generateKeyPair('RS256');
307
+ const service = jwtAuthService(store, mockLogger);
308
+ const jwt = await new SignJWT({
309
+ iss: SELF_SIGNED_ISSUER,
310
+ sub: 'user-1',
311
+ aud: SELF_SIGNED_AUDIENCE,
312
+ scope: 'openid',
313
+ exp: Math.floor(Date.now() / 1000) + 3600,
314
+ })
315
+ .setProtectedHeader({
316
+ alg: 'RS256',
317
+ kid: SELF_SIGNED_NETWORK_ID,
318
+ })
319
+ .sign(privateKey);
320
+ await expect(service.verifyToken(`Bearer ${jwt}`)).resolves.toBeUndefined();
321
+ });
322
+ describe('multiple networks', () => {
323
+ const AUD_A = 'audience-a';
324
+ const AUD_B = 'audience-b';
325
+ const SECRET_A = 'secret-a';
326
+ const SECRET_B = 'secret-b';
327
+ const NETWORK_A = 'network-a';
328
+ const NETWORK_B = 'network-b';
329
+ const claims = (aud) => ({
330
+ iss: SELF_SIGNED_ISSUER,
331
+ sub: 'user-1',
332
+ aud,
333
+ scope: 'openid',
334
+ });
335
+ it('accepts tokens only when kid, secret, and audience belong to the same network', async () => {
336
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_A, AUD_A, SECRET_A));
337
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_B, AUD_B, SECRET_B));
338
+ const service = jwtAuthService(store, mockLogger);
339
+ await expect(service.verifyToken(await hs256BearerToken(claims(AUD_A), SECRET_A, NETWORK_A))).resolves.toMatchObject({ userId: 'user-1' });
340
+ await expect(service.verifyToken(await hs256BearerToken(claims(AUD_B), SECRET_B, NETWORK_B))).resolves.toMatchObject({ userId: 'user-1' });
341
+ });
342
+ it('does not fall back to another network secret when the kid-selected secret rejects the token', async () => {
343
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_A, AUD_A, SECRET_A));
344
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_B, AUD_A, SECRET_B));
345
+ const service = jwtAuthService(store, mockLogger);
346
+ const tokenSignedWithNetworkBSecret = await hs256BearerToken(claims(AUD_A), SECRET_B, NETWORK_A);
347
+ await expect(service.verifyToken(tokenSignedWithNetworkBSecret)).resolves.toBeUndefined();
348
+ });
349
+ it('does not accept another network audience when networks share a secret', async () => {
350
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_A, AUD_A, SECRET_A));
351
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_B, AUD_B, SECRET_A));
352
+ const service = jwtAuthService(store, mockLogger);
353
+ const tokenForNetworkBAudience = await hs256BearerToken(claims(AUD_B), SECRET_A, NETWORK_A);
354
+ await expect(service.verifyToken(tokenForNetworkBAudience)).resolves.toBeUndefined();
355
+ });
356
+ it('rejects changing a valid token kid to another network id', async () => {
357
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_A, AUD_A, SECRET_A));
358
+ await store.addNetwork(createSelfSignedNetwork(NETWORK_B, AUD_B, SECRET_B));
359
+ const service = jwtAuthService(store, mockLogger);
360
+ const networkATokenWithNetworkBKid = await hs256BearerToken(claims(AUD_A), SECRET_A, NETWORK_B);
361
+ await expect(service.verifyToken(networkATokenWithNetworkBKid)).resolves.toBeUndefined();
362
+ });
363
+ });
156
364
  });
157
365
  describe('oauth identity provider', () => {
158
366
  const configUrl = 'https://oauth.example.com/.well-known/openid-configuration';
367
+ let oauthPrivateKey;
368
+ let oauthPublicJwk;
369
+ beforeAll(async () => {
370
+ const { publicKey, privateKey } = await generateKeyPair('RS256');
371
+ oauthPrivateKey = privateKey;
372
+ oauthPublicJwk = {
373
+ ...(await exportJWK(publicKey)),
374
+ kid: OAUTH_KEY_ID,
375
+ alg: 'RS256',
376
+ use: 'sig',
377
+ };
378
+ });
159
379
  beforeEach(async () => {
160
380
  await store.addIdp({
161
381
  id: 'idp-oauth',
@@ -164,30 +384,26 @@ describe('jwtAuthService', () => {
164
384
  configUrl,
165
385
  });
166
386
  mockFetch.mockResolvedValue({
167
- json: async () => ({
168
- jwks_uri: 'https://oauth.example.com/jwks',
169
- }),
387
+ ok: true,
388
+ status: 200,
389
+ json: async () => ({ jwks_uri: OAUTH_JWKS_URI }),
170
390
  });
391
+ mockCreateRemoteJWKSet.mockImplementation(() => createLocalJWKSet({ keys: [oauthPublicJwk] }));
171
392
  });
172
393
  it('returns auth context when JWT verifies and audience matches', async () => {
173
- await store.addNetwork(createNetwork('network-1', 'idp-oauth', 'ledger-audience'));
174
- mockJwtVerify.mockResolvedValue({
175
- payload: { sub: 'oauth-user', aud: 'ledger-audience' },
176
- });
394
+ await store.addNetwork(createOAuthNetwork('network-1', 'idp-oauth', 'ledger-audience'));
177
395
  const service = jwtAuthService(store, mockLogger);
178
- const token = await bearerToken({
396
+ const token = await rs256BearerToken({
179
397
  iss: OAUTH_ISSUER,
180
398
  sub: 'oauth-user',
399
+ aud: 'ledger-audience',
181
400
  scope: 'openid',
182
401
  email: 'oauth@example.com',
183
- });
402
+ }, oauthPrivateKey);
184
403
  const rawJwt = token.split(' ')[1];
185
404
  const result = await service.verifyToken(token);
186
405
  expect(mockFetch).toHaveBeenCalledWith(configUrl);
187
- expect(mockCreateRemoteJWKSet).toHaveBeenCalledWith(new URL('https://oauth.example.com/jwks'));
188
- expect(mockJwtVerify).toHaveBeenCalledWith(rawJwt, 'jwks', {
189
- algorithms: ['RS256'],
190
- });
406
+ expect(mockCreateRemoteJWKSet).toHaveBeenCalledWith(new URL(OAUTH_JWKS_URI));
191
407
  expect(result).toEqual({
192
408
  userId: 'oauth-user',
193
409
  accessToken: rawJwt,
@@ -195,63 +411,53 @@ describe('jwtAuthService', () => {
195
411
  });
196
412
  });
197
413
  it('returns undefined when no networks are configured for the IDP', async () => {
198
- mockJwtVerify.mockResolvedValue({
199
- payload: { sub: 'oauth-user', aud: 'ledger-audience' },
200
- });
201
414
  const service = jwtAuthService(store, mockLogger);
202
- const token = await bearerToken({
415
+ const token = await rs256BearerToken({
203
416
  iss: OAUTH_ISSUER,
204
417
  sub: 'oauth-user',
418
+ aud: 'ledger-audience',
205
419
  scope: 'openid',
206
- });
420
+ }, oauthPrivateKey);
207
421
  await expect(service.verifyToken(token)).resolves.toBeUndefined();
208
422
  });
209
423
  it('returns undefined when audience does not match configured networks', async () => {
210
- await store.addNetwork(createNetwork('network-1', 'idp-oauth', 'expected-audience'));
211
- mockJwtVerify.mockResolvedValue({
212
- payload: { sub: 'oauth-user', aud: 'other-audience' },
213
- });
424
+ await store.addNetwork(createOAuthNetwork('network-1', 'idp-oauth', 'expected-audience'));
214
425
  const service = jwtAuthService(store, mockLogger);
215
- const token = await bearerToken({
426
+ const token = await rs256BearerToken({
216
427
  iss: OAUTH_ISSUER,
217
428
  sub: 'oauth-user',
429
+ aud: 'other-audience',
218
430
  scope: 'openid',
219
- });
431
+ }, oauthPrivateKey);
220
432
  await expect(service.verifyToken(token)).resolves.toBeUndefined();
221
433
  });
222
434
  it('returns undefined when verified JWT has no audience', async () => {
223
- await store.addNetwork(createNetwork('network-1', 'idp-oauth', 'expected-audience'));
224
- mockJwtVerify.mockResolvedValue({
225
- payload: { sub: 'oauth-user' },
226
- });
435
+ await store.addNetwork(createOAuthNetwork('network-1', 'idp-oauth', 'expected-audience'));
227
436
  const service = jwtAuthService(store, mockLogger);
228
- const token = await bearerToken({
437
+ const token = await rs256BearerToken({
229
438
  iss: OAUTH_ISSUER,
230
439
  sub: 'oauth-user',
231
440
  scope: 'openid',
232
- });
441
+ }, oauthPrivateKey);
233
442
  await expect(service.verifyToken(token)).resolves.toBeUndefined();
234
443
  });
235
444
  it('returns undefined when verified JWT has no subject', async () => {
236
- await store.addNetwork(createNetwork('network-1', 'idp-oauth', 'expected-audience'));
237
- mockJwtVerify.mockResolvedValue({
238
- payload: { aud: 'expected-audience' },
239
- });
445
+ await store.addNetwork(createOAuthNetwork('network-1', 'idp-oauth', 'expected-audience'));
240
446
  const service = jwtAuthService(store, mockLogger);
241
- const token = await bearerToken({
447
+ const token = await rs256BearerToken({
242
448
  iss: OAUTH_ISSUER,
243
- sub: 'oauth-user',
449
+ aud: 'expected-audience',
244
450
  scope: 'openid',
245
- });
451
+ }, oauthPrivateKey);
246
452
  await expect(service.verifyToken(token)).resolves.toBeUndefined();
247
453
  });
248
454
  it('returns undefined when JWT verification fails', async () => {
249
- await store.addNetwork(createNetwork('network-1', 'idp-oauth', 'expected-audience'));
250
- mockJwtVerify.mockRejectedValue(new Error('invalid signature'));
455
+ await store.addNetwork(createOAuthNetwork('network-1', 'idp-oauth', 'expected-audience'));
251
456
  const service = jwtAuthService(store, mockLogger);
252
- const token = await bearerToken({
457
+ const token = await hs256BearerToken({
253
458
  iss: OAUTH_ISSUER,
254
459
  sub: 'oauth-user',
460
+ aud: 'expected-audience',
255
461
  scope: 'openid',
256
462
  });
257
463
  await expect(service.verifyToken(token)).resolves.toBeUndefined();
@@ -1 +1 @@
1
- {"version":3,"file":"controller.d.ts","sourceRoot":"","sources":["../../src/user-api/controller.ts"],"names":[],"mappings":"AAmDA,OAAO,EAAE,KAAK,EAAW,MAAM,mCAAmC,CAAA;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAA;AAC5E,OAAO,EAEH,WAAW,EAKd,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAEhD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAA;AAenE,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAA;AAElD,eAAO,MAAM,cAAc,GACvB,YAAY,UAAU,EACtB,SAAS,MAAM,EACf,OAAO,KAAK,EACZ,qBAAqB,mBAAmB,EACxC,aAAa,WAAW,GAAG,SAAS,EACpC,SAAS,cAAc,EACvB,SAAS,MAAM,EACf,sBAAsB,sBAAsB,EAC5C,cAAc,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+rCvB,CAAA"}
1
+ {"version":3,"file":"controller.d.ts","sourceRoot":"","sources":["../../src/user-api/controller.ts"],"names":[],"mappings":"AAmDA,OAAO,EAAE,KAAK,EAAW,MAAM,mCAAmC,CAAA;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAA;AAC5E,OAAO,EAEH,WAAW,EAKd,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAEhD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAA;AAenE,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAA;AAElD,eAAO,MAAM,cAAc,GACvB,YAAY,UAAU,EACtB,SAAS,MAAM,EACf,OAAO,KAAK,EACZ,qBAAqB,mBAAmB,EACxC,aAAa,WAAW,GAAG,SAAS,EACpC,SAAS,cAAc,EACvB,SAAS,MAAM,EACf,sBAAsB,sBAAsB,EAC5C,cAAc,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0sCvB,CAAA"}
@@ -135,7 +135,14 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
135
135
  if (auth.method !== 'self_signed') {
136
136
  throw new Error('Network does not use self_signed authentication');
137
137
  }
138
- if (params.clientSecret !== auth.clientSecret) {
138
+ const clientSecretMatch = crypto.timingSafeEqual(crypto
139
+ .createHash('sha256')
140
+ .update(params.clientSecret, 'utf8')
141
+ .digest(), crypto
142
+ .createHash('sha256')
143
+ .update(auth.clientSecret, 'utf8')
144
+ .digest());
145
+ if (!clientSecretMatch) {
139
146
  throw providerErrors.unauthorized({
140
147
  message: 'Invalid client secret',
141
148
  });
@@ -150,6 +157,7 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
150
157
  const accessToken = await new AuthTokenProvider({
151
158
  method: 'self_signed',
152
159
  issuer: idp.issuer,
160
+ keyId: network.id,
153
161
  credentials: {
154
162
  clientId: params.clientId,
155
163
  clientSecret: auth.clientSecret,
@@ -327,7 +327,9 @@ describe('userController', () => {
327
327
  clientSecret: 'network-secret',
328
328
  });
329
329
  expect(typeof result.accessToken).toBe('string');
330
+ const header = JSON.parse(Buffer.from(result.accessToken.split('.')[0], 'base64url').toString());
330
331
  const payload = JSON.parse(Buffer.from(result.accessToken.split('.')[1], 'base64url').toString());
332
+ expect(header.kid).toBe('network-self-signed');
331
333
  expect(payload.sub).toBe('test-user');
332
334
  });
333
335
  it('rejects when the client secret does not match', async () => {
@@ -836,6 +838,32 @@ describe('userController', () => {
836
838
  networkId: 'network1',
837
839
  })).rejects.toThrow('Failed to add session');
838
840
  });
841
+ it('addSession rejects token with client_id claim and auth.clientId mismatch', async () => {
842
+ const authWithInvalidSubject = createAuthWithAddSessionClaims({
843
+ client_id: 'wrong-client-id',
844
+ });
845
+ const store = await createStore(logger, authWithInvalidSubject, {
846
+ withWallet: false,
847
+ });
848
+ const controller = createController(store, notificationService, logger, authWithInvalidSubject);
849
+ await expect(controller.addSession({
850
+ origin: 'dapp-1',
851
+ networkId: 'network1',
852
+ })).rejects.toThrow('Failed to add session');
853
+ });
854
+ it('addSession rejects token with azp claim and auth.clientId mismatch', async () => {
855
+ const authWithInvalidSubject = createAuthWithAddSessionClaims({
856
+ azp: 'wrong-client-id',
857
+ });
858
+ const store = await createStore(logger, authWithInvalidSubject, {
859
+ withWallet: false,
860
+ });
861
+ const controller = createController(store, notificationService, logger, authWithInvalidSubject);
862
+ await expect(controller.addSession({
863
+ origin: 'dapp-1',
864
+ networkId: 'network1',
865
+ })).rejects.toThrow('Failed to add session');
866
+ });
839
867
  it("addSession passes when token doesn't token have azp and client-id claims", async () => {
840
868
  const authWithInvalidSubject = createAuthWithAddSessionClaims();
841
869
  const store = await createStore(logger, authWithInvalidSubject, {