@oxyhq/core 3.10.0 → 3.11.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.
Files changed (105) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/AuthManager.js +9 -2
  3. package/dist/cjs/HttpService.js +27 -9
  4. package/dist/cjs/OxyServices.base.js +3 -2
  5. package/dist/cjs/crypto/canonicalJson.js +107 -0
  6. package/dist/cjs/crypto/keyManager.js +67 -8
  7. package/dist/cjs/crypto/signatureService.js +103 -0
  8. package/dist/cjs/i18n/locales/en-US.json +9 -0
  9. package/dist/cjs/i18n/locales/es-ES.json +9 -0
  10. package/dist/cjs/i18n/locales/locales/en-US.json +9 -0
  11. package/dist/cjs/i18n/locales/locales/es-ES.json +9 -0
  12. package/dist/cjs/index.js +15 -5
  13. package/dist/cjs/mixins/OxyServices.assets.js +45 -7
  14. package/dist/cjs/mixins/OxyServices.auth.js +190 -1
  15. package/dist/cjs/mixins/OxyServices.identity.js +291 -0
  16. package/dist/cjs/mixins/OxyServices.sso.js +28 -1
  17. package/dist/cjs/mixins/OxyServices.user.js +1 -0
  18. package/dist/cjs/mixins/OxyServices.utility.js +52 -23
  19. package/dist/cjs/mixins/index.js +3 -0
  20. package/dist/cjs/server/cors.js +20 -21
  21. package/dist/cjs/server/rateLimit.js +32 -8
  22. package/dist/cjs/utils/fapiAutoDetect.js +12 -42
  23. package/dist/cjs/utils/ssoReturn.js +1 -1
  24. package/dist/esm/.tsbuildinfo +1 -1
  25. package/dist/esm/AuthManager.js +9 -2
  26. package/dist/esm/HttpService.js +27 -9
  27. package/dist/esm/OxyServices.base.js +3 -2
  28. package/dist/esm/crypto/canonicalJson.js +104 -0
  29. package/dist/esm/crypto/keyManager.js +67 -8
  30. package/dist/esm/crypto/signatureService.js +102 -0
  31. package/dist/esm/i18n/locales/en-US.json +9 -0
  32. package/dist/esm/i18n/locales/es-ES.json +9 -0
  33. package/dist/esm/i18n/locales/locales/en-US.json +9 -0
  34. package/dist/esm/i18n/locales/locales/es-ES.json +9 -0
  35. package/dist/esm/index.js +10 -2
  36. package/dist/esm/mixins/OxyServices.assets.js +45 -7
  37. package/dist/esm/mixins/OxyServices.auth.js +190 -1
  38. package/dist/esm/mixins/OxyServices.identity.js +287 -0
  39. package/dist/esm/mixins/OxyServices.sso.js +28 -1
  40. package/dist/esm/mixins/OxyServices.user.js +1 -0
  41. package/dist/esm/mixins/OxyServices.utility.js +52 -23
  42. package/dist/esm/mixins/index.js +3 -0
  43. package/dist/esm/server/cors.js +20 -21
  44. package/dist/esm/server/rateLimit.js +32 -8
  45. package/dist/esm/utils/fapiAutoDetect.js +12 -41
  46. package/dist/esm/utils/ssoReturn.js +1 -1
  47. package/dist/types/.tsbuildinfo +1 -1
  48. package/dist/types/HttpService.d.ts +3 -0
  49. package/dist/types/OxyServices.d.ts +2 -2
  50. package/dist/types/crypto/canonicalJson.d.ts +44 -0
  51. package/dist/types/crypto/keyManager.d.ts +7 -0
  52. package/dist/types/crypto/signatureService.d.ts +61 -0
  53. package/dist/types/index.d.ts +7 -3
  54. package/dist/types/mixins/OxyServices.assets.d.ts +6 -1
  55. package/dist/types/mixins/OxyServices.auth.d.ts +136 -0
  56. package/dist/types/mixins/OxyServices.identity.d.ts +249 -0
  57. package/dist/types/mixins/OxyServices.sso.d.ts +4 -1
  58. package/dist/types/mixins/OxyServices.utility.d.ts +3 -3
  59. package/dist/types/mixins/index.d.ts +2 -1
  60. package/dist/types/models/interfaces.d.ts +3 -0
  61. package/dist/types/server/cors.d.ts +5 -5
  62. package/dist/types/utils/fapiAutoDetect.d.ts +6 -23
  63. package/dist/types/utils/ssoReturn.d.ts +1 -1
  64. package/package.json +3 -2
  65. package/src/AuthManager.ts +8 -2
  66. package/src/HttpService.ts +36 -8
  67. package/src/OxyServices.base.ts +3 -2
  68. package/src/OxyServices.ts +1 -1
  69. package/src/__tests__/authManager.security.test.ts +31 -0
  70. package/src/__tests__/authSocket.test.ts +96 -0
  71. package/src/__tests__/httpServiceCsrf.test.ts +75 -0
  72. package/src/crypto/__tests__/canonicalJson.test.ts +116 -0
  73. package/src/crypto/__tests__/keyManager.atomicity.test.ts +41 -2
  74. package/src/crypto/__tests__/signChallengeShared.test.ts +64 -0
  75. package/src/crypto/__tests__/signedRecord.test.ts +125 -0
  76. package/src/crypto/canonicalJson.ts +120 -0
  77. package/src/crypto/keyManager.ts +62 -12
  78. package/src/crypto/signatureService.ts +126 -0
  79. package/src/i18n/locales/en-US.json +9 -0
  80. package/src/i18n/locales/es-ES.json +9 -0
  81. package/src/index.ts +28 -3
  82. package/src/mixins/OxyServices.assets.ts +56 -7
  83. package/src/mixins/OxyServices.auth.ts +309 -1
  84. package/src/mixins/OxyServices.identity.ts +445 -0
  85. package/src/mixins/OxyServices.sso.ts +30 -1
  86. package/src/mixins/OxyServices.user.ts +1 -0
  87. package/src/mixins/OxyServices.utility.ts +57 -23
  88. package/src/mixins/__tests__/OxyServices.identity.test.ts +364 -0
  89. package/src/mixins/__tests__/assetCredentials.test.ts +47 -0
  90. package/src/mixins/__tests__/assetUpload.test.ts +191 -0
  91. package/src/mixins/__tests__/commonsSignIn.test.ts +277 -0
  92. package/src/mixins/__tests__/getFileDownloadUrl.test.ts +13 -0
  93. package/src/mixins/__tests__/serviceAuth.test.ts +49 -2
  94. package/src/mixins/__tests__/sso.test.ts +31 -0
  95. package/src/mixins/index.ts +4 -0
  96. package/src/models/interfaces.ts +3 -0
  97. package/src/server/__tests__/cors.test.ts +5 -1
  98. package/src/server/__tests__/rateLimit.test.ts +116 -0
  99. package/src/server/cors.ts +25 -20
  100. package/src/server/rateLimit.ts +39 -8
  101. package/src/utils/__tests__/consumeSsoReturn.test.ts +1 -1
  102. package/src/utils/__tests__/fapiAutoDetect.test.ts +40 -11
  103. package/src/utils/__tests__/ssoReturn.test.ts +1 -1
  104. package/src/utils/fapiAutoDetect.ts +12 -39
  105. package/src/utils/ssoReturn.ts +2 -2
