@oxy.so/services 15.1.4 → 15.1.5

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.
@@ -2,18 +2,9 @@ import { type OxyServices } from '@oxy.so/core';
2
2
  import { type AuthStateStore, type IdentityBinding, type SessionMode } from '@oxy.so/core/session';
3
3
  import type { SessionClient } from '@oxy.so/core/session';
4
4
  import type { CommitInput } from '../context/oxyContextTypes.js';
5
- /** How long the cold boot waits for the post-boot SessionClient handoff (ms). */
6
- export declare const SESSION_HANDOFF_DEADLINE_MS = 6000;
7
5
  /**
8
- * HARD overall deadline (ms) for the whole `runSessionColdBoot` step chain.
9
- *
10
- * Bounds time-to-route: routing gates on `isAuthResolved`, which resolves when
11
- * the cold boot finishes, so a network step that never settles (a black-hole
12
- * network that neither connects nor rejects) would otherwise hang routing
13
- * indefinitely. 12s comfortably exceeds the healthy worst case of the
14
- * sequential, single-attempt (`retry:false`), 5s-capped network steps, so it is
15
- * INERT on healthy loads and only trips on a pathological network. Offline
16
- * devices short-circuit far sooner via the connectivity hint below.
6
+ * HARD overall deadline (ms) for the whole `runSessionColdBoot` step chain; see
7
+ * `runWebSessionColdBoot` in `@oxy.so/core/session`, which owns the boot.
17
8
  */
18
9
  export declare const COLD_BOOT_OVERALL_DEADLINE_MS = 12000;
