@oxyhq/core 2.2.1 → 2.2.2
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/index.js +17 -1
- package/dist/cjs/mixins/OxyServices.auth.js +45 -0
- package/dist/cjs/mixins/OxyServices.user.js +15 -5
- package/dist/cjs/utils/authWebUrl.js +14 -3
- package/dist/cjs/utils/fapiAutoDetect.js +47 -6
- package/dist/cjs/utils/ssoBounce.js +192 -0
- package/dist/cjs/utils/ssoReturn.js +111 -0
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/index.js +5 -3
- package/dist/esm/mixins/OxyServices.auth.js +45 -0
- package/dist/esm/mixins/OxyServices.user.js +15 -5
- package/dist/esm/utils/authWebUrl.js +13 -2
- package/dist/esm/utils/fapiAutoDetect.js +45 -6
- package/dist/esm/utils/ssoBounce.js +181 -0
- package/dist/esm/utils/ssoReturn.js +110 -0
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +5 -4
- package/dist/types/mixins/OxyServices.auth.d.ts +35 -0
- package/dist/types/mixins/OxyServices.user.d.ts +7 -0
- package/dist/types/utils/authWebUrl.d.ts +12 -1
- package/dist/types/utils/fapiAutoDetect.d.ts +36 -0
- package/dist/types/utils/ssoBounce.d.ts +124 -0
- package/dist/types/utils/ssoReturn.d.ts +65 -0
- package/package.json +1 -1
- package/src/index.ts +18 -4
- package/src/mixins/OxyServices.auth.ts +54 -0
- package/src/mixins/OxyServices.user.ts +14 -5
- package/src/mixins/__tests__/serviceAuth.test.ts +92 -0
- package/src/utils/__tests__/authWebUrl.test.ts +11 -1
- package/src/utils/__tests__/consumeSsoReturn.test.ts +401 -0
- package/src/utils/__tests__/fapiAutoDetect.test.ts +62 -1
- package/src/utils/__tests__/ssoBounce.test.ts +148 -0
- package/src/utils/authWebUrl.ts +14 -2
- package/src/utils/fapiAutoDetect.ts +41 -5
- package/src/utils/ssoBounce.ts +198 -0
- package/src/utils/ssoReturn.ts +168 -0
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
* before relying on this helper, otherwise auto-detection silently bails to
|
|
48
48
|
* `undefined` and the consumer must pass `authWebUrl` explicitly.
|
|
49
49
|
*/
|
|
50
|
-
const MULTIPART_TLDS: ReadonlySet<string> = new Set([
|
|
50
|
+
export const MULTIPART_TLDS: ReadonlySet<string> = new Set([
|
|
51
51
|
'co.uk',
|
|
52
52
|
'com.au',
|
|
53
53
|
'co.jp',
|
|
@@ -60,6 +60,42 @@ const MULTIPART_TLDS: ReadonlySet<string> = new Set([
|
|
|
60
60
|
'com.sg',
|
|
61
61
|
]);
|
|
62
62
|
|
|
63
|
+
/**
|
|
64
|
+
* Compute the bare registrable apex (eTLD+1) of a hostname, guarding against
|
|
65
|
+
* multi-part public suffixes.
|
|
66
|
+
*
|
|
67
|
+
* This is the pure host-handling kernel shared by {@link autoDetectAuthWebUrl}
|
|
68
|
+
* and the IdP worker — it performs NO protocol handling, NO `auth.` prefixing,
|
|
69
|
+
* and builds NO URL. It only answers "what is the registrable domain of this
|
|
70
|
+
* host, or is that undefinable?".
|
|
71
|
+
*
|
|
72
|
+
* Returns `null` (apex undefinable) for:
|
|
73
|
+
* - empty input;
|
|
74
|
+
* - IPv4 literals (`192.168.1.10`);
|
|
75
|
+
* - IPv6 literals or any host carrying a port (`[::1]`, anything with `:`);
|
|
76
|
+
* - single-label hosts (`intranet`, `localhost`);
|
|
77
|
+
* - hosts whose trailing two labels form a known multi-part public suffix
|
|
78
|
+
* (e.g. `foo.co.uk`), where `labels.slice(-2)` would yield an
|
|
79
|
+
* attacker-registrable suffix (`co.uk`) rather than a real registrable
|
|
80
|
+
* domain. Such hosts MUST configure `authWebUrl` explicitly.
|
|
81
|
+
*
|
|
82
|
+
* @param hostname - A bare hostname (no scheme), e.g. `www.mention.earth`.
|
|
83
|
+
* @returns The eTLD+1 (`mention.earth`), or `null` when undefinable.
|
|
84
|
+
*/
|
|
85
|
+
export function registrableApex(hostname: string): string | null {
|
|
86
|
+
if (!hostname) return null;
|
|
87
|
+
const host = hostname.toLowerCase();
|
|
88
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return null;
|
|
89
|
+
// IPv6 literals are bracketed; any remaining ':' implies a port — neither
|
|
90
|
+
// yields a registrable apex.
|
|
91
|
+
if (host.startsWith('[') || host.includes(':')) return null;
|
|
92
|
+
const labels = host.split('.');
|
|
93
|
+
if (labels.length < 2) return null;
|
|
94
|
+
const lastTwo = labels.slice(-2).join('.');
|
|
95
|
+
if (MULTIPART_TLDS.has(lastTwo)) return null;
|
|
96
|
+
return lastTwo;
|
|
97
|
+
}
|
|
98
|
+
|
|
63
99
|
export function autoDetectAuthWebUrl(
|
|
64
100
|
location: Pick<Location, 'hostname' | 'protocol'> | undefined =
|
|
65
101
|
typeof window !== 'undefined' ? window.location : undefined
|
|
@@ -71,12 +107,12 @@ export function autoDetectAuthWebUrl(
|
|
|
71
107
|
if (hostname === 'localhost' || hostname === '127.0.0.1') return undefined;
|
|
72
108
|
if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) return undefined;
|
|
73
109
|
if (hostname.startsWith('[')) return undefined;
|
|
110
|
+
// Already ON the IdP — keep everything same-origin instead of hopping to a
|
|
111
|
+
// sibling host.
|
|
74
112
|
if (hostname.startsWith('auth.')) {
|
|
75
113
|
return `${protocol}//${hostname}`;
|
|
76
114
|
}
|
|
77
|
-
const
|
|
78
|
-
if (
|
|
79
|
-
if (MULTIPART_TLDS.has(labels.slice(-2).join('.'))) return undefined;
|
|
80
|
-
const apex = labels.slice(-2).join('.');
|
|
115
|
+
const apex = registrableApex(hostname);
|
|
116
|
+
if (apex === null) return undefined;
|
|
81
117
|
return `${protocol}//auth.${apex}`;
|
|
82
118
|
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Central cross-domain SSO bounce — per-origin sessionStorage keys, the bounce
|
|
3
|
+
* URL builder, and the small pure predicates shared by every consumer's
|
|
4
|
+
* cold-boot `sso-return` / `sso-bounce` steps and bfcache `pageshow`
|
|
5
|
+
* re-evaluation.
|
|
6
|
+
*
|
|
7
|
+
* This is the single source of truth for the SSO bounce wire/storage contract.
|
|
8
|
+
* `@oxyhq/auth` (`WebOxyProvider`) and `@oxyhq/services` (`OxyContext`) both
|
|
9
|
+
* consume these helpers so the two providers behave identically.
|
|
10
|
+
*
|
|
11
|
+
* TRUE central SSO (Google/Meta/Clerk style) works like this for a Relying
|
|
12
|
+
* Party (mention.earth, homiio.com, alia.onl, …) with no local session:
|
|
13
|
+
*
|
|
14
|
+
* 1. `sso-bounce` (terminal, once): a TOP-LEVEL navigation to
|
|
15
|
+
* `auth.oxy.so/sso?prompt=none&client_id=<origin>&return_to=<origin>{@link SSO_CALLBACK_PATH}&state=<s>`.
|
|
16
|
+
* Before navigating it records, in this origin's `sessionStorage`, the
|
|
17
|
+
* CSRF `state` ({@link ssoStateKey}), a guard timestamp ({@link ssoGuardKey},
|
|
18
|
+
* the loop breaker), and the real destination URL ({@link ssoDestKey}) to
|
|
19
|
+
* restore after the callback.
|
|
20
|
+
* 2. The central IdP worker reads its first-party `fedcm_session`, mints a
|
|
21
|
+
* session, stores it under an opaque single-use `code`, and 303-redirects
|
|
22
|
+
* back to `<origin>{@link SSO_CALLBACK_PATH}#oxy_sso=ok&code=<code>&state=<s>`
|
|
23
|
+
* (or `#oxy_sso=none` / `#oxy_sso=error`).
|
|
24
|
+
* 3. `sso-return` parses the fragment (`parseSsoReturnFragment`), validates
|
|
25
|
+
* `state`, exchanges the `code` via `oxyServices.exchangeSsoCode`, commits
|
|
26
|
+
* the session, then restores the original destination.
|
|
27
|
+
*
|
|
28
|
+
* Loop proof (logged-out): first load all steps skip → `sso-bounce` sets
|
|
29
|
+
* guard/state/dest and navigates; the IdP (no central session) returns
|
|
30
|
+
* `#oxy_sso=none`; the callback load's `sso-return` sees `none`, sets the
|
|
31
|
+
* NO_SESSION flag ({@link ssoNoSessionKey}), and `sso-bounce` is then disabled.
|
|
32
|
+
* Exactly ONE bounce, no loop. An interrupted bounce (user hit back
|
|
33
|
+
* mid-redirect) self-heals once the {@link SSO_GUARD_TTL_MS} guard TTL lapses.
|
|
34
|
+
*
|
|
35
|
+
* All state lives in `sessionStorage` (per tab, cleared on tab close) and is
|
|
36
|
+
* keyed per-origin so two RPs hosted in the same browser never collide. The
|
|
37
|
+
* key strings and the 30s TTL are a wire/storage contract — they MUST match
|
|
38
|
+
* the values the IdP and every consumer expect and must not change lightly.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import { CENTRAL_AUTH_URL, resolveCentralAuthUrl } from './authWebUrl';
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The RP callback path the central IdP redirects back to after a bounce. The
|
|
45
|
+
* SSO result is delivered in the fragment of this URL; the `sso-return` step
|
|
46
|
+
* consumes it and then restores the user's real destination (stored under
|
|
47
|
+
* {@link ssoDestKey}), so the user never lingers on this internal path.
|
|
48
|
+
*/
|
|
49
|
+
export const SSO_CALLBACK_PATH = '/__oxy/sso-callback';
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Self-healing TTL (ms) for the bounce guard. An in-flight bounce sets a
|
|
53
|
+
* timestamp guard; if the bounce is interrupted before the callback lands
|
|
54
|
+
* (e.g. the user navigates back mid-redirect), the guard would otherwise pin
|
|
55
|
+
* the RP signed-out forever. After this window the guard is treated as stale
|
|
56
|
+
* and a fresh single bounce is permitted. 30s comfortably exceeds a real
|
|
57
|
+
* redirect round-trip while keeping a crash short-lived.
|
|
58
|
+
*/
|
|
59
|
+
export const SSO_GUARD_TTL_MS = 30_000;
|
|
60
|
+
|
|
61
|
+
const STATE_KEY_PREFIX = 'oxy_sso_state:';
|
|
62
|
+
const GUARD_KEY_PREFIX = 'oxy_sso_guard:';
|
|
63
|
+
const DEST_KEY_PREFIX = 'oxy_sso_dest:';
|
|
64
|
+
const NO_SESSION_KEY_PREFIX = 'oxy_sso_no_session:';
|
|
65
|
+
|
|
66
|
+
/** Per-origin CSRF state key (matched on return to defeat fragment forgery). */
|
|
67
|
+
export function ssoStateKey(origin: string): string {
|
|
68
|
+
return `${STATE_KEY_PREFIX}${origin}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Per-origin bounce guard key (a timestamp; loop breaker + self-heal TTL). */
|
|
72
|
+
export function ssoGuardKey(origin: string): string {
|
|
73
|
+
return `${GUARD_KEY_PREFIX}${origin}`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Per-origin destination key (the real URL to restore after the callback). */
|
|
77
|
+
export function ssoDestKey(origin: string): string {
|
|
78
|
+
return `${DEST_KEY_PREFIX}${origin}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Per-origin "the central IdP has no session for me" key. Set after a
|
|
83
|
+
* `none`/`error` return (or a failed/forged exchange) so `sso-bounce` does not
|
|
84
|
+
* fire again this tab — the definitive loop breaker.
|
|
85
|
+
*/
|
|
86
|
+
export function ssoNoSessionKey(origin: string): string {
|
|
87
|
+
return `${NO_SESSION_KEY_PREFIX}${origin}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Perform the terminal top-level SSO bounce navigation.
|
|
92
|
+
*
|
|
93
|
+
* A thin wrapper over `window.location.assign(url)` so the single navigation
|
|
94
|
+
* seam lives in one place (and stays mockable in tests, where jsdom's
|
|
95
|
+
* `Location.assign` is a non-configurable native method). In production this is
|
|
96
|
+
* exactly `window.location.assign` — the document is torn down and replaced by
|
|
97
|
+
* the central IdP page. Off-browser (SSR / native) it is a no-op: native never
|
|
98
|
+
* bounces.
|
|
99
|
+
*/
|
|
100
|
+
export function ssoNavigate(url: string): void {
|
|
101
|
+
if (typeof window === 'undefined' || typeof window.location === 'undefined') {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
window.location.assign(url);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Build the central IdP `/sso` bounce URL for an RP.
|
|
109
|
+
*
|
|
110
|
+
* Pure (no DOM access) so it is unit-testable and shared by every consumer's
|
|
111
|
+
* terminal `sso-bounce` step. The IdP reads `client_id` (the RP origin) and
|
|
112
|
+
* `return_to` to mint an origin-bound opaque code and 303-redirect back.
|
|
113
|
+
*
|
|
114
|
+
* The IdP base is resolved via {@link resolveCentralAuthUrl} so an explicit
|
|
115
|
+
* `authWebUrl` override (e.g. a staging IdP) drives the SSO bounce exactly the
|
|
116
|
+
* way it drives FedCM. When omitted, the central default {@link CENTRAL_AUTH_URL}
|
|
117
|
+
* is used.
|
|
118
|
+
*
|
|
119
|
+
* @param origin - The RP origin (`window.location.origin`).
|
|
120
|
+
* @param state - The CSRF state minted for this bounce.
|
|
121
|
+
* @param authWebUrl - Optional explicit IdP base URL override. Falls back to
|
|
122
|
+
* the central default when `undefined`/empty.
|
|
123
|
+
* @returns The absolute `<idp-origin>/sso?...` URL string.
|
|
124
|
+
*/
|
|
125
|
+
export function buildSsoBounceUrl(
|
|
126
|
+
origin: string,
|
|
127
|
+
state: string,
|
|
128
|
+
authWebUrl?: string,
|
|
129
|
+
): string {
|
|
130
|
+
const url = new URL('/sso', resolveCentralAuthUrl(authWebUrl));
|
|
131
|
+
url.searchParams.set('prompt', 'none');
|
|
132
|
+
url.searchParams.set('client_id', origin);
|
|
133
|
+
url.searchParams.set('return_to', origin + SSO_CALLBACK_PATH);
|
|
134
|
+
url.searchParams.set('state', state);
|
|
135
|
+
return url.toString();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Whether `origin` IS the central IdP origin. The RP must NEVER bounce while
|
|
140
|
+
* sitting on `auth.oxy.so` itself — doing so would loop the IdP against itself.
|
|
141
|
+
*
|
|
142
|
+
* Both sides are normalised via `new URL(...).origin` so a trailing-slash or
|
|
143
|
+
* path difference never defeats the guard. Returns `false` on any parse
|
|
144
|
+
* failure (an unparseable candidate is, by definition, not the central IdP).
|
|
145
|
+
*/
|
|
146
|
+
export function isCentralIdPOrigin(origin: string): boolean {
|
|
147
|
+
let centralOrigin: string;
|
|
148
|
+
try {
|
|
149
|
+
centralOrigin = new URL(CENTRAL_AUTH_URL).origin;
|
|
150
|
+
} catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
let candidateOrigin: string;
|
|
154
|
+
try {
|
|
155
|
+
candidateOrigin = new URL(origin).origin;
|
|
156
|
+
} catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
return candidateOrigin === centralOrigin;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Read the bounce guard and decide whether it is still ACTIVE.
|
|
164
|
+
*
|
|
165
|
+
* Active means: a guard value is present AND it parses to a finite timestamp
|
|
166
|
+
* AND less than {@link SSO_GUARD_TTL_MS} has elapsed since it was set. An active
|
|
167
|
+
* guard disables `sso-bounce` (a bounce is already in flight this tab). A
|
|
168
|
+
* missing, malformed, or expired guard is NOT active, so a fresh bounce may
|
|
169
|
+
* proceed (this is the 30s self-heal for an interrupted bounce).
|
|
170
|
+
*
|
|
171
|
+
* Defensive: a `getItem` that throws (e.g. a locked/disabled storage) is
|
|
172
|
+
* treated as "not active" so the guard never wedges the flow.
|
|
173
|
+
*
|
|
174
|
+
* @param storage - The session storage to read (injected for testability).
|
|
175
|
+
* @param origin - The page origin whose guard to evaluate.
|
|
176
|
+
* @param now - Current epoch ms (injected for deterministic tests). Defaults to
|
|
177
|
+
* `Date.now()`.
|
|
178
|
+
*/
|
|
179
|
+
export function guardActive(
|
|
180
|
+
storage: Pick<Storage, 'getItem'>,
|
|
181
|
+
origin: string,
|
|
182
|
+
now: number = Date.now(),
|
|
183
|
+
): boolean {
|
|
184
|
+
let raw: string | null;
|
|
185
|
+
try {
|
|
186
|
+
raw = storage.getItem(ssoGuardKey(origin));
|
|
187
|
+
} catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
if (raw === null || raw.length === 0) {
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
const ts = Number(raw);
|
|
194
|
+
if (!Number.isFinite(ts)) {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
return now - ts < SSO_GUARD_TTL_MS;
|
|
198
|
+
}
|
package/src/utils/ssoReturn.ts
CHANGED
|
@@ -21,6 +21,15 @@
|
|
|
21
21
|
* value), so the caller can ignore unrelated fragments without special-casing.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
+
import type { SessionLoginResponse } from '../models/session';
|
|
25
|
+
import {
|
|
26
|
+
SSO_CALLBACK_PATH,
|
|
27
|
+
ssoStateKey,
|
|
28
|
+
ssoGuardKey,
|
|
29
|
+
ssoDestKey,
|
|
30
|
+
ssoNoSessionKey,
|
|
31
|
+
} from './ssoBounce';
|
|
32
|
+
|
|
24
33
|
/**
|
|
25
34
|
* The recognised outcomes of an SSO bounce.
|
|
26
35
|
*/
|
|
@@ -92,3 +101,162 @@ export function parseSsoReturnFragment(hash: string | undefined | null): SsoRetu
|
|
|
92
101
|
|
|
93
102
|
return result;
|
|
94
103
|
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Injectable dependencies for {@link consumeSsoReturn}.
|
|
107
|
+
*
|
|
108
|
+
* Every web seam (storage, location, history, web-detection) is injectable so
|
|
109
|
+
* the function is fully unit-testable with fakes and so SSR / native callers
|
|
110
|
+
* can supply their own (or rely on the defaults, which resolve to `window.*`
|
|
111
|
+
* only when a browser is present). Defaults are evaluated lazily inside
|
|
112
|
+
* `consumeSsoReturn` so importing this module never touches `window`.
|
|
113
|
+
*/
|
|
114
|
+
export interface ConsumeSsoReturnDeps {
|
|
115
|
+
/** Per-tab SSO state store. Default: `window.sessionStorage`. */
|
|
116
|
+
storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
|
|
117
|
+
/** The current location. Default: `window.location`. */
|
|
118
|
+
location?: Pick<Location, 'hash' | 'origin' | 'pathname' | 'search'>;
|
|
119
|
+
/** History API for fragment stripping / dest restore. Default: `window.history`. */
|
|
120
|
+
history?: Pick<History, 'replaceState'>;
|
|
121
|
+
/**
|
|
122
|
+
* Whether the current environment is a web browser with usable
|
|
123
|
+
* `sessionStorage`. Default: `typeof window !== 'undefined' && typeof
|
|
124
|
+
* window.sessionStorage !== 'undefined'`.
|
|
125
|
+
*/
|
|
126
|
+
isWeb?: () => boolean;
|
|
127
|
+
/**
|
|
128
|
+
* Optional debug hook invoked with the thrown error when the code exchange
|
|
129
|
+
* fails. NEVER rethrown — `consumeSsoReturn` is total. Default: no-op.
|
|
130
|
+
*/
|
|
131
|
+
onExchangeError?: (error: unknown) => void;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Consume an SSO return: the commit-free, security-critical kernel of the
|
|
136
|
+
* cross-domain SSO `sso-return` cold-boot step.
|
|
137
|
+
*
|
|
138
|
+
* This performs the CSRF/fragment/exchange/dest-restore/loop-breaker sequence
|
|
139
|
+
* and RETURNS the exchanged session (or `null`). It deliberately does NOT
|
|
140
|
+
* commit any UI/auth state — each provider commits its own way AROUND this
|
|
141
|
+
* (e.g. `@oxyhq/services` `OxyContext` calls its `handleWebSSOSession`,
|
|
142
|
+
* `@oxyhq/auth` `WebOxyProvider` updates its React state). Hoisting the kernel
|
|
143
|
+
* here keeps the two providers byte-for-byte identical on the parts that matter
|
|
144
|
+
* for security (state validation, fragment stripping order, loop prevention).
|
|
145
|
+
*
|
|
146
|
+
* Security/loop invariants (preserved exactly from both former copies):
|
|
147
|
+
* - The fragment is stripped via `history.replaceState` FIRST — before the
|
|
148
|
+
* exchange — so the opaque code never lingers in the URL, browser history,
|
|
149
|
+
* or a `Referer` header even if a later step throws.
|
|
150
|
+
* - `state` must match (CSRF). A mismatch or a missing code sets the
|
|
151
|
+
* NO_SESSION flag so `sso-bounce` is disabled (no rebounce loop).
|
|
152
|
+
* - `none`/`error` outcomes set the NO_SESSION flag (the load2 half of the
|
|
153
|
+
* loop proof).
|
|
154
|
+
* - A throwing exchange is caught, reported via `onExchangeError`, and
|
|
155
|
+
* treated exactly like "no session" (never loops, never rethrows).
|
|
156
|
+
* - After a successful exchange landing on {@link SSO_CALLBACK_PATH}, the real
|
|
157
|
+
* destination is restored from the DEST key — same-origin only (an
|
|
158
|
+
* attacker-planted cross-origin or relative-evil dest is rejected). The
|
|
159
|
+
* DEST key is removed unconditionally.
|
|
160
|
+
*
|
|
161
|
+
* Total: this function NEVER throws. Off-web it is a no-op returning `null`.
|
|
162
|
+
*
|
|
163
|
+
* @param oxy - The exchange surface (`oxyServices.exchangeSsoCode`).
|
|
164
|
+
* @param deps - Injectable web seams; see {@link ConsumeSsoReturnDeps}.
|
|
165
|
+
* @returns The exchanged session on success, otherwise `null`.
|
|
166
|
+
*/
|
|
167
|
+
export async function consumeSsoReturn(
|
|
168
|
+
oxy: { exchangeSsoCode: (code: string) => Promise<SessionLoginResponse> },
|
|
169
|
+
deps: ConsumeSsoReturnDeps = {},
|
|
170
|
+
): Promise<SessionLoginResponse | null> {
|
|
171
|
+
const isWeb =
|
|
172
|
+
deps.isWeb ??
|
|
173
|
+
(() =>
|
|
174
|
+
typeof window !== 'undefined' &&
|
|
175
|
+
typeof window.sessionStorage !== 'undefined');
|
|
176
|
+
|
|
177
|
+
if (!isWeb()) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const storage = deps.storage ?? window.sessionStorage;
|
|
182
|
+
const location = deps.location ?? window.location;
|
|
183
|
+
const history = deps.history ?? window.history;
|
|
184
|
+
const onExchangeError = deps.onExchangeError;
|
|
185
|
+
|
|
186
|
+
const ret = parseSsoReturnFragment(location.hash);
|
|
187
|
+
if (!ret) {
|
|
188
|
+
// Not an oxy_sso fragment — nothing to do (do NOT touch any flags).
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const origin = location.origin;
|
|
193
|
+
const expectedState = storage.getItem(ssoStateKey(origin));
|
|
194
|
+
const stateOk = !!ret.state && !!expectedState && ret.state === expectedState;
|
|
195
|
+
|
|
196
|
+
// Strip the fragment FIRST so the opaque code never lingers in the address
|
|
197
|
+
// bar, history, or a `Referer` — even if a later step throws.
|
|
198
|
+
history.replaceState(null, '', location.pathname + location.search);
|
|
199
|
+
storage.removeItem(ssoStateKey(origin));
|
|
200
|
+
|
|
201
|
+
// The in-flight bounce is now resolved — drop its guard so a later cold boot
|
|
202
|
+
// (e.g. after sign-out) can bounce again.
|
|
203
|
+
storage.removeItem(ssoGuardKey(origin));
|
|
204
|
+
|
|
205
|
+
const markNoSession = () => {
|
|
206
|
+
storage.setItem(ssoNoSessionKey(origin), '1');
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
if (ret.kind === 'none' || ret.kind === 'error') {
|
|
210
|
+
// The central IdP had no session (or the bounce failed). Record it so we do
|
|
211
|
+
// not bounce again this tab — the definitive loop breaker.
|
|
212
|
+
markNoSession();
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (!stateOk || !ret.code) {
|
|
217
|
+
// Forged / replayed / stale fragment, or a malformed ok with no code. Treat
|
|
218
|
+
// exactly like "no session": never exchange, never loop.
|
|
219
|
+
markNoSession();
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let session: SessionLoginResponse | undefined;
|
|
224
|
+
try {
|
|
225
|
+
session = await oxy.exchangeSsoCode(ret.code);
|
|
226
|
+
} catch (error) {
|
|
227
|
+
onExchangeError?.(error);
|
|
228
|
+
markNoSession();
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!session?.sessionId) {
|
|
233
|
+
markNoSession();
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// If we landed on the internal callback path, restore the user's real
|
|
238
|
+
// destination (captured at bounce time). Same-origin only — never honour a
|
|
239
|
+
// cross-origin destination that could have been planted to redirect the
|
|
240
|
+
// freshly signed-in user. `new URL(dest, origin)` tolerates relative dests
|
|
241
|
+
// and is still re-checked against the page origin.
|
|
242
|
+
if (location.pathname === SSO_CALLBACK_PATH) {
|
|
243
|
+
const dest = storage.getItem(ssoDestKey(origin));
|
|
244
|
+
if (dest) {
|
|
245
|
+
try {
|
|
246
|
+
const destUrl = new URL(dest, origin);
|
|
247
|
+
if (destUrl.origin === origin) {
|
|
248
|
+
history.replaceState(
|
|
249
|
+
null,
|
|
250
|
+
'',
|
|
251
|
+
destUrl.pathname + destUrl.search + destUrl.hash,
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
} catch {
|
|
255
|
+
// Malformed stored destination — leave the URL on the callback path.
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
storage.removeItem(ssoDestKey(origin));
|
|
260
|
+
|
|
261
|
+
return session;
|
|
262
|
+
}
|