@oxyhq/core 20.0.0 → 21.0.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 (94) hide show
  1. package/NOTICE +10 -9
  2. package/dist/cjs/.tsbuildinfo +1 -1
  3. package/dist/cjs/boot/sessionColdBoot.js +107 -8
  4. package/dist/cjs/i18n/locales/en-US.json +19 -2
  5. package/dist/cjs/i18n/locales/es-ES.json +19 -2
  6. package/dist/cjs/i18n/locales/locales/en-US.json +19 -2
  7. package/dist/cjs/i18n/locales/locales/es-ES.json +19 -2
  8. package/dist/cjs/index.js +50 -16
  9. package/dist/cjs/mixins/OxyServices.auth.js +27 -3
  10. package/dist/cjs/mixins/OxyServices.chains.js +73 -0
  11. package/dist/cjs/mixins/OxyServices.store.js +266 -0
  12. package/dist/cjs/mixins/OxyServices.utility.js +159 -104
  13. package/dist/cjs/mixins/index.js +7 -0
  14. package/dist/cjs/server/rateLimit.js +15 -6
  15. package/dist/cjs/session/SessionClient.js +361 -1
  16. package/dist/cjs/session/accountDialogController.js +121 -147
  17. package/dist/cjs/session/accountSwitchTargets.js +75 -0
  18. package/dist/cjs/session/deviceDirectory.js +143 -0
  19. package/dist/cjs/session/deviceSwitcherRows.js +76 -0
  20. package/dist/cjs/session/projectSessionState.js +8 -1
  21. package/dist/cjs/session/sharedDeviceCredential.js +247 -0
  22. package/dist/esm/.tsbuildinfo +1 -1
  23. package/dist/esm/boot/sessionColdBoot.js +107 -8
  24. package/dist/esm/i18n/locales/en-US.json +19 -2
  25. package/dist/esm/i18n/locales/es-ES.json +19 -2
  26. package/dist/esm/i18n/locales/locales/en-US.json +19 -2
  27. package/dist/esm/i18n/locales/locales/es-ES.json +19 -2
  28. package/dist/esm/index.js +32 -10
  29. package/dist/esm/mixins/OxyServices.auth.js +27 -3
  30. package/dist/esm/mixins/OxyServices.chains.js +70 -0
  31. package/dist/esm/mixins/OxyServices.store.js +263 -0
  32. package/dist/esm/mixins/OxyServices.utility.js +159 -104
  33. package/dist/esm/mixins/index.js +7 -0
  34. package/dist/esm/server/rateLimit.js +15 -6
  35. package/dist/esm/session/SessionClient.js +362 -2
  36. package/dist/esm/session/accountDialogController.js +121 -147
  37. package/dist/esm/session/accountSwitchTargets.js +71 -0
  38. package/dist/esm/session/deviceDirectory.js +135 -0
  39. package/dist/esm/session/deviceSwitcherRows.js +72 -0
  40. package/dist/esm/session/projectSessionState.js +8 -2
  41. package/dist/esm/session/sharedDeviceCredential.js +239 -0
  42. package/dist/types/.tsbuildinfo +1 -1
  43. package/dist/types/boot/sessionColdBoot.d.ts +24 -4
  44. package/dist/types/index.d.ts +15 -3
  45. package/dist/types/mixins/OxyServices.auth.d.ts +75 -3
  46. package/dist/types/mixins/OxyServices.chains.d.ts +156 -0
  47. package/dist/types/mixins/OxyServices.store.d.ts +334 -0
  48. package/dist/types/mixins/OxyServices.utility.d.ts +31 -8
  49. package/dist/types/mixins/index.d.ts +3 -1
  50. package/dist/types/models/session.d.ts +11 -0
  51. package/dist/types/session/SessionClient.d.ts +202 -1
  52. package/dist/types/session/accountDialogController.d.ts +76 -64
  53. package/dist/types/session/accountSwitchTargets.d.ts +64 -0
  54. package/dist/types/session/deviceDirectory.d.ts +182 -0
  55. package/dist/types/session/deviceSwitcherRows.d.ts +92 -0
  56. package/dist/types/session/projectSessionState.d.ts +29 -0
  57. package/dist/types/session/sharedDeviceCredential.d.ts +202 -0
  58. package/package.json +3 -3
  59. package/src/boot/__tests__/sessionColdBoot.sharedDevice.test.ts +325 -0
  60. package/src/boot/sessionColdBoot.ts +133 -9
  61. package/src/i18n/locales/en-US.json +19 -2
  62. package/src/i18n/locales/es-ES.json +19 -2
  63. package/src/index.ts +105 -18
  64. package/src/mixins/OxyServices.auth.ts +67 -5
  65. package/src/mixins/OxyServices.chains.ts +134 -0
  66. package/src/mixins/OxyServices.store.ts +585 -0
  67. package/src/mixins/OxyServices.utility.ts +161 -108
  68. package/src/mixins/__tests__/chains.test.ts +113 -0
  69. package/src/mixins/__tests__/preSessionSkipAuth.test.ts +54 -1
  70. package/src/mixins/__tests__/store.test.ts +304 -0
  71. package/src/mixins/__tests__/userTokenAuth.test.ts +746 -0
  72. package/src/mixins/index.ts +9 -0
  73. package/src/models/session.ts +11 -0
  74. package/src/server/__tests__/rateLimit.test.ts +47 -0
  75. package/src/server/rateLimit.ts +18 -8
  76. package/src/session/SessionClient.ts +386 -1
  77. package/src/session/__tests__/SessionClient.directory.test.ts +688 -0
  78. package/src/session/__tests__/accountDialogController.test.ts +411 -278
  79. package/src/session/__tests__/accountSwitchTargets.test.ts +132 -0
  80. package/src/session/__tests__/deviceDirectory.test.ts +422 -0
  81. package/src/session/__tests__/deviceSwitcherRows.test.ts +223 -0
  82. package/src/session/__tests__/projectSessionState.test.ts +17 -0
  83. package/src/session/__tests__/sharedDeviceCredential.test.ts +300 -0
  84. package/src/session/accountDialogController.ts +141 -179
  85. package/src/session/accountSwitchTargets.ts +87 -0
  86. package/src/session/deviceDirectory.ts +269 -0
  87. package/src/session/deviceSwitcherRows.ts +145 -0
  88. package/src/session/projectSessionState.ts +9 -3
  89. package/src/session/sharedDeviceCredential.ts +349 -0
  90. package/dist/cjs/session/accountProjection.js +0 -213
  91. package/dist/esm/session/accountProjection.js +0 -207
  92. package/dist/types/session/accountProjection.d.ts +0 -198
  93. package/src/session/__tests__/accountProjection.test.ts +0 -447
  94. package/src/session/accountProjection.ts +0 -354