@@ -41,6 +41,9 @@ import type { OxyServices } from '../OxyServices';
41
41
  interface OxyAuthedRequest extends Request {
42
42
  userId?: string | null;
43
43
  user?: { id?: string; _id?: string } | null;
44
+ sessionId?: string | null;
45
+ serviceApp?: { appId?: string } | null;
46
+ serviceActingAs?: { userId?: string } | null;
44
47
  }
45
48
 
46
49
  export interface OxyRateLimitOptions {
@@ -101,12 +104,40 @@ function ipKeyGenerator(ip: string): string {
101
104
  return ip.replace(/:/g, '_');
102
105
  }
103
106
 
104
- /** Resolve the rate-limit key: per authenticated user, else per (IPv6-safe) IP. */
105
- function resolveKey(req: OxyAuthedRequest): string {
107
+ /**
108
+ * Resolve the trusted authenticated rate-limit key.
109
+ *
110
+ * `oxy.auth({ optional: true })` preserves legacy non-session user tokens by
111
+ * decoding their JWT claims locally. Those claims are not cryptographically
112
+ * verified and therefore MUST NOT influence abuse-control buckets. Only use
113
+ * identities that came from a server-validated session or a verified service
114
+ * token/delegation.
115
+ */
116
+ function resolveTrustedAuthenticatedKey(req: OxyAuthedRequest): string | null {
106
117
  const userId = req.userId ?? req.user?.id ?? req.user?._id;
107
- if (userId) {
118
+ if (userId && req.sessionId) {
108
119
  return `user:${userId}`;
109
120
  }
121
+
122
+ const delegatedUserId = req.serviceActingAs?.userId;
123
+ if (delegatedUserId && req.serviceApp?.appId) {
124
+ return `user:${delegatedUserId}`;
125
+ }
126
+
127
+ const serviceAppId = req.serviceApp?.appId;
128
+ if (serviceAppId) {
129
+ return `service:${serviceAppId}`;
130
+ }
131
+
132
+ return null;
133
+ }
134
+
135
+ /** Resolve the rate-limit key: per trusted authenticated identity, else per (IPv6-safe) IP. */
136
+ function resolveKey(req: OxyAuthedRequest): string {
137
+ const authenticatedKey = resolveTrustedAuthenticatedKey(req);
138
+ if (authenticatedKey) {
139
+ return authenticatedKey;
140
+ }
110
141
  const ip = req.ip || req.socket.remoteAddress || 'unknown';
111
142
  return ipKeyGenerator(ip);
112
143
  }
@@ -139,9 +170,9 @@ export function createOxyRateLimit(
139
170
  windowMs,
140
171
  ...(store ? { store } : {}),
141
172
  max: (req: Request): number => {
142
- const authed = req as OxyAuthedRequest;
143
- const userId = authed.userId ?? authed.user?.id ?? authed.user?._id;
144
- return userId ? authenticatedMax : anonymousMax;
173
+ return resolveTrustedAuthenticatedKey(req as OxyAuthedRequest)
174
+ ? authenticatedMax
175
+ : anonymousMax;
145
176
  },
146
177
  keyGenerator: (req: Request): string => resolveKey(req as OxyAuthedRequest),
147
178
  message,
@@ -160,8 +191,8 @@ export function createOxyRateLimit(
160
191
  resolveSession(req, res, (err?: unknown) => {
161
192
  if (err) {
162
193
  // Optional auth never rejects; a token error just means "anonymous".
163
- // Swallow the error and continue to limit as anonymous.
164
- next();
194
+ // Swallow the error and continue through the anonymous limiter.
195
+ limiter(req, res, next);
165
196
  return;
166
197
  }
167
198
  limiter(req, res, next);
@@ -218,7 +218,7 @@ describe('consumeSsoReturn', () => {
218
218
  });
219
219
 
220
220
  expect(result).toEqual(SESSION);
221
- expect(oxy.exchangeSsoCode).toHaveBeenCalledWith('opaque-code');
221
+ expect(oxy.exchangeSsoCode).toHaveBeenCalledWith('opaque-code', 's');
222
222
  expect(storage.map.has(ssoStateKey(ORIGIN))).toBe(false);
223
223
  expect(storage.map.has(ssoGuardKey(ORIGIN))).toBe(false);
224
224
  expect(storage.map.has(ssoNoSessionKey(ORIGIN))).toBe(false);
@@ -6,8 +6,8 @@
6
6
  * one subdomain over.
7
7
  *
8
8
  * Ported verbatim from packages/auth-sdk/__tests__/utils/fapiAutoDetect.test.ts
9
- * plus multi-part-TLD bail-out cases that are unique to the core copy's
10
- * MULTIPART_TLDS guard.
9
+ * plus Public Suffix List regression cases that are unique to the core
10
+ * implementation's registrable-apex guard.
11
11
  */
12
12
 
13
13
  import { autoDetectAuthWebUrl, registrableApex } from '../fapiAutoDetect';
@@ -81,13 +81,28 @@ describe('autoDetectAuthWebUrl', () => {
81
81
  });
82
82
  });
83
83
 
84
- describe('bails out on multi-part public suffixes (would derive an attacker-registrable apex)', () => {
85
- it('does not derive auth.co.uk from a two-label co.uk host', () => {
86
- expect(autoDetectAuthWebUrl(loc('foo.co.uk'))).toBeUndefined();
84
+ describe('uses the Public Suffix List for registrable apex detection', () => {
85
+ it('derives from the registrable domain under multi-part public suffixes', () => {
86
+ expect(autoDetectAuthWebUrl(loc('foo.co.uk'))).toBe('https://auth.foo.co.uk');
87
+ expect(autoDetectAuthWebUrl(loc('shop.com.au'))).toBe('https://auth.shop.com.au');
88
+ expect(autoDetectAuthWebUrl(loc('shop.victim.com.tr'))).toBe('https://auth.victim.com.tr');
87
89
  });
88
90
 
89
- it('does not derive auth.com.au from a two-label com.au host', () => {
90
- expect(autoDetectAuthWebUrl(loc('shop.com.au'))).toBeUndefined();
91
+ it('derives from the registrable domain under private hosted suffixes', () => {
92
+ expect(autoDetectAuthWebUrl(loc('honest.github.io'))).toBe('https://auth.honest.github.io');
93
+ expect(autoDetectAuthWebUrl(loc('app.victim.pages.dev'))).toBe(
94
+ 'https://auth.victim.pages.dev'
95
+ );
96
+ expect(autoDetectAuthWebUrl(loc('site.victim.netlify.app'))).toBe(
97
+ 'https://auth.victim.netlify.app'
98
+ );
99
+ });
100
+
101
+ it('returns undefined for bare public and private suffixes', () => {
102
+ expect(autoDetectAuthWebUrl(loc('co.uk'))).toBeUndefined();
103
+ expect(autoDetectAuthWebUrl(loc('github.io'))).toBeUndefined();
104
+ expect(autoDetectAuthWebUrl(loc('pages.dev'))).toBeUndefined();
105
+ expect(autoDetectAuthWebUrl(loc('netlify.app'))).toBeUndefined();
91
106
  });
92
107
  });
93
108
 
@@ -105,7 +120,7 @@ describe('autoDetectAuthWebUrl', () => {
105
120
  ['[::1]', undefined],
106
121
  ['intranet', undefined],
107
122
  ['', undefined],
108
- ['foo.co.uk', undefined],
123
+ ['foo.co.uk', 'https://auth.foo.co.uk'],
109
124
  ];
110
125
  it.each(cases)('autoDetectAuthWebUrl(%s) === %s', (hostname, expected) => {
111
126
  const protocol = hostname === 'localhost' || hostname === '[::1]' ? 'http:' : 'https:';
@@ -128,9 +143,23 @@ describe('registrableApex', () => {
128
143
  expect(registrableApex('WWW.Mention.EARTH')).toBe('mention.earth');
129
144
  });
130
145
 
131
- it('returns null for a multi-part public suffix (foo.co.uk -> null)', () => {
132
- expect(registrableApex('foo.co.uk')).toBeNull();
133
- expect(registrableApex('shop.com.au')).toBeNull();
146
+ it('returns the eTLD+1 for hosts under multi-part public suffixes', () => {
147
+ expect(registrableApex('foo.co.uk')).toBe('foo.co.uk');
148
+ expect(registrableApex('www.foo.co.uk')).toBe('foo.co.uk');
149
+ expect(registrableApex('shop.victim.com.tr')).toBe('victim.com.tr');
150
+ });
151
+
152
+ it('returns the eTLD+1 for hosts under private hosted suffixes', () => {
153
+ expect(registrableApex('honest.github.io')).toBe('honest.github.io');
154
+ expect(registrableApex('app.victim.pages.dev')).toBe('victim.pages.dev');
155
+ expect(registrableApex('site.victim.netlify.app')).toBe('victim.netlify.app');
156
+ });
157
+
158
+ it('returns null for bare public and private suffixes', () => {
159
+ expect(registrableApex('co.uk')).toBeNull();
160
+ expect(registrableApex('github.io')).toBeNull();
161
+ expect(registrableApex('pages.dev')).toBeNull();
162
+ expect(registrableApex('netlify.app')).toBeNull();
134
163
  });
135
164
 
136
165
  it('returns null for IPv4 literals', () => {
@@ -188,7 +188,7 @@ describe('consumeSsoReturn pre-hydration callback bootstrap', () => {
188
188
  );
189
189
 
190
190
  expect(session).toBe(exchangedSession);
191
- expect(exchangeSsoCode).toHaveBeenCalledWith('opaque-code');
191
+ expect(exchangeSsoCode).toHaveBeenCalledWith('opaque-code', 'state-ok');
192
192
  expect(replaceStateCalls).toEqual(['/', '/explore?tab=home#top']);
193
193
  expect(dispatchPopState).toHaveBeenCalledTimes(1);
194
194
  expect(hardRedirect).not.toHaveBeenCalled();
@@ -20,10 +20,9 @@
20
20
  * - SSR / non-browser (no `window`).
21
21
  * - `localhost`, `127.0.0.1`, IPv4/IPv6 literals.
22
22
  * - Hostnames with fewer than two labels.
23
- * - Hostnames whose trailing two labels form a known multi-part public
24
- * suffix (e.g. `co.uk`), where the naive `labels.slice(-2)` apex would be
25
- * an attacker-registrable suffix like `auth.co.uk` rather than the real
26
- * registrable domain.
23
+ * - Hostnames where a registrable domain cannot be determined from the
24
+ * Public Suffix List, including private hosted suffixes such as
25
+ * `github.io`, `pages.dev`, and `netlify.app`.
27
26
  *
28
27
  * When the page is already loaded ON the IdP itself (`auth.<anything>`),
29
28
  * the helper returns the current origin so the SDK keeps everything
@@ -35,34 +34,11 @@
35
34
  * is required for end-to-end FedCM correctness — no per-RP config.
36
35
  */
37
36
 
38
- /**
39
- * Known multi-part public suffixes where the registrable domain is the LAST
40
- * THREE labels, not two. Deriving an apex from `labels.slice(-2)` against any
41
- * of these would yield an attacker-registrable suffix (e.g. `auth.co.uk`),
42
- * so we bail out instead.
43
- *
44
- * This is intentionally a small, explicit allow-list rather than the full
45
- * Public Suffix List — it covers the suffixes the Oxy ecosystem's RPs use.
46
- * Any multi-part-TLD RP MUST extend this set (or wire in a proper PSL check)
47
- * before relying on this helper, otherwise auto-detection silently bails to
48
- * `undefined` and the consumer must pass `authWebUrl` explicitly.
49
- */
50
- export const MULTIPART_TLDS: ReadonlySet<string> = new Set([
51
- 'co.uk',
52
- 'com.au',
53
- 'co.jp',
54
- 'co.nz',
55
- 'com.br',
56
- 'co.za',
57
- 'com.mx',
58
- 'co.in',
59
- 'co.kr',
60
- 'com.sg',
61
- ]);
37
+ import { getDomain } from 'tldts';
62
38
 
63
39
  /**
64
- * Compute the bare registrable apex (eTLD+1) of a hostname, guarding against
65
- * multi-part public suffixes.
40
+ * Compute the bare registrable apex (eTLD+1) of a hostname using the Public
41
+ * Suffix List, including private hosted suffixes.
66
42
  *
67
43
  * This is the pure host-handling kernel shared by {@link autoDetectAuthWebUrl}
68
44
  * and the IdP worker — it performs NO protocol handling, NO `auth.` prefixing,
@@ -74,10 +50,7 @@ export const MULTIPART_TLDS: ReadonlySet<string> = new Set([
74
50
  * - IPv4 literals (`192.168.1.10`);
75
51
  * - IPv6 literals or any host carrying a port (`[::1]`, anything with `:`);
76
52
  * - single-label hosts (`intranet`, `localhost`);
77
- * - hosts whose trailing two labels form a known multi-part public suffix
78
- * (e.g. `foo.co.uk`), where `labels.slice(-2)` would yield an
79
- * attacker-registrable suffix (`co.uk`) rather than a real registrable
80
- * domain. Such hosts MUST configure `authWebUrl` explicitly.
53
+ * - public suffixes without a registrable label (e.g. `co.uk`, `github.io`).
81
54
  *
82
55
  * @param hostname - A bare hostname (no scheme), e.g. `www.mention.earth`.
83
56
  * @returns The eTLD+1 (`mention.earth`), or `null` when undefinable.
@@ -89,11 +62,11 @@ export function registrableApex(hostname: string): string | null {
89
62
  // IPv6 literals are bracketed; any remaining ':' implies a port — neither
90
63
  // yields a registrable apex.
91
64
  if (host.startsWith('[') || host.includes(':')) return null;
92
- const labels = host.split('.');
93
- if (labels.length < 2) return null;
94
- const lastTwo = labels.slice(-2).join('.');
95
- if (MULTIPART_TLDS.has(lastTwo)) return null;
96
- return lastTwo;
65
+ // The Public Suffix List (private suffixes included) is the source of truth
66
+ // for what an attacker can register. A multi-part public suffix like `co.uk`
67
+ // or a hosted suffix like `github.io` returns no registrable domain, so
68
+ // deriving `auth.<apex>` against it is impossible — `getDomain` returns null.
69
+ return getDomain(host, { allowPrivateDomains: true });
97
70
  }
98
71
 
99
72
  export function autoDetectAuthWebUrl(
@@ -202,7 +202,7 @@ export interface ConsumeSsoReturnDeps {
202
202
  * @returns The exchanged session on success, otherwise `null`.
203
203
  */
204
204
  export async function consumeSsoReturn(
205
- oxy: { exchangeSsoCode: (code: string) => Promise<SessionLoginResponse> },
205
+ oxy: { exchangeSsoCode: (code: string, state?: string) => Promise<SessionLoginResponse> },
206
206
  deps: ConsumeSsoReturnDeps = {},
207
207
  ): Promise<SessionLoginResponse | null> {
208
208
  const isWeb =
@@ -344,7 +344,7 @@ export async function consumeSsoReturn(
344
344
 
345
345
  let session: SessionLoginResponse | undefined;
346
346
  try {
347
- session = await oxy.exchangeSsoCode(ret.code);
347
+ session = await oxy.exchangeSsoCode(ret.code, ret.state);
348
348
  } catch (error) {
349
349
  onExchangeError?.(error);
350
350
  markNoSession();