@oxyhq/core 3.10.1 → 3.12.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 (92) 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 +189 -0
  8. package/dist/cjs/index.js +30 -4
  9. package/dist/cjs/mixins/OxyServices.assets.js +16 -1
  10. package/dist/cjs/mixins/OxyServices.auth.js +190 -1
  11. package/dist/cjs/mixins/OxyServices.civic.js +611 -0
  12. package/dist/cjs/mixins/OxyServices.identity.js +291 -0
  13. package/dist/cjs/mixins/OxyServices.sso.js +28 -1
  14. package/dist/cjs/mixins/OxyServices.user.js +1 -0
  15. package/dist/cjs/mixins/index.js +6 -0
  16. package/dist/cjs/server/cors.js +20 -21
  17. package/dist/cjs/server/rateLimit.js +32 -8
  18. package/dist/cjs/utils/profileLinks.js +52 -0
  19. package/dist/cjs/utils/ssoReturn.js +1 -1
  20. package/dist/esm/.tsbuildinfo +1 -1
  21. package/dist/esm/AuthManager.js +9 -2
  22. package/dist/esm/HttpService.js +27 -9
  23. package/dist/esm/OxyServices.base.js +3 -2
  24. package/dist/esm/crypto/canonicalJson.js +104 -0
  25. package/dist/esm/crypto/keyManager.js +67 -8
  26. package/dist/esm/crypto/signatureService.js +187 -0
  27. package/dist/esm/index.js +19 -1
  28. package/dist/esm/mixins/OxyServices.assets.js +16 -1
  29. package/dist/esm/mixins/OxyServices.auth.js +190 -1
  30. package/dist/esm/mixins/OxyServices.civic.js +605 -0
  31. package/dist/esm/mixins/OxyServices.identity.js +287 -0
  32. package/dist/esm/mixins/OxyServices.sso.js +28 -1
  33. package/dist/esm/mixins/OxyServices.user.js +1 -0
  34. package/dist/esm/mixins/index.js +6 -0
  35. package/dist/esm/server/cors.js +20 -21
  36. package/dist/esm/server/rateLimit.js +32 -8
  37. package/dist/esm/utils/profileLinks.js +49 -0
  38. package/dist/esm/utils/ssoReturn.js +1 -1
  39. package/dist/types/.tsbuildinfo +1 -1
  40. package/dist/types/HttpService.d.ts +3 -0
  41. package/dist/types/OxyServices.d.ts +2 -2
  42. package/dist/types/crypto/canonicalJson.d.ts +44 -0
  43. package/dist/types/crypto/keyManager.d.ts +7 -0
  44. package/dist/types/crypto/signatureService.d.ts +112 -0
  45. package/dist/types/index.d.ts +10 -2
  46. package/dist/types/mixins/OxyServices.auth.d.ts +136 -0
  47. package/dist/types/mixins/OxyServices.civic.d.ts +512 -0
  48. package/dist/types/mixins/OxyServices.identity.d.ts +249 -0
  49. package/dist/types/mixins/OxyServices.sso.d.ts +4 -1
  50. package/dist/types/mixins/index.d.ts +3 -1
  51. package/dist/types/models/interfaces.d.ts +3 -0
  52. package/dist/types/server/cors.d.ts +5 -5
  53. package/dist/types/utils/profileLinks.d.ts +36 -0
  54. package/dist/types/utils/ssoReturn.d.ts +1 -1
  55. package/package.json +2 -2
  56. package/src/AuthManager.ts +8 -2
  57. package/src/HttpService.ts +36 -8
  58. package/src/OxyServices.base.ts +3 -2
  59. package/src/OxyServices.ts +1 -1
  60. package/src/__tests__/authManager.security.test.ts +31 -0
  61. package/src/__tests__/httpServiceCsrf.test.ts +75 -0
  62. package/src/crypto/__tests__/canonicalJson.test.ts +116 -0
  63. package/src/crypto/__tests__/keyManager.atomicity.test.ts +41 -2
  64. package/src/crypto/__tests__/signChallengeShared.test.ts +64 -0
  65. package/src/crypto/__tests__/signedRecord.test.ts +345 -0
  66. package/src/crypto/canonicalJson.ts +120 -0
  67. package/src/crypto/keyManager.ts +62 -12
  68. package/src/crypto/signatureService.ts +225 -0
  69. package/src/index.ts +55 -2
  70. package/src/mixins/OxyServices.assets.ts +16 -1
  71. package/src/mixins/OxyServices.auth.ts +309 -1
  72. package/src/mixins/OxyServices.civic.ts +956 -0
  73. package/src/mixins/OxyServices.identity.ts +445 -0
  74. package/src/mixins/OxyServices.sso.ts +30 -1
  75. package/src/mixins/OxyServices.user.ts +1 -0
  76. package/src/mixins/__tests__/OxyServices.civic.test.ts +1097 -0
  77. package/src/mixins/__tests__/OxyServices.identity.test.ts +364 -0
  78. package/src/mixins/__tests__/assetCredentials.test.ts +47 -0
  79. package/src/mixins/__tests__/commonsSignIn.test.ts +277 -0
  80. package/src/mixins/__tests__/serviceAuth.test.ts +19 -0
  81. package/src/mixins/__tests__/sso.test.ts +31 -0
  82. package/src/mixins/index.ts +8 -0
  83. package/src/models/interfaces.ts +3 -0
  84. package/src/server/__tests__/cors.test.ts +5 -1
  85. package/src/server/__tests__/rateLimit.test.ts +116 -0
  86. package/src/server/cors.ts +25 -20
  87. package/src/server/rateLimit.ts +39 -8
  88. package/src/utils/__tests__/consumeSsoReturn.test.ts +1 -1
  89. package/src/utils/__tests__/profileLinks.test.ts +126 -0
  90. package/src/utils/__tests__/ssoReturn.test.ts +1 -1
  91. package/src/utils/profileLinks.ts +74 -0
  92. package/src/utils/ssoReturn.ts +2 -2
