@oxyhq/core 3.1.0 → 3.4.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 (74) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/AuthManager.js +14 -3
  3. package/dist/cjs/HttpService.js +89 -0
  4. package/dist/cjs/OxyServices.js +2 -1
  5. package/dist/cjs/constants/version.js +1 -1
  6. package/dist/cjs/i18n/locales/en-US.json +44 -44
  7. package/dist/cjs/i18n/locales/es-ES.json +44 -44
  8. package/dist/cjs/i18n/locales/locales/en-US.json +44 -44
  9. package/dist/cjs/i18n/locales/locales/es-ES.json +44 -44
  10. package/dist/cjs/index.js +4 -0
  11. package/dist/cjs/mixins/OxyServices.applications.js +33 -3
  12. package/dist/cjs/mixins/OxyServices.reputation.js +244 -0
  13. package/dist/cjs/mixins/OxyServices.workspaces.js +146 -0
  14. package/dist/cjs/mixins/index.js +4 -2
  15. package/dist/cjs/utils/accountUtils.js +12 -5
  16. package/dist/cjs/utils/ssoReturn.js +80 -33
  17. package/dist/esm/.tsbuildinfo +1 -1
  18. package/dist/esm/AuthManager.js +14 -3
  19. package/dist/esm/HttpService.js +89 -0
  20. package/dist/esm/OxyServices.js +2 -1
  21. package/dist/esm/constants/version.js +1 -1
  22. package/dist/esm/i18n/locales/en-US.json +44 -44
  23. package/dist/esm/i18n/locales/es-ES.json +44 -44
  24. package/dist/esm/i18n/locales/locales/en-US.json +44 -44
  25. package/dist/esm/i18n/locales/locales/es-ES.json +44 -44
  26. package/dist/esm/index.js +4 -0
  27. package/dist/esm/mixins/OxyServices.applications.js +33 -3
  28. package/dist/esm/mixins/OxyServices.reputation.js +241 -0
  29. package/dist/esm/mixins/OxyServices.workspaces.js +143 -0
  30. package/dist/esm/mixins/index.js +4 -2
  31. package/dist/esm/utils/accountUtils.js +12 -5
  32. package/dist/esm/utils/ssoReturn.js +80 -33
  33. package/dist/types/.tsbuildinfo +1 -1
  34. package/dist/types/HttpService.d.ts +57 -0
  35. package/dist/types/OxyServices.d.ts +2 -1
  36. package/dist/types/constants/version.d.ts +2 -2
  37. package/dist/types/index.d.ts +4 -2
  38. package/dist/types/mixins/OxyServices.applications.d.ts +86 -10
  39. package/dist/types/mixins/OxyServices.features.d.ts +0 -1
  40. package/dist/types/mixins/OxyServices.reputation.d.ts +436 -0
  41. package/dist/types/mixins/OxyServices.workspaces.d.ts +205 -0
  42. package/dist/types/mixins/index.d.ts +3 -2
  43. package/dist/types/models/interfaces.d.ts +24 -26
  44. package/dist/types/utils/accountUtils.d.ts +17 -4
  45. package/dist/types/utils/ssoReturn.d.ts +30 -9
  46. package/package.json +2 -1
  47. package/src/AuthManager.ts +14 -3
  48. package/src/HttpService.ts +91 -0
  49. package/src/OxyServices.ts +2 -1
  50. package/src/__tests__/authManager.cookiePath.test.ts +49 -0
  51. package/src/__tests__/httpServiceCache.test.ts +198 -0
  52. package/src/constants/version.ts +1 -1
  53. package/src/i18n/locales/en-US.json +44 -44
  54. package/src/i18n/locales/es-ES.json +44 -44
  55. package/src/index.ts +51 -4
  56. package/src/mixins/OxyServices.applications.ts +103 -5
  57. package/src/mixins/OxyServices.auth.ts +2 -1
  58. package/src/mixins/OxyServices.features.ts +0 -1
  59. package/src/mixins/OxyServices.reputation.ts +674 -0
  60. package/src/mixins/OxyServices.workspaces.ts +315 -0
  61. package/src/mixins/__tests__/reputation.test.ts +408 -0
  62. package/src/mixins/index.ts +6 -3
  63. package/src/models/interfaces.ts +25 -32
  64. package/src/utils/__tests__/accountUtils.test.ts +142 -0
  65. package/src/utils/__tests__/consumeSsoReturn.test.ts +229 -37
  66. package/src/utils/accountUtils.ts +20 -5
  67. package/src/utils/ssoReturn.ts +98 -37
  68. package/dist/cjs/mixins/OxyServices.developer.js +0 -97
  69. package/dist/cjs/mixins/OxyServices.karma.js +0 -108
  70. package/dist/esm/mixins/OxyServices.developer.js +0 -94
  71. package/dist/esm/mixins/OxyServices.karma.js +0 -105
  72. package/dist/types/mixins/OxyServices.developer.d.ts +0 -106
  73. package/dist/types/mixins/OxyServices.karma.d.ts +0 -92
  74. package/src/mixins/OxyServices.karma.ts +0 -111
