@oxyhq/core 12.5.4 → 12.7.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 (60) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/HttpService.js +4 -1
  3. package/dist/cjs/OxyServices.errors.js +42 -1
  4. package/dist/cjs/OxyServices.js +2 -1
  5. package/dist/cjs/crypto/keyManager.js +50 -0
  6. package/dist/cjs/i18n/locales/en-US.json +7 -0
  7. package/dist/cjs/i18n/locales/es-ES.json +7 -0
  8. package/dist/cjs/i18n/locales/locales/en-US.json +7 -0
  9. package/dist/cjs/i18n/locales/locales/es-ES.json +7 -0
  10. package/dist/cjs/index.js +5 -4
  11. package/dist/cjs/mixins/OxyServices.assets.js +175 -25
  12. package/dist/cjs/mixins/OxyServices.deviceTransfer.js +319 -0
  13. package/dist/cjs/mixins/index.js +4 -0
  14. package/dist/cjs/session/SessionClient.js +57 -8
  15. package/dist/cjs/utils/redactUrl.js +29 -0
  16. package/dist/esm/.tsbuildinfo +1 -1
  17. package/dist/esm/HttpService.js +4 -1
  18. package/dist/esm/OxyServices.errors.js +40 -0
  19. package/dist/esm/OxyServices.js +2 -2
  20. package/dist/esm/crypto/keyManager.js +50 -0
  21. package/dist/esm/i18n/locales/en-US.json +7 -0
  22. package/dist/esm/i18n/locales/es-ES.json +7 -0
  23. package/dist/esm/i18n/locales/locales/en-US.json +7 -0
  24. package/dist/esm/i18n/locales/locales/es-ES.json +7 -0
  25. package/dist/esm/index.js +1 -1
  26. package/dist/esm/mixins/OxyServices.assets.js +175 -25
  27. package/dist/esm/mixins/OxyServices.deviceTransfer.js +317 -0
  28. package/dist/esm/mixins/index.js +4 -0
  29. package/dist/esm/session/SessionClient.js +57 -8
  30. package/dist/esm/utils/redactUrl.js +26 -0
  31. package/dist/types/.tsbuildinfo +1 -1
  32. package/dist/types/OxyServices.d.ts +2 -2
  33. package/dist/types/OxyServices.errors.d.ts +40 -0
  34. package/dist/types/crypto/keyManager.d.ts +20 -0
  35. package/dist/types/index.d.ts +3 -2
  36. package/dist/types/mixins/OxyServices.assets.d.ts +103 -13
  37. package/dist/types/mixins/OxyServices.deviceTransfer.d.ts +149 -0
  38. package/dist/types/mixins/index.d.ts +2 -1
  39. package/dist/types/models/interfaces.d.ts +18 -0
  40. package/dist/types/session/SessionClient.d.ts +19 -2
  41. package/dist/types/utils/redactUrl.d.ts +17 -0
  42. package/package.json +1 -1
  43. package/src/HttpService.ts +4 -1
  44. package/src/OxyServices.errors.ts +51 -0
  45. package/src/OxyServices.ts +2 -2
  46. package/src/crypto/__tests__/scopedSeed.test.ts +126 -0
  47. package/src/crypto/keyManager.ts +55 -0
  48. package/src/i18n/locales/en-US.json +7 -0
  49. package/src/i18n/locales/es-ES.json +7 -0
  50. package/src/index.ts +7 -1
  51. package/src/mixins/OxyServices.assets.ts +192 -28
  52. package/src/mixins/OxyServices.deviceTransfer.ts +397 -0
  53. package/src/mixins/__tests__/OxyServices.deviceTransfer.test.ts +270 -0
  54. package/src/mixins/__tests__/getFileDownloadUrl.test.ts +265 -1
  55. package/src/mixins/index.ts +6 -0
  56. package/src/models/interfaces.ts +20 -0
  57. package/src/session/SessionClient.ts +59 -8
  58. package/src/session/__tests__/SessionClient.switchTokenOrder.test.ts +170 -0
  59. package/src/utils/__tests__/redactUrl.test.ts +33 -0
  60. package/src/utils/redactUrl.ts +28 -0
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Device-to-device Identity Transfer Mixin (b3 Feature 2 — "add a device")
3
+ *
4
+ * Clones an existing device's secp256k1 identity onto a fresh device over a
5
+ * short-lived, unauthenticated relay, WITHOUT the server ever holding a
6
+ * decryption key. Both devices end up holding the SAME private key.
7
+ *
8
+ * The two devices agree on a symmetric key via an ephemeral secp256k1 ECDH
9
+ * handshake (Phase-0 crypto): `deriveSharedSecret` → `hkdfSha256` → a per-pairing
10
+ * transfer key, used with `encryptAead`/`decryptAead` (XChaCha20-Poly1305) to
11
+ * seal `{ privateKey, publicKey }`. The relay carries only ephemeral public keys
12
+ * plus opaque ciphertext — a passive/at-rest-compromised backend cannot decrypt.
13
+ *
14
+ * Roles:
15
+ * - NEW device (no identity): {@link initDeviceTransfer} (generate ephemeral
16
+ * pair, register the pairing, render `pairingId` as a QR) then
17
+ * {@link subscribeDeviceTransfer} (await approval over the `/device-pair`
18
+ * socket with a poll fallback, decrypt, and import the key).
19
+ * - OLD device (has identity): {@link getDeviceTransferInfo} (resolve the
20
+ * scanned `pairingId` server-side — the QR is NOT self-contained) then
21
+ * {@link approveDeviceTransfer} (biometric-gate in the UI, seal the key
22
+ * material, and post it with a fresh signature over the CURRENT identity key).
23
+ *
24
+ * SECURITY: E2E against a passive relay only. Explicitly NOT hardened against an
25
+ * actively-malicious backend MITM'ing the ephemeral keys (same trust boundary as
26
+ * the existing QR sign-in; SAS compare deferred per owner decision). Approve
27
+ * requires BOTH a bearer token AND a fresh identity-key signature.
28
+ */
29
+ import _cjs_elliptic from 'elliptic';
30
+ const { ec: EC } = _cjs_elliptic;
31
+ import { bytesToHex, hexToBytes, utf8ToBytes, bytesToUtf8 } from '@noble/hashes/utils';
32
+ import { deriveSharedSecret } from '../crypto/ecdh.js';
33
+ import { hkdfSha256 } from '../crypto/kdf.js';
34
+ import { encryptAead, decryptAead } from '../crypto/aead.js';
35
+ import { KeyManager } from '../crypto/keyManager.js';
36
+ import { SignatureService } from '../crypto/signatureService.js';
37
+ import { getSocketIO } from '../session/socketLoader.js';
38
+ import { logger } from '../logger/index.js';
39
+ const ecCurve = new EC('secp256k1');
40
+ /**
41
+ * Ephemeral private keys for pairings an instance INITIATED, keyed by pairingId,
42
+ * held per OxyServices instance. In-memory ONLY (never persisted — single-use),
43
+ * cleared once the transfer settles. A module-level WeakMap (rather than a class
44
+ * field) keeps it off the mixin's emitted `.d.ts` (avoids TS4094 on the exported
45
+ * anonymous class) and lets the GC drop it with the instance.
46
+ */
47
+ const ephemeralKeyStore = new WeakMap();
48
+ function getEphemeralKeys(instance) {
49
+ let keys = ephemeralKeyStore.get(instance);
50
+ if (!keys) {
51
+ keys = new Map();
52
+ ephemeralKeyStore.set(instance, keys);
53
+ }
54
+ return keys;
55
+ }
56
+ /** HKDF `info` binding — MUST match the server/other-device byte-for-byte. */
57
+ const DEVICE_TRANSFER_HKDF_INFO = 'oxy-device-transfer-v1';
58
+ /** Socket.IO namespace the API pushes device-pair approval events on. */
59
+ const DEVICE_PAIR_NAMESPACE = '/device-pair';
60
+ /** Fallback poll cadence — the socket delivers approval instantly; this covers
61
+ * the case where the socket can't connect. */
62
+ const DEVICE_TRANSFER_POLL_INTERVAL_MS = 2500;
63
+ /** Action string signed on approve (mirrors `link_identity`'s scheme). */
64
+ const DEVICE_TRANSFER_APPROVE_ACTION = 'approve_device_transfer';
65
+ /**
66
+ * Derive the per-pairing symmetric transfer key from an ECDH shared secret.
67
+ * Identical on both devices: `HKDF(ECDH, salt=pairingId, info=v1)`.
68
+ */
69
+ function deriveTransferKey(sharedSecret, pairingId) {
70
+ return hkdfSha256(sharedSecret, utf8ToBytes(pairingId), utf8ToBytes(DEVICE_TRANSFER_HKDF_INFO), 32);
71
+ }
72
+ export function OxyServicesDeviceTransferMixin(Base) {
73
+ return class extends Base {
74
+ constructor(...args) {
75
+ super(...args);
76
+ }
77
+ /**
78
+ * NEW device — begin an "add a device" transfer. Generates a single-use
79
+ * ephemeral secp256k1 pair, registers the pairing, and returns the
80
+ * `pairingId` to render as a QR. The ephemeral private key is held in memory
81
+ * (keyed by `pairingId`) for the subsequent {@link subscribeDeviceTransfer}.
82
+ *
83
+ * @param label - Optional human-readable label for this new device.
84
+ */
85
+ async initDeviceTransfer(label) {
86
+ try {
87
+ const ephKeyPair = ecCurve.genKeyPair();
88
+ const ephPrivateKey = ephKeyPair.getPrivate('hex');
89
+ const ephPublicKey = ephKeyPair.getPublic('hex');
90
+ const res = await this.makeRequest('POST', '/identity/device-transfer/init', { newEphPub: ephPublicKey, ...(label ? { newDeviceLabel: label } : {}) }, { cache: false });
91
+ getEphemeralKeys(this).set(res.pairingId, ephPrivateKey);
92
+ return {
93
+ pairingId: res.pairingId,
94
+ expiresAt: res.expiresAt,
95
+ newEphemeralPublicKey: ephPublicKey,
96
+ };
97
+ }
98
+ catch (error) {
99
+ throw this.handleError(error);
100
+ }
101
+ }
102
+ /**
103
+ * Resolve a pairing server-side (the QR carries only `pairingId`). The OLD
104
+ * device calls this after scanning to read the new device's ephemeral public
105
+ * key + label; the NEW device polls it to fetch the sealed material once
106
+ * approved. Public — no auth required.
107
+ */
108
+ async getDeviceTransferInfo(pairingId) {
109
+ try {
110
+ return await this.makeRequest('GET', `/identity/device-transfer/${encodeURIComponent(pairingId)}`, undefined, { cache: false, retry: false });
111
+ }
112
+ catch (error) {
113
+ throw this.handleError(error);
114
+ }
115
+ }
116
+ /**
117
+ * OLD device — approve a scanned transfer. Reads the new device's ephemeral
118
+ * public key, derives the shared transfer key, AEAD-seals
119
+ * `{ privateKey, publicKey }`, and posts it PLUS a fresh signature over
120
+ * `{ action:'approve_device_transfer', pairingId, timestamp }` made with the
121
+ * CURRENT identity key (dual-proof alongside the bearer token).
122
+ *
123
+ * NATIVE-ONLY: requires a stored identity (throws otherwise). The UI must
124
+ * biometric-gate before calling this — a key clone leaves the device.
125
+ */
126
+ async approveDeviceTransfer(pairingId) {
127
+ try {
128
+ const info = await this.getDeviceTransferInfo(pairingId);
129
+ if (info.status !== 'pending') {
130
+ throw new Error(`This transfer can no longer be approved (status: ${info.status}).`);
131
+ }
132
+ const privateKey = await KeyManager.getPrivateKey();
133
+ const publicKey = await KeyManager.getPublicKey();
134
+ if (!privateKey || !publicKey) {
135
+ throw new Error('No identity found on this device. Create or import an identity first.');
136
+ }
137
+ // Ephemeral ECDH → per-pairing transfer key.
138
+ const oldEphKeyPair = ecCurve.genKeyPair();
139
+ const oldEphPrivateKey = oldEphKeyPair.getPrivate('hex');
140
+ const oldEphPublicKey = oldEphKeyPair.getPublic('hex');
141
+ const sharedSecret = deriveSharedSecret(oldEphPrivateKey, info.newDeviceEphemeralPublicKey);
142
+ const transferKey = deriveTransferKey(sharedSecret, pairingId);
143
+ // Seal the identity key material.
144
+ const plaintext = utf8ToBytes(JSON.stringify({ privateKey, publicKey }));
145
+ const { nonce, ciphertext } = encryptAead(transferKey, plaintext);
146
+ // Dual-proof: prove control of the CURRENT identity key (a bearer alone
147
+ // must not be able to exfiltrate the private key).
148
+ const timestamp = Date.now();
149
+ const message = JSON.stringify({
150
+ action: DEVICE_TRANSFER_APPROVE_ACTION,
151
+ pairingId,
152
+ timestamp,
153
+ });
154
+ const signature = await SignatureService.sign(message);
155
+ return await this.makeRequest('POST', `/identity/device-transfer/${encodeURIComponent(pairingId)}/approve`, {
156
+ oldEphPub: oldEphPublicKey,
157
+ ciphertext: bytesToHex(ciphertext),
158
+ nonce: bytesToHex(nonce),
159
+ signature,
160
+ timestamp,
161
+ }, { cache: false });
162
+ }
163
+ catch (error) {
164
+ throw this.handleError(error);
165
+ }
166
+ }
167
+ /**
168
+ * OLD device — deny (cancel) a scanned transfer so the waiting new device
169
+ * stops. Public — no auth required.
170
+ */
171
+ async denyDeviceTransfer(pairingId) {
172
+ try {
173
+ return await this.makeRequest('POST', `/identity/device-transfer/${encodeURIComponent(pairingId)}/deny`, undefined, { cache: false });
174
+ }
175
+ catch (error) {
176
+ throw this.handleError(error);
177
+ }
178
+ }
179
+ /**
180
+ * NEW device — await approval for a pairing started with
181
+ * {@link initDeviceTransfer}, then decrypt and import the transferred
182
+ * identity key. Primary path is an instant `device_pair_update` push over the
183
+ * `/device-pair` socket; a poll backstops a socket that can't connect.
184
+ *
185
+ * On `approved`: re-derives the shared transfer key from the old device's
186
+ * ephemeral public key, decrypts `{ privateKey, publicKey }`, imports it via
187
+ * `KeyManager.importKeyPair(privateKey, { overwrite: false })`, and invokes
188
+ * `onOutcome({ status:'approved', publicKey })`. The caller then runs the
189
+ * NORMAL challenge/verify sign-in — this method does not mint a session.
190
+ *
191
+ * @returns An unsubscribe function; call it to stop waiting (also called
192
+ * automatically once the transfer settles).
193
+ */
194
+ subscribeDeviceTransfer(pairingId, onOutcome) {
195
+ const ephemeralKeys = getEphemeralKeys(this);
196
+ const ephPrivateKey = ephemeralKeys.get(pairingId);
197
+ if (!ephPrivateKey) {
198
+ throw new Error('No pending device transfer for this pairing id. Call initDeviceTransfer first.');
199
+ }
200
+ let settled = false;
201
+ let inFlight = false;
202
+ let socket = null;
203
+ let pollTimer = null;
204
+ const cleanup = () => {
205
+ if (pollTimer !== null) {
206
+ clearInterval(pollTimer);
207
+ pollTimer = null;
208
+ }
209
+ if (socket) {
210
+ try {
211
+ socket.off('device_pair_update');
212
+ socket.off('connect');
213
+ socket.disconnect();
214
+ }
215
+ catch (error) {
216
+ logger.debug('[DeviceTransfer] socket close failed', { component: 'DeviceTransfer' }, error);
217
+ }
218
+ socket = null;
219
+ }
220
+ ephemeralKeys.delete(pairingId);
221
+ };
222
+ const finish = (outcome) => {
223
+ if (settled)
224
+ return;
225
+ settled = true;
226
+ cleanup();
227
+ onOutcome(outcome);
228
+ };
229
+ // Re-check authoritative status; on `approved`, decrypt + import.
230
+ const check = async () => {
231
+ if (settled || inFlight)
232
+ return;
233
+ inFlight = true;
234
+ try {
235
+ const info = await this.getDeviceTransferInfo(pairingId);
236
+ if (settled)
237
+ return;
238
+ if (info.status === 'denied') {
239
+ finish({ status: 'denied' });
240
+ return;
241
+ }
242
+ if (info.status === 'expired') {
243
+ finish({ status: 'expired' });
244
+ return;
245
+ }
246
+ if (info.status === 'approved' &&
247
+ info.oldDeviceEphemeralPublicKey &&
248
+ info.ciphertext &&
249
+ info.nonce) {
250
+ const sharedSecret = deriveSharedSecret(ephPrivateKey, info.oldDeviceEphemeralPublicKey);
251
+ const transferKey = deriveTransferKey(sharedSecret, pairingId);
252
+ const plaintext = decryptAead(transferKey, hexToBytes(info.nonce), hexToBytes(info.ciphertext));
253
+ const parsed = JSON.parse(bytesToUtf8(plaintext));
254
+ // Import WITHOUT overwrite: a fresh device has no identity, and we
255
+ // must never silently clobber an existing one.
256
+ const importedPublicKey = await KeyManager.importKeyPair(parsed.privateKey, {
257
+ overwrite: false,
258
+ });
259
+ finish({ status: 'approved', publicKey: importedPublicKey });
260
+ }
261
+ }
262
+ catch (error) {
263
+ // Transient (a poll tick that raced the approve write, a decrypt on a
264
+ // half-written row) — keep waiting; the next tick/push retries.
265
+ logger.debug('[DeviceTransfer] status check failed', { component: 'DeviceTransfer' }, error);
266
+ }
267
+ finally {
268
+ inFlight = false;
269
+ }
270
+ };
271
+ // Primary: instant socket wake. Fall back to polling if unavailable.
272
+ void (async () => {
273
+ const io = await getSocketIO();
274
+ if (settled || !io)
275
+ return;
276
+ try {
277
+ const s = io(`${this.getBaseURL()}${DEVICE_PAIR_NAMESPACE}`, {
278
+ transports: ['websocket'],
279
+ autoConnect: true,
280
+ reconnection: true,
281
+ reconnectionAttempts: Number.POSITIVE_INFINITY,
282
+ reconnectionDelay: 1000,
283
+ reconnectionDelayMax: 10000,
284
+ });
285
+ const join = () => {
286
+ try {
287
+ s.emit('join', pairingId);
288
+ }
289
+ catch (error) {
290
+ logger.debug('[DeviceTransfer] join failed', { component: 'DeviceTransfer' }, error);
291
+ }
292
+ };
293
+ s.on('connect', join);
294
+ if (s.connected)
295
+ join();
296
+ s.on('device_pair_update', () => {
297
+ void check();
298
+ });
299
+ socket = s;
300
+ }
301
+ catch (error) {
302
+ logger.debug('[DeviceTransfer] socket create failed (poll fallback)', { component: 'DeviceTransfer' }, error);
303
+ }
304
+ })();
305
+ // Fallback poll (also covers the already-approved-before-subscribe case via
306
+ // the immediate first tick below). unref so it never holds a Node event
307
+ // loop / test runner open.
308
+ pollTimer = setInterval(() => {
309
+ void check();
310
+ }, DEVICE_TRANSFER_POLL_INTERVAL_MS);
311
+ pollTimer.unref?.();
312
+ // Immediate first check — the transfer may already be approved/denied.
313
+ void check();
314
+ return cleanup;
315
+ }
316
+ };
317
+ }
@@ -29,6 +29,7 @@ import { OxyServicesCivicMixin } from './OxyServices.civic.js';
29
29
  import { OxyServicesNodesMixin } from './OxyServices.nodes.js';
