@oxyhq/core 9.2.1 → 9.2.3
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/cjs/.tsbuildinfo +1 -1
- package/dist/cjs/HttpService.js +27 -0
- package/dist/cjs/boot/sessionColdBoot.js +83 -53
- package/dist/cjs/crypto/keyManager.js +45 -12
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/mixins/OxyServices.utility.js +9 -5
- package/dist/cjs/session/SessionClient.js +54 -4
- package/dist/cjs/session/accountDialogController.js +30 -0
- package/dist/cjs/session/authStateStore.js +204 -16
- package/dist/cjs/session/refresh.js +110 -37
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/HttpService.js +27 -0
- package/dist/esm/boot/sessionColdBoot.js +83 -53
- package/dist/esm/crypto/keyManager.js +46 -13
- package/dist/esm/index.js +1 -1
- package/dist/esm/mixins/OxyServices.utility.js +9 -5
- package/dist/esm/session/SessionClient.js +54 -4
- package/dist/esm/session/accountDialogController.js +30 -0
- package/dist/esm/session/authStateStore.js +203 -15
- package/dist/esm/session/refresh.js +109 -37
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/HttpService.d.ts +21 -0
- package/dist/types/boot/sessionColdBoot.d.ts +7 -3
- package/dist/types/index.d.ts +3 -3
- package/dist/types/session/SessionClient.d.ts +37 -4
- package/dist/types/session/accountDialogController.d.ts +17 -0
- package/dist/types/session/authStateStore.d.ts +48 -9
- package/dist/types/session/refresh.d.ts +67 -31
- package/package.json +2 -2
- package/src/HttpService.ts +31 -0
- package/src/boot/__tests__/sessionColdBoot.test.ts +119 -0
- package/src/boot/sessionColdBoot.ts +93 -74
- package/src/crypto/keyManager.ts +42 -15
- package/src/index.ts +3 -2
- package/src/mixins/OxyServices.utility.ts +10 -9
- package/src/session/SessionClient.ts +79 -7
- package/src/session/__tests__/SessionClient.additive.test.ts +58 -1
- package/src/session/__tests__/SessionClient.serverEvents.test.ts +71 -0
- package/src/session/__tests__/SessionClient.socket.test.ts +32 -0
- package/src/session/__tests__/accountDialogController.test.ts +85 -0
- package/src/session/__tests__/authStateStore.test.ts +232 -4
- package/src/session/__tests__/refresh.test.ts +141 -2
- package/src/session/accountDialogController.ts +45 -0
- package/src/session/authStateStore.ts +242 -16
- package/src/session/refresh.ts +146 -40
package/dist/esm/HttpService.js
CHANGED
|
@@ -132,6 +132,7 @@ export class HttpService {
|
|
|
132
132
|
this.tokenRefreshCooldownUntil = 0;
|
|
133
133
|
this.authRefreshHandler = null;
|
|
134
134
|
this.accessTokenProvider = null;
|
|
135
|
+
this.deviceSecretMintInFlight = null;
|
|
135
136
|
/**
|
|
136
137
|
* Epoch (ms) before which a cache-size telemetry warning must not be
|
|
137
138
|
* re-emitted. Throttles the {@link CACHE_SOFT_MAX_ENTRIES} warning to at most
|
|
@@ -834,6 +835,32 @@ export class HttpService {
|
|
|
834
835
|
}
|
|
835
836
|
return this.tokenRefreshPromise;
|
|
836
837
|
}
|
|
838
|
+
/**
|
|
839
|
+
* PROCESS-WIDE single-flight for the rotating device-secret mint
|
|
840
|
+
* (`POST /session/device/token`).
|
|
841
|
+
*
|
|
842
|
+
* The server rotates the presented `deviceSecret` on every successful mint, so
|
|
843
|
+
* two concurrent mints would double-rotate and the durable store could end up
|
|
844
|
+
* holding a superseded secret → a later cold-boot mint 401s → the user is
|
|
845
|
+
* signed out. Every mint lane (the re-mint handler behind `refreshAccessToken`,
|
|
846
|
+
* the device-first cold boot, the socket token transport, the tab-focus
|
|
847
|
+
* reconcile) funnels its `refreshDeviceSecretArm` call through here, so
|
|
848
|
+
* concurrent callers await the SAME in-flight mint and all receive its result —
|
|
849
|
+
* exactly one server rotation.
|
|
850
|
+
*
|
|
851
|
+
* Distinct from {@link tokenRefreshPromise} (which dedups the FULL re-mint
|
|
852
|
+
* handler incl. the native shared-key arm + the failure cooldown): this inner
|
|
853
|
+
* guard serializes the rotation itself across BOTH the handler and the
|
|
854
|
+
* handler-independent cold boot, which never runs through `refreshAccessToken`.
|
|
855
|
+
*/
|
|
856
|
+
runSingleFlightDeviceSecretMint(mint) {
|
|
857
|
+
if (!this.deviceSecretMintInFlight) {
|
|
858
|
+
this.deviceSecretMintInFlight = mint().finally(() => {
|
|
859
|
+
this.deviceSecretMintInFlight = null;
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
return this.deviceSecretMintInFlight;
|
|
863
|
+
}
|
|
837
864
|
/**
|
|
838
865
|
* Unwrap standardized API response format
|
|
839
866
|
*/
|
|
@@ -7,31 +7,23 @@
|
|
|
7
7
|
* the app renders with a "Sign in with Oxy" button.
|
|
8
8
|
*
|
|
9
9
|
* Ordered steps (first to yield a session wins):
|
|
10
|
-
* 1. `
|
|
10
|
+
* 1. `warm-token-plant` (web + native) — the fastest path: when the persisted
|
|
11
|
+
* store still holds a warm access token that is valid for more than the
|
|
12
|
+
* refresh lead window, plant it and yield the session with NO network
|
|
13
|
+
* round-trip. The background scheduler rotates it shortly after.
|
|
14
|
+
* 2. `device-secret-mint` (web + native) — the zero-cookie transport: when the
|
|
11
15
|
* origin persisted a `deviceId` + `deviceSecret`, mint a short access token
|
|
12
16
|
* with a single bearer-less POST to `/session/device/token` (no cookie, no
|
|
13
17
|
* navigation) and rotate the secret in-use.
|
|
14
|
-
*
|
|
15
|
-
*
|
|
18
|
+
* 3. `shared-key-signin` (native) — re-mint from the shared-keychain identity.
|
|
19
|
+
* 4. Signed out.
|
|
16
20
|
*
|
|
17
21
|
* ESM-safe (no `require()`); no react/react-native/expo imports.
|
|
18
22
|
*/
|
|
19
23
|
import { runColdBoot } from '../utils/coldBoot.js';
|
|
20
24
|
import { isNative as detectNative } from '../utils/platform.js';
|
|
21
|
-
import { extractErrorStatus } from '../utils/errorUtils.js';
|
|
22
25
|
import { logger } from '../utils/loggerUtils.js';
|
|
23
|
-
|
|
24
|
-
if (extractErrorStatus(error) === 401) {
|
|
25
|
-
// Structural read (not `instanceof Error`): the thrown value can be a plain
|
|
26
|
-
// ApiError-shaped object or come from another realm, where instanceof fails
|
|
27
|
-
// and a `no_active_session` would be misread as a stale secret and dropped.
|
|
28
|
-
const message = error?.message;
|
|
29
|
-
return typeof message === 'string' && message.includes('no_active_session')
|
|
30
|
-
? 'no_active_session'
|
|
31
|
-
: 'invalid_secret';
|
|
32
|
-
}
|
|
33
|
-
return 'transient';
|
|
34
|
-
}
|
|
26
|
+
import { TOKEN_REFRESH_LEAD_MS, refreshDeviceSecretArm } from '../session/refresh.js';
|
|
35
27
|
/**
|
|
36
28
|
* Run the device-first cold boot. Resolves to the `runColdBoot` outcome and, as
|
|
37
29
|
* a side effect, invokes `onSession` (winning session, token already planted) or
|
|
@@ -44,60 +36,98 @@ export async function runSessionColdBoot(opts) {
|
|
|
44
36
|
// bundler re-evaluation.
|
|
45
37
|
let signedOutReason = 'no_session';
|
|
46
38
|
const steps = [];
|
|
47
|
-
// 1.
|
|
48
|
-
//
|
|
49
|
-
//
|
|
39
|
+
// 1. warm-token-plant (web + native) — the fastest path. When the persisted
|
|
40
|
+
// store already holds a still-valid warm access token (its expiry more than
|
|
41
|
+
// the refresh lead window away) plus its owning session identity, plant it
|
|
42
|
+
// and yield the session IMMEDIATELY, skipping the blocking mint round-trip on
|
|
43
|
+
// first paint. The token is used AS-IS: this step NEVER mints, rotates, or
|
|
44
|
+
// persists anything. The proactive `startTokenRefreshScheduler` + the
|
|
45
|
+
// request-time preflight (both wired in the services provider) rotate it in
|
|
46
|
+
// the background; a revoked token self-heals via the 401 -> re-mint -> clear
|
|
47
|
+
// path. This exposure is sanctioned by `authStateStore.ts` (~L30-36): the
|
|
48
|
+
// warm token is short-lived and adds nothing over the already-persisted
|
|
49
|
+
// `deviceSecret`.
|
|
50
50
|
steps.push({
|
|
51
|
-
id: '
|
|
51
|
+
id: 'warm-token-plant',
|
|
52
52
|
run: async () => {
|
|
53
53
|
const persisted = await store.load();
|
|
54
|
-
if (!persisted?.
|
|
54
|
+
if (!persisted?.accessToken || !persisted.sessionId || !persisted.userId || !persisted.expiresAt) {
|
|
55
55
|
return { kind: 'skip' };
|
|
56
56
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const next = {
|
|
65
|
-
...persisted,
|
|
66
|
-
deviceId: mint.state.deviceId,
|
|
67
|
-
deviceSecret: mint.nextDeviceSecret,
|
|
68
|
-
accessToken: mint.accessToken,
|
|
69
|
-
expiresAt: mint.expiresAt,
|
|
70
|
-
...(active ? { sessionId: active.sessionId, userId: active.accountId } : {}),
|
|
71
|
-
};
|
|
72
|
-
await store.save(next);
|
|
73
|
-
oxy.setTokens(mint.accessToken);
|
|
74
|
-
return {
|
|
75
|
-
kind: 'session',
|
|
76
|
-
session: { sessionId: next.sessionId, userId: next.userId, accessToken: mint.accessToken },
|
|
77
|
-
};
|
|
57
|
+
// Guard a malformed `expiresAt` (Date.parse -> NaN): treat as not-valid and
|
|
58
|
+
// fall through to the mint lane. A token still inside the refresh lead
|
|
59
|
+
// window (or already expired) is likewise skipped — let the mint lane get a
|
|
60
|
+
// fresh one rather than plant a token about to expire.
|
|
61
|
+
const expiresAtMs = new Date(persisted.expiresAt).getTime();
|
|
62
|
+
if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now() + TOKEN_REFRESH_LEAD_MS) {
|
|
63
|
+
return { kind: 'skip' };
|
|
78
64
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
65
|
+
oxy.setTokens(persisted.accessToken);
|
|
66
|
+
return {
|
|
67
|
+
kind: 'session',
|
|
68
|
+
session: {
|
|
69
|
+
sessionId: persisted.sessionId,
|
|
70
|
+
userId: persisted.userId,
|
|
71
|
+
accessToken: persisted.accessToken,
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
// 2. device-secret-mint (web + native) — the zero-cookie fast path. When the
|
|
77
|
+
// origin persisted a deviceId + deviceSecret, mint a short access token with
|
|
78
|
+
// a single bearer-less POST (no cookie, no navigation). The mint itself runs
|
|
79
|
+
// through `refreshDeviceSecretArm`, which acquires the client's PROCESS-WIDE
|
|
80
|
+
// single-flight, persists the rotated `nextDeviceSecret` BEFORE planting the
|
|
81
|
+
// token, and returns a classified outcome — so this step can never
|
|
82
|
+
// double-rotate the server against the scheduler/transport/401 lanes, and
|
|
83
|
+
// the durable store always converges on the true `current` secret.
|
|
84
|
+
steps.push({
|
|
85
|
+
id: 'device-secret-mint',
|
|
86
|
+
run: async () => {
|
|
87
|
+
const result = await refreshDeviceSecretArm({ oxy, store });
|
|
88
|
+
switch (result.status) {
|
|
89
|
+
case 'ok':
|
|
90
|
+
// The arm persisted the rotated secret and planted the token.
|
|
91
|
+
return {
|
|
92
|
+
kind: 'session',
|
|
93
|
+
session: {
|
|
94
|
+
sessionId: result.sessionId,
|
|
95
|
+
userId: result.userId,
|
|
96
|
+
accessToken: result.token,
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
case 'invalid-secret': {
|
|
82
100
|
// Stale/diverged secret — drop it so the mint lane stops firing. On
|
|
83
101
|
// native the shared-key step below can still recover; on web this ends
|
|
84
102
|
// signed out. Setting it undefined drops the key on the store's JSON
|
|
85
103
|
// serialization, and the mint guard treats undefined as absent.
|
|
86
|
-
await store.
|
|
104
|
+
const persisted = await store.load();
|
|
105
|
+
if (persisted) {
|
|
106
|
+
await store.save({ ...persisted, deviceSecret: undefined });
|
|
107
|
+
}
|
|
87
108
|
return { kind: 'skip' };
|
|
88
109
|
}
|
|
89
|
-
|
|
90
|
-
// Device known, no live session — authoritative signed-out.
|
|
110
|
+
case 'no-session':
|
|
111
|
+
// Device known, no live session — authoritative signed-out. Keep the
|
|
112
|
+
// secret (the device may sign in again).
|
|
91
113
|
signedOutReason = 'no_session';
|
|
92
114
|
return { kind: 'skip' };
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
115
|
+
case 'persist-failed':
|
|
116
|
+
// The mint rotated the secret but it could not be durably persisted —
|
|
117
|
+
// refuse to advertise a session that will not survive a reload. Keep
|
|
118
|
+
// the secret; a later boot/attempt re-mints once storage recovers.
|
|
119
|
+
logger.error('device-secret mint rotated the secret but it could not be durably persisted — not planting', undefined, { component: 'sessionColdBoot', method: 'device-secret-mint' });
|
|
120
|
+
return { kind: 'skip' };
|
|
121
|
+
case 'transient':
|
|
122
|
+
// Network / 5xx: keep the secret; a later attempt can succeed.
|
|
123
|
+
logger.debug('device-secret mint failed (transient) — keeping secret', { component: 'sessionColdBoot', method: 'device-secret-mint' });
|
|
124
|
+
return { kind: 'skip' };
|
|
125
|
+
case 'no-secret':
|
|
126
|
+
return { kind: 'skip' };
|
|
97
127
|
}
|
|
98
128
|
},
|
|
99
129
|
});
|
|
100
|
-
//
|
|
130
|
+
// 3. shared-key-signin (native) — re-mint from the shared identity.
|
|
101
131
|
steps.push({
|
|
102
132
|
id: 'shared-key-signin',
|
|
103
133
|
enabled: () => isNative,
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import _cjs_elliptic from 'elliptic';
|
|
8
8
|
const { ec: EC } = _cjs_elliptic;
|
|
9
9
|
import { isWeb, isIOS, isAndroid } from '../utils/platform.js';
|
|
10
|
-
import { isReactNative, isNodeJS, loadExpoCrypto, loadNodeCrypto, loadSecureStore } from '@oxyhq/protocol';
|
|
10
|
+
import { isReactNative, isNodeJS, loadExpoCrypto, loadNodeCrypto, loadSecureStore, loadSharedIdentityBridge } from '@oxyhq/protocol';
|
|
11
11
|
import { logger } from '../utils/loggerUtils.js';
|
|
12
12
|
import { isDev } from '../shared/utils/debugUtils.js';
|
|
13
13
|
/**
|
|
@@ -230,12 +230,21 @@ export class KeyManager {
|
|
|
230
230
|
}
|
|
231
231
|
}
|
|
232
232
|
else if (isAndroid()) {
|
|
233
|
-
// Android:
|
|
234
|
-
//
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
await
|
|
233
|
+
// Android: write through the cross-app bridge (`@oxyhq/expo-oxy-identity`)
|
|
234
|
+
// when present — it persists into Commons's hardware-backed
|
|
235
|
+
// EncryptedSharedPreferences behind a signature-protected ContentProvider,
|
|
236
|
+
// so same-key Oxy apps can read it. When the bridge is not linked, fall
|
|
237
|
+
// back to the package-private secure store (no cross-app sharing).
|
|
238
|
+
const bridge = await loadSharedIdentityBridge();
|
|
239
|
+
if (bridge) {
|
|
240
|
+
await bridge.putShared(privateKey, publicKey);
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, privateKey, {
|
|
244
|
+
keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
|
|
245
|
+
});
|
|
246
|
+
await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey);
|
|
247
|
+
}
|
|
239
248
|
}
|
|
240
249
|
// Update cache
|
|
241
250
|
KeyManager.cachedSharedPublicKey = publicKey;
|
|
@@ -266,7 +275,15 @@ export class KeyManager {
|
|
|
266
275
|
publicKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, opts);
|
|
267
276
|
}
|
|
268
277
|
else if (isAndroid()) {
|
|
269
|
-
|
|
278
|
+
// Android reads through the cross-app bridge; when it is not linked, fall
|
|
279
|
+
// back to the package-private store the fallback write path used.
|
|
280
|
+
const bridge = await loadSharedIdentityBridge();
|
|
281
|
+
if (bridge) {
|
|
282
|
+
publicKey = (await bridge.getShared())?.publicKey ?? null;
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
publicKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY);
|
|
286
|
+
}
|
|
270
287
|
}
|
|
271
288
|
// Cache result
|
|
272
289
|
KeyManager.cachedSharedPublicKey = publicKey;
|
|
@@ -300,7 +317,15 @@ export class KeyManager {
|
|
|
300
317
|
privateKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, opts);
|
|
301
318
|
}
|
|
302
319
|
else if (isAndroid()) {
|
|
303
|
-
|
|
320
|
+
// Android reads through the cross-app bridge; when it is not linked, fall
|
|
321
|
+
// back to the package-private store the fallback write path used.
|
|
322
|
+
const bridge = await loadSharedIdentityBridge();
|
|
323
|
+
if (bridge) {
|
|
324
|
+
privateKey = (await bridge.getShared())?.privateKey ?? null;
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
privateKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY);
|
|
328
|
+
}
|
|
304
329
|
}
|
|
305
330
|
return privateKey;
|
|
306
331
|
}
|
|
@@ -373,10 +398,18 @@ export class KeyManager {
|
|
|
373
398
|
await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey, publicOpts);
|
|
374
399
|
}
|
|
375
400
|
else if (isAndroid()) {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
401
|
+
// Android: write through the cross-app bridge when present; otherwise the
|
|
402
|
+
// package-private store (kept consistent with the read fallback).
|
|
403
|
+
const bridge = await loadSharedIdentityBridge();
|
|
404
|
+
if (bridge) {
|
|
405
|
+
await bridge.putShared(canonicalPrivate, publicKey);
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, canonicalPrivate, {
|
|
409
|
+
keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
|
|
410
|
+
});
|
|
411
|
+
await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey);
|
|
412
|
+
}
|
|
380
413
|
}
|
|
381
414
|
// Update cache
|
|
382
415
|
KeyManager.cachedSharedPublicKey = publicKey;
|
package/dist/esm/index.js
CHANGED
|
@@ -166,7 +166,7 @@ export { AccountDialogController, createAccountDialogController, } from './sessi
|
|
|
166
166
|
// via `POST /session/device/token`.
|
|
167
167
|
// ---------------------------------------------------------------------------
|
|
168
168
|
export { createWebAuthStateStore, createNativeAuthStateStore, createMemoryAuthStateStore, AUTH_STATE_STORAGE_KEY, } from './session/authStateStore.js';
|
|
169
|
-
export { refreshPersistedSession, createAuthRefreshHandler, installAuthRefreshHandler, startTokenRefreshScheduler, TOKEN_REFRESH_LEAD_MS, } from './session/refresh.js';
|
|
169
|
+
export { refreshPersistedSession, refreshDeviceSecretArm, createAuthRefreshHandler, installAuthRefreshHandler, startTokenRefreshScheduler, TOKEN_REFRESH_LEAD_MS, } from './session/refresh.js';
|
|
170
170
|
export { runSessionColdBoot } from './boot/sessionColdBoot.js';
|
|
171
171
|
// API response contracts (request/response Zod schemas + inferred types) live in
|
|
172
172
|
// `@oxyhq/contracts` — the single source of truth shared by the backend and every
|
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { jwtDecode } from 'jwt-decode';
|
|
8
8
|
import { loadNodeCrypto } from '@oxyhq/protocol';
|
|
9
|
+
import { buildUrl } from '../utils/apiUtils.js';
|
|
9
10
|
import { logger } from '../utils/loggerUtils.js';
|
|
10
|
-
import { CACHE_TIMES } from './mixinHelpers.js';
|
|
11
11
|
/**
|
|
12
12
|
* Expected JWT audience for tokens issued by the Oxy auth service.
|
|
13
13
|
*/
|
|
@@ -108,10 +108,14 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
108
108
|
*/
|
|
109
109
|
async fetchLinkMetadata(url) {
|
|
110
110
|
try {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
111
|
+
const path = buildUrl('/links/preview', { url, wait: 1 });
|
|
112
|
+
const preview = await this.makeRequest('GET', path, undefined, { cache: false });
|
|
113
|
+
return {
|
|
114
|
+
url: preview.url,
|
|
115
|
+
title: preview.title?.trim() || preview.url.replace(/^https?:\/\//, '').replace(/\/$/, ''),
|
|
116
|
+
description: preview.description?.trim() || 'Link',
|
|
117
|
+
image: preview.image,
|
|
118
|
+
};
|
|
115
119
|
}
|
|
116
120
|
catch (error) {
|
|
117
121
|
throw this.handleError(error);
|
|
@@ -21,6 +21,10 @@ export class SessionClient {
|
|
|
21
21
|
this.started = false;
|
|
22
22
|
/** Same-origin cross-tab state-propagation channel; null on platforms without BroadcastChannel. */
|
|
23
23
|
this.channel = null;
|
|
24
|
+
/** App-facing subscriptions to named server-pushed socket events. */
|
|
25
|
+
this.serverEvents = new Map();
|
|
26
|
+
/** Event names already bound on the CURRENT socket instance. */
|
|
27
|
+
this.boundServerEvents = new Set();
|
|
24
28
|
}
|
|
25
29
|
getState() {
|
|
26
30
|
return this.state;
|
|
@@ -31,6 +35,41 @@ export class SessionClient {
|
|
|
31
35
|
this.listeners.delete(listener);
|
|
32
36
|
};
|
|
33
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Subscribe to a named server-pushed Socket.IO event (e.g. `civic:attested`).
|
|
40
|
+
* Listeners survive reconnects and socket re-creation; the returned function
|
|
41
|
+
* unsubscribes. Payloads are delivered as-is — callers validate shape.
|
|
42
|
+
*/
|
|
43
|
+
onServerEvent(event, listener) {
|
|
44
|
+
let listeners = this.serverEvents.get(event);
|
|
45
|
+
if (!listeners) {
|
|
46
|
+
listeners = new Set();
|
|
47
|
+
this.serverEvents.set(event, listeners);
|
|
48
|
+
}
|
|
49
|
+
listeners.add(listener);
|
|
50
|
+
this.bindServerEvent(event);
|
|
51
|
+
return () => {
|
|
52
|
+
listeners.delete(listener);
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
bindServerEvent(event) {
|
|
56
|
+
if (!this.socket || this.boundServerEvents.has(event))
|
|
57
|
+
return;
|
|
58
|
+
this.boundServerEvents.add(event);
|
|
59
|
+
this.socket.on(event, (payload) => {
|
|
60
|
+
const listeners = this.serverEvents.get(event);
|
|
61
|
+
if (!listeners)
|
|
62
|
+
return;
|
|
63
|
+
for (const listener of [...listeners]) {
|
|
64
|
+
try {
|
|
65
|
+
listener(payload);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
logger.warn('[SessionClient] server-event listener threw', { component: 'SessionClient' }, error);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
34
73
|
notify() {
|
|
35
74
|
for (const listener of this.listeners) {
|
|
36
75
|
try {
|
|
@@ -42,7 +81,7 @@ export class SessionClient {
|
|
|
42
81
|
}
|
|
43
82
|
}
|
|
44
83
|
/** Validate + last-writer-wins by revision. Returns true if applied. */
|
|
45
|
-
applyState(raw) {
|
|
84
|
+
applyState(raw, origin = 'push') {
|
|
46
85
|
const next = safeParseContract(deviceSessionStateSchema, raw);
|
|
47
86
|
if (!next) {
|
|
48
87
|
logger.warn('[SessionClient] discarded invalid session state');
|
|
@@ -66,7 +105,7 @@ export class SessionClient {
|
|
|
66
105
|
this.notify();
|
|
67
106
|
if (next.accounts.length === 0 && this.options.onUnauthenticated) {
|
|
68
107
|
try {
|
|
69
|
-
this.options.onUnauthenticated();
|
|
108
|
+
this.options.onUnauthenticated(origin);
|
|
70
109
|
}
|
|
71
110
|
catch (error) {
|
|
72
111
|
logger.error('[SessionClient] onUnauthenticated threw', error);
|
|
@@ -112,7 +151,10 @@ export class SessionClient {
|
|
|
112
151
|
logger.warn('[SessionClient] discarded invalid session sync', { component: 'SessionClient', issues, keys });
|
|
113
152
|
return;
|
|
114
153
|
}
|
|
115
|
-
this
|
|
154
|
+
// A `sync` is always the response to a direct REST call this client made
|
|
155
|
+
// (bootstrap / switch / signOut / add) → a `request`-origin, authoritative
|
|
156
|
+
// verdict.
|
|
157
|
+
this.applyState(sync.state, 'request');
|
|
116
158
|
if (sync.activeToken && this.state && sync.state.activeAccountId === this.state.activeAccountId) {
|
|
117
159
|
this.host.setTokens(sync.activeToken.accessToken);
|
|
118
160
|
}
|
|
@@ -210,6 +252,7 @@ export class SessionClient {
|
|
|
210
252
|
if (this.socket) {
|
|
211
253
|
this.socket.disconnect();
|
|
212
254
|
this.socket = null;
|
|
255
|
+
this.boundServerEvents.clear();
|
|
213
256
|
}
|
|
214
257
|
}
|
|
215
258
|
async connectSocket() {
|
|
@@ -249,7 +292,9 @@ export class SessionClient {
|
|
|
249
292
|
},
|
|
250
293
|
});
|
|
251
294
|
socket.on('session_state', (payload) => {
|
|
252
|
-
|
|
295
|
+
// A socket broadcast is a `push`-origin — potentially transient, so an
|
|
296
|
+
// empty state here must not erase the durable device credential.
|
|
297
|
+
const applied = this.applyState(payload, 'push');
|
|
253
298
|
if (!applied)
|
|
254
299
|
return;
|
|
255
300
|
// A push changed the active account on another device/tab — re-fetch state
|
|
@@ -264,6 +309,11 @@ export class SessionClient {
|
|
|
264
309
|
}
|
|
265
310
|
});
|
|
266
311
|
this.socket = socket;
|
|
312
|
+
// (Re)bind app-facing server-event subscriptions on the fresh socket.
|
|
313
|
+
this.boundServerEvents.clear();
|
|
314
|
+
for (const event of this.serverEvents.keys()) {
|
|
315
|
+
this.bindServerEvent(event);
|
|
316
|
+
}
|
|
267
317
|
}
|
|
268
318
|
/**
|
|
269
319
|
* Open the same-origin `BroadcastChannel` (web only). A sibling tab that
|
|
@@ -30,6 +30,12 @@ import { CENTRAL_IDP_APEX } from '../utils/authWebUrl.js';
|
|
|
30
30
|
import { generateOAuthState, generatePkcePair, normalizeOAuthRedirectUri, persistOAuthHandshake, } from '../utils/oauthPkce.js';
|
|
31
31
|
import { projectSwitchableAccounts, switchableAccountIds, } from './accountProjection.js';
|
|
32
32
|
const DEFAULT_POLL_INTERVAL_MS = 3000;
|
|
33
|
+
/**
|
|
34
|
+
* Commons's custom URL scheme. Probed via the injected `canOpenApp` to detect an
|
|
35
|
+
* installed Commons on the same device; the `oxycommons://approve?...` deep link
|
|
36
|
+
* itself is the flow's `qrPayload`.
|
|
37
|
+
*/
|
|
38
|
+
const COMMONS_APP_SCHEME = 'oxycommons://';
|
|
33
39
|
const IDLE_SIGN_IN = {
|
|
34
40
|
phase: 'idle',
|
|
35
41
|
authorizeCode: null,
|
|
@@ -72,6 +78,7 @@ export class AccountDialogController {
|
|
|
72
78
|
this.authRedirectUri = options.authRedirectUri ?? null;
|
|
73
79
|
this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
74
80
|
this.openUrl = options.openUrl;
|
|
81
|
+
this.canOpenApp = options.canOpenApp;
|
|
75
82
|
this.snapshot = this.computeSnapshot();
|
|
76
83
|
}
|
|
77
84
|
// =========================================================================
|
|
@@ -396,11 +403,34 @@ export class AccountDialogController {
|
|
|
396
403
|
error: null,
|
|
397
404
|
});
|
|
398
405
|
this.scheduleNextPoll(handle.sessionToken);
|
|
406
|
+
// Same-device convenience: if Commons is installed (native only — `canOpenApp`
|
|
407
|
+
// is undefined/false on web), deep-link straight into its approve screen with
|
|
408
|
+
// the same `oxycommons://approve?...` payload the QR encodes. The QR + polling
|
|
409
|
+
// stay live as the fallback, so a user who dismisses the app-open still
|
|
410
|
+
// completes the sign-in by scanning.
|
|
411
|
+
void this.maybeOpenCommons(handle.qrPayload);
|
|
399
412
|
}
|
|
400
413
|
catch (error) {
|
|
401
414
|
this.setSignIn({ ...IDLE_SIGN_IN, phase: 'error', error: errorMessage(error) });
|
|
402
415
|
}
|
|
403
416
|
}
|
|
417
|
+
/**
|
|
418
|
+
* When a `canOpenApp` probe is injected and reports Commons installed, open the
|
|
419
|
+
* approve deep link via the injected `openUrl`. Best-effort and non-blocking: a
|
|
420
|
+
* probe/open failure is logged and swallowed — the QR/polling fallback remains.
|
|
421
|
+
*/
|
|
422
|
+
async maybeOpenCommons(qrPayload) {
|
|
423
|
+
if (!this.canOpenApp || !this.openUrl)
|
|
424
|
+
return;
|
|
425
|
+
try {
|
|
426
|
+
if (await this.canOpenApp(COMMONS_APP_SCHEME)) {
|
|
427
|
+
this.openUrl(qrPayload);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
catch (error) {
|
|
431
|
+
logger.debug('[AccountDialogController] Commons deep-link probe failed (QR fallback active)', { component: 'AccountDialogController' }, error);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
404
434
|
/** Tear down the active sign-in device flow (timers + token) and reset to idle. */
|
|
405
435
|
cancelSignIn() {
|
|
406
436
|
this.clearPollTimer();
|