@oxyhq/core 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,7 @@
21
21
  * const session = await auth.signInWithPopup();
22
22
  * ```
23
23
  */
24
+ import { logger } from './utils/loggerUtils.js';
24
25
  export class CrossDomainAuth {
25
26
  constructor(oxyServices) {
26
27
  this.oxyServices = oxyServices;
@@ -94,7 +95,7 @@ export class CrossDomainAuth {
94
95
  return session;
95
96
  }
96
97
  catch (error) {
97
- console.warn('[CrossDomainAuth] FedCM failed, trying popup...', error);
98
+ logger.warn('FedCM failed, trying popup', { component: 'CrossDomainAuth', method: 'autoSignIn' }, error);
98
99
  }
99
100
  }
100
101
  // 2. Try popup (good UX, widely supported)
@@ -103,7 +104,7 @@ export class CrossDomainAuth {
103
104
  return await this.signInWithPopup(options);
104
105
  }
105
106
  catch (error) {
106
- console.warn('[CrossDomainAuth] Popup failed, falling back to redirect...', error);
107
+ logger.warn('Popup failed, falling back to redirect', { component: 'CrossDomainAuth', method: 'autoSignIn' }, error);
107
108
  // Popup path failed — close the pre-opened popup before redirecting.
108
109
  this.closeOrphanPopup(options.popup);
109
110
  }
@@ -172,7 +173,7 @@ export class CrossDomainAuth {
172
173
  }
173
174
  }
174
175
  catch (error) {
175
- console.warn('[CrossDomainAuth] FedCM silent sign-in failed:', error);
176
+ logger.debug('FedCM silent sign-in did not resolve', { component: 'CrossDomainAuth', method: 'silentSignIn' }, error);
176
177
  }
177
178
  }
178
179
  // Fallback to iframe-based silent auth
@@ -180,7 +181,7 @@ export class CrossDomainAuth {
180
181
  return await this.oxyServices.silentSignIn();
181
182
  }
182
183
  catch (error) {
183
- console.warn('[CrossDomainAuth] Silent sign-in failed:', error);
184
+ logger.debug('iframe silent sign-in did not resolve', { component: 'CrossDomainAuth', method: 'silentSignIn' }, error);
184
185
  return null;
185
186
  }
186
187
  }
@@ -265,7 +266,7 @@ export class CrossDomainAuth {
265
266
  }
266
267
  }
267
268
  catch (error) {
268
- console.warn('[CrossDomainAuth] Stored session invalid:', error);
269
+ logger.debug('stored session invalid', { component: 'CrossDomainAuth', method: 'initialize' }, error);
269
270
  }
270
271
  }
271
272
  // 3. Try silent sign-in (check for SSO session at auth.oxy.so)
package/dist/esm/index.js CHANGED
@@ -97,6 +97,11 @@ export { updateAvatarVisibility } from './utils/avatarUtils.js';
97
97
  // ---------------------------------------------------------------------------
98
98
  export { buildAccountsArray, createQuickAccount, getAccountDisplayName, getAccountFallbackHandle, formatPublicKeyHandle, mergeAccountsFromRefreshAll, getAccountColor, } from './utils/accountUtils.js';
99
99
  // ---------------------------------------------------------------------------
100
+ // Cross-domain SSO infrastructure
101
+ // ---------------------------------------------------------------------------
102
+ export { autoDetectAuthWebUrl } from './utils/fapiAutoDetect.js';
103
+ export { runColdBoot } from './utils/coldBoot.js';
104
+ // ---------------------------------------------------------------------------
100
105
  // Constants
101
106
  // ---------------------------------------------------------------------------
102
107
  export { packageInfo } from './constants/version.js';
@@ -0,0 +1,68 @@
1
+ /**
2
+ * coldBoot — a pure, ordered, short-circuit runner for "cold boot"
3
+ * authentication resolution.
4
+ *
5
+ * On a fresh page load / app launch the SDK may have several ways to recover an
6
+ * existing session (silent FedCM, a persisted refresh token, a cross-domain
7
+ * claim, an explicit popup flow, …). They must be attempted in a *deterministic
8
+ * order*, and the FIRST one that yields a session wins — every later step is
9
+ * skipped. This module encodes exactly that contract and nothing else.
10
+ *
11
+ * Design constraints (all enforced):
12
+ * - PURE: no DOM, no `navigator`, no `window`, no React, no platform globals.
13
+ * - NO module-level mutable state. Every call to {@link runColdBoot} is fully
14
+ * self-contained, so it is safe under bundler re-evaluation (e.g. the Metro
15
+ * web bundle, which is precisely why the FedCM silent-SSO guard had to live
16
+ * in consumers rather than a core singleton).
17
+ * - Architecture-agnostic: both candidate cross-domain SSO designs consume
18
+ * this same primitive; it knows nothing about HOW a step resolves a session.
19
+ *
20
+ * A step is skipped (without running) when its `enabled` predicate returns
21
+ * false. Any thrown error — from either `enabled` or `run` — is reported via
22
+ * `onStepError` and treated as a non-fatal skip, so one broken recovery path
23
+ * can never prevent a later, healthy one from succeeding.
24
+ */
25
+ /**
26
+ * Run the ordered cold-boot steps and resolve to the first recovered session,
27
+ * or `unauthenticated` if none recovers one.
28
+ *
29
+ * Semantics:
30
+ * 1. Iterate `steps` in order.
31
+ * 2. If a step has an `enabled` predicate, call it inside try/catch:
32
+ * - throw → report via `onStepError(id, err)` → treat as disabled → continue.
33
+ * - returns false → continue (skip, `run` not called).
34
+ * 3. Otherwise await `step.run()` inside try/catch:
35
+ * - throw → report via `onStepError(id, err)` → continue.
36
+ * - `{ kind: 'session' }` → return `{ kind: 'session', via: step.id, session }`.
37
+ * - `{ kind: 'skip' }` → continue.
38
+ * 4. After the loop with no winner → `{ kind: 'unauthenticated' }`.
39
+ */
40
+ export async function runColdBoot(options) {
41
+ const { steps, onStepError } = options;
42
+ for (const step of steps) {
43
+ if (step.enabled) {
44
+ let isEnabled;
45
+ try {
46
+ isEnabled = step.enabled();
47
+ }
48
+ catch (error) {
49
+ onStepError?.(step.id, error);
50
+ continue;
51
+ }
52
+ if (!isEnabled)
53
+ continue;
54
+ }
55
+ let result;
56
+ try {
57
+ result = await step.run();
58
+ }
59
+ catch (error) {
60
+ onStepError?.(step.id, error);
61
+ continue;
62
+ }
63
+ if (result.kind === 'session') {
64
+ return { kind: 'session', via: step.id, session: result.session };
65
+ }
66
+ }
67
+ return { kind: 'unauthenticated' };
68
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Auto-detect the FAPI (IdP) URL from the current browser hostname.
3
+ *
4
+ * This is the canonical cross-domain IdP-resolution primitive for the Oxy
5
+ * ecosystem. Both candidate cross-domain SSO designs derive `auth.<rp-apex>`
6
+ * through this helper; do not fork it.
7
+ *
8
+ * Clerk-style multi-domain SSO depends on the IdP being reachable on a
9
+ * subdomain of the RP's own apex (e.g. `auth.mention.earth` CNAMEd to the
10
+ * central Oxy IdP). That way every FedCM endpoint, the session cookie,
11
+ * and any popup/redirect target are same-site with the RP — the only way
12
+ * to get first-party cookies in Safari ITP and Firefox Total Cookie
13
+ * Protection.
14
+ *
15
+ * This helper computes `https://auth.<rp-apex>` from
16
+ * `window.location.hostname` so a consuming app doesn't have to pass
17
+ * `authWebUrl` explicitly. Returns `undefined` for environments where
18
+ * auto-detection would be wrong:
19
+ *
20
+ * - SSR / non-browser (no `window`).
21
+ * - `localhost`, `127.0.0.1`, IPv4/IPv6 literals.
22
+ * - Hostnames with fewer than two labels.
23
+ * - Hostnames whose trailing two labels form a known multi-part public
24
+ * suffix (e.g. `co.uk`), where the naive `labels.slice(-2)` apex would be
25
+ * an attacker-registrable suffix like `auth.co.uk` rather than the real
26
+ * registrable domain.
27
+ *
28
+ * When the page is already loaded ON the IdP itself (`auth.<anything>`),
29
+ * the helper returns the current origin so the SDK keeps everything
30
+ * same-origin instead of hopping to a different IdP host.
31
+ *
32
+ * The IdP backend independently derives `iss`, `provider_urls`, and the
33
+ * `fedcm.json` icon URLs from the request host
34
+ * (`packages/auth/server/index.ts`), so an honest CNAME pair is all that
35
+ * is required for end-to-end FedCM correctness — no per-RP config.
36
+ */
37
+ /**
38
+ * Known multi-part public suffixes where the registrable domain is the LAST
39
+ * THREE labels, not two. Deriving an apex from `labels.slice(-2)` against any
40
+ * of these would yield an attacker-registrable suffix (e.g. `auth.co.uk`),
41
+ * so we bail out instead.
42
+ *
43
+ * This is intentionally a small, explicit allow-list rather than the full
44
+ * Public Suffix List — it covers the suffixes the Oxy ecosystem's RPs use.
45
+ * Any multi-part-TLD RP MUST extend this set (or wire in a proper PSL check)
46
+ * before relying on this helper, otherwise auto-detection silently bails to
47
+ * `undefined` and the consumer must pass `authWebUrl` explicitly.
48
+ */
49
+ const MULTIPART_TLDS = new Set([
50
+ 'co.uk',
51
+ 'com.au',
52
+ 'co.jp',
53
+ 'co.nz',
54
+ 'com.br',
55
+ 'co.za',
56
+ 'com.mx',
57
+ 'co.in',
58
+ 'co.kr',
59
+ 'com.sg',
60
+ ]);
61
+ export function autoDetectAuthWebUrl(location = typeof window !== 'undefined' ? window.location : undefined) {
62
+ if (!location)
63
+ return undefined;
64
+ const { hostname, protocol } = location;
65
+ if (!hostname)
66
+ return undefined;
67
+ if (protocol !== 'https:' && protocol !== 'http:')
68
+ return undefined;
69
+ if (hostname === 'localhost' || hostname === '127.0.0.1')
70
+ return undefined;
71
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname))
72
+ return undefined;
73
+ if (hostname.startsWith('['))
74
+ return undefined;
75
+ if (hostname.startsWith('auth.')) {
76
+ return `${protocol}//${hostname}`;
77
+ }
78
+ const labels = hostname.split('.');
79
+ if (labels.length < 2)
80
+ return undefined;
81
+ if (MULTIPART_TLDS.has(labels.slice(-2).join('.')))
82
+ return undefined;
83
+ const apex = labels.slice(-2).join('.');
84
+ return `${protocol}//auth.${apex}`;
85
+ }