30
30
  import { OxyServicesLinksMixin } from './OxyServices.links.js';
31
31
  import { OxyServicesDeviceBootMixin } from './OxyServices.deviceBoot.js';
32
+ import { OxyServicesDeviceTransferMixin } from './OxyServices.deviceTransfer.js';
32
33
  /**
33
34
  * Mixin pipeline - applied in order from first to last.
34
35
  *
@@ -82,6 +83,9 @@ const MIXIN_PIPELINE = [
82
83
  // Device-first token mint: the client half of the zero-cookie transport
83
84
  // (`mintFromDeviceSecret` → `POST /session/device/token`).
84
85
  OxyServicesDeviceBootMixin,
86
+ // Device-to-device identity transfer ("add a device"): E2E-encrypted key
87
+ // clone over a short-lived relay (b3 Feature 2).
88
+ OxyServicesDeviceTransferMixin,
85
89
  // Utility (last, can use all above)
86
90
  OxyServicesUtilityMixin,
87
91
  ];
@@ -1,5 +1,6 @@
1
1
  import { deviceSessionStateSchema, deviceSessionSyncSchema, safeParseContract, SESSION_ACCOUNTS_CHANGED_EVENT, sessionAccountsChangedEventSchema, } from '@oxyhq/contracts';
2
2
  import { logger } from '../logger/index.js';
3
+ import { computeIdentityTag } from '../utils/cacheKey.js';
3
4
  import { getSocketIO } from './socketLoader.js';
4
5
  /**
5
6
  * Same-origin `BroadcastChannel` name for instant, network-free session-state
@@ -80,8 +81,25 @@ export class SessionClient {
80
81
  }
81
82
  }
82
83
  }
83
- /** Validate + last-writer-wins by revision. Returns true if applied. */
84
- applyState(raw, origin = 'push') {
84
+ /**
85
+ * Validate + last-writer-wins by revision. Returns true if applied.
86
+ *
87
+ * `activeToken` (sync path only) is the server-issued access token for
88
+ * `raw.activeAccountId`. When present and the state is applied, it is planted
89
+ * BEFORE any subscriber is notified so the bearer already belongs to the new
90
+ * active account — the local switch/bootstrap path then needs no redundant
91
+ * device-secret mint. Push-origin applies carry no token and rely on the
92
+ * mint-before-notify gate below.
93
+ *
94
+ * ORDERING INVARIANT: a subscriber must NEVER observe a newly-active account
95
+ * while the planted bearer still identifies the PREVIOUS one — otherwise a
96
+ * `useCurrentUser`-style refetch fires under the wrong account's token (the
97
+ * account-switch 404 race). So when a transport is available and the planted
98
+ * bearer does not already belong to `next.activeAccountId`, minting is awaited
99
+ * BEFORE `notify()`. This covers EVERY notify source (a switch push, a
100
+ * cross-device push, a cold mint), not just the initial "no bearer yet" case.
101
+ */
102
+ applyState(raw, origin = 'push', activeToken) {
85
103
  const next = safeParseContract(deviceSessionStateSchema, raw);
86
104
  if (!next) {
87
105
  logger.warn('[SessionClient] discarded invalid session state');
@@ -98,9 +116,26 @@ export class SessionClient {
98
116
  next.revision <= this.state.revision) {
99
117
  return false;
100
118
  }
119
+ const previousState = this.state;
101
120
  this.state = next;
121
+ // Plant the sync-supplied active token (it is for `next.activeAccountId`)
122
+ // now — before the notify below — so the bearer matches the new active
123
+ // account when subscribers observe it. Guarded on difference to avoid a
124
+ // redundant token-change notification on an unchanged token (bootstrap
125
+ // restate).
126
+ if (activeToken && next.activeAccountId !== null && activeToken !== this.host.getAccessToken()) {
127
+ this.host.setTokens(activeToken);
128
+ }
102
129
  const transport = this.options.transport;
103
- const needsMintBeforeNotify = transport != null && next.accounts.length > 0 && !this.host.getAccessToken();
130
+ const activeAccountId = next.activeAccountId;
131
+ // Mint before notifying when the bearer does not already belong to the new
132
+ // active account: no bearer at all, an opaque bearer, OR a bearer for a
133
+ // DIFFERENT account. `computeIdentityTag` yields the token's `userId`/`id`
134
+ // for a real JWT (comparable to the account id) and a non-account sentinel
135
+ // otherwise, so a mismatch always resolves to "mint".
136
+ const needsMintBeforeNotify = transport != null &&
137
+ next.accounts.length > 0 &&
138
+ (activeAccountId === null || computeIdentityTag(this.host.getAccessToken()) !== activeAccountId);
104
139
  const finishApply = () => {
105
140
  this.notify();
106
141
  if (next.accounts.length === 0 && this.options.onUnauthenticated) {
@@ -114,8 +149,10 @@ export class SessionClient {
114
149
  };
115
150
  if (needsMintBeforeNotify) {
116
151
  void transport.ensureActiveToken(next).then(finishApply).catch((error) => {
117
- logger.warn('[SessionClient] ensureActiveToken failed', { component: 'SessionClient' }, error);
118
- finishApply();
152
+ logger.warn('[SessionClient] ensureActiveToken failed — reverting session state', { component: 'SessionClient' }, error);
153
+ // Do NOT notify under a mismatched bearer. Revert to the last applied
154
+ // state so subscribers keep observing the account whose token is planted.
155
+ this.state = previousState ?? null;
119
156
  });
120
157
  }
121
158
  else {
@@ -153,9 +190,21 @@ export class SessionClient {
153
190
  }
154
191
  // A `sync` is always the response to a direct REST call this client made
155
192
  // (bootstrap / switch / signOut / add) → a `request`-origin, authoritative
156
- // verdict.
157
- this.applyState(sync.state, 'request');
158
- if (sync.activeToken && this.state && sync.state.activeAccountId === this.state.activeAccountId) {
193
+ // verdict. Hand the active token to `applyState`: in the applied path it is
194
+ // planted BEFORE notify (bearer matches the new active account when
195
+ // subscribers observe it, and no redundant device-secret mint is triggered).
196
+ const applied = this.applyState(sync.state, 'request', sync.activeToken?.accessToken);
197
+ // Equal-revision restate (this revision was already applied by a preceding
198
+ // socket push): `applyState` no-ops without planting, but the token still
199
+ // needs planting. Guard on the sync's active account STILL being the current
200
+ // active account so a stale response cannot adopt a token for an account a
201
+ // newer state already switched away from.
202
+ if (!applied &&
203
+ sync.activeToken &&
204
+ this.state &&
205
+ sync.state.activeAccountId !== null &&
206
+ sync.state.activeAccountId === this.state.activeAccountId &&
207
+ sync.activeToken.accessToken !== this.host.getAccessToken()) {
159
208
  this.host.setTokens(sync.activeToken.accessToken);
160
209
  }
161
210
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * URL redaction for logging.
3
+ *
4
+ * Asset URLs the API hands back for private assets carry a scoped, short-lived
5
+ * media token (`mt=…`) in their query string. That token is a bearer credential
6
+ * for the underlying object, so it must never land in a log line, breadcrumb,
7
+ * or metric — a captured log would otherwise grant read access until the token
8
+ * expires. Query strings on API URLs can also carry other sensitive params, so
9
+ * we redact the whole query rather than allow-listing one key.
10
+ *
11
+ * `redactUrlQuery` returns the URL's path portion with a `?<redacted>` marker
12
+ * when a query string is present, and the input unchanged otherwise. It is
13
+ * defensive: any input that does not parse as a URL is passed through as-is,
14
+ * except that a bare `?query` tail is still stripped so a relative path with a
15
+ * query never leaks.
16
+ */
17
+ export function redactUrlQuery(url) {
18
+ if (typeof url !== 'string' || url.length === 0) {
19
+ return url;
20
+ }
21
+ const queryIndex = url.indexOf('?');
22
+ if (queryIndex === -1) {
23
+ return url;
24
+ }
25
+ return `${url.slice(0, queryIndex)}?<redacted>`;
26
+ }