19
10
  export interface RunProviderColdBootOptions {
@@ -72,27 +63,13 @@ export interface RunProviderColdBootOptions {
72
63
  onCachedSessionUnconfirmed?: (retry: () => Promise<void>) => void;
73
64
  }
74
65
  /**
75
- * Device-first cold boot for `@oxy.so/services` providers.
76
- *
77
- * A returning session saved on this device (account mode, the app last
78
- * classified `device`, its profile cached) paints first, with no network, and
79
- * is then checked in the background — see `paintCachedSession`. Otherwise, a
80
- * first boot:
81
- *
82
- * Ordered pipeline:
83
- * 1. Complete an OAuth authorization-code return already on the URL (web)
84
- * 2. `runSessionColdBoot` — device-secret mint (+ the native Commons-proof lane,
85
- * or the primary-identity-key lane in `sessionMode: 'identity'`)
86
- *
87
- * Step 1 is ACCOUNT-MODE ONLY: it commits whichever account the IdP resolves,
88
- * which for an identity-bound client is somebody else's account by construction.
89
- * In `'identity'` mode the boot is exactly step 2.
66
+ * Device-first cold boot for `@oxy.so/services` providers: core's
67
+ * `runWebSessionColdBoot` (the order, the deadlines, the verdicts) with this
68
+ * package's platform parts — the registry classifier, the native connectivity
69
+ * probe, the shared device credential slot and the OAuth return leg.
90
70
  *
91
- * The boot NEVER navigates the top-level window. There is no automatic
92
- * `prompt=none` bounce to the IdP: a web origin with no local device credential
93
- * resolves SIGNED OUT and waits for the user's next explicit "Continue with
94
- * Oxy", which opens a popup from a real gesture (#691 phase 7b). Step 1 is not a
95
- * navigation — it only consumes a code that is already in the address bar.
71
+ * The boot NEVER navigates the top-level window; the OAuth return leg only
72
+ * consumes a code that is already in the address bar (#691 phase 7b).
96
73
  */
97
74
  export declare function runProviderColdBoot(opts: RunProviderColdBootOptions): Promise<void>;
98
75
  //# sourceMappingURL=runProviderColdBoot.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runProviderColdBoot.d.ts","sourceRoot":"","sources":["../../../../../src/ui/boot/runProviderColdBoot.ts"],"names":[],"mappings":"AACA,OAAO,EAAwB,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AACtE,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,WAAW,EACjB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAM1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA4B,CAAC;AAwB9D,iFAAiF;AACjF,eAAO,MAAM,2BAA2B,OAAO,CAAC;AAEhD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,6BAA6B,QAAS,CAAC;AA2CpD,MAAM,WAAW,0BAA0B;IACzC,WAAW,EAAE,WAAW,CAAC;IACzB,SAAS,EAAE,cAAc,CAAC;IAC1B,QAAQ,CA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CAAC,CAAC;IAChD,aAAa,EAAE,CACb,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE;QAAE,QAAQ,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,KAC5C,OAAO,CAAC,IAAI,CAAC,CAAC;IACnB,gBAAgB,EAAE,MAAM,IAAI,CAAC;IAC7B,aAAa,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACxC;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5C;;;;OAIG;IACH,uBAAuB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C;;;OAGG;IACH,0BAA0B,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;CACnE;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,0BAA0B,GAAG,OAAO,CAAC,IAAI,CAAC,CAsBnF"}
@@ -1,34 +1,2 @@
1
- import { type OxyServices } from '@oxy.so/core';
2
- import type { TokenTransport } from '@oxy.so/core/session';
3
- /**
4
- * Platform `TokenTransport` for `SessionClient` (device-first model).
5
- *
6
- * `ensureActiveToken` is the fallback the client uses when a `session_state`
7
- * push arrived WITHOUT an embedded `activeToken` and the planted bearer does not
8
- * already belong to the state's active account. It mints one through the ONE
9
- * unified single-flight the scheduler, the request-time preflight, and the 401
10
- * retry all use — `oxyServices.http.refreshAccessToken(...)` — which runs
11
- * the installed refresh handler (present the persisted zero-cookie `deviceId` +
12
- * `deviceSecret` at `POST /session/device/token`, which mints for the device's
13
- * CURRENT active account). Routing through the SAME entry point means this lane
14
- * can never double-rotate the device secret against the others: it has NO
15
- * private single-flight of its own.
16
- *
17
- * The short-circuit compares the planted bearer's ACCOUNT against
18
- * `state.activeAccountId`, not mere token presence: a bearer for the PREVIOUS
19
- * account (an account switch) must still mint the new account's token — skipping
20
- * on presence alone would leave a subscriber observing the new active account
21
- * under the old account's bearer (the account-switch 404 race).
22
- *
23
- * A failure is logged and swallowed: this method must never throw out (it runs
24
- * inside the socket state handler).
25
- *
26
- * `getPinnedAccountId` is the identity-bound escape hatch. Converging the bearer
27
- * on `state.activeAccountId` is precisely what an identity-bound client must
28
- * never do — its token is minted for the PINNED account by the cold boot /
29
- * re-mint lane. `SessionClient` already bypasses the transport entirely while
30
- * pinned; this guard is the services-side half of that contract, so no future
31
- * wiring can reintroduce the convergence from this end.
32
- */
33
- export declare function createTokenTransport(oxyServices: OxyServices, getPinnedAccountId?: () => string | null): TokenTransport;
1
+ export { createTokenTransport } from '@oxy.so/core/session';
34
2
  //# sourceMappingURL=tokenTransport.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tokenTransport.d.ts","sourceRoot":"","sources":["../../../../../src/ui/session/tokenTransport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,oBAAoB,CAClC,WAAW,EAAE,WAAW,EACxB,kBAAkB,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,GACvC,cAAc,CAqChB"}
1
+ {"version":3,"file":"tokenTransport.d.ts","sourceRoot":"","sources":["../../../../../src/ui/session/tokenTransport.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxy.so/services",
3
- "version": "15.1.4",
3
+ "version": "15.1.5",
4
4
  "description": "OxyHQ Expo/React Native SDK — UI components, screens, and native features",
5
5
  "main": "lib/commonjs/index.js",
6
6
  "module": "lib/module/index.js",
@@ -197,7 +197,7 @@
197
197
  "devDependencies": {
198
198
  "@expo/app-integrity": "~58.0.2",
199
199
  "@expo/vector-icons": "^15.1.1",
200
- "@oxy.so/core": "7.65.0",
200
+ "@oxy.so/core": "7.66.0",
201
201
  "@react-native-async-storage/async-storage": "^3.1.1",
202
202
  "@react-native-community/netinfo": "^12.0.1",
203
203
  "@react-native/babel-preset": "^0.88.1",
@@ -248,7 +248,7 @@
248
248
  "@expo/vector-icons": "^15.0.3",
249
249
  "@oxy.so/bloom": ">=23.0.0",
250
250
  "@oxy.so/bloom-data": ">=0.1.0",
251
- "@oxy.so/core": "^7.49.0",
251
+ "@oxy.so/core": "^7.66.0",
252
252
  "@react-native-async-storage/async-storage": ">=2.0.0 <4.0.0",
253
253
  "@react-native-community/netinfo": ">=11.4.1 <13.0.0",
254
254
  "@types/react": "<20.0.0",
@@ -2,12 +2,12 @@ import { resolveApplicationSessionLane } from '../oauth/applicationSessionLane';
2
2
  import { logger as loggerUtil, type OxyServices } from '@oxy.so/core';
3
3
  import {
4
4
  runSessionColdBoot,
5
+ runWebSessionColdBoot,
5
6
  type AuthStateStore,
6
7
  type IdentityBinding,
7
8
  type SessionMode,
8
9
  } from '@oxy.so/core/session';
9
10
  import type { SessionClient } from '@oxy.so/core/session';
10
- import { loadPersistedDeviceCredential } from '../utils/deviceCredential';
11
11
  import { createPlatformSharedDeviceCredentialStore } from '../session/sharedDeviceCredentialStore';
12
12
  import { tryCompleteOAuthReturn } from '../utils/oauthReturn';
13
13
  import { isWebBrowser } from '../utils/isWebBrowser';
@@ -15,40 +15,8 @@ import { isNetConnectivityOnline } from '../utils/netConnectivity';
15
15
  import type { CommitInput } from '../context/oxyContextTypes';
16
16
 
17
17
  /**
18
- * Whether the URL carries an OAuth return (`?code=` or `?error=`) for
19
- * `tryCompleteOAuthReturn` to consume. Reads the address bar only.
20
- */
21
- function hasOAuthReturnOnUrl(): boolean {
22
- const search = (globalThis as { location?: { search?: string } }).location?.search;
23
- if (!search) return false;
24
- const params = new URLSearchParams(search);
25
- return params.has('code') || params.has('error');
26
- }
27
-
28
- /**
29
- * Whether this origin's own store holds anything a web boot could restore from:
30
- * a warm access token to plant or a device secret to mint with. A presence
31
- * check only — nothing read here is used, sent or synced before the
32
- * classification allows it.
33
- */
34
- async function hasRestorableState(store: AuthStateStore): Promise<boolean> {
35
- const persisted = await store.load();
36
- return Boolean(persisted?.accessToken || persisted?.deviceSecret);
37
- }
38
-
39
- /** How long the cold boot waits for the post-boot SessionClient handoff (ms). */
40
- export const SESSION_HANDOFF_DEADLINE_MS = 6000;
41
-
42
- /**
43
- * HARD overall deadline (ms) for the whole `runSessionColdBoot` step chain.
44
- *
45
- * Bounds time-to-route: routing gates on `isAuthResolved`, which resolves when
46
- * the cold boot finishes, so a network step that never settles (a black-hole
47
- * network that neither connects nor rejects) would otherwise hang routing
48
- * indefinitely. 12s comfortably exceeds the healthy worst case of the
49
- * sequential, single-attempt (`retry:false`), 5s-capped network steps, so it is
50
- * INERT on healthy loads and only trips on a pathological network. Offline
51
- * devices short-circuit far sooner via the connectivity hint below.
18
+ * HARD overall deadline (ms) for the whole `runSessionColdBoot` step chain; see
19
+ * `runWebSessionColdBoot` in `@oxy.so/core/session`, which owns the boot.
52
20
  */
53
21
  export const COLD_BOOT_OVERALL_DEADLINE_MS = 12_000;
54
22
 
@@ -60,37 +28,23 @@ export const COLD_BOOT_OVERALL_DEADLINE_MS = 12_000;
60
28
  const OFFLINE_PROBE_TIMEOUT_MS = 500;
61
29
 
62
30
  /**
63
- * Best-effort, FAST connectivity probe run once before the cold boot.
64
- *
65
- * Returns `true` ONLY on an EXPLICIT disconnected verdict; every ambiguous
66
- * outcome (probe timeout, unknown/`null` state, NetInfo unavailable, a thrown
67
- * error) resolves to `false` (assume online) so a flaky probe can never falsely
68
- * skip a real sign-in. Never rejects. On web it reads `navigator.onLine`; on
69
- * native it races `NetInfo.fetch()` against {@link OFFLINE_PROBE_TIMEOUT_MS},
70
- * mirroring the existing NetInfo dynamic-import pattern in `OxyProvider`.
31
+ * The native half of the boot's connectivity probe: races `NetInfo.fetch()`
32
+ * against {@link OFFLINE_PROBE_TIMEOUT_MS}. `true` ONLY on an EXPLICIT
33
+ * disconnected verdict; a timeout or an unknown state is "online". A missing
34
+ * NetInfo rejects, which the boot also reads as "online".
71
35
  */
72
- async function detectOfflineHint(): Promise<boolean> {
73
- try {
74
- if (isWebBrowser()) {
75
- const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;
76
- // Only an explicit `false` is an offline verdict; `undefined` ⇒ assume online.
77
- return online === false;
78
- }
79
- const NetInfo = await import('@react-native-community/netinfo');
80
- const state = await Promise.race([
81
- NetInfo.default.fetch(),
82
- new Promise<null>((resolve) => {
83
- setTimeout(() => resolve(null), OFFLINE_PROBE_TIMEOUT_MS);
84
- }),
85
- ]);
86
- // `null` ⇒ the probe timed out (unknown → assume online). Only an explicit
87
- // disconnected verdict disables the network steps (the same rule as the
88
- // online signal: `isConnected`, never the reachability probe).
89
- return state !== null && !isNetConnectivityOnline(state);
90
- } catch {
91
- // NetInfo missing / probe threw — never block sign-in on a probe failure.
92
- return false;
93
- }
36
+ async function probeNetInfoOffline(): Promise<boolean> {
37
+ const NetInfo = await import('@react-native-community/netinfo');
38
+ const state = await Promise.race([
39
+ NetInfo.default.fetch(),
40
+ new Promise<null>((resolve) => {
41
+ setTimeout(() => resolve(null), OFFLINE_PROBE_TIMEOUT_MS);
42
+ }),
43
+ ]);
44
+ // `null` ⇒ the probe timed out (unknown → assume online). Only an explicit
45
+ // disconnected verdict disables the network steps (the same rule as the
46
+ // online signal: `isConnected`, never the reachability probe).
47
+ return state !== null && !isNetConnectivityOnline(state);
94
48
  }
95
49
 
96
50
  export interface RunProviderColdBootOptions {
@@ -149,310 +103,35 @@ export interface RunProviderColdBootOptions {
149
103
  onCachedSessionUnconfirmed?: (retry: () => Promise<void>) => void;
150
104
  }
151
105
 
152
- type ClassificationLane = 'device' | 'oauth';
153
-
154
- /** Starts the provider's fresh classification; a rejection is observed, not swallowed. */
155
- function startClassification(opts: RunProviderColdBootOptions): Promise<ClassificationLane> {
156
- const classification = (async () =>
157
- opts.resolveSessionLane?.() ??
158
- resolveApplicationSessionLane(opts.oxyServices, opts.clientId))();
159
- // Observed so a rejection that lands before it is awaited is not reported as
160
- // unhandled; every caller still awaits it and sees the rejection.
161
- classification.catch(() => undefined);
162
- return classification;
163
- }
164
-
165
- /** What the device lanes made of this holder: a session, a verdict against it, or no answer. */
166
- type DeviceRestoreOutcome = 'session' | 'rejected' | 'unreachable';
167
-
168
106
  /**
169
- * The device lanes of the boot (`runSessionColdBoot`), for a first boot or for
170
- * the background check of a painted one.
107
+ * Device-first cold boot for `@oxy.so/services` providers: core's
108
+ * `runWebSessionColdBoot` (the order, the deadlines, the verdicts) with this
109
+ * package's platform parts — the registry classifier, the native connectivity
110
+ * probe, the shared device credential slot and the OAuth return leg.
171
111
  *
172
- * A first boot (`painted: false`) is on the critical path: its committed
173
- * session resolves auth, bounded by {@link SESSION_HANDOFF_DEADLINE_MS}. A
174
- * painted boot already resolved auth from the cache, so nothing waits on the
175
- * handoff and the pure-local warm token is skipped: the check needs the mint's
176
- * verdict, which a still-valid token cannot give.
112
+ * The boot NEVER navigates the top-level window; the OAuth return leg only
113
+ * consumes a code that is already in the address bar (#691 phase 7b).
177
114
  */
178
- async function restoreDeviceSession(
179
- opts: RunProviderColdBootOptions,
180
- painted: boolean,
181
- ): Promise<DeviceRestoreOutcome> {
182
- const {
183
- oxyServices,
184
- authStore,
185
- sessionMode = 'account',
186
- identity,
187
- sessionClient,
188
- syncDeviceCredentialToHost,
189
- commitSession,
190
- markAuthResolved,
191
- } = opts;
192
-
193
- await opts.beforeDeviceBoot?.();
194
-
195
- // Best-effort connectivity probe up front: an EXPLICIT offline verdict skips
196
- // the two doomed network steps so routing settles immediately instead of
197
- // burning the overall deadline on a mint that cannot succeed. Any ambiguity
198
- // resolves to "online" — the network steps still run.
199
- const offline = await detectOfflineHint();
200
-
201
- let outcome: DeviceRestoreOutcome = 'unreachable';
202
- let holderRejected = false;
203
- await runSessionColdBoot({
204
- oxy: oxyServices,
205
- store: authStore,
206
- platform: { isWeb: isWebBrowser(), isNative: !isWebBrowser() },
207
- sessionMode,
208
- identity,
209
- // The device-wide shared credential slot, enabling the `shared-device-adopt`
210
- // lane: a newly installed official app joins this device's existing session
211
- // instead of falling back to signing a challenge with the Commons identity
212
- // key. `null` on web, where each origin is its own device by design; the
213
- // core lane is also skipped outright in `sessionMode: 'identity'`.
214
- // Off when the provider was given a platform's own store: the credential
215
- // then lives there and nowhere else.
216
- sharedDeviceCredential:
217
- opts.useSharedDeviceCredential === false
218
- ? undefined
219
- : (createPlatformSharedDeviceCredentialStore() ?? undefined),
115
+ export function runProviderColdBoot(opts: RunProviderColdBootOptions): Promise<void> {
116
+ const { oxyServices, clientId, authRedirectUri, commitSession } = opts;
117
+ return runWebSessionColdBoot({
118
+ ...opts,
119
+ resolveSessionLane: () =>
120
+ opts.resolveSessionLane?.() ?? resolveApplicationSessionLane(oxyServices, clientId),
220
121
  overallDeadlineMs: COLD_BOOT_OVERALL_DEADLINE_MS,
221
- isOffline: () => offline,
222
- requireServerVerdict: painted,
223
- onHolderRejected: () => {
224
- holderRejected = true;
225
- },
226
- onStepDeadline: (stepId) => {
227
- loggerUtil.warn(
228
- `Cold-boot step "${stepId}" exceeded the ${COLD_BOOT_OVERALL_DEADLINE_MS}ms overall deadline — abandoned; routing proceeds signed-out`,
229
- { component: 'runProviderColdBoot', method: 'onStepDeadline' },
230
- );
231
- },
232
- onSession: async (session) => {
233
- outcome = 'session';
234
- // Mint already persisted `{deviceId, deviceSecret}` to the store; sync the
235
- // in-memory SessionClient host so sockets + tab-focus re-mint can use it.
236
- await syncDeviceCredentialToHost();
237
- const handoff = commitSession(
238
- {
239
- sessionId: session.sessionId,
240
- accessToken: session.accessToken,
241
- userId: session.userId,
242
- deviceState: session.state,
243
- },
244
- { activate: false },
245
- );
246
- if (painted) {
247
- // The account is already on screen; the commit refreshes its profile.
248
- await handoff;
249
- return;
250
- }
251
- let handoffDeadlineId: ReturnType<typeof setTimeout> | undefined;
252
- await Promise.race([
253
- handoff,
254
- new Promise<void>((resolve) => {
255
- handoffDeadlineId = setTimeout(resolve, SESSION_HANDOFF_DEADLINE_MS);
256
- }),
257
- ]).finally(() => {
258
- if (handoffDeadlineId !== undefined) {
259
- clearTimeout(handoffDeadlineId);
260
- }
261
- });
262
- markAuthResolved();
263
- },
264
- onSignedOut: async () => {
265
- outcome = holderRejected ? 'rejected' : 'unreachable';
266
- await syncDeviceCredentialToHost();
267
- // A painted session is the caller's to end or keep (see verifyCachedSession).
268
- if (painted) return;
269
- const cred = await loadPersistedDeviceCredential(authStore);
270
- if (cred) {
271
- try {
272
- await sessionClient.start();
273
- } catch (socketError) {
274
- if (__DEV__) {
275
- loggerUtil.debug(
276
- 'Device socket start failed (non-fatal)',
277
- { component: 'runProviderColdBoot' },
278
- socketError,
279
- );
280
- }
281
- }
282
- }
283
- markAuthResolved();
284
- },
285
- onStepError: (id, error) => {
286
- if (__DEV__) {
287
- loggerUtil.debug(
288
- `Cold-boot step "${id}" errored (non-fatal, falling through)`,
289
- { component: 'runProviderColdBoot' },
290
- error,
291
- );
292
- }
293
- },
294
- });
295
- await opts.afterDeviceBoot?.();
296
- return outcome;
297
- }
298
-
299
- /**
300
- * The background check of a painted session: the registry's classification and
301
- * a mint with this holder's own credential (whose commit refreshes the profile).
302
- * Each is asked until the server answers it. A verdict against the session
303
- * signs out at that moment; no answer keeps the cached session on screen and
304
- * hands the caller a retry.
305
- */
306
- async function verifyCachedSession(
307
- opts: RunProviderColdBootOptions,
308
- verified: { lane: boolean; session: boolean },
309
- classification: Promise<ClassificationLane>,
310
- ): Promise<void> {
311
- if (!verified.lane) {
312
- let lane: ClassificationLane | null = null;
313
- try {
314
- lane = await classification;
315
- } catch {
316
- // The registry could not be asked (offline, timeout, 5xx). That is no
317
- // verdict on this app: the cached `device` classification stands until it
318
- // answers.
319
- }
320
- if (lane === 'oauth') {
321
- await opts.onCachedSessionRejected?.();
322
- return;
323
- }
324
- verified.lane = lane === 'device';
325
- }
326
- if (!verified.session) {
327
- const outcome = await restoreDeviceSession(opts, true);
328
- if (outcome === 'rejected') {
329
- await opts.onCachedSessionRejected?.();
330
- return;
331
- }
332
- verified.session = outcome === 'session';
333
- }
334
- if (!verified.lane || !verified.session) {
335
- opts.onCachedSessionUnconfirmed?.(() =>
336
- verifyCachedSession(
337
- opts,
338
- verified,
339
- verified.lane ? Promise.resolve('device') : startClassification(opts),
340
- ),
341
- );
342
- }
343
- }
344
-
345
- /**
346
- * Device-first cold boot for `@oxy.so/services` providers.
347
- *
348
- * A returning session saved on this device (account mode, the app last
349
- * classified `device`, its profile cached) paints first, with no network, and
350
- * is then checked in the background — see `paintCachedSession`. Otherwise, a
351
- * first boot:
352
- *
353
- * Ordered pipeline:
354
- * 1. Complete an OAuth authorization-code return already on the URL (web)
355
- * 2. `runSessionColdBoot` — device-secret mint (+ the native Commons-proof lane,
356
- * or the primary-identity-key lane in `sessionMode: 'identity'`)
357
- *
358
- * Step 1 is ACCOUNT-MODE ONLY: it commits whichever account the IdP resolves,
359
- * which for an identity-bound client is somebody else's account by construction.
360
- * In `'identity'` mode the boot is exactly step 2.
361
- *
362
- * The boot NEVER navigates the top-level window. There is no automatic
363
- * `prompt=none` bounce to the IdP: a web origin with no local device credential
364
- * resolves SIGNED OUT and waits for the user's next explicit "Continue with
365
- * Oxy", which opens a popup from a real gesture (#691 phase 7b). Step 1 is not a
366
- * navigation — it only consumes a code that is already in the address bar.
367
- */
368
- export async function runProviderColdBoot(opts: RunProviderColdBootOptions): Promise<void> {
369
- const {
370
- oxyServices,
371
- authStore,
372
- clientId,
373
- authRedirectUri,
374
- sessionMode = 'account',
375
- commitSession,
376
- markAuthResolved,
377
- setTokenReady,
378
- } = opts;
379
-
380
- const identityBound = sessionMode === 'identity';
381
-
382
- setTokenReady(false);
383
-
384
- try {
385
- // Classification precedes every USE of a local secret, the shared credential
386
- // and the identity key. Unavailable registry metadata fails closed on a first
387
- // boot, including offline. It starts now, before anything else, so its round
388
- // trip overlaps the local work below.
389
- const classification = startClassification(opts);
390
-
391
- // A returning session saved on this device paints at once from the cache:
392
- // the account, its cached content, auth resolved, no network on the way.
393
- // The classification and the session are then checked in the background,
394
- // and a verdict against either signs out at that moment. Identity-bound
395
- // clients and OAuth returns keep the path below.
396
- const freshLaunch = !identityBound && !hasOAuthReturnOnUrl();
397
- if (freshLaunch && (await opts.paintCachedSession?.())) {
398
- await verifyCachedSession(opts, { lane: false, session: false }, classification);
399
- return;
400
- }
401
-
402
- // The verdict decides HOW a session is restored, never WHETHER there is one.
403
- // A web origin with nothing to restore and no OAuth return on the URL ends
404
- // signed out on either lane, so routing need not wait a network round trip
405
- // for an answer that cannot change the outcome. The classification still
406
- // completes below and still gates every later sign-in
407
- // (`ensureDeviceSessionLane` shares this same in-flight lookup).
408
- if (freshLaunch && isWebBrowser()) {
409
- if (!(await hasRestorableState(authStore))) {
410
- markAuthResolved();
411
- const lane = await classification;
412
- await opts.onClassified?.(lane);
413
- if (lane === 'oauth') setTokenReady(true);
414
- return;
415
- }
416
- }
417
-
418
- const lane = await classification;
419
- await opts.onClassified?.(lane);
420
- if (identityBound && lane !== 'device') return;
421
- // The redirect transport's RETURN leg. An app reaches it whenever the browser
422
- // BLOCKED the sign-in popup and `startWebOAuthSignIn` fell back to a
423
- // full-page redirect (`popup-blocked` / `popup-navigation-failed`), so it is
424
- // load-bearing even though nothing here ever starts a redirect. It consumes a
425
- // code (or a stale OAuth `error`) already in the address bar and rewrites the
426
- // URL via `history.replaceState`; it never begins a navigation.
427
- const oauthCompleted = identityBound
428
- ? false
429
- : await tryCompleteOAuthReturn({
122
+ platform: {
123
+ isWeb: isWebBrowser,
124
+ probeNativeOffline: probeNetInfoOffline,
125
+ completeOAuthReturn: () =>
126
+ tryCompleteOAuthReturn({
430
127
  oxyServices,
431
128
  clientId,
432
129
  authRedirectUri,
433
130
  commitSession: (input) => commitSession(input, { activate: true, oauth: true }),
434
- });
435
- if (oauthCompleted) {
436
- setTokenReady(true);
437
- markAuthResolved();
438
- return;
439
- }
440
-
441
- if (lane === 'oauth') {
442
- setTokenReady(true);
443
- return;
444
- }
445
-
446
- await restoreDeviceSession(opts, false);
447
- } catch (error) {
448
- if (__DEV__) {
449
- loggerUtil.error(
450
- 'Cold boot error',
451
- error instanceof Error ? error : new Error(String(error)),
452
- { component: 'runProviderColdBoot' },
453
- );
454
- }
455
- } finally {
456
- markAuthResolved();
457
- }
131
+ }),
132
+ sharedDeviceCredential: createPlatformSharedDeviceCredentialStore,
133
+ runSessionColdBoot,
134
+ logger: loggerUtil,
135
+ },
136
+ });
458
137
  }
@@ -1,75 +1,3 @@
1
- import { logger, type OxyServices } from '@oxy.so/core';
2
- import type { TokenTransport } from '@oxy.so/core/session';
3
- import type { DeviceSessionState } from '@oxy.so/contracts';
4
-
5
- /**
6
- * Platform `TokenTransport` for `SessionClient` (device-first model).
7
- *
8
- * `ensureActiveToken` is the fallback the client uses when a `session_state`
9
- * push arrived WITHOUT an embedded `activeToken` and the planted bearer does not
10
- * already belong to the state's active account. It mints one through the ONE
11
- * unified single-flight the scheduler, the request-time preflight, and the 401
12
- * retry all use — `oxyServices.http.refreshAccessToken(...)` — which runs
13
- * the installed refresh handler (present the persisted zero-cookie `deviceId` +
14
- * `deviceSecret` at `POST /session/device/token`, which mints for the device's
15
- * CURRENT active account). Routing through the SAME entry point means this lane
16
- * can never double-rotate the device secret against the others: it has NO
17
- * private single-flight of its own.
18
- *
19
- * The short-circuit compares the planted bearer's ACCOUNT against
20
- * `state.activeAccountId`, not mere token presence: a bearer for the PREVIOUS
21
- * account (an account switch) must still mint the new account's token — skipping
22
- * on presence alone would leave a subscriber observing the new active account
23
- * under the old account's bearer (the account-switch 404 race).
24
- *
25
- * A failure is logged and swallowed: this method must never throw out (it runs
26
- * inside the socket state handler).
27
- *
28
- * `getPinnedAccountId` is the identity-bound escape hatch. Converging the bearer
29
- * on `state.activeAccountId` is precisely what an identity-bound client must
30
- * never do — its token is minted for the PINNED account by the cold boot /
31
- * re-mint lane. `SessionClient` already bypasses the transport entirely while
32
- * pinned; this guard is the services-side half of that contract, so no future
33
- * wiring can reintroduce the convergence from this end.
34
- */
35
- export function createTokenTransport(
36
- oxyServices: OxyServices,
37
- getPinnedAccountId?: () => string | null,
38
- ): TokenTransport {
39
- return {
40
- async ensureActiveToken(state: DeviceSessionState): Promise<void> {
41
- if ((getPinnedAccountId?.() ?? null) !== null) {
42
- return;
43
- }
44
- try {
45
- // Skip the mint ONLY when the planted bearer already identifies the
46
- // active account. `getCurrentUserId()` decodes the bearer's `userId`/`id`
47
- // (null when absent/opaque), directly comparable to the account id.
48
- const activeAccountId = state.activeAccountId;
49
- if (activeAccountId !== null && oxyServices.session.userId === activeAccountId) {
50
- return;
51
- }
52
- } catch (error) {
53
- logger.warn(
54
- 'ensureActiveToken: bearer-account check threw',
55
- { component: 'TokenTransport' },
56
- error,
57
- );
58
- }
59
-
60
- try {
61
- // The shared HttpService single-flight coalesces concurrent callers onto
62
- // one in-flight mint; no local `inFlightMint` guard is needed.
63
- const token = await oxyServices.http.refreshAccessToken('preflight');
64
- if (!token) {
65
- logger.debug('ensureActiveToken: refresh produced no session', {
66
- component: 'TokenTransport',
67
- deviceId: state.deviceId,
68
- });
69
- }
70
- } catch (error) {
71
- logger.warn('ensureActiveToken: refresh failed', { component: 'TokenTransport' }, error);
72
- }
73
- },
74
- };
75
- }
1
+ // The transport moved to `@oxy.so/core/session` (core 7.66.0) so the React-free
2
+ // web session shares it; this module keeps the package's import site.
3
+ export { createTokenTransport } from '@oxy.so/core/session';