@@ -0,0 +1,287 @@
1
+ import { KeyManager } from '../crypto/keyManager.js';
2
+ import { SignatureService } from '../crypto/signatureService.js';
3
+ import { CACHE_TIMES } from './mixinHelpers.js';
4
+ /**
5
+ * Registrable apex the Oxy DID method is anchored on. A user's DID is
6
+ * `did:web:<OXY_IDENTITY_APEX>:u:<userId>`, anchored on the stable account id
7
+ * (NOT the keypair).
8
+ */
9
+ const OXY_IDENTITY_APEX = 'oxy.so';
10
+ /**
11
+ * Derive a user's Oxy DID from their stable account id.
12
+ * `did:web:oxy.so:u:<userId>`.
13
+ */
14
+ export function buildUserDid(userId) {
15
+ return `did:web:${OXY_IDENTITY_APEX}:u:${userId}`;
16
+ }
17
+ export function OxyServicesIdentityMixin(Base) {
18
+ return class extends Base {
19
+ constructor(...args) {
20
+ super(...args);
21
+ }
22
+ /**
23
+ * Resolve the W3C DID document for any user. The API derives it on demand
24
+ * from the account's `authMethods` + `publicKey` — there is no stored
25
+ * document. Public (no auth required); short-TTL cached.
26
+ *
27
+ * @param userId - The account's Mongo `_id`. URL-encoded into the path.
28
+ */
29
+ async resolveDid(userId) {
30
+ try {
31
+ return await this.makeRequest('GET', `/u/${encodeURIComponent(userId)}/did.json`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
32
+ }
33
+ catch (error) {
34
+ throw this.handleError(error);
35
+ }
36
+ }
37
+ /**
38
+ * The current user's DID (`did:web:oxy.so:u:<userId>`), derived locally from
39
+ * the access token's user id. Throws if no user is authenticated.
40
+ */
41
+ getMyDid() {
42
+ const userId = this.getCurrentUserId();
43
+ if (!userId) {
44
+ throw new Error('No authenticated user — cannot derive DID.');
45
+ }
46
+ return buildUserDid(userId);
47
+ }
48
+ /** Resolve the current user's DID document. Requires an authenticated session. */
49
+ async getMyDidDocument() {
50
+ const userId = this.getCurrentUserId();
51
+ if (!userId) {
52
+ throw new Error('No authenticated user — cannot resolve DID document.');
53
+ }
54
+ return this.resolveDid(userId);
55
+ }
56
+ /**
57
+ * List the current user's linked authentication methods plus their DID.
58
+ * Each `identity` method carries a `verificationMethodId` linking it to its
59
+ * DID verification-method fragment.
60
+ */
61
+ async listAuthMethods() {
62
+ try {
63
+ return await this.makeRequest('GET', '/auth/methods', undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
64
+ }
65
+ catch (error) {
66
+ throw this.handleError(error);
67
+ }
68
+ }
69
+ /**
70
+ * Link the on-device cryptographic identity to the current account,
71
+ * upgrading it from custodial to self-sovereign. Signs a proof of private
72
+ * key ownership and posts it to `POST /auth/link`.
73
+ *
74
+ * NATIVE-ONLY: requires a stored identity (throws if `KeyManager` has no key
75
+ * or no user is authenticated). The signed payload is
76
+ * `JSON.stringify({ action: 'link_identity', userId, timestamp })` — the
77
+ * exact bytes the server reconstructs and verifies.
78
+ */
79
+ async linkIdentityKey() {
80
+ try {
81
+ const userId = this.getCurrentUserId();
82
+ if (!userId) {
83
+ throw new Error('No authenticated user — sign in before linking an identity key.');
84
+ }
85
+ const publicKey = await KeyManager.getPublicKey();
86
+ if (!publicKey) {
87
+ throw new Error('No identity found on this device. Create or import an identity first.');
88
+ }
89
+ const timestamp = Date.now();
90
+ // The signed message MUST match the server's reconstruction byte-for-byte:
91
+ // JSON.stringify with this exact key order (action, userId, timestamp).
92
+ const message = JSON.stringify({ action: 'link_identity', userId, timestamp });
93
+ const signature = await SignatureService.sign(message);
94
+ const result = await this.makeRequest('POST', '/auth/link', { type: 'identity', publicKey, signature, timestamp }, { cache: false });
95
+ this._invalidateIdentityCaches(userId);
96
+ return result;
97
+ }
98
+ catch (error) {
99
+ throw this.handleError(error);
100
+ }
101
+ }
102
+ /**
103
+ * Link password authentication to the current account. Adds a `password`
104
+ * auth method (does not remove existing methods).
105
+ *
106
+ * @param email - The email to associate with password auth.
107
+ * @param password - The new password (server enforces strength rules).
108
+ */
109
+ async linkPassword(email, password) {
110
+ try {
111
+ const result = await this.makeRequest('POST', '/auth/link', { type: 'password', email, password }, { cache: false });
112
+ this._invalidateIdentityCaches(this.getCurrentUserId());
113
+ return result;
114
+ }
115
+ catch (error) {
116
+ throw this.handleError(error);
117
+ }
118
+ }
119
+ /**
120
+ * Unlink an authentication method from the current account. The server
121
+ * refuses to remove the last remaining method (the account would become
122
+ * inaccessible). Unlinking `identity` downgrades the account to custodial.
123
+ *
124
+ * @param type - The auth-method type to remove.
125
+ */
126
+ async unlinkAuthMethod(type) {
127
+ try {
128
+ const result = await this.makeRequest('DELETE', `/auth/link/${encodeURIComponent(type)}`, undefined, { cache: false });
129
+ this._invalidateIdentityCaches(this.getCurrentUserId());
130
+ return result;
131
+ }
132
+ catch (error) {
133
+ throw this.handleError(error);
134
+ }
135
+ }
136
+ /**
137
+ * Sign a record with the on-device identity key, WITHOUT publishing it.
138
+ * The subject is the current user's DID. NATIVE-ONLY (requires a stored
139
+ * key). Use {@link publishRecord} to sign and store in one step.
140
+ *
141
+ * @param type - The record category.
142
+ * @param record - The arbitrary record payload to attest to.
143
+ */
144
+ async signRecord(type, record) {
145
+ const subject = this.getMyDid();
146
+ return SignatureService.signRecord(type, subject, record);
147
+ }
148
+ /**
149
+ * Sign a record and publish it to the append-only record store
150
+ * (`POST /identity/records`). NATIVE-ONLY (requires a stored key).
151
+ *
152
+ * @param type - The record category.
153
+ * @param record - The arbitrary record payload to attest to.
154
+ */
155
+ async publishRecord(type, record) {
156
+ try {
157
+ const envelope = await this.signRecord(type, record);
158
+ return await this.makeRequest('POST', '/identity/records', envelope, { cache: false });
159
+ }
160
+ catch (error) {
161
+ throw this.handleError(error);
162
+ }
163
+ }
164
+ /**
165
+ * Fetch a user's most recent signed record of a given type. Public (no auth
166
+ * required); short-TTL cached.
167
+ *
168
+ * @param userId - The subject account's Mongo `_id`.
169
+ * @param type - The record category to fetch.
170
+ */
171
+ async getRecord(userId, type) {
172
+ try {
173
+ const res = await this.makeRequest('GET', `/identity/records/${encodeURIComponent(userId)}/${encodeURIComponent(type)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
174
+ return res.record;
175
+ }
176
+ catch (error) {
177
+ throw this.handleError(error);
178
+ }
179
+ }
180
+ /**
181
+ * Ask the server to verify a user's stored record: it recomputes the
182
+ * canonical signing input, checks the signature, and asserts the signing key
183
+ * is a current verification method on the subject's DID.
184
+ *
185
+ * @param userId - The subject account's Mongo `_id`.
186
+ * @param type - The record category to verify.
187
+ */
188
+ async verifyRecord(userId, type) {
189
+ try {
190
+ return await this.makeRequest('GET', `/identity/records/${encodeURIComponent(userId)}/${encodeURIComponent(type)}/verify`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
191
+ }
192
+ catch (error) {
193
+ throw this.handleError(error);
194
+ }
195
+ }
196
+ /**
197
+ * Download the current user's signed, open-format data-export bundle
198
+ * (`GET /users/me/export`) — the "credible exit" snapshot. Always carries an
199
+ * Oxy provenance `attestation`; carries an optional client `proof` when the
200
+ * account holds its own key.
201
+ */
202
+ async exportMyData() {
203
+ try {
204
+ return await this.makeRequest('GET', '/users/me/export', undefined, { cache: false });
205
+ }
206
+ catch (error) {
207
+ throw this.handleError(error);
208
+ }
209
+ }
210
+ /**
211
+ * Start verifying ownership of a domain. Returns the instructions: publish
212
+ * EITHER the DNS-TXT record OR the `/.well-known/oxy-domain` file, then call
213
+ * {@link verifyDomain}.
214
+ *
215
+ * @param domain - The domain to claim (e.g. `nate.com`).
216
+ */
217
+ async requestDomainVerification(domain) {
218
+ try {
219
+ return await this.makeRequest('POST', '/identity/domains', { domain }, { cache: false });
220
+ }
221
+ catch (error) {
222
+ throw this.handleError(error);
223
+ }
224
+ }
225
+ /**
226
+ * Complete domain verification: the server checks the DNS-TXT record or
227
+ * well-known file and, on success, attaches the domain to the account
228
+ * (surfaced in the DID's `alsoKnownAs` and the user's `verifiedDomains`).
229
+ *
230
+ * @param domain - The domain previously requested via
231
+ * {@link requestDomainVerification}.
232
+ */
233
+ async verifyDomain(domain) {
234
+ try {
235
+ const result = await this.makeRequest('POST', `/identity/domains/${encodeURIComponent(domain)}/verify`, undefined, { cache: false });
236
+ this._invalidateIdentityCaches(this.getCurrentUserId());
237
+ return result;
238
+ }
239
+ catch (error) {
240
+ throw this.handleError(error);
241
+ }
242
+ }
243
+ /** List the current user's verified domains. */
244
+ async listDomains() {
245
+ try {
246
+ const res = await this.makeRequest('GET', '/identity/domains', undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
247
+ return res.domains ?? [];
248
+ }
249
+ catch (error) {
250
+ throw this.handleError(error);
251
+ }
252
+ }
253
+ /**
254
+ * Remove a verified domain from the current account.
255
+ * @param domain - The verified domain to remove.
256
+ */
257
+ async removeDomain(domain) {
258
+ try {
259
+ const result = await this.makeRequest('DELETE', `/identity/domains/${encodeURIComponent(domain)}`, undefined, { cache: false });
260
+ this._invalidateIdentityCaches(this.getCurrentUserId());
261
+ return result;
262
+ }
263
+ catch (error) {
264
+ throw this.handleError(error);
265
+ }
266
+ }
267
+ /**
268
+ * Bust the cached reads that an identity mutation invalidates: the current
269
+ * user (`/users/me*`), the linked auth-methods list, the verified-domains
270
+ * list, and the user's derived DID document (which embeds auth methods +
271
+ * verified domains, so it goes stale on link/unlink/domain changes).
272
+ *
273
+ * Internal helper (leading underscore); not part of the supported public
274
+ * surface. Public rather than `private` because mixins compose into an
275
+ * exported anonymous class, where TypeScript cannot represent a private
276
+ * member in the emitted declaration file (TS4094).
277
+ */
278
+ _invalidateIdentityCaches(userId) {
279
+ this.clearCacheByPrefix('GET:/users/me');
280
+ this.clearCacheEntry('GET:/auth/methods');
281
+ this.clearCacheEntry('GET:/identity/domains');
282
+ if (userId) {
283
+ this.clearCacheEntry(`GET:/u/${encodeURIComponent(userId)}/did.json`);
284
+ }
285
+ }
286
+ };
287
+ }
@@ -23,6 +23,7 @@
23
23
  * `verifyChallenge` — so callers do NOT need to plant tokens manually.
24
24
  */
25
25
  import { createDebugLogger } from '../shared/utils/debugUtils.js';
26
+ import { ssoStateKey } from '../utils/ssoBounce.js';
26
27
  const debug = createDebugLogger('SSO');
27
28
  /**
28
29
  * Generate a cryptographically secure state value for the SSO bounce.
@@ -42,6 +43,25 @@ export function generateSsoState() {
42
43
  }
43
44
  throw new Error('No secure random source available for SSO state generation');
44
45
  }
46
+ /**
47
+ * Read the SSO bounce state stored for the current browser origin, if any.
48
+ *
49
+ * Returns `null` outside a browser (no `window`/`sessionStorage`) or when no
50
+ * state is stored — in which case the caller cannot (and must not) enforce a
51
+ * state match, e.g. native flows or pre-hydration callbacks that already
52
+ * validated the state before this exchange.
53
+ */
54
+ function getStoredSsoStateForCurrentOrigin() {
55
+ if (typeof window === 'undefined' || !window.location || !window.sessionStorage) {
56
+ return null;
57
+ }
58
+ try {
59
+ return window.sessionStorage.getItem(ssoStateKey(window.location.origin));
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
45
65
  export function OxyServicesSsoMixin(Base) {
46
66
  return class extends Base {
47
67
  constructor(...args) {
@@ -68,12 +88,19 @@ export function OxyServicesSsoMixin(Base) {
68
88
  * @param code - The opaque single-use code delivered in the SSO return
69
89
  * fragment (see {@link parseSsoReturnFragment}). The central store burns
70
90
  * it atomically on exchange.
91
+ * @param state - The state value returned alongside the code. In browsers,
92
+ * when an SSO bounce state is still stored for the current origin, this
93
+ * must match before any token-committing exchange is attempted.
71
94
  * @returns The resolved {@link SessionLoginResponse}.
72
95
  */
73
- async exchangeSsoCode(code) {
96
+ async exchangeSsoCode(code, state) {
74
97
  if (typeof code !== 'string' || code.length === 0) {
75
98
  throw this.handleError(new Error('exchangeSsoCode requires a non-empty code'));
76
99
  }
100
+ const expectedState = getStoredSsoStateForCurrentOrigin();
101
+ if (expectedState !== null && (typeof state !== 'string' || state.length === 0 || state !== expectedState)) {
102
+ throw this.handleError(new Error('SSO exchange state mismatch'));
103
+ }
77
104
  const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/sso/exchange`;
78
105
  debug.log('Exchanging SSO code for session...');
79
106
  let response;
@@ -415,6 +415,7 @@ export function OxyServicesUserMixin(Base) {
415
415
  url: `/users/me/data`,
416
416
  params: { format },
417
417
  cache: false,
418
+ responseType: 'blob',
418
419
  });
419
420
  return result;
420
421
  }
@@ -11,6 +11,7 @@ import { OxyServicesSilentAuthMixin } from './OxyServices.silent.js';
11
11
  import { OxyServicesRedirectAuthMixin } from './OxyServices.redirect.js';
12
12
  import { OxyServicesSsoMixin } from './OxyServices.sso.js';
13
13
  import { OxyServicesUserMixin } from './OxyServices.user.js';
14
+ import { OxyServicesIdentityMixin } from './OxyServices.identity.js';
14
15
  import { OxyServicesPrivacyMixin } from './OxyServices.privacy.js';
15
16
  import { OxyServicesLanguageMixin } from './OxyServices.language.js';
16
17
  import { OxyServicesPaymentMixin } from './OxyServices.payment.js';
@@ -28,6 +29,7 @@ import { OxyServicesTopicsMixin } from './OxyServices.topics.js';
28
29
  import { OxyServicesManagedAccountsMixin } from './OxyServices.managedAccounts.js';
29
30
  import { OxyServicesContactsMixin } from './OxyServices.contacts.js';
30
31
  import { OxyServicesAppDataMixin } from './OxyServices.appData.js';
32
+ import { OxyServicesCivicMixin } from './OxyServices.civic.js';
31
33
  /**
32
34
  * Mixin pipeline - applied in order from first to last.
33
35
  *
@@ -54,6 +56,8 @@ const MIXIN_PIPELINE = [
54
56
  OxyServicesSsoMixin,
55
57
  // User management (requires auth)
56
58
  OxyServicesUserMixin,
59
+ // Self-sovereign identity (DID, signed records, auth-method ↔ VM mapping)
60
+ OxyServicesIdentityMixin,
57
61
  OxyServicesPrivacyMixin,
58
62
  // Feature mixins
59
63
  OxyServicesLanguageMixin,
@@ -71,6 +75,8 @@ const MIXIN_PIPELINE = [
71
75
  OxyServicesManagedAccountsMixin,
72
76
  OxyServicesContactsMixin,
73
77
  OxyServicesAppDataMixin,
78
+ // Civic / Commons "Oxy ID" (public signed cards, Oxy ID QR payload)
79
+ OxyServicesCivicMixin,
74
80
  // Utility (last, can use all above)
75
81
  OxyServicesUtilityMixin,
76
82
  ];
@@ -11,10 +11,9 @@
11
11
  *
12
12
  * `createOxyCors` returns a self-contained Express middleware (no `cors`
13
13
  * package dependency) that:
14
- * - allows the Oxy apex origin family (anything under `*.${CENTRAL_IDP_APEX}`,
15
- * i.e. `oxy.so` covering `auth.oxy.so`, `api.oxy.so`, `accounts.oxy.so`,
16
- * `console.oxy.so`, `inbox.oxy.so`, the marketing site, …) reusing the
17
- * central-origin constants already in core, NOT a fresh hardcoded list,
14
+ * - allows the Oxy apex origin family over HTTPS only: the apex plus
15
+ * one-label subdomains such as `auth.oxy.so`, `api.oxy.so`,
16
+ * `accounts.oxy.so`, `console.oxy.so`, and `inbox.oxy.so`,
18
17
  * - allows the caller's explicit `appOrigins`,
19
18
  * - DENIES everything else (no reflection, never a wildcard with credentials),
20
19
  * - echoes back the EXACT matched origin (so credentialed requests work) and
@@ -24,7 +23,6 @@
24
23
  * Node/Express-only: exported solely from `@oxyhq/core/server`.
25
24
  */
26
25
  import { CENTRAL_IDP_APEX } from '../utils/authWebUrl.js';
27
- import { registrableApex } from '../utils/fapiAutoDetect.js';
28
26
  /** Default HTTP methods allowed across origins. */
29
27
  const DEFAULT_ALLOWED_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'];
30
28
  /** Default request headers a browser may send on a credentialed cross-origin call. */
@@ -38,29 +36,30 @@ const DEFAULT_ALLOWED_HEADERS = [
38
36
  ];
39
37
  /** How long (seconds) a browser may cache a successful preflight. */
40
38
  const DEFAULT_MAX_AGE_SECONDS = 86400;
39
+ const OXY_ONE_LABEL_SUBDOMAIN_PATTERN = new RegExp(`^[a-z0-9-]+\\.${CENTRAL_IDP_APEX.replace('.', '\\.')}$`);
41
40
  /**
42
- * Whether `candidate` belongs to the Oxy apex origin family — i.e. its
43
- * registrable apex equals {@link CENTRAL_IDP_APEX} (`oxy.so`). This matches the
44
- * apex itself (`https://oxy.so`) and any subdomain (`https://auth.oxy.so`,
45
- * `https://api.oxy.so`, …) over http or https, ports allowed. Returns false on
46
- * any parse failure (fail closed).
41
+ * Whether `candidate` belongs to the built-in Oxy apex origin family. This
42
+ * intentionally mirrors the API allowlist shape: HTTPS only, no custom port,
43
+ * the apex itself (`https://oxy.so`), or exactly one lowercase subdomain label
44
+ * (`https://auth.oxy.so`, `https://api.oxy.so`, …).
45
+ *
46
+ * Arbitrary/multi-level subdomains and `http://*.oxy.so` are not implicitly
47
+ * trusted for credentialed CORS. If a service needs a non-standard development
48
+ * or tenant origin, it must opt in explicitly via `appOrigins`.
47
49
  */
48
50
  function isOxyFamilyOrigin(candidate) {
49
- let hostname;
50
- let protocol;
51
51
  try {
52
52
  const url = new URL(candidate);
53
- hostname = url.hostname.toLowerCase();
54
- protocol = url.protocol;
53
+ if (url.protocol !== 'https:' || url.port !== '')
54
+ return false;
55
+ const hostname = url.hostname;
56
+ if (hostname === CENTRAL_IDP_APEX)
57
+ return true;
58
+ return OXY_ONE_LABEL_SUBDOMAIN_PATTERN.test(hostname);
55
59
  }
56
60
  catch {
57
61
  return false;
58
62
  }
59
- if (protocol !== 'https:' && protocol !== 'http:')
60
- return false;
61
- if (hostname === CENTRAL_IDP_APEX)
62
- return true;
63
- return registrableApex(hostname) === CENTRAL_IDP_APEX;
64
63
  }
65
64
  /** Normalize a raw origin string to its canonical `scheme://host[:port]` form. */
66
65
  function normalizeOrigin(raw) {
@@ -72,8 +71,8 @@ function normalizeOrigin(raw) {
72
71
  }
73
72
  }
74
73
  /**
75
- * Build the origin-matching predicate: true iff `origin` is in the Oxy apex
76
- * family OR exactly matches one of the configured app origins.
74
+ * Build the origin-matching predicate: true iff `origin` is in the built-in
75
+ * HTTPS Oxy apex family OR exactly matches one of the configured app origins.
77
76
  */
78
77
  function buildOriginAllowed(appOrigins) {
79
78
  const explicit = new Set();
@@ -19,12 +19,36 @@ function isBuiltInExempt(req) {
19
19
  function ipKeyGenerator(ip) {
20
20
  return ip.replace(/:/g, '_');
21
21
  }
22
- /** Resolve the rate-limit key: per authenticated user, else per (IPv6-safe) IP. */
23
- function resolveKey(req) {
22
+ /**
23
+ * Resolve the trusted authenticated rate-limit key.
24
+ *
25
+ * `oxy.auth({ optional: true })` preserves legacy non-session user tokens by
26
+ * decoding their JWT claims locally. Those claims are not cryptographically
27
+ * verified and therefore MUST NOT influence abuse-control buckets. Only use
28
+ * identities that came from a server-validated session or a verified service
29
+ * token/delegation.
30
+ */
31
+ function resolveTrustedAuthenticatedKey(req) {
24
32
  const userId = req.userId ?? req.user?.id ?? req.user?._id;
25
- if (userId) {
33
+ if (userId && req.sessionId) {
26
34
  return `user:${userId}`;
27
35
  }
36
+ const delegatedUserId = req.serviceActingAs?.userId;
37
+ if (delegatedUserId && req.serviceApp?.appId) {
38
+ return `user:${delegatedUserId}`;
39
+ }
40
+ const serviceAppId = req.serviceApp?.appId;
41
+ if (serviceAppId) {
42
+ return `service:${serviceAppId}`;
43
+ }
44
+ return null;
45
+ }
46
+ /** Resolve the rate-limit key: per trusted authenticated identity, else per (IPv6-safe) IP. */
47
+ function resolveKey(req) {
48
+ const authenticatedKey = resolveTrustedAuthenticatedKey(req);
49
+ if (authenticatedKey) {
50
+ return authenticatedKey;
51
+ }
28
52
  const ip = req.ip || req.socket.remoteAddress || 'unknown';
29
53
  return ipKeyGenerator(ip);
30
54
  }
@@ -41,9 +65,9 @@ export function createOxyRateLimit(oxy, options = {}) {
41
65
  windowMs,
42
66
  ...(store ? { store } : {}),
43
67
  max: (req) => {
44
- const authed = req;
45
- const userId = authed.userId ?? authed.user?.id ?? authed.user?._id;
46
- return userId ? authenticatedMax : anonymousMax;
68
+ return resolveTrustedAuthenticatedKey(req)
69
+ ? authenticatedMax
70
+ : anonymousMax;
47
71
  },
48
72
  keyGenerator: (req) => resolveKey(req),
49
73
  message,
@@ -61,8 +85,8 @@ export function createOxyRateLimit(oxy, options = {}) {
61
85
  resolveSession(req, res, (err) => {
62
86
  if (err) {
63
87
  // Optional auth never rejects; a token error just means "anonymous".
64
- // Swallow the error and continue to limit as anonymous.
65
- next();
88
+ // Swallow the error and continue through the anonymous limiter.
89
+ limiter(req, res, next);
66
90
  return;
67
91
  }
68
92
  limiter(req, res, next);
@@ -0,0 +1,49 @@
1
+ function cleanUrl(value) {
2
+ if (typeof value !== 'string')
3
+ return null;
4
+ const trimmed = value.trim();
5
+ return trimmed.length > 0 ? trimmed : null;
6
+ }
7
+ /**
8
+ * Normalizes a user's profile links into a clean display shape.
9
+ *
10
+ * Pure, no side effects, no I/O.
11
+ *
12
+ * - Prefers `linksMetadata` when it is a non-empty array: maps each entry to
13
+ * `{ id, title, url }`, using `entry.id` when present and falling back to the
14
+ * entry index. Entries without a non-empty string `url` are dropped.
15
+ * - Otherwise falls back to the legacy `links` string array: maps each string to
16
+ * `{ id: <index>, url }` (no title). Empty/non-string values are dropped.
17
+ * - Returns `[]` when both are absent or empty (including when `linksMetadata`
18
+ * is present but every entry is dropped — it does NOT fall back to `links`).
19
+ *
20
+ * URLs are trimmed and blanks are filtered out. This does NOT add a scheme such
21
+ * as `https://`; prefixing is a display concern left to the caller.
22
+ */
23
+ export function normalizeProfileLinks(linksMetadata, links) {
24
+ if (Array.isArray(linksMetadata) && linksMetadata.length > 0) {
25
+ const result = [];
26
+ linksMetadata.forEach((entry, index) => {
27
+ const url = cleanUrl(entry?.url);
28
+ if (!url)
29
+ return;
30
+ const id = typeof entry?.id === 'string' && entry.id.trim().length > 0
31
+ ? entry.id
32
+ : String(index);
33
+ const title = typeof entry?.title === 'string' ? entry.title : undefined;
34
+ result.push({ id, url, ...(title !== undefined ? { title } : {}) });
35
+ });
36
+ return result;
37
+ }
38
+ if (Array.isArray(links) && links.length > 0) {
39
+ const result = [];
40
+ links.forEach((value, index) => {
41
+ const url = cleanUrl(value);
42
+ if (!url)
43
+ return;
44
+ result.push({ id: String(index), url });
45
+ });
46
+ return result;
47
+ }
48
+ return [];
49
+ }
@@ -237,7 +237,7 @@ export async function consumeSsoReturn(oxy, deps = {}) {
237
237
  }
238
238
  let session;
239
239
  try {
240
- session = await oxy.exchangeSsoCode(ret.code);
240
+ session = await oxy.exchangeSsoCode(ret.code, ret.state);
241
241
  }
242
242
  catch (error) {
243
243
  onExchangeError?.(error);