@oxy.so/services 14.10.0 → 14.11.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.
- package/lib/commonjs/index.js +10 -0
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/ui/boot/runProviderColdBoot.js +3 -1
- package/lib/commonjs/ui/boot/runProviderColdBoot.js.map +1 -1
- package/lib/commonjs/ui/components/OxyProvider.js +52 -18
- package/lib/commonjs/ui/components/OxyProvider.js.map +1 -1
- package/lib/commonjs/ui/context/OxyContext.js +15 -5
- package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
- package/lib/commonjs/ui/context/OxyHostedContext.js +515 -0
- package/lib/commonjs/ui/context/OxyHostedContext.js.map +1 -0
- package/lib/commonjs/ui/context/oxyRuntimeContext.js.map +1 -1
- package/lib/commonjs/ui/hooks/useAuth.js +13 -2
- package/lib/commonjs/ui/hooks/useAuth.js.map +1 -1
- package/lib/commonjs/ui/hooks/useOxyEvent.js +9 -5
- package/lib/commonjs/ui/hooks/useOxyEvent.js.map +1 -1
- package/lib/commonjs/ui/session/hostSession.js +474 -0
- package/lib/commonjs/ui/session/hostSession.js.map +1 -0
- package/lib/module/index.js +3 -0
- package/lib/module/index.js.map +1 -1
- package/lib/module/ui/boot/runProviderColdBoot.js +3 -1
- package/lib/module/ui/boot/runProviderColdBoot.js.map +1 -1
- package/lib/module/ui/components/OxyProvider.js +53 -19
- package/lib/module/ui/components/OxyProvider.js.map +1 -1
- package/lib/module/ui/context/OxyContext.js +15 -5
- package/lib/module/ui/context/OxyContext.js.map +1 -1
- package/lib/module/ui/context/OxyHostedContext.js +510 -0
- package/lib/module/ui/context/OxyHostedContext.js.map +1 -0
- package/lib/module/ui/context/oxyRuntimeContext.js.map +1 -1
- package/lib/module/ui/hooks/useAuth.js +13 -2
- package/lib/module/ui/hooks/useAuth.js.map +1 -1
- package/lib/module/ui/hooks/useOxyEvent.js +9 -5
- package/lib/module/ui/hooks/useOxyEvent.js.map +1 -1
- package/lib/module/ui/session/hostSession.js +467 -0
- package/lib/module/ui/session/hostSession.js.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +1 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/boot/runProviderColdBoot.d.ts +6 -0
- package/lib/typescript/commonjs/ui/boot/runProviderColdBoot.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/components/OxyProvider.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/context/OxyContext.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/context/OxyHostedContext.d.ts +40 -0
- package/lib/typescript/commonjs/ui/context/OxyHostedContext.d.ts.map +1 -0
- package/lib/typescript/commonjs/ui/context/oxyContextTypes.d.ts +19 -2
- package/lib/typescript/commonjs/ui/context/oxyContextTypes.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/context/oxyRuntimeContext.d.ts +6 -0
- package/lib/typescript/commonjs/ui/context/oxyRuntimeContext.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/hooks/useAuth.d.ts +3 -0
- package/lib/typescript/commonjs/ui/hooks/useAuth.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/hooks/useOxyEvent.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/session/hostSession.d.ts +69 -0
- package/lib/typescript/commonjs/ui/session/hostSession.d.ts.map +1 -0
- package/lib/typescript/commonjs/ui/types/navigation.d.ts +24 -1
- package/lib/typescript/commonjs/ui/types/navigation.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/utils/identityCrypto.d.ts +9 -0
- package/lib/typescript/commonjs/ui/utils/identityCrypto.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +1 -0
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/ui/boot/runProviderColdBoot.d.ts +6 -0
- package/lib/typescript/module/ui/boot/runProviderColdBoot.d.ts.map +1 -1
- package/lib/typescript/module/ui/components/OxyProvider.d.ts.map +1 -1
- package/lib/typescript/module/ui/context/OxyContext.d.ts.map +1 -1
- package/lib/typescript/module/ui/context/OxyHostedContext.d.ts +40 -0
- package/lib/typescript/module/ui/context/OxyHostedContext.d.ts.map +1 -0
- package/lib/typescript/module/ui/context/oxyContextTypes.d.ts +19 -2
- package/lib/typescript/module/ui/context/oxyContextTypes.d.ts.map +1 -1
- package/lib/typescript/module/ui/context/oxyRuntimeContext.d.ts +6 -0
- package/lib/typescript/module/ui/context/oxyRuntimeContext.d.ts.map +1 -1
- package/lib/typescript/module/ui/hooks/useAuth.d.ts +3 -0
- package/lib/typescript/module/ui/hooks/useAuth.d.ts.map +1 -1
- package/lib/typescript/module/ui/hooks/useOxyEvent.d.ts.map +1 -1
- package/lib/typescript/module/ui/session/hostSession.d.ts +69 -0
- package/lib/typescript/module/ui/session/hostSession.d.ts.map +1 -0
- package/lib/typescript/module/ui/types/navigation.d.ts +24 -1
- package/lib/typescript/module/ui/types/navigation.d.ts.map +1 -1
- package/lib/typescript/module/ui/utils/identityCrypto.d.ts +9 -0
- package/lib/typescript/module/ui/utils/identityCrypto.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +3 -0
- package/src/ui/boot/runProviderColdBoot.ts +12 -1
- package/src/ui/components/OxyProvider.tsx +77 -34
- package/src/ui/context/OxyContext.tsx +19 -4
- package/src/ui/context/OxyHostedContext.tsx +678 -0
- package/src/ui/context/oxyContextTypes.ts +21 -2
- package/src/ui/context/oxyRuntimeContext.ts +9 -1
- package/src/ui/hooks/useAuth.ts +13 -1
- package/src/ui/hooks/useOxyEvent.ts +8 -5
- package/src/ui/session/hostSession.ts +515 -0
- package/src/ui/types/navigation.ts +24 -1
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
import type {
|
|
18
18
|
AccountDialogController,
|
|
19
19
|
AccountDialogView,
|
|
20
|
+
AuthStateStore,
|
|
20
21
|
SessionClient,
|
|
21
22
|
SessionMode,
|
|
22
23
|
} from '@oxy.so/core/session';
|
|
@@ -39,8 +40,14 @@ import type { AccountQueriesConfig } from '../hooks/accountQueryPersistence';
|
|
|
39
40
|
* The session is still installed on this device, and nothing about the
|
|
40
41
|
* outcome may be presented as revoked. The error is also reported through
|
|
41
42
|
* the provider's `onError`, as before.
|
|
43
|
+
* - `requested` — a platform holds the session (a session host, ADR 0058): the
|
|
44
|
+
* sign-out was handed to the platform, which decides whether to ask. The
|
|
45
|
+
* outcome arrives as the session changes; nothing is signed out yet.
|
|
42
46
|
*/
|
|
43
|
-
export type LogoutResult =
|
|
47
|
+
export type LogoutResult =
|
|
48
|
+
| { status: 'signed-out' }
|
|
49
|
+
| { status: 'failed'; error: unknown }
|
|
50
|
+
| { status: 'requested' };
|
|
44
51
|
|
|
45
52
|
export interface OxyContextState {
|
|
46
53
|
user: User | null;
|
|
@@ -169,8 +176,18 @@ export interface OxyContextState {
|
|
|
169
176
|
storageKeyPrefix: string;
|
|
170
177
|
clientId: string | null;
|
|
171
178
|
oxyServices: OxyServices;
|
|
172
|
-
/**
|
|
179
|
+
/**
|
|
180
|
+
* Server-authoritative device session client. `null` before an `OxyProvider`
|
|
181
|
+
* is mounted, and on a session host (ADR 0058), where the device is the
|
|
182
|
+
* platform's.
|
|
183
|
+
*/
|
|
173
184
|
sessionClient: SessionClient | null;
|
|
185
|
+
/**
|
|
186
|
+
* Subscribe to a named server-pushed socket event when the provider's socket
|
|
187
|
+
* is not `sessionClient`'s (a session host's user socket). `useOxyEvent`
|
|
188
|
+
* reads it; apps use `useOxyEvent`.
|
|
189
|
+
*/
|
|
190
|
+
onServerEvent?: (event: string, listener: (payload: unknown) => void) => () => void;
|
|
174
191
|
useFollow?: UseFollowHook;
|
|
175
192
|
showBottomSheet?: (
|
|
176
193
|
screenOrConfig: RouteName | { screen: RouteName; props?: Record<string, unknown> },
|
|
@@ -241,6 +258,8 @@ export interface OxyRuntimeProviderProps {
|
|
|
241
258
|
onError?: (error: ApiError) => void;
|
|
242
259
|
/** Storage instance owned by the public provider; internal composition seam. */
|
|
243
260
|
platformStorage?: StorageInterface | null;
|
|
261
|
+
/** See `OxyProviderProps.authStateStore`. Read once, at mount. */
|
|
262
|
+
authStateStore?: AuthStateStore;
|
|
244
263
|
/** See `OxyProviderProps.accountQueries`. Read once, at mount. */
|
|
245
264
|
accountQueries?: AccountQueriesConfig;
|
|
246
265
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createContext, useContext } from 'react';
|
|
2
|
+
import type { OxyHostRequest } from '@oxy.so/core/host';
|
|
2
3
|
import type { OxyContextState } from './oxyContextTypes';
|
|
3
4
|
|
|
4
5
|
export const OxyRuntimeContext = createContext<OxyContextState | null>(null);
|
|
@@ -55,7 +56,14 @@ export type OxyAuthActionsContextState = Pick<
|
|
|
55
56
|
| 'showBottomSheet'
|
|
56
57
|
| 'openAvatarPicker'
|
|
57
58
|
| 'openAccountDialog'
|
|
58
|
-
> & {
|
|
59
|
+
> & {
|
|
60
|
+
ensureDeviceSessionLane: () => void | Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Present only on a session host (ADR 0058): hands an action to the
|
|
63
|
+
* platform's own UI. `useAuth().signIn()` uses it instead of the dialog.
|
|
64
|
+
*/
|
|
65
|
+
hostRequest?: (action: OxyHostRequest) => Promise<void>;
|
|
66
|
+
};
|
|
59
67
|
|
|
60
68
|
export const OxyAuthActionsContext = createContext<OxyAuthActionsContextState | null>(null);
|
|
61
69
|
|
package/src/ui/hooks/useAuth.ts
CHANGED
|
@@ -84,6 +84,9 @@ export interface AuthActions {
|
|
|
84
84
|
* Sign in
|
|
85
85
|
* - Web + native: opens the in-app Oxy account dialog (`openAccountDialog('signin')`).
|
|
86
86
|
* Never navigates to auth.oxy.so — that origin is third-party OAuth only.
|
|
87
|
+
* - On a platform that holds the session (a session host, ADR 0058): asks
|
|
88
|
+
* the platform's own sign-in and resolves `dialog-opened`; the account
|
|
89
|
+
* arrives as the session changes.
|
|
87
90
|
*
|
|
88
91
|
* @param publicKey - Native: identity public key. Ignored on web.
|
|
89
92
|
*/
|
|
@@ -183,6 +186,7 @@ export function useAuth(): UseAuthReturn {
|
|
|
183
186
|
openAvatarPicker,
|
|
184
187
|
openAccountDialog,
|
|
185
188
|
ensureDeviceSessionLane,
|
|
189
|
+
hostRequest,
|
|
186
190
|
} = useOxyAuthActions();
|
|
187
191
|
|
|
188
192
|
const bearerSubject = useKnownBearerSubject(oxyServices);
|
|
@@ -190,6 +194,12 @@ export function useAuth(): UseAuthReturn {
|
|
|
190
194
|
|
|
191
195
|
const signIn = useCallback(
|
|
192
196
|
async (publicKey?: string): Promise<SignInOutcome> => {
|
|
197
|
+
// A platform holds the session (ADR 0058): its own sign-in UI, never this
|
|
198
|
+
// app's, and never a key of this app's.
|
|
199
|
+
if (hostRequest) {
|
|
200
|
+
await hostRequest('sign_in');
|
|
201
|
+
return { status: 'dialog-opened' };
|
|
202
|
+
}
|
|
193
203
|
const classification = ensureDeviceSessionLane();
|
|
194
204
|
if (classification) await classification;
|
|
195
205
|
// Native: sign in directly with the cryptographic identity when a public key
|
|
@@ -215,10 +225,12 @@ export function useAuth(): UseAuthReturn {
|
|
|
215
225
|
openAccountDialog('signin');
|
|
216
226
|
return { status: 'dialog-opened' };
|
|
217
227
|
},
|
|
218
|
-
[oxySignIn, hasIdentity, getPublicKey, openAccountDialog, ensureDeviceSessionLane],
|
|
228
|
+
[oxySignIn, hasIdentity, getPublicKey, openAccountDialog, ensureDeviceSessionLane, hostRequest],
|
|
219
229
|
);
|
|
220
230
|
|
|
221
231
|
const signOut = useCallback(async (): Promise<void> => {
|
|
232
|
+
// `requested` (a session host) resolves: the platform decides, and its
|
|
233
|
+
// answer arrives as the session changes.
|
|
222
234
|
const result = await logout();
|
|
223
235
|
if (result.status === 'failed') throw result.error;
|
|
224
236
|
}, [logout]);
|
|
@@ -9,14 +9,17 @@ import { useOxy } from '../context/oxyRuntimeContext';
|
|
|
9
9
|
* is always invoked.
|
|
10
10
|
*/
|
|
11
11
|
export function useOxyEvent(event: string, handler: (payload: unknown) => void): void {
|
|
12
|
-
const { sessionClient } = useOxy();
|
|
12
|
+
const { sessionClient, onServerEvent } = useOxy();
|
|
13
13
|
const handlerRef = useRef(handler);
|
|
14
14
|
handlerRef.current = handler;
|
|
15
15
|
|
|
16
16
|
useEffect(() => {
|
|
17
|
-
|
|
18
|
-
return sessionClient.onServerEvent(event, (payload) => {
|
|
17
|
+
const listener = (payload: unknown) => {
|
|
19
18
|
handlerRef.current(payload);
|
|
20
|
-
}
|
|
21
|
-
|
|
19
|
+
};
|
|
20
|
+
// A session host's user socket, else the device session's socket.
|
|
21
|
+
if (onServerEvent) return onServerEvent(event, listener);
|
|
22
|
+
if (!sessionClient) return;
|
|
23
|
+
return sessionClient.onServerEvent(event, listener);
|
|
24
|
+
}, [sessionClient, onServerEvent, event]);
|
|
22
25
|
}
|
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider's session source on a platform that holds the Oxy session
|
|
3
|
+
* (ADR 0058 decision 1).
|
|
4
|
+
*
|
|
5
|
+
* Headless: it reads an {@link OxySessionHost} and drives the provider's
|
|
6
|
+
* runtime (ADR 0004) and the client's two auth seams with it. Nothing here
|
|
7
|
+
* persists anything, mints anything, or touches `/session/device/*`:
|
|
8
|
+
*
|
|
9
|
+
* - `http.setAccessTokenProvider` answers the host's last token from memory;
|
|
10
|
+
* `http.setAuthRefreshHandler` asks the host (`preflight`, `response-401`).
|
|
11
|
+
* - A snapshot whose `revision` (or status, or account) changes is ONE context
|
|
12
|
+
* transition, in ADR 0002's order: the token is dropped and the session
|
|
13
|
+
* epoch bumped, a token for the new account is awaited, and only then is the
|
|
14
|
+
* account published.
|
|
15
|
+
* - Offline the account is published with no token: `canUsePrivateApi` stays
|
|
16
|
+
* false and the app shows what it cached under that account's id.
|
|
17
|
+
* - Sign-in, switch, sign-out and account management are the platform's:
|
|
18
|
+
* {@link HostSession.request} hands them over and changes nothing here.
|
|
19
|
+
*/
|
|
20
|
+
import type { OxyServices, User } from '@oxy.so/core';
|
|
21
|
+
import type {
|
|
22
|
+
OxyHostAccount,
|
|
23
|
+
OxyHostRequest,
|
|
24
|
+
OxyHostSnapshot,
|
|
25
|
+
OxyHostToken,
|
|
26
|
+
OxyHostTokenReason,
|
|
27
|
+
OxySessionHost,
|
|
28
|
+
} from '@oxy.so/core/host';
|
|
29
|
+
import type { OxyRuntime } from '../runtime';
|
|
30
|
+
import { TOKEN_RECOVERY_BACKOFF_MS } from './tokenLossRecovery';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Thrown by an operation a hosted provider leaves to the platform that holds
|
|
34
|
+
* the session (ADR 0058 decision 1): a sign-in this app would commit itself,
|
|
35
|
+
* device management, a switch that must return the new account. The platform's
|
|
36
|
+
* own UI does these; the result reaches the app as a snapshot.
|
|
37
|
+
*/
|
|
38
|
+
export class HostedSessionError extends Error {
|
|
39
|
+
readonly code = 'oxy_session_hosted';
|
|
40
|
+
|
|
41
|
+
constructor(readonly operation: string) {
|
|
42
|
+
super(
|
|
43
|
+
`${operation} is done by the platform that holds the Oxy session; its result arrives as the session changes`,
|
|
44
|
+
);
|
|
45
|
+
this.name = 'HostedSessionError';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** How long a context transition waits for the host's token before publishing the account without one. */
|
|
50
|
+
export const HOST_TOKEN_DEADLINE_MS = 10_000;
|
|
51
|
+
|
|
52
|
+
export interface HostSessionOptions {
|
|
53
|
+
host: OxySessionHost;
|
|
54
|
+
oxyServices: OxyServices;
|
|
55
|
+
runtime: OxyRuntime;
|
|
56
|
+
/**
|
|
57
|
+
* The account changed (`'account'`) or a token for the same account arrived
|
|
58
|
+
* or went (`'token'`). The user socket follows this.
|
|
59
|
+
*/
|
|
60
|
+
onTokenChange?: (kind: 'account' | 'token') => void;
|
|
61
|
+
logger: (message: string, error?: unknown) => void;
|
|
62
|
+
/** Tests. */
|
|
63
|
+
tokenDeadlineMs?: number;
|
|
64
|
+
/** Tests. */
|
|
65
|
+
retryBackoffMs?: readonly number[];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface HostSession {
|
|
69
|
+
/** Begin following the host. Returns the disposer; may be started again after it. */
|
|
70
|
+
start(): () => void;
|
|
71
|
+
/** Hand an action to the platform's own UI. Never changes the session itself. */
|
|
72
|
+
request(action: OxyHostRequest): Promise<void>;
|
|
73
|
+
/** Re-read the host's snapshot now, and fetch a token if one is due. */
|
|
74
|
+
refresh(): Promise<void>;
|
|
75
|
+
/** The platform this session comes from. */
|
|
76
|
+
readonly platform: OxySessionHost['platform'];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const UNAVAILABLE: OxyHostSnapshot = Object.freeze({
|
|
80
|
+
status: 'unavailable',
|
|
81
|
+
revision: Number.NaN,
|
|
82
|
+
account: null,
|
|
83
|
+
online: false,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
function validAccount(account: unknown): OxyHostAccount | null {
|
|
87
|
+
if (!account || typeof account !== 'object') return null;
|
|
88
|
+
const candidate = account as Partial<OxyHostAccount>;
|
|
89
|
+
if (typeof candidate.id !== 'string' || !candidate.id) return null;
|
|
90
|
+
if (typeof candidate.handle !== 'string' || !candidate.handle) return null;
|
|
91
|
+
return {
|
|
92
|
+
id: candidate.id,
|
|
93
|
+
handle: candidate.handle,
|
|
94
|
+
...(typeof candidate.displayName === 'string' && candidate.displayName
|
|
95
|
+
? { displayName: candidate.displayName }
|
|
96
|
+
: {}),
|
|
97
|
+
...(typeof candidate.avatar === 'string' && candidate.avatar
|
|
98
|
+
? { avatar: candidate.avatar }
|
|
99
|
+
: {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The host's snapshot, checked. A host that throws or answers something that is
|
|
105
|
+
* not a snapshot is `unavailable` — signed out, never a reason to sign in here.
|
|
106
|
+
*/
|
|
107
|
+
export function readHostSnapshot(host: OxySessionHost): OxyHostSnapshot {
|
|
108
|
+
let raw: unknown;
|
|
109
|
+
try {
|
|
110
|
+
raw = host.snapshot();
|
|
111
|
+
} catch {
|
|
112
|
+
return UNAVAILABLE;
|
|
113
|
+
}
|
|
114
|
+
if (!raw || typeof raw !== 'object') return UNAVAILABLE;
|
|
115
|
+
const candidate = raw as Partial<OxyHostSnapshot>;
|
|
116
|
+
if (typeof candidate.revision !== 'number' || !Number.isFinite(candidate.revision)) {
|
|
117
|
+
return UNAVAILABLE;
|
|
118
|
+
}
|
|
119
|
+
const online = candidate.online === true;
|
|
120
|
+
if (candidate.status === 'signed_in') {
|
|
121
|
+
const account = validAccount(candidate.account);
|
|
122
|
+
if (!account) return UNAVAILABLE;
|
|
123
|
+
return { status: 'signed_in', revision: candidate.revision, account, online };
|
|
124
|
+
}
|
|
125
|
+
if (candidate.status === 'signed_out' || candidate.status === 'unavailable') {
|
|
126
|
+
return { status: candidate.status, revision: candidate.revision, account: null, online };
|
|
127
|
+
}
|
|
128
|
+
return UNAVAILABLE;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The provider's `User` for the snapshot's account, over what the API said about it. */
|
|
132
|
+
export function userFromHostAccount(account: OxyHostAccount, base: User | null): User {
|
|
133
|
+
const known = base && base.id === account.id ? base : null;
|
|
134
|
+
const name = { ...(known?.name ?? {}) };
|
|
135
|
+
if (account.displayName) name.displayName = account.displayName;
|
|
136
|
+
return {
|
|
137
|
+
...(known ?? {}),
|
|
138
|
+
id: account.id,
|
|
139
|
+
username: account.handle,
|
|
140
|
+
publicKey: known?.publicKey ?? '',
|
|
141
|
+
name,
|
|
142
|
+
avatar: account.avatar ?? known?.avatar ?? null,
|
|
143
|
+
} as User;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function sameProfile(user: User | null, account: OxyHostAccount): boolean {
|
|
147
|
+
return (
|
|
148
|
+
user !== null &&
|
|
149
|
+
user.id === account.id &&
|
|
150
|
+
user.username === account.handle &&
|
|
151
|
+
(account.displayName === undefined || user.name?.displayName === account.displayName) &&
|
|
152
|
+
(account.avatar === undefined || user.avatar === account.avatar)
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
interface Applied {
|
|
157
|
+
revision: number;
|
|
158
|
+
status: OxyHostSnapshot['status'];
|
|
159
|
+
accountId: string | null;
|
|
160
|
+
online: boolean;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function createHostSession(options: HostSessionOptions): HostSession {
|
|
164
|
+
const { host, oxyServices, runtime, logger } = options;
|
|
165
|
+
const deadlineMs = options.tokenDeadlineMs ?? HOST_TOKEN_DEADLINE_MS;
|
|
166
|
+
const backoff = options.retryBackoffMs ?? TOKEN_RECOVERY_BACKOFF_MS;
|
|
167
|
+
|
|
168
|
+
let running = false;
|
|
169
|
+
let applied: Applied | null = null;
|
|
170
|
+
/** Bumped by every context transition and by stop: a result for an older one plants nothing. */
|
|
171
|
+
let seq = 0;
|
|
172
|
+
let token: OxyHostToken | null = null;
|
|
173
|
+
/** True while this module itself writes the client's token, so its own write is not taken for a loss. */
|
|
174
|
+
let writing = false;
|
|
175
|
+
let pendingToken: Promise<void> | null = null;
|
|
176
|
+
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
|
177
|
+
let retryAttempt = 0;
|
|
178
|
+
let enrichedFor = -1;
|
|
179
|
+
|
|
180
|
+
const cancelRetry = (): void => {
|
|
181
|
+
if (retryTimer !== null) clearTimeout(retryTimer);
|
|
182
|
+
retryTimer = null;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/** What the host returned, if it is a token at all (whose token it is is checked once planted). */
|
|
186
|
+
const accept = (candidate: unknown): OxyHostToken | null => {
|
|
187
|
+
if (!candidate || typeof candidate !== 'object') return null;
|
|
188
|
+
const { accessToken, expiresAt } = candidate as Partial<OxyHostToken>;
|
|
189
|
+
if (typeof accessToken !== 'string' || !accessToken) return null;
|
|
190
|
+
return { accessToken, expiresAt: typeof expiresAt === 'string' ? expiresAt : '' };
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const ask = async (reason: OxyHostTokenReason): Promise<OxyHostToken | null> => {
|
|
194
|
+
try {
|
|
195
|
+
return accept(await host.getAccessToken({ reason }));
|
|
196
|
+
} catch (error) {
|
|
197
|
+
logger('The session host could not give a token', error);
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const writeToken = (next: OxyHostToken | null): void => {
|
|
203
|
+
writing = true;
|
|
204
|
+
try {
|
|
205
|
+
if (next) {
|
|
206
|
+
oxyServices.session.setAccessToken(next.accessToken);
|
|
207
|
+
} else {
|
|
208
|
+
// Drops the bearer, bumps the session epoch and abandons every refresh
|
|
209
|
+
// in flight, so nothing minted for the previous account lands after it.
|
|
210
|
+
oxyServices.session.clear();
|
|
211
|
+
}
|
|
212
|
+
} finally {
|
|
213
|
+
writing = false;
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
/** Plant `next` for `accountId`; false when the token names somebody else. */
|
|
218
|
+
const plant = (next: OxyHostToken, accountId: string): boolean => {
|
|
219
|
+
token = next;
|
|
220
|
+
writeToken(next);
|
|
221
|
+
const subject = oxyServices.session.userId;
|
|
222
|
+
if (subject !== null && subject !== accountId) {
|
|
223
|
+
logger('The session host gave a token for another account; it was dropped');
|
|
224
|
+
token = null;
|
|
225
|
+
writeToken(null);
|
|
226
|
+
runtime.setHasAccessToken(false);
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
runtime.setHasAccessToken(true);
|
|
230
|
+
return true;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
/** The shared session the planted token names, or none without a token. */
|
|
234
|
+
const publishSessionId = (accountId: string | null): void => {
|
|
235
|
+
const sessionId = accountId && token ? oxyServices.session.sessionId : null;
|
|
236
|
+
if (runtime.getSnapshot().activeSessionId === sessionId) return;
|
|
237
|
+
if (!accountId || !sessionId) {
|
|
238
|
+
runtime.batch(() => {
|
|
239
|
+
runtime.mergeSessions([], { merge: false });
|
|
240
|
+
runtime.setActiveSessionId(null);
|
|
241
|
+
});
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const now = new Date().toISOString();
|
|
245
|
+
runtime.batch(() => {
|
|
246
|
+
runtime.mergeSessions(
|
|
247
|
+
[
|
|
248
|
+
{
|
|
249
|
+
sessionId,
|
|
250
|
+
deviceId: '',
|
|
251
|
+
expiresAt: token?.expiresAt || now,
|
|
252
|
+
lastActive: now,
|
|
253
|
+
userId: accountId,
|
|
254
|
+
isCurrent: true,
|
|
255
|
+
},
|
|
256
|
+
],
|
|
257
|
+
{ merge: false },
|
|
258
|
+
);
|
|
259
|
+
runtime.setActiveSessionId(sessionId);
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/** Read the full profile once a token is held, for this transition only. */
|
|
264
|
+
const enrich = (account: OxyHostAccount): void => {
|
|
265
|
+
const forSeq = seq;
|
|
266
|
+
if (enrichedFor === forSeq) return;
|
|
267
|
+
enrichedFor = forSeq;
|
|
268
|
+
void oxyServices.users
|
|
269
|
+
.me()
|
|
270
|
+
.then((me) => {
|
|
271
|
+
if (forSeq !== seq || !running || !me || me.id !== account.id) return;
|
|
272
|
+
const current = readHostSnapshot(host);
|
|
273
|
+
const latest = current.account?.id === account.id ? current.account : account;
|
|
274
|
+
runtime.setAccount(userFromHostAccount(latest, me));
|
|
275
|
+
})
|
|
276
|
+
.catch((error) => {
|
|
277
|
+
enrichedFor = -1;
|
|
278
|
+
logger('Could not read the signed-in profile', error);
|
|
279
|
+
});
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const scheduleRetry = (): void => {
|
|
283
|
+
if (!running || retryTimer !== null) return;
|
|
284
|
+
if (applied?.status !== 'signed_in' || !applied.online || token) return;
|
|
285
|
+
const delay = backoff[Math.min(retryAttempt, backoff.length - 1)];
|
|
286
|
+
retryAttempt += 1;
|
|
287
|
+
retryTimer = setTimeout(() => {
|
|
288
|
+
retryTimer = null;
|
|
289
|
+
void ensureToken('preflight');
|
|
290
|
+
}, delay);
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Get a token for the applied account when none is held (reconnecting, a
|
|
295
|
+
* token lost to a 401, a slow first answer). One at a time.
|
|
296
|
+
*/
|
|
297
|
+
const ensureToken = (reason: OxyHostTokenReason): Promise<void> => {
|
|
298
|
+
if (pendingToken) return pendingToken;
|
|
299
|
+
const forSeq = seq;
|
|
300
|
+
const accountId = applied?.status === 'signed_in' ? applied.accountId : null;
|
|
301
|
+
if (!running || !accountId || token) return Promise.resolve();
|
|
302
|
+
pendingToken = (async () => {
|
|
303
|
+
const next = await ask(reason);
|
|
304
|
+
if (forSeq !== seq || !running || token) return;
|
|
305
|
+
let planted = false;
|
|
306
|
+
runtime.batch(() => {
|
|
307
|
+
planted = next !== null && plant(next, accountId);
|
|
308
|
+
if (!planted) return;
|
|
309
|
+
publishSessionId(accountId);
|
|
310
|
+
runtime.setTokenReady(true);
|
|
311
|
+
});
|
|
312
|
+
if (planted) {
|
|
313
|
+
retryAttempt = 0;
|
|
314
|
+
cancelRetry();
|
|
315
|
+
options.onTokenChange?.('token');
|
|
316
|
+
const account = readHostSnapshot(host).account;
|
|
317
|
+
if (account?.id === accountId) enrich(account);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
scheduleRetry();
|
|
321
|
+
})().finally(() => {
|
|
322
|
+
pendingToken = null;
|
|
323
|
+
});
|
|
324
|
+
return pendingToken;
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const signedOut = (): void => {
|
|
328
|
+
runtime.batch(() => {
|
|
329
|
+
runtime.clearSession();
|
|
330
|
+
runtime.markAuthResolved();
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
const transition = async (snapshot: OxyHostSnapshot): Promise<void> => {
|
|
335
|
+
seq += 1;
|
|
336
|
+
const forSeq = seq;
|
|
337
|
+
cancelRetry();
|
|
338
|
+
retryAttempt = 0;
|
|
339
|
+
applied = {
|
|
340
|
+
revision: snapshot.revision,
|
|
341
|
+
status: snapshot.status,
|
|
342
|
+
accountId: snapshot.account?.id ?? null,
|
|
343
|
+
online: snapshot.online,
|
|
344
|
+
};
|
|
345
|
+
// 1. Drop the token and bump the epoch before anything else can run.
|
|
346
|
+
token = null;
|
|
347
|
+
writeToken(null);
|
|
348
|
+
runtime.setHasAccessToken(false);
|
|
349
|
+
options.onTokenChange?.('account');
|
|
350
|
+
|
|
351
|
+
const account = snapshot.status === 'signed_in' ? snapshot.account : null;
|
|
352
|
+
if (!account) {
|
|
353
|
+
signedOut();
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// 2. Await a token for the new account; the previous account stays on
|
|
358
|
+
// screen meanwhile with no token, so nothing private runs for anybody.
|
|
359
|
+
runtime.setTokenReady(false);
|
|
360
|
+
let settled = false;
|
|
361
|
+
const answer = ask('boot').then((next) => {
|
|
362
|
+
settled = true;
|
|
363
|
+
return next;
|
|
364
|
+
});
|
|
365
|
+
const deadline = new Promise<null>((resolve) => {
|
|
366
|
+
const timer = setTimeout(() => resolve(null), deadlineMs);
|
|
367
|
+
void answer.finally(() => clearTimeout(timer));
|
|
368
|
+
});
|
|
369
|
+
const next = await Promise.race([answer, deadline]);
|
|
370
|
+
if (forSeq !== seq || !running) return;
|
|
371
|
+
|
|
372
|
+
// 3. Plant it and only then publish the account, in ONE runtime transition
|
|
373
|
+
// (the account-scoped cache reset runs inside it, before anyone is woken).
|
|
374
|
+
let planted = false;
|
|
375
|
+
runtime.batch(() => {
|
|
376
|
+
planted = next !== null && plant(next, account.id);
|
|
377
|
+
publishSessionId(planted ? account.id : null);
|
|
378
|
+
runtime.setAccount(userFromHostAccount(account, runtime.getSnapshot().account));
|
|
379
|
+
runtime.setTokenReady(true);
|
|
380
|
+
runtime.markAuthResolved();
|
|
381
|
+
});
|
|
382
|
+
if (planted) {
|
|
383
|
+
options.onTokenChange?.('token');
|
|
384
|
+
enrich(account);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (!settled) {
|
|
388
|
+
// The host is slow: the account is shown without a token, and the token
|
|
389
|
+
// is planted when it arrives (if this is still the account).
|
|
390
|
+
void answer.then((late) => {
|
|
391
|
+
if (forSeq !== seq || !running || token) return;
|
|
392
|
+
let latePlanted = false;
|
|
393
|
+
runtime.batch(() => {
|
|
394
|
+
latePlanted = late !== null && plant(late, account.id);
|
|
395
|
+
if (latePlanted) publishSessionId(account.id);
|
|
396
|
+
});
|
|
397
|
+
if (latePlanted) {
|
|
398
|
+
options.onTokenChange?.('token');
|
|
399
|
+
enrich(account);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
scheduleRetry();
|
|
403
|
+
});
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
scheduleRetry();
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
const apply = (snapshot: OxyHostSnapshot): void => {
|
|
410
|
+
const previous = applied;
|
|
411
|
+
if (
|
|
412
|
+
previous === null ||
|
|
413
|
+
!Object.is(previous.revision, snapshot.revision) ||
|
|
414
|
+
previous.status !== snapshot.status ||
|
|
415
|
+
previous.accountId !== (snapshot.account?.id ?? null)
|
|
416
|
+
) {
|
|
417
|
+
void transition(snapshot).catch((error) => {
|
|
418
|
+
logger('The session host transition failed', error);
|
|
419
|
+
});
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
// The same context: the profile, or the platform going on or offline.
|
|
423
|
+
const wasOnline = previous.online;
|
|
424
|
+
applied = { ...previous, online: snapshot.online };
|
|
425
|
+
const account = snapshot.account;
|
|
426
|
+
if (!account) return;
|
|
427
|
+
const current = runtime.getSnapshot().account;
|
|
428
|
+
if (current && current.id === account.id && !sameProfile(current, account)) {
|
|
429
|
+
runtime.setAccount(userFromHostAccount(account, current));
|
|
430
|
+
}
|
|
431
|
+
if (snapshot.online && !token) {
|
|
432
|
+
if (!wasOnline) {
|
|
433
|
+
retryAttempt = 0;
|
|
434
|
+
cancelRetry();
|
|
435
|
+
}
|
|
436
|
+
void ensureToken('preflight');
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
const onClientToken = (accessToken: string | null): void => {
|
|
441
|
+
if (writing) return;
|
|
442
|
+
runtime.setHasAccessToken(Boolean(accessToken));
|
|
443
|
+
if (accessToken) return;
|
|
444
|
+
// The client dropped the bearer itself: a 401 the host's fresh token could
|
|
445
|
+
// not answer either. Forget it and ask again, with backoff.
|
|
446
|
+
if (token) {
|
|
447
|
+
token = null;
|
|
448
|
+
options.onTokenChange?.('token');
|
|
449
|
+
scheduleRetry();
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
return {
|
|
454
|
+
platform: host.platform,
|
|
455
|
+
|
|
456
|
+
start() {
|
|
457
|
+
running = true;
|
|
458
|
+
applied = null;
|
|
459
|
+
oxyServices.http.setAccessTokenProvider(() => token?.accessToken ?? null);
|
|
460
|
+
oxyServices.http.setAuthRefreshHandler(async (reason) => {
|
|
461
|
+
const forSeq = seq;
|
|
462
|
+
const accountId = applied?.status === 'signed_in' ? applied.accountId : null;
|
|
463
|
+
if (!running || !accountId) return null;
|
|
464
|
+
const next = await ask(reason);
|
|
465
|
+
if (forSeq !== seq || !running) return null;
|
|
466
|
+
if (!next) return null;
|
|
467
|
+
const hadToken = token !== null;
|
|
468
|
+
if (!plant(next, accountId)) return null;
|
|
469
|
+
if (!hadToken) options.onTokenChange?.('token');
|
|
470
|
+
return next.accessToken;
|
|
471
|
+
});
|
|
472
|
+
const unsubscribeToken = oxyServices.session.onChange(onClientToken);
|
|
473
|
+
let unsubscribeHost: () => void = () => undefined;
|
|
474
|
+
try {
|
|
475
|
+
unsubscribeHost = host.subscribe(() => {
|
|
476
|
+
if (running) apply(readHostSnapshot(host));
|
|
477
|
+
});
|
|
478
|
+
} catch (error) {
|
|
479
|
+
logger('Could not subscribe to the session host', error);
|
|
480
|
+
}
|
|
481
|
+
apply(readHostSnapshot(host));
|
|
482
|
+
|
|
483
|
+
return () => {
|
|
484
|
+
running = false;
|
|
485
|
+
seq += 1;
|
|
486
|
+
cancelRetry();
|
|
487
|
+
unsubscribeToken();
|
|
488
|
+
try {
|
|
489
|
+
unsubscribeHost();
|
|
490
|
+
} catch (error) {
|
|
491
|
+
logger('Could not unsubscribe from the session host', error);
|
|
492
|
+
}
|
|
493
|
+
oxyServices.http.setAuthRefreshHandler(null);
|
|
494
|
+
oxyServices.http.setAccessTokenProvider(null);
|
|
495
|
+
token = null;
|
|
496
|
+
writeToken(null);
|
|
497
|
+
};
|
|
498
|
+
},
|
|
499
|
+
|
|
500
|
+
async request(action) {
|
|
501
|
+
try {
|
|
502
|
+
await host.request(action);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
logger(`The session host could not ${action.replace('_', ' ')}`, error);
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
},
|
|
508
|
+
|
|
509
|
+
async refresh() {
|
|
510
|
+
if (!running) return;
|
|
511
|
+
apply(readHostSnapshot(host));
|
|
512
|
+
if (applied?.status === 'signed_in' && !token) await ensureToken('preflight');
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
}
|