@@ -0,0 +1,263 @@
1
+ import { CACHE_TIMES } from './mixinHelpers.js';
2
+ /** Read one page out of that envelope. */
3
+ function pageOf(res) {
4
+ return {
5
+ items: res.data ?? [],
6
+ total: res.pagination?.total ?? 0,
7
+ hasMore: res.pagination?.hasMore ?? false,
8
+ };
9
+ }
10
+ /**
11
+ * Build a query string from the options that were actually supplied.
12
+ *
13
+ * Generic over the options object rather than taking a `Record`: an interface
14
+ * has no implicit index signature in TypeScript, so `StoreReviewsOptions` would
15
+ * not be assignable to one and every call site would need a cast.
16
+ */
17
+ function queryOf(params) {
18
+ const search = new URLSearchParams();
19
+ for (const [key, value] of Object.entries(params)) {
20
+ if (value !== undefined)
21
+ search.set(key, String(value));
22
+ }
23
+ const rendered = search.toString();
24
+ return rendered ? `?${rendered}` : '';
25
+ }
26
+ export function OxyServicesStoreMixin(Base) {
27
+ return class extends Base {
28
+ constructor(...args) {
29
+ super(...args);
30
+ }
31
+ // =========================================================================
32
+ // The storefront — /store. No authentication: everything served is public.
33
+ // =========================================================================
34
+ /** The shelves, in the order the store curates them. */
35
+ async listStoreCategories() {
36
+ try {
37
+ const res = await this.makeRequest('GET', '/store/categories', undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
38
+ return res.data ?? [];
39
+ }
40
+ catch (error) {
41
+ throw this.handleError(error);
42
+ }
43
+ }
44
+ /**
45
+ * Published listings, newest first, optionally one shelf.
46
+ *
47
+ * An unknown category slug is an EMPTY shelf, not every app on the store —
48
+ * so a typo shows nothing rather than showing everything.
49
+ *
50
+ * @param options - `category` is a category slug; `limit` defaults to 24.
51
+ */
52
+ async listStoreApps(options = {}) {
53
+ try {
54
+ const res = await this.makeRequest('GET', `/store/apps${queryOf(options)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
55
+ return pageOf(res);
56
+ }
57
+ catch (error) {
58
+ throw this.handleError(error);
59
+ }
60
+ }
61
+ /**
62
+ * One store page.
63
+ *
64
+ * A draft answers 404 exactly as an unknown slug does: whether an
65
+ * unpublished page exists under a name is not something a visitor learns.
66
+ *
67
+ * @param slug - The listing's public slug, not an application id.
68
+ */
69
+ async getStoreApp(slug) {
70
+ try {
71
+ const res = await this.makeRequest('GET', `/store/apps/${encodeURIComponent(slug)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
72
+ return res.data;
73
+ }
74
+ catch (error) {
75
+ throw this.handleError(error);
76
+ }
77
+ }
78
+ /** Visible reviews for a published app, each with the publisher's reply. */
79
+ async listStoreReviews(slug, options = {}) {
80
+ try {
81
+ const res = await this.makeRequest('GET', `/store/apps/${encodeURIComponent(slug)}/reviews${queryOf(options)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
82
+ return pageOf(res);
83
+ }
84
+ catch (error) {
85
+ throw this.handleError(error);
86
+ }
87
+ }
88
+ // =========================================================================
89
+ // Reviewing — any signed-in Oxy account
90
+ // =========================================================================
91
+ /** The caller's own review of an app, or `null` if they have not written one. */
92
+ async getMyStoreReview(slug) {
93
+ try {
94
+ const res = await this.makeRequest('GET', `/store/apps/${encodeURIComponent(slug)}/review`, undefined, { cache: false });
95
+ return res.data ?? null;
96
+ }
97
+ catch (error) {
98
+ throw this.handleError(error);
99
+ }
100
+ }
101
+ /**
102
+ * Write the caller's review, or replace what they said before.
103
+ *
104
+ * A person has one review per app, so this sets it rather than adding one.
105
+ * Rewriting does not clear a moderator's decision: a hidden review stays
106
+ * hidden when its author edits it.
107
+ */
108
+ async writeStoreReview(slug, input) {
109
+ try {
110
+ const res = await this.makeRequest('PUT', `/store/apps/${encodeURIComponent(slug)}/review`, input, { cache: false });
111
+ return res.data;
112
+ }
113
+ catch (error) {
114
+ throw this.handleError(error);
115
+ }
116
+ }
117
+ /** Withdraw the caller's own review. A real delete — the words were theirs. */
118
+ async deleteMyStoreReview(slug) {
119
+ try {
120
+ await this.makeRequest('DELETE', `/store/apps/${encodeURIComponent(slug)}/review`, undefined, { cache: false });
121
+ }
122
+ catch (error) {
123
+ throw this.handleError(error);
124
+ }
125
+ }
126
+ /**
127
+ * Answer a review on the publisher's behalf.
128
+ *
129
+ * Requires `app:update` over the application's owning account — the same
130
+ * permission that guards every other write to that application. Addressed
131
+ * by review id because the reply belongs to the review, and a listing can be
132
+ * renamed or withdrawn out from under it.
133
+ */
134
+ async replyToStoreReview(reviewId, body) {
135
+ try {
136
+ const res = await this.makeRequest('PUT', `/store/reviews/${encodeURIComponent(reviewId)}/reply`, { body }, { cache: false });
137
+ return res.data;
138
+ }
139
+ catch (error) {
140
+ throw this.handleError(error);
141
+ }
142
+ }
143
+ /** Withdraw the publisher's answer. Same permission that wrote it. */
144
+ async deleteStoreReviewReply(reviewId) {
145
+ try {
146
+ await this.makeRequest('DELETE', `/store/reviews/${encodeURIComponent(reviewId)}/reply`, undefined, { cache: false });
147
+ }
148
+ catch (error) {
149
+ throw this.handleError(error);
150
+ }
151
+ }
152
+ // =========================================================================
153
+ // The publisher's listing — /applications/:appId/listing
154
+ // =========================================================================
155
+ /** The application's store page in whatever state, or `null` if it has none. */
156
+ async getAppListing(applicationId) {
157
+ try {
158
+ return await this.makeRequest('GET', `/applications/${encodeURIComponent(applicationId)}/listing`, undefined, { cache: false });
159
+ }
160
+ catch (error) {
161
+ throw this.handleError(error);
162
+ }
163
+ }
164
+ /**
165
+ * Create the page or replace its content. Never its status.
166
+ *
167
+ * Editing does not move a page: correcting a typo on a live listing leaves
168
+ * it live, and fixing a rejected one does not re-submit it.
169
+ */
170
+ async writeAppListing(applicationId, input) {
171
+ try {
172
+ return await this.makeRequest('PUT', `/applications/${encodeURIComponent(applicationId)}/listing`, input, { cache: false });
173
+ }
174
+ catch (error) {
175
+ throw this.handleError(error);
176
+ }
177
+ }
178
+ /** Hand the page to the store for review. From a draft, or a rejected page once fixed. */
179
+ async submitAppListing(applicationId) {
180
+ try {
181
+ return await this.makeRequest('POST', `/applications/${encodeURIComponent(applicationId)}/listing/submit`, undefined, { cache: false });
182
+ }
183
+ catch (error) {
184
+ throw this.handleError(error);
185
+ }
186
+ }
187
+ /**
188
+ * Take the page down, or withdraw it from the queue.
189
+ *
190
+ * Back to a draft, never deleted: the slug, the words and the screenshots
191
+ * are the publisher's work, and the reviews were never the listing's to take
192
+ * with them.
193
+ */
194
+ async unpublishAppListing(applicationId) {
195
+ try {
196
+ return await this.makeRequest('POST', `/applications/${encodeURIComponent(applicationId)}/listing/unpublish`, undefined, { cache: false });
197
+ }
198
+ catch (error) {
199
+ throw this.handleError(error);
200
+ }
201
+ }
202
+ // =========================================================================
203
+ // Screenshots
204
+ // =========================================================================
205
+ /** Every picture on the listing, in the author's order. */
206
+ async listAppListingScreenshots(applicationId) {
207
+ try {
208
+ return await this.makeRequest('GET', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots`, undefined, { cache: false });
209
+ }
210
+ catch (error) {
211
+ throw this.handleError(error);
212
+ }
213
+ }
214
+ /**
215
+ * Attach an already-uploaded image, appended to the end.
216
+ *
217
+ * Upload through the assets surface first; the store keeps a reference
218
+ * rather than a second copy of the asset pipeline. The file must be live, an
219
+ * image, and one the caller is entitled to.
220
+ */
221
+ async addAppListingScreenshot(applicationId, input) {
222
+ try {
223
+ return await this.makeRequest('POST', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots`, input, { cache: false });
224
+ }
225
+ catch (error) {
226
+ throw this.handleError(error);
227
+ }
228
+ }
229
+ /** Edit a picture's caption or the frame it was taken in. Order is {@link reorderAppListingScreenshots}. */
230
+ async updateAppListingScreenshot(applicationId, screenshotId, input) {
231
+ try {
232
+ return await this.makeRequest('PATCH', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots/${encodeURIComponent(screenshotId)}`, input, { cache: false });
233
+ }
234
+ catch (error) {
235
+ throw this.handleError(error);
236
+ }
237
+ }
238
+ /** Remove a picture. The uploaded file stays — it may be in use elsewhere. */
239
+ async deleteAppListingScreenshot(applicationId, screenshotId) {
240
+ try {
241
+ await this.makeRequest('DELETE', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots/${encodeURIComponent(screenshotId)}`, undefined, { cache: false });
242
+ }
243
+ catch (error) {
244
+ throw this.handleError(error);
245
+ }
246
+ }
247
+ /**
248
+ * Set the order of every picture at once.
249
+ *
250
+ * Send EVERY id on the listing, exactly once, in the order they should
251
+ * appear. A partial list is rejected rather than applied: it would leave the
252
+ * pictures it omits at their old positions, interleaved with the new ones.
253
+ */
254
+ async reorderAppListingScreenshots(applicationId, screenshotIds) {
255
+ try {
256
+ return await this.makeRequest('PUT', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots/order`, { screenshotIds }, { cache: false });
257
+ }
258
+ catch (error) {
259
+ throw this.handleError(error);
260
+ }
261
+ }
262
+ };
263
+ }
@@ -133,18 +133,41 @@ export function OxyServicesUtilityMixin(Base) {
133
133
  * Uses server-side session validation for security (not just JWT decode).
134
134
  *
135
135
  * **Design note — jwtDecode vs jwt.verify:**
136
- * This middleware intentionally uses `jwtDecode()` (decode-only, no signature
137
- * verification) for user tokens. This is by design, NOT a security gap:
138
- * - Third-party apps using `oxy.auth()` don't have the Oxy JWT secret
139
- * - Security comes from API-based session validation (`validateSession()`)
140
- * which checks the session server-side on every request
141
- * - Service tokens (type: 'service') DO use cryptographic HMAC verification
142
- * via the `jwtSecret` option, since they are stateless. Service tokens
143
- * are additionally checked for `aud`, `iss`, and `type` claims to prevent
136
+ * This middleware uses `jwtDecode()` (decode-only, NO signature check) for
137
+ * user tokens, because third-party apps mounting `oxy.auth()` do not hold
138
+ * the Oxy signing secret. **Every claim in a user token is therefore
139
+ * attacker-controlled and proves nothing on its own.** The identity comes
140
+ * from somewhere else entirely:
141
+ * - A user token MUST carry a `sessionId`. That session is validated
142
+ * server-side on every request via `validateSession()`, and the user id
143
+ * is read off the VALIDATED SESSION never off the token. A token whose
144
+ * `userId` claim disagrees with the session is refused
145
+ * (`SESSION_USER_MISMATCH`); a token with no `sessionId` at all is
146
+ * refused outright (`SESSION_REQUIRED`). There is no local-claims path.
147
+ * - Service tokens (type: 'service') ARE stateless, so they use
148
+ * cryptographic HMAC verification via the `jwtSecret` option, and are
149
+ * additionally checked for `aud`, `iss`, and `type` claims to prevent
144
150
  * cross-token-type confusion attacks.
145
151
  * - The backend's own `authMiddleware` uses `jwt.verify()` because it has
146
152
  * direct access to `SERVICE_TOKEN_SECRET` / `ACCESS_TOKEN_SECRET`.
147
153
  *
154
+ * **Why session-less user tokens are refused rather than trusted:**
155
+ * every user access token the Oxy API issues carries a `sessionId` (see
156
+ * `packages/api/src/utils/sessionUtils.ts`, `generateSessionTokens` — the
157
+ * only mint site for user tokens, including the OAuth code exchange). So
158
+ * refusing session-less user tokens costs nothing legitimate, while
159
+ * accepting them let anyone authenticate as anyone by hand-rolling a JWT
160
+ * with a `userId` claim and a garbage signature.
161
+ *
162
+ * **Why the claimed user id is cross-checked against the session:**
163
+ * `GET /session/validate/:sessionId` is UNAUTHENTICATED and does not bind
164
+ * the bearer token — it returns whoever owns the session id it was handed.
165
+ * Trusting the token's `userId` claim after a successful validation would
166
+ * therefore let a caller holding ANY live session id (their own, for
167
+ * instance) pair it with a forged `userId` and be trusted as that user.
168
+ * `authSocket()` has always cross-checked this; the HTTP middleware now
169
+ * does too.
170
+ *
148
171
  * **Service-token delegation (X-Oxy-User-Id):**
149
172
  * When a service token is accompanied by `X-Oxy-User-Id`, the SDK calls
150
173
  * `verifyServiceActingAs(appId, userId)` to confirm an explicit delegation
@@ -407,8 +430,10 @@ export function OxyServicesUtilityMixin(Base) {
407
430
  }
408
431
  return next();
409
432
  }
410
- const userId = decoded.userId || decoded.id;
411
- if (!userId) {
433
+ // The CLAIMED user id. Never trusted as an identity — it is only ever
434
+ // compared against the id the validated session resolves to.
435
+ const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
436
+ if (!claimedUserId) {
412
437
  if (optional) {
413
438
  req.userId = null;
414
439
  req.user = null;
@@ -442,111 +467,129 @@ export function OxyServicesUtilityMixin(Base) {
442
467
  return onError(error);
443
468
  return res.status(401).json(error);
444
469
  }
445
- // Validate token against the Oxy API for session-based verification
446
- // This ensures the session hasn't been revoked server-side
447
- if (decoded.sessionId) {
448
- try {
449
- const validationResult = await oxyInstance.validateSession(decoded.sessionId, {
450
- useHeaderValidation: true,
451
- });
452
- if (!validationResult || !validationResult.valid) {
453
- if (optional) {
454
- req.userId = null;
455
- req.user = null;
456
- return next();
457
- }
458
- const error = {
459
- error: 'INVALID_SESSION',
460
- message: 'Session invalid or expired',
461
- code: 'INVALID_SESSION',
462
- status: 401
463
- };
464
- if (onError)
465
- return onError(error);
466
- return res.status(401).json(error);
467
- }
468
- // Use validated user data from session validation (already has full user)
469
- req.userId = userId;
470
- req.accessToken = token;
471
- req.sessionId = decoded.sessionId;
472
- if (loadUser && validationResult.user) {
473
- // Session validation already returns full user data
474
- req.user = validationResult.user;
475
- }
476
- else {
477
- req.user = { id: userId };
478
- }
479
- if (debug) {
480
- logger.debug(`[oxy.auth] OK user=${userId} session=${decoded.sessionId}`, {
481
- component: 'auth',
482
- method: 'auth',
483
- });
484
- }
470
+ // A server-validated session is MANDATORY for a user token. The JWT
471
+ // signature is not verified on this path, so a bare decoded token
472
+ // proves nothing: without the session round-trip a forged token could
473
+ // claim any user id. Mirrors `authSocket()`, which has always
474
+ // required this.
475
+ const sessionId = readStringClaim(decoded.sessionId);
476
+ if (!sessionId) {
477
+ if (optional) {
478
+ req.userId = null;
479
+ req.user = null;
485
480
  return next();
486
481
  }
487
- catch (validationError) {
488
- if (debug) {
489
- logger.debug('[oxy.auth] Session validation failed', {
490
- component: 'auth',
491
- method: 'auth',
492
- }, validationError);
493
- }
482
+ const error = {
483
+ error: 'SESSION_REQUIRED',
484
+ message: 'Access token is not bound to a session',
485
+ code: 'SESSION_REQUIRED',
486
+ status: 401
487
+ };
488
+ if (onError)
489
+ return onError(error);
490
+ return res.status(401).json(error);
491
+ }
492
+ // Validate the token against the Oxy API. This proves the session is
493
+ // real and unrevoked, AND yields the identity it belongs to.
494
+ try {
495
+ const validationResult = await oxyInstance.validateSession(sessionId, {
496
+ useHeaderValidation: true,
497
+ });
498
+ if (!validationResult || !validationResult.valid || !validationResult.user) {
494
499
  if (optional) {
495
500
  req.userId = null;
496
501
  req.user = null;
497
502
  return next();
498
503
  }
499
504
  const error = {
500
- error: 'SESSION_VALIDATION_ERROR',
501
- message: 'Session validation failed',
502
- code: 'SESSION_VALIDATION_ERROR',
505
+ error: 'INVALID_SESSION',
506
+ message: 'Session invalid or expired',
507
+ code: 'INVALID_SESSION',
503
508
  status: 401
504
509
  };
505
510
  if (onError)
506
511
  return onError(error);
507
512
  return res.status(401).json(error);
508
513
  }
509
- }
510
- // Non-session token: use local validation only (userId from JWT)
511
- req.userId = userId;
512
- req.accessToken = token;
513
- req.user = { id: userId };
514
- // If loadUser requested with non-session token, fetch from API
515
- if (loadUser) {
516
- try {
517
- // Temporarily set token to make the API call
518
- const prevToken = oxyInstance.getAccessToken();
519
- oxyInstance.setTokens(token);
520
- const fullUser = await oxyInstance.getCurrentUser();
521
- // Restore previous token
522
- if (prevToken) {
523
- oxyInstance.setTokens(prevToken);
524
- }
525
- else {
526
- oxyInstance.clearTokens();
514
+ // The session — not the token — is the source of truth for identity.
515
+ const validatedUserId = getUserIdentityId(validationResult.user);
516
+ if (!validatedUserId) {
517
+ if (optional) {
518
+ req.userId = null;
519
+ req.user = null;
520
+ return next();
527
521
  }
528
- if (fullUser) {
529
- req.user = fullUser;
522
+ const error = {
523
+ error: 'INVALID_SESSION',
524
+ message: 'Session did not resolve to a usable identity',
525
+ code: 'INVALID_SESSION',
526
+ status: 401
527
+ };
528
+ if (onError)
529
+ return onError(error);
530
+ return res.status(401).json(error);
531
+ }
532
+ if (validatedUserId !== claimedUserId) {
533
+ // Session-id/claim confusion: the caller presented a live session
534
+ // that belongs to somebody else. Worth a warning — it has no
535
+ // benign cause. Ids only; never the token or the payload.
536
+ logger.warn('[oxy.auth] Token rejected — claimed user does not own the session', {
537
+ component: 'auth',
538
+ method: 'auth',
539
+ claimedUserId,
540
+ validatedUserId,
541
+ });
542
+ if (optional) {
543
+ req.userId = null;
544
+ req.user = null;
545
+ return next();
530
546
  }
547
+ const error = {
548
+ error: 'SESSION_USER_MISMATCH',
549
+ message: 'Token user does not match the session',
550
+ code: 'SESSION_USER_MISMATCH',
551
+ status: 401
552
+ };
553
+ if (onError)
554
+ return onError(error);
555
+ return res.status(401).json(error);
531
556
  }
532
- catch (loadUserError) {
533
- // Loading the full user is best-effort here; the basic { id }
534
- // object is already attached. Log so misconfigured deployments
535
- // can be diagnosed instead of silently failing.
536
- logger.warn('[oxy.auth] loadUser fallback could not fetch full profile', {
557
+ req.userId = validatedUserId;
558
+ req.accessToken = token;
559
+ req.sessionId = sessionId;
560
+ // Session validation already returned the full user, so `loadUser`
561
+ // costs no extra round-trip.
562
+ req.user = loadUser ? validationResult.user : { id: validatedUserId };
563
+ if (debug) {
564
+ logger.debug(`[oxy.auth] OK user=${validatedUserId} session=${sessionId}`, {
537
565
  component: 'auth',
538
- method: 'auth.loadUser',
539
- userId,
540
- }, loadUserError);
566
+ method: 'auth',
567
+ });
541
568
  }
569
+ return next();
542
570
  }
543
- if (debug) {
544
- logger.debug(`[oxy.auth] OK user=${userId} (no session)`, {
545
- component: 'auth',
546
- method: 'auth',
547
- });
571
+ catch (validationError) {
572
+ if (debug) {
573
+ logger.debug('[oxy.auth] Session validation failed', {
574
+ component: 'auth',
575
+ method: 'auth',
576
+ }, validationError);
577
+ }
578
+ if (optional) {
579
+ req.userId = null;
580
+ req.user = null;
581
+ return next();
582
+ }
583
+ const error = {
584
+ error: 'SESSION_VALIDATION_ERROR',
585
+ message: 'Session validation failed',
586
+ code: 'SESSION_VALIDATION_ERROR',
587
+ status: 401
588
+ };
589
+ if (onError)
590
+ return onError(error);
591
+ return res.status(401).json(error);
548
592
  }
549
- next();
550
593
  }
551
594
  catch (error) {
552
595
  const handled = oxyInstance.handleError(error);
@@ -615,7 +658,7 @@ export function OxyServicesUtilityMixin(Base) {
615
658
  }
616
659
  return next(new Error('Invalid token'));
617
660
  }
618
- const claimedUserId = decoded.userId || decoded.id;
661
+ const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
619
662
  if (!claimedUserId) {
620
663
  return next(new Error('Invalid token payload'));
621
664
  }
@@ -626,12 +669,13 @@ export function OxyServicesUtilityMixin(Base) {
626
669
  // A server-validated session is mandatory. A bare decoded JWT proves
627
670
  // nothing — the signature is not verified here, so without a session
628
671
  // round-trip a forged token could claim any user id.
629
- if (!decoded.sessionId) {
672
+ const sessionId = readStringClaim(decoded.sessionId);
673
+ if (!sessionId) {
630
674
  return next(new Error('Session required'));
631
675
  }
632
676
  let userId = claimedUserId;
633
677
  try {
634
- const result = await oxyInstance.validateSession(decoded.sessionId, {
678
+ const result = await oxyInstance.validateSession(sessionId, {
635
679
  useHeaderValidation: true,
636
680
  });
637
681
  if (!result || !result.valid || !result.user) {
@@ -661,9 +705,9 @@ export function OxyServicesUtilityMixin(Base) {
661
705
  // reads from `socket.user.id`.
662
706
  socket.data = socket.data || {};
663
707
  socket.data.userId = userId;
664
- socket.data.sessionId = decoded.sessionId || null;
708
+ socket.data.sessionId = sessionId;
665
709
  socket.data.token = token;
666
- socket.user = { id: userId, userId, sessionId: decoded.sessionId };
710
+ socket.user = { id: userId, userId, sessionId };
667
711
  if (debug) {
668
712
  logger.debug(`[oxy.authSocket] OK user=${userId}`, {
669
713
  component: 'auth',
@@ -807,12 +851,16 @@ async function verifyServiceTokenSignature(token, secret) {
807
851
  }
808
852
  }
809
853
  /**
810
- * Verify that a decoded service-token payload carries the expected `aud`,
811
- * `iss`, and `type` claims. Throws `ServiceTokenClaimError` on mismatch.
812
- * This is the defence against the H4 vulnerability where a recovery / 2FA /
813
- * access token signed by the same shared secret could be replayed as a
814
- * service token because no claim binding existed.
854
+ * Read a JWT claim that is only usable as a non-empty string.
855
+ *
856
+ * A decoded payload is attacker-controlled JSON: a claim the type declares as
857
+ * `string` can arrive as a number, an object, or `null`. Narrowing here keeps
858
+ * those values out of URL construction and identity comparison, so an
859
+ * unexpected shape becomes a 401 rather than a stringified surprise.
815
860
  */
861
+ function readStringClaim(value) {
862
+ return typeof value === 'string' && value.length > 0 ? value : null;
863
+ }
816
864
  /**
817
865
  * Resolve the canonical user id from a validated session's user object.
818
866
  *
@@ -825,6 +873,13 @@ function getUserIdentityId(user) {
825
873
  ?? user._id;
826
874
  return typeof candidate === 'string' && candidate.length > 0 ? candidate : null;
827
875
  }
876
+ /**
877
+ * Verify that a decoded service-token payload carries the expected `aud`,
878
+ * `iss`, and `type` claims. Throws `ServiceTokenClaimError` on mismatch.
879
+ * This is the defence against the H4 vulnerability where a recovery / 2FA /
880
+ * access token signed by the same shared secret could be replayed as a
881
+ * service token because no claim binding existed.
882
+ */
828
883
  function verifyServiceTokenClaims(decoded, expected) {
829
884
  if (decoded.type !== 'service') {
830
885
  throw new ServiceTokenClaimError(`Service token has unexpected type '${String(decoded.type)}'`);
@@ -16,6 +16,7 @@ import { OxyServicesReputationMixin } from './OxyServices.reputation.js';
16
16
  import { OxyServicesAssetsMixin } from './OxyServices.assets.js';
17
17
  import { OxyServicesAccountsMixin } from './OxyServices.accounts.js';
18
18
  import { OxyServicesConnectedAppsMixin } from './OxyServices.connectedApps.js';
19
+ import { OxyServicesStoreMixin } from './OxyServices.store.js';
19
20
  import { OxyServicesLocationMixin } from './OxyServices.location.js';
20
21
  import { OxyServicesAnalyticsMixin } from './OxyServices.analytics.js';
21
22
  import { OxyServicesDevicesMixin } from './OxyServices.devices.js';
@@ -27,6 +28,7 @@ import { OxyServicesContactsMixin } from './OxyServices.contacts.js';
27
28
  import { OxyServicesNotificationsMixin } from './OxyServices.notifications.js';
28
29
  import { OxyServicesAppDataMixin } from './OxyServices.appData.js';
29
30
  import { OxyServicesCivicMixin } from './OxyServices.civic.js';
31
+ import { OxyServicesChainsMixin } from './OxyServices.chains.js';
30
32
  import { OxyServicesNodesMixin } from './OxyServices.nodes.js';
31
33
  import { OxyServicesLinksMixin } from './OxyServices.links.js';
32
34
  import { OxyServicesFollowGraphMixin } from './OxyServices.followGraph.js';
@@ -66,6 +68,10 @@ const MIXIN_PIPELINE = [
66
68
  // OAuth-consent surface (public app identity + connected-app grants). Kept
67
69
  // separate from account ownership.
68
70
  OxyServicesConnectedAppsMixin,
71
+ // The app store: the public storefront, the reviews on it, and the listing a
72
+ // publisher edits. A module OVER the platform — turn it off and OAuth still
73
+ // works — so it is its own surface rather than more of `accounts`.
74
+ OxyServicesStoreMixin,
69
75
  OxyServicesLocationMixin,
70
76
  OxyServicesAnalyticsMixin,
71
77
  OxyServicesDevicesMixin,
@@ -80,6 +86,7 @@ const MIXIN_PIPELINE = [
80
86
  OxyServicesAppDataMixin,
81
87
  // Civic / Commons "Oxy ID" (public signed cards, Oxy ID QR payload)
82
88
  OxyServicesCivicMixin,
89
+ OxyServicesChainsMixin,
83
90
  // User nodes / decentralization (Fase 5): register/read/revoke/manage the
84
91
  // caller's personal data node + ingest hint.
85
92
  OxyServicesNodesMixin,