@@ -0,0 +1,241 @@
1
+ import { CACHE_TIMES } from './mixinHelpers.js';
2
+ /** Cache-key prefix for every cached `GET /reputation/...` response. */
3
+ const REPUTATION_CACHE_PREFIX = 'GET:/reputation/';
4
+ export function OxyServicesReputationMixin(Base) {
5
+ return class extends Base {
6
+ constructor(...args) {
7
+ super(...args);
8
+ }
9
+ /**
10
+ * Get a user's cached reputation balance — derived totals, per-category
11
+ * breakdown, trust tier, capped influence weights, and reliability signals.
12
+ * @param userId - The subject user's `_id` or publicKey.
13
+ */
14
+ async getReputationBalance(userId) {
15
+ try {
16
+ return await this.makeRequest('GET', `/reputation/${encodeURIComponent(userId)}/balance`, undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
17
+ }
18
+ catch (error) {
19
+ throw this.handleError(error);
20
+ }
21
+ }
22
+ /**
23
+ * Get the reputation leaderboard, ordered by lifetime total descending.
24
+ * @param limit - Page size (server-capped).
25
+ * @param offset - Page offset.
26
+ */
27
+ async getReputationLeaderboard(limit, offset) {
28
+ try {
29
+ const params = {};
30
+ if (limit !== undefined)
31
+ params.limit = limit;
32
+ if (offset !== undefined)
33
+ params.offset = offset;
34
+ const res = await this.makeRequest('GET', '/reputation/leaderboard', Object.keys(params).length > 0 ? params : undefined, { cache: true, cacheTTL: CACHE_TIMES.LONG });
35
+ return res.data ?? [];
36
+ }
37
+ catch (error) {
38
+ throw this.handleError(error);
39
+ }
40
+ }
41
+ /**
42
+ * List the enabled reputation rules (for client display).
43
+ */
44
+ async getReputationRules() {
45
+ try {
46
+ const res = await this.makeRequest('GET', '/reputation/rules', undefined, { cache: true, cacheTTL: CACHE_TIMES.EXTRA_LONG });
47
+ return res.rules ?? [];
48
+ }
49
+ catch (error) {
50
+ throw this.handleError(error);
51
+ }
52
+ }
53
+ /**
54
+ * Get a user's paginated reputation ledger, newest first (auth required).
55
+ * @param userId - The subject user's `_id` or publicKey.
56
+ * @param limit - Page size (server-capped).
57
+ * @param offset - Page offset.
58
+ */
59
+ async getReputationTransactions(userId, limit, offset) {
60
+ try {
61
+ const params = {};
62
+ if (limit !== undefined)
63
+ params.limit = limit;
64
+ if (offset !== undefined)
65
+ params.offset = offset;
66
+ const res = await this.makeRequest('GET', `/reputation/${encodeURIComponent(userId)}/transactions`, Object.keys(params).length > 0 ? params : undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
67
+ return res.data ?? [];
68
+ }
69
+ catch (error) {
70
+ throw this.handleError(error);
71
+ }
72
+ }
73
+ /**
74
+ * Get a user's capped influence weight for a given context (auth required).
75
+ * @param userId - The subject user's `_id` or publicKey.
76
+ * @param context - The weight axis to read (defaults server-side to `default`).
77
+ */
78
+ async getReputationInfluence(userId, context) {
79
+ try {
80
+ return await this.makeRequest('GET', `/reputation/${encodeURIComponent(userId)}/influence`, context ? { context } : undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
81
+ }
82
+ catch (error) {
83
+ throw this.handleError(error);
84
+ }
85
+ }
86
+ /**
87
+ * Award (or penalise) reputation to a user by `actionType`. Restricted to
88
+ * service tokens and platform staff. Invalidates cached reputation reads.
89
+ * @param input - The award payload (subject, action, source, target, etc.).
90
+ */
91
+ async awardReputation(input) {
92
+ try {
93
+ const res = await this.makeRequest('POST', '/reputation/award', input, { cache: false });
94
+ this.clearCacheByPrefix(REPUTATION_CACHE_PREFIX);
95
+ return res.transaction;
96
+ }
97
+ catch (error) {
98
+ throw this.handleError(error);
99
+ }
100
+ }
101
+ /**
102
+ * Open a dispute against a transaction (auth required; the disputer is the
103
+ * authenticated user and must own the transaction).
104
+ * @param input - The transaction id, reason, and optional evidence.
105
+ */
106
+ async createReputationDispute(input) {
107
+ try {
108
+ const res = await this.makeRequest('POST', '/reputation/disputes', input, { cache: false });
109
+ this.clearCacheByPrefix(REPUTATION_CACHE_PREFIX);
110
+ return res.dispute;
111
+ }
112
+ catch (error) {
113
+ throw this.handleError(error);
114
+ }
115
+ }
116
+ /**
117
+ * List a user's own reputation disputes (auth required; the caller must be
118
+ * the subject or platform staff).
119
+ * @param userId - The subject user's `_id` or publicKey.
120
+ * @param limit - Page size (server-capped).
121
+ * @param offset - Page offset.
122
+ */
123
+ async getUserReputationDisputes(userId, limit, offset) {
124
+ try {
125
+ const params = {};
126
+ if (limit !== undefined)
127
+ params.limit = limit;
128
+ if (offset !== undefined)
129
+ params.offset = offset;
130
+ const res = await this.makeRequest('GET', `/reputation/${encodeURIComponent(userId)}/disputes`, Object.keys(params).length > 0 ? params : undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
131
+ return res.data ?? [];
132
+ }
133
+ catch (error) {
134
+ throw this.handleError(error);
135
+ }
136
+ }
137
+ // =========================================================================
138
+ // STAFF / ADMIN METHODS (require staff privileges server-side)
139
+ // =========================================================================
140
+ /**
141
+ * Create or update a reputation rule, keyed by `actionType` (staff only).
142
+ * Invalidates the cached rule list.
143
+ * @param input - The rule definition.
144
+ */
145
+ async upsertReputationRule(input) {
146
+ try {
147
+ const res = await this.makeRequest('POST', '/reputation/rules', input, { cache: false });
148
+ this.clearCacheByPrefix(REPUTATION_CACHE_PREFIX);
149
+ return res.rule;
150
+ }
151
+ catch (error) {
152
+ throw this.handleError(error);
153
+ }
154
+ }
155
+ /**
156
+ * Reverse a transaction (staff only): mark the original `reversed` and append
157
+ * a compensating `active` reversal with negated points. Invalidates cached
158
+ * reputation reads.
159
+ * @param transactionId - The transaction's id.
160
+ * @param input - Optional reason for the reversal.
161
+ */
162
+ async reverseReputationTransaction(transactionId, input) {
163
+ try {
164
+ const res = await this.makeRequest('POST', `/reputation/transactions/${encodeURIComponent(transactionId)}/reverse`, input ?? {}, { cache: false });
165
+ this.clearCacheByPrefix(REPUTATION_CACHE_PREFIX);
166
+ return res;
167
+ }
168
+ catch (error) {
169
+ throw this.handleError(error);
170
+ }
171
+ }
172
+ /**
173
+ * Void a transaction (staff only): mark it `voided` so it is excluded from
174
+ * the balance, with NO compensating entry. Invalidates cached reputation
175
+ * reads.
176
+ * @param transactionId - The transaction's id.
177
+ * @param input - Optional reason for the void.
178
+ */
179
+ async voidReputationTransaction(transactionId, input) {
180
+ try {
181
+ const res = await this.makeRequest('POST', `/reputation/transactions/${encodeURIComponent(transactionId)}/void`, input ?? {}, { cache: false });
182
+ this.clearCacheByPrefix(REPUTATION_CACHE_PREFIX);
183
+ return res.transaction;
184
+ }
185
+ catch (error) {
186
+ throw this.handleError(error);
187
+ }
188
+ }
189
+ /**
190
+ * Force a recompute of a user's balance snapshot from their active ledger
191
+ * (staff only). Invalidates cached reputation reads.
192
+ * @param userId - The subject user's `_id` or publicKey.
193
+ */
194
+ async recalculateReputation(userId) {
195
+ try {
196
+ const res = await this.makeRequest('POST', `/reputation/${encodeURIComponent(userId)}/recalculate`, undefined, { cache: false });
197
+ this.clearCacheByPrefix(REPUTATION_CACHE_PREFIX);
198
+ return res;
199
+ }
200
+ catch (error) {
201
+ throw this.handleError(error);
202
+ }
203
+ }
204
+ /**
205
+ * Get the open dispute queue across all users (staff only).
206
+ * @param limit - Page size (server-capped).
207
+ * @param offset - Page offset.
208
+ */
209
+ async getReputationDisputeQueue(limit, offset) {
210
+ try {
211
+ const params = {};
212
+ if (limit !== undefined)
213
+ params.limit = limit;
214
+ if (offset !== undefined)
215
+ params.offset = offset;
216
+ const res = await this.makeRequest('GET', '/reputation/disputes', Object.keys(params).length > 0 ? params : undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
217
+ return res.data ?? [];
218
+ }
219
+ catch (error) {
220
+ throw this.handleError(error);
221
+ }
222
+ }
223
+ /**
224
+ * Resolve a dispute (staff only). Accepting reverses the disputed
225
+ * transaction; rejecting restores it to `active`. Invalidates cached
226
+ * reputation reads.
227
+ * @param disputeId - The dispute's id.
228
+ * @param input - The resolution (`accepted` or `rejected`).
229
+ */
230
+ async resolveReputationDispute(disputeId, input) {
231
+ try {
232
+ const res = await this.makeRequest('POST', `/reputation/disputes/${encodeURIComponent(disputeId)}/resolve`, input, { cache: false });
233
+ this.clearCacheByPrefix(REPUTATION_CACHE_PREFIX);
234
+ return res.dispute;
235
+ }
236
+ catch (error) {
237
+ throw this.handleError(error);
238
+ }
239
+ }
240
+ };
241
+ }
@@ -0,0 +1,143 @@
1
+ import { CACHE_TIMES } from './mixinHelpers.js';
2
+ export function OxyServicesWorkspacesMixin(Base) {
3
+ return class extends Base {
4
+ constructor(...args) {
5
+ super(...args);
6
+ }
7
+ /**
8
+ * List workspaces the current user is an active member of.
9
+ */
10
+ async getWorkspaces() {
11
+ try {
12
+ const res = await this.makeRequest('GET', '/workspaces', undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
13
+ return res.workspaces ?? [];
14
+ }
15
+ catch (error) {
16
+ throw this.handleError(error);
17
+ }
18
+ }
19
+ /**
20
+ * Create a new team workspace. The caller becomes its `owner`.
21
+ * @param data - Workspace configuration.
22
+ */
23
+ async createWorkspace(data) {
24
+ try {
25
+ const res = await this.makeRequest('POST', '/workspaces', data, { cache: false });
26
+ return res.workspace;
27
+ }
28
+ catch (error) {
29
+ throw this.handleError(error);
30
+ }
31
+ }
32
+ /**
33
+ * Fetch a single workspace by id.
34
+ * @param workspaceId - The workspace's Mongo `_id`.
35
+ */
36
+ async getWorkspace(workspaceId) {
37
+ try {
38
+ const res = await this.makeRequest('GET', `/workspaces/${encodeURIComponent(workspaceId)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.LONG });
39
+ return res.workspace;
40
+ }
41
+ catch (error) {
42
+ throw this.handleError(error);
43
+ }
44
+ }
45
+ /**
46
+ * Update a workspace's mutable fields.
47
+ * @param workspaceId - The workspace's Mongo `_id`.
48
+ * @param data - Subset of updatable fields.
49
+ */
50
+ async updateWorkspace(workspaceId, data) {
51
+ try {
52
+ const res = await this.makeRequest('PATCH', `/workspaces/${encodeURIComponent(workspaceId)}`, data, { cache: false });
53
+ return res.workspace;
54
+ }
55
+ catch (error) {
56
+ throw this.handleError(error);
57
+ }
58
+ }
59
+ /**
60
+ * Soft-delete a workspace (owner only).
61
+ * @param workspaceId - The workspace's Mongo `_id`.
62
+ */
63
+ async deleteWorkspace(workspaceId) {
64
+ try {
65
+ return await this.makeRequest('DELETE', `/workspaces/${encodeURIComponent(workspaceId)}`, undefined, { cache: false });
66
+ }
67
+ catch (error) {
68
+ throw this.handleError(error);
69
+ }
70
+ }
71
+ /**
72
+ * List members of a workspace.
73
+ * @param workspaceId - The workspace's Mongo `_id`.
74
+ */
75
+ async getWorkspaceMembers(workspaceId) {
76
+ try {
77
+ const res = await this.makeRequest('GET', `/workspaces/${encodeURIComponent(workspaceId)}/members`, undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
78
+ return res.members ?? [];
79
+ }
80
+ catch (error) {
81
+ throw this.handleError(error);
82
+ }
83
+ }
84
+ /**
85
+ * Add a member to a workspace.
86
+ * @param workspaceId - The workspace's Mongo `_id`.
87
+ * @param data - Target user's username or email and role (never `owner`).
88
+ * The server resolves `usernameOrEmail` to a user; an unknown value yields
89
+ * a 404 "User not found".
90
+ */
91
+ async inviteWorkspaceMember(workspaceId, data) {
92
+ try {
93
+ const res = await this.makeRequest('POST', `/workspaces/${encodeURIComponent(workspaceId)}/members`, data, { cache: false });
94
+ return res.member;
95
+ }
96
+ catch (error) {
97
+ throw this.handleError(error);
98
+ }
99
+ }
100
+ /**
101
+ * Change a member's role.
102
+ * @param workspaceId - The workspace's Mongo `_id`.
103
+ * @param memberId - The member's Mongo `_id`.
104
+ * @param data - New role (never `owner`).
105
+ */
106
+ async updateWorkspaceMember(workspaceId, memberId, data) {
107
+ try {
108
+ const res = await this.makeRequest('PATCH', `/workspaces/${encodeURIComponent(workspaceId)}/members/${encodeURIComponent(memberId)}`, data, { cache: false });
109
+ return res.member;
110
+ }
111
+ catch (error) {
112
+ throw this.handleError(error);
113
+ }
114
+ }
115
+ /**
116
+ * Remove a member from a workspace.
117
+ * @param workspaceId - The workspace's Mongo `_id`.
118
+ * @param memberId - The member's Mongo `_id`.
119
+ */
120
+ async removeWorkspaceMember(workspaceId, memberId) {
121
+ try {
122
+ return await this.makeRequest('DELETE', `/workspaces/${encodeURIComponent(workspaceId)}/members/${encodeURIComponent(memberId)}`, undefined, { cache: false });
123
+ }
124
+ catch (error) {
125
+ throw this.handleError(error);
126
+ }
127
+ }
128
+ /**
129
+ * Transfer ownership of a workspace to another member (owner only).
130
+ * Demotes the current owner and promotes the target to `owner`.
131
+ * @param workspaceId - The workspace's Mongo `_id`.
132
+ * @param data - Target user id.
133
+ */
134
+ async transferWorkspaceOwnership(workspaceId, data) {
135
+ try {
136
+ return await this.makeRequest('POST', `/workspaces/${encodeURIComponent(workspaceId)}/transfer-ownership`, data, { cache: false });
137
+ }
138
+ catch (error) {
139
+ throw this.handleError(error);
140
+ }
141
+ }
142
+ };
143
+ }
@@ -14,9 +14,10 @@ import { OxyServicesUserMixin } from './OxyServices.user.js';
14
14
  import { OxyServicesPrivacyMixin } from './OxyServices.privacy.js';
15
15
  import { OxyServicesLanguageMixin } from './OxyServices.language.js';
16
16
  import { OxyServicesPaymentMixin } from './OxyServices.payment.js';
17
- import { OxyServicesKarmaMixin } from './OxyServices.karma.js';
17
+ import { OxyServicesReputationMixin } from './OxyServices.reputation.js';
18
18
  import { OxyServicesAssetsMixin } from './OxyServices.assets.js';
19
19
  import { OxyServicesApplicationsMixin } from './OxyServices.applications.js';
20
+ import { OxyServicesWorkspacesMixin } from './OxyServices.workspaces.js';
20
21
  import { OxyServicesLocationMixin } from './OxyServices.location.js';
21
22
  import { OxyServicesAnalyticsMixin } from './OxyServices.analytics.js';
22
23
  import { OxyServicesDevicesMixin } from './OxyServices.devices.js';
@@ -58,9 +59,10 @@ const MIXIN_PIPELINE = [
58
59
  // Feature mixins
59
60
  OxyServicesLanguageMixin,
60
61
  OxyServicesPaymentMixin,
61
- OxyServicesKarmaMixin,
62
+ OxyServicesReputationMixin,
62
63
  OxyServicesAssetsMixin,
63
64
  OxyServicesApplicationsMixin,
65
+ OxyServicesWorkspacesMixin,
64
66
  OxyServicesLocationMixin,
65
67
  OxyServicesAnalyticsMixin,
66
68
  OxyServicesDevicesMixin,
@@ -17,11 +17,16 @@ export const formatPublicKeyHandle = (publicKey) => {
17
17
  * Resolve a friendly display name for a user.
18
18
  *
19
19
  * Order of preference:
20
- * 1. `name.full`, or composed `name.first name.last`
20
+ * 1. `name.full`, or composed `name.first name.last` (FIRST-NAME-ONLY SAFE —
21
+ * a user with only a first name resolves to that first name, never to the
22
+ * lowercase username; this is the exact drift bug the auth app hit).
21
23
  * 2. `name` (when stored as a plain string)
22
- * 3. `username`
23
- * 4. `Account 0x12345678…` (derived from publicKey, when present)
24
- * 5. Translated fallback (e.g. "Unnamed")
24
+ * 3. `displayName` (server `displayName` virtual — `username || truncatedKey`).
25
+ * Placed AFTER the structured name on purpose: the server virtual ignores
26
+ * `name`, so preferring it first would re-introduce the first-only bug.
27
+ * 4. `username`
28
+ * 5. `Account 0x12345678…` (derived from publicKey, when present)
29
+ * 6. Translated fallback (e.g. "Unnamed")
25
30
  *
26
31
  * The translation key `common.unnamed` is used for the final fallback. If the
27
32
  * caller does not pass a locale, the default English translation is used.
@@ -29,7 +34,7 @@ export const formatPublicKeyHandle = (publicKey) => {
29
34
  export const getAccountDisplayName = (user, locale) => {
30
35
  if (!user)
31
36
  return translate(locale, 'common.unnamed');
32
- const { name, username, publicKey } = user;
37
+ const { name, displayName, username, publicKey } = user;
33
38
  if (name && typeof name === 'object') {
34
39
  if (typeof name.full === 'string' && name.full.trim())
35
40
  return name.full.trim();
@@ -42,6 +47,8 @@ export const getAccountDisplayName = (user, locale) => {
42
47
  else if (typeof name === 'string' && name.trim()) {
43
48
  return name.trim();
44
49
  }
50
+ if (typeof displayName === 'string' && displayName.trim())
51
+ return displayName.trim();
45
52
  if (typeof username === 'string' && username.trim())
46
53
  return username.trim();
47
54
  if (typeof publicKey === 'string' && publicKey.length > 0) {
@@ -92,14 +92,22 @@ export function parseSsoReturnFragment(hash) {
92
92
  * treated exactly like "no session" (never loops, never rethrows).
93
93
  * - On EVERY consumed outcome (ok, none, error, state-mismatch, no-code,
94
94
  * failed-exchange, no-sessionId) — not just ok — if the page landed on
95
- * {@link SSO_CALLBACK_PATH}, the real pre-bounce destination is restored
96
- * from the DEST key so the user is never stranded on the internal callback
97
- * path. Same-origin only (an attacker-planted cross-origin or relative-evil
98
- * dest is rejected). The DEST key is removed unconditionally.
99
- * - After a same-origin dest restore (which uses `history.replaceState`, that
100
- * does NOT itself emit `popstate`), a synthetic `popstate` is dispatched so
101
- * URL-driven routers (Expo Router / React Navigation web) re-sync to the
102
- * restored route. It is NOT dispatched when the dest is rejected/absent.
95
+ * {@link SSO_CALLBACK_PATH}, the user is taken to a same-origin TARGET so
96
+ * they are never stranded on the internal callback path (which is an
97
+ * unregistered route in every consumer router a hard 404). The target is
98
+ * the stored DEST when it parses as same-origin (an attacker-planted
99
+ * cross-origin / protocol-relative dest is rejected), ELSE the app root
100
+ * (`origin + '/'`). The DEST key is removed unconditionally.
101
+ * - For the `ok` outcome the target is applied via a SOFT
102
+ * `history.replaceState` + synthetic `popstate` so the freshly exchanged
103
+ * in-memory session the provider is about to commit is preserved (no
104
+ * reload). `popstate` is dispatched only on the `ok` same-origin restore.
105
+ * - For every NON-`ok` outcome there is no in-memory session to preserve, and
106
+ * the consumer router has ALREADY synchronously rendered its 404 for the
107
+ * unregistered callback route — a soft replaceState+popstate does not
108
+ * reliably make it re-resolve. So these outcomes perform a HARD
109
+ * full-document navigation to the target (`hardRedirect`), which is both
110
+ * safe (nothing to lose) and guaranteed to clear the 404 in every router.
103
111
  *
104
112
  * Total: this function NEVER throws. Off-web it is a no-op returning `null`.
105
113
  *
@@ -133,6 +141,17 @@ export async function consumeSsoReturn(oxy, deps = {}) {
133
141
  window.dispatchEvent(new Event('popstate'));
134
142
  }
135
143
  });
144
+ // Default: a hard, full-document navigation used to leave the callback path
145
+ // on non-`ok` outcomes. Feature-detected end to end so it never throws in any
146
+ // environment (SSR / native / a stubbed location without `replace`).
147
+ const hardRedirect = deps.hardRedirect ??
148
+ ((url) => {
149
+ if (typeof window !== 'undefined' &&
150
+ window.location &&
151
+ typeof window.location.replace === 'function') {
152
+ window.location.replace(url);
153
+ }
154
+ });
136
155
  const ret = parseSsoReturnFragment(location.hash);
137
156
  if (!ret) {
138
157
  // Not an oxy_sso fragment — nothing to do (do NOT touch any flags).
@@ -155,42 +174,62 @@ export async function consumeSsoReturn(oxy, deps = {}) {
155
174
  // even if some consumer path skipped setting it pre-bounce.
156
175
  storage.setItem(ssoAttemptedKey(origin), '1');
157
176
  };
158
- // Restore the user's real pre-bounce destination so they are never stranded
159
- // on the internal callback path invoked on EVERY consumed outcome, not just
160
- // success. Same-origin only never honour a cross-origin/protocol-relative
161
- // dest that could have been planted to redirect the user. The DEST key is
162
- // removed unconditionally. After a successful same-origin restore a synthetic
163
- // `popstate` is dispatched so URL-driven routers re-sync.
164
- const restoreDest = () => {
165
- if (location.pathname === SSO_CALLBACK_PATH) {
166
- const dest = storage.getItem(ssoDestKey(origin));
167
- if (dest) {
168
- try {
169
- const destUrl = new URL(dest, origin);
170
- if (destUrl.origin === origin) {
171
- history.replaceState(null, '', destUrl.pathname + destUrl.search + destUrl.hash);
172
- dispatchPopState();
173
- }
174
- }
175
- catch {
176
- // Malformed stored destination — leave the URL on the callback path.
177
+ // Compute the same-origin TARGET to leave the callback path for. Returns the
178
+ // stored DEST when present AND it parses as same-origin (never honour a
179
+ // cross-origin / protocol-relative dest that could have been planted to
180
+ // redirect the user), ELSE the app root (`origin + '/'`) so the user is never
181
+ // stranded on the internal callback path even when no dest was stored. The
182
+ // DEST key is removed unconditionally. Returns the relative path+search+hash
183
+ // (so it can be fed to either `history.replaceState` or a `hardRedirect`),
184
+ // or `null` when the page is not on the callback path (nothing to leave).
185
+ const consumeCallbackTarget = () => {
186
+ if (location.pathname !== SSO_CALLBACK_PATH) {
187
+ // Not on the callback path — still drop the dest key (consumed) but there
188
+ // is nothing to navigate away from.
189
+ storage.removeItem(ssoDestKey(origin));
190
+ return null;
191
+ }
192
+ const dest = storage.getItem(ssoDestKey(origin));
193
+ storage.removeItem(ssoDestKey(origin));
194
+ if (dest) {
195
+ try {
196
+ const destUrl = new URL(dest, origin);
197
+ if (destUrl.origin === origin) {
198
+ return destUrl.pathname + destUrl.search + destUrl.hash;
177
199
  }
178
200
  }
201
+ catch {
202
+ // Malformed stored destination — fall through to the app-root fallback.
203
+ }
204
+ }
205
+ // No dest, a cross-origin/protocol-relative dest, or an unparseable dest:
206
+ // fall back to the app root so the router always leaves the 404.
207
+ return '/';
208
+ };
209
+ // Non-`ok` outcomes: there is no in-memory session to preserve, and the
210
+ // consumer router has already rendered its 404 for the unregistered callback
211
+ // route — a soft replaceState+popstate does not reliably make it re-resolve.
212
+ // Perform a HARD full-document navigation to the target (safe: nothing to
213
+ // lose; guaranteed: every router leaves the 404). Off the callback path this
214
+ // is a no-op (target is null).
215
+ const leaveCallbackHard = () => {
216
+ const target = consumeCallbackTarget();
217
+ if (target !== null) {
218
+ hardRedirect(origin + target);
179
219
  }
180
- storage.removeItem(ssoDestKey(origin));
181
220
  };
182
221
  if (ret.kind === 'none' || ret.kind === 'error') {
183
222
  // The central IdP had no session (or the bounce failed). Record it so we do
184
223
  // not bounce again this tab — the definitive loop breaker.
185
224
  markNoSession();
186
- restoreDest();
225
+ leaveCallbackHard();
187
226
  return null;
188
227
  }
189
228
  if (!stateOk || !ret.code) {
190
229
  // Forged / replayed / stale fragment, or a malformed ok with no code. Treat
191
230
  // exactly like "no session": never exchange, never loop.
192
231
  markNoSession();
193
- restoreDest();
232
+ leaveCallbackHard();
194
233
  return null;
195
234
  }
196
235
  let session;
@@ -200,14 +239,22 @@ export async function consumeSsoReturn(oxy, deps = {}) {
200
239
  catch (error) {
201
240
  onExchangeError?.(error);
202
241
  markNoSession();
203
- restoreDest();
242
+ leaveCallbackHard();
204
243
  return null;
205
244
  }
206
245
  if (!session?.sessionId) {
207
246
  markNoSession();
208
- restoreDest();
247
+ leaveCallbackHard();
209
248
  return null;
210
249
  }
211
- restoreDest();
250
+ // `ok`: the provider is about to commit the freshly exchanged in-memory
251
+ // session — do NOT hard-redirect (a full navigation would discard it). Use a
252
+ // SOFT `history.replaceState` to the target + a synthetic `popstate` so
253
+ // URL-driven routers re-sync to the restored route without a reload.
254
+ const target = consumeCallbackTarget();
255
+ if (target !== null) {
256
+ history.replaceState(null, '', target);
257
+ dispatchPopState();
258
+ }
212
259
  return session;
213
260
  }