@oxyhq/core 7.0.0 → 7.1.1

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.
package/dist/esm/index.js CHANGED
@@ -146,6 +146,17 @@ export { SessionClient } from './session/SessionClient.js';
146
146
  export { createSessionClientHost } from './session/sessionClientHost.js';
147
147
  export { createSessionClient } from './session/createSessionClient.js';
148
148
  export { deviceStateToClientSessions, activeSessionIdOf, activeUserOf, accountIdsOf, } from './session/projectSessionState.js';
149
+ // Unified account-list projection (THE single source of truth for the account
150
+ // chooser: device sign-ins ∪ account graph, deduped by accountId). Pure +
151
+ // I/O-free — the caller hydrates profiles via `getUsersByIds`. Shared by
152
+ // `@oxyhq/services`, `@oxyhq/auth`, and auth.oxy.so so the list can't diverge.
153
+ export { projectSwitchableAccounts, switchableAccountIds, } from './session/accountProjection.js';
154
+ // Headless controller for the unified account dialog. Framework-agnostic
155
+ // state machine + subscribe/getSnapshot store (bind via `useSyncExternalStore`)
156
+ // — no password/2FA logic (that lives at the IdP; `openPasswordAtOxyAuth` only
157
+ // hands off). Reuses `SessionClient.switchAccount` / `oxyServices.switchToAccount`
158
+ // for the uniform switch and the existing device-flow methods for sign-in.
159
+ export { AccountDialogController, createAccountDialogController, } from './session/accountDialogController.js';
149
160
  // ---------------------------------------------------------------------------
150
161
  // Device-first session machinery (auth centralization, wave 1) — additive.
151
162
  // Persisted auth-state store, the unified refresh handler + scheduler, the
@@ -1,6 +1,14 @@
1
1
  import { deviceSessionStateSchema, deviceSessionSyncSchema, safeParseContract, } from '@oxyhq/contracts';
2
2
  import { logger } from '../utils/loggerUtils.js';
3
3
  import { getSocketIO } from './socketLoader.js';
