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