4
+ /**
5
+ * Same-origin `BroadcastChannel` name for instant, network-free session wake
6
+ * across tabs of the SAME origin (e.g. two `accounts.oxy.so` tabs). Complements
7
+ * the cookie-authed device socket, which covers same-apex cross-origin
8
+ * (`accounts` ↔ `console` ↔ `inbox`, all `*.oxy.so`). Cross-APEX (mention.earth)
9
+ * is covered by neither and relies on a reload — the documented limitation.
10
+ */
11
+ const SESSION_BROADCAST_CHANNEL = 'oxy.session';
4
12
  export class SessionClient {
5
13
  constructor(host, options = {}) {
6
14
  this.host = host;
@@ -10,6 +18,12 @@ export class SessionClient {
10
18
  this.socket = null;
11
19
  this.tokenUnsub = null;
12
20
  this.started = false;
21
+ /** In-flight guard so a burst of pushes triggers at most ONE acquisition. */
22
+ this.acquiring = false;
23
+ /** True while the live socket is an anonymous (signed-out) device connection. */
24
+ this.socketAnonymous = false;
25
+ /** Same-origin cross-tab wake channel; null on platforms without BroadcastChannel. */
26
+ this.channel = null;
13
27
  }
14
28
  getState() {
15
29
  return this.state;
@@ -102,14 +116,17 @@ export class SessionClient {
102
116
  async switchAccount(accountId) {
103
117
  const res = await this.host.makeRequest('POST', '/session/device/switch', { accountId }, { cache: false });
104
118
  this.applySync(res);
119
+ this.postCommitPing();
105
120
  }
106
121
  async signOut(target) {
107
122
  const res = await this.host.makeRequest('POST', '/session/device/signout', target, { cache: false });
108
123
  this.applySync(res);
124
+ this.postCommitPing();
109
125
  }
110
126
  async addCurrentAccount() {
111
127
  const res = await this.host.makeRequest('POST', '/session/device/add', undefined, { cache: false });
112
128
  this.applySync(res);
129
+ this.postCommitPing();
113
130
  }
114
131
  /**
115
132
  * Register the just-signed-in account into the device set AND make it the
@@ -137,19 +154,58 @@ export class SessionClient {
137
154
  return;
138
155
  this.started = true;
139
156
  this.tokenUnsub = this.host.onTokensChanged((token) => {
140
- if (token && this.socket && !this.socket.connected) {
157
+ if (!token)
158
+ return;
159
+ // A bearer just landed: an in-flight acquisition (if any) succeeded — clear
160
+ // the guard so a later sign-out can re-acquire.
161
+ this.acquiring = false;
162
+ if (!this.socket)
163
+ return;
164
+ if (this.socketAnonymous) {
165
+ // The live socket was an anonymous (device-room-only) connection. Force a
166
+ // reconnect so the handshake re-runs authenticated and also joins the
167
+ // `user:<id>` notification room.
168
+ this.socketAnonymous = false;
169
+ this.socket.disconnect();
170
+ this.socket.connect();
171
+ }
172
+ else if (!this.socket.connected) {
141
173
  this.socket.connect();
142
174
  }
143
175
  });
144
- await this.bootstrap();
176
+ this.openBroadcastChannel();
177
+ // `bootstrap` (`GET /session/device/state`) is bearer-authenticated: skip it
178
+ // when signed out (the signed-out socket below still joins the device room to
179
+ // receive pushes). A bootstrap failure is non-fatal — the socket must still
180
+ // connect so realtime sync survives a transient state-fetch error.
181
+ if (this.host.getAccessToken()) {
182
+ try {
183
+ await this.bootstrap();
184
+ }
185
+ catch (error) {
186
+ logger.warn('[SessionClient] bootstrap during start failed (non-fatal)', { component: 'SessionClient' }, error);
187
+ }
188
+ }
145
189
  await this.connectSocket();
146
190
  }
147
191
  stop() {
148
192
  this.started = false;
193
+ this.acquiring = false;
194
+ this.socketAnonymous = false;
149
195
  if (this.tokenUnsub) {
150
196
  this.tokenUnsub();
151
197
  this.tokenUnsub = null;
152
198
  }
199
+ if (this.channel) {
200
+ this.channel.onmessage = null;
201
+ try {
202
+ this.channel.close();
203
+ }
204
+ catch (error) {
205
+ logger.debug('[SessionClient] BroadcastChannel close failed', { component: 'SessionClient' }, error);
206
+ }
207
+ this.channel = null;
208
+ }
153
209
  if (this.socket) {
154
210
  this.socket.disconnect();
155
211
  this.socket = null;
@@ -167,24 +223,139 @@ export class SessionClient {
167
223
  if (!this.started)
168
224
  return; // stopped while the dynamic import was in flight
169
225
  const hasToken = Boolean(this.host.getAccessToken());
226
+ // Signed-out connect gate: when there is no bearer, only open the socket if
227
+ // the consumer supplies a device anchor (web cookie → `true`; native token →
228
+ // string). This lets an idle tab receive its device's `session_state` pushes
229
+ // and self-acquire when a sibling signs in.
230
+ let signedOutAuth = false;
231
+ if (!hasToken && this.options.signedOutSocketAuth) {
232
+ try {
233
+ signedOutAuth = await this.options.signedOutSocketAuth();
234
+ }
235
+ catch (error) {
236
+ logger.warn('[SessionClient] signedOutSocketAuth failed', { component: 'SessionClient' }, error);
237
+ signedOutAuth = false;
238
+ }
239
+ if (!this.started)
240
+ return; // stopped while the async gate was in flight
241
+ }
242
+ const signedOutConnect = signedOutAuth !== false && signedOutAuth != null;
243
+ const signedOutDeviceToken = typeof signedOutAuth === 'string' ? signedOutAuth : undefined;
244
+ this.socketAnonymous = !hasToken && signedOutConnect;
170
245
  const socket = io(this.host.getBaseURL(), {
171
246
  transports: ['websocket'],
172
- autoConnect: hasToken,
247
+ // Send the first-party `oxy_device` cookie on the same-site handshake so a
248
+ // signed-out browser tab can be resolved to its device room server-side.
249
+ withCredentials: true,
250
+ autoConnect: hasToken || signedOutConnect,
173
251
  auth: (cb) => {
174
- cb({ token: this.host.getAccessToken() ?? '' });
252
+ const token = this.host.getAccessToken() ?? '';
253
+ // Present the native device token only while signed out (no bearer). Once
254
+ // a token is held the bearer path wins and the deviceToken is redundant.
255
+ cb(token || !signedOutDeviceToken ? { token } : { token, deviceToken: signedOutDeviceToken });
175
256
  },
176
257
  });
177
258
  socket.on('session_state', (payload) => {
178
259
  const applied = this.applyState(payload);
179
- if (applied) {
180
- const active = this.state?.activeAccountId ?? null;
181
- if (active && active !== this.host.getCurrentAccountId()) {
182
- void this.bootstrap().catch((error) => {
183
- logger.warn('[SessionClient] post-push token fetch failed', { component: 'SessionClient' }, error);
184
- });
260
+ if (!applied)
261
+ return;
262
+ // Signed-out tab: a session appeared on this device (a sibling signed in).
263
+ // Acquire it so this tab flips to signed-in; the planted token then
264
+ // reconnects the socket on the authenticated path.
265
+ if (!this.host.getAccessToken()) {
266
+ if ((this.state?.accounts.length ?? 0) > 0) {
267
+ this.requestAcquisition();
185
268
  }
269
+ return;
270
+ }
271
+ const active = this.state?.activeAccountId ?? null;
272
+ if (active && active !== this.host.getCurrentAccountId()) {
273
+ void this.bootstrap().catch((error) => {
274
+ logger.warn('[SessionClient] post-push token fetch failed', { component: 'SessionClient' }, error);
275
+ });
186
276
  }
187
277
  });
188
278
  this.socket = socket;
189
279
  }
280
+ /**
281
+ * Run the consumer's session acquisition at most once at a time. A returned
282
+ * promise gates the next attempt (reset on settle), so a failed acquisition
283
+ * can retry on the NEXT push while a burst of identical pushes cannot pile up.
284
+ */
285
+ requestAcquisition() {
286
+ if (this.acquiring || !this.options.onSessionAppeared)
287
+ return;
288
+ this.acquiring = true;
289
+ let result;
290
+ try {
291
+ result = this.options.onSessionAppeared();
292
+ }
293
+ catch (error) {
294
+ this.acquiring = false;
295
+ logger.error('[SessionClient] onSessionAppeared threw', error);
296
+ return;
297
+ }
298
+ void Promise.resolve(result).catch((error) => {
299
+ logger.warn('[SessionClient] onSessionAppeared rejected', { component: 'SessionClient' }, error);
300
+ }).finally(() => {
301
+ this.acquiring = false;
302
+ });
303
+ }
304
+ /**
305
+ * Open the same-origin `BroadcastChannel` (web only). A sibling tab that
306
+ * commits a session posts a wake ping; on receipt a signed-in tab re-syncs its
307
+ * device state and a signed-out tab self-acquires — instant + network-free for
308
+ * the common "two tabs of the same origin" case, with no state (and no tokens)
309
+ * ever crossing the channel. No-op on native (no BroadcastChannel).
310
+ */
311
+ openBroadcastChannel() {
312
+ if (this.channel)
313
+ return;
314
+ const Ctor = globalThis.BroadcastChannel;
315
+ if (typeof Ctor !== 'function')
316
+ return; // native RN / SSR — feature absent
317
+ let channel;
318
+ try {
319
+ channel = new Ctor(SESSION_BROADCAST_CHANNEL);
320
+ }
321
+ catch (error) {
322
+ logger.debug('[SessionClient] BroadcastChannel unavailable', { component: 'SessionClient' }, error);
323
+ return;
324
+ }
325
+ channel.onmessage = (event) => {
326
+ if (!event || typeof event.data !== 'object' || event.data === null)
327
+ return;
328
+ if (event.data.type !== 'commit')
329
+ return;
330
+ // BroadcastChannel never echoes to the posting context, so this is a
331
+ // sibling's commit. Re-sync (signed-in) or acquire (signed-out). Neither
332
+ // path re-posts, so there is no cross-tab ping loop.
333
+ if (this.host.getAccessToken()) {
334
+ void this.bootstrap().catch((error) => {
335
+ logger.warn('[SessionClient] broadcast re-sync failed', { component: 'SessionClient' }, error);
336
+ });
337
+ }
338
+ else {
339
+ this.requestAcquisition();
340
+ }
341
+ };
342
+ this.channel = channel;
343
+ }
344
+ /**
345
+ * Wake same-origin sibling tabs after a locally-initiated session mutation.
346
+ * Opens the channel lazily: a sign-in registers the account (`addCurrentAccount`
347
+ * / `switchAccount`) BEFORE `start()` runs, so the ping must not depend on
348
+ * `start()` having opened the channel first.
349
+ */
350
+ postCommitPing() {
351
+ this.openBroadcastChannel();
352
+ if (!this.channel)
353
+ return;
354
+ try {
355
+ this.channel.postMessage({ type: 'commit', at: Date.now() });
356
+ }
357
+ catch (error) {
358
+ logger.debug('[SessionClient] BroadcastChannel post failed', { component: 'SessionClient' }, error);
359
+ }
360
+ }
190
361
  }