@oxyhq/core 2.0.0 → 2.1.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/dist/cjs/index.js CHANGED
@@ -20,7 +20,7 @@
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.normalizeColorScheme = exports.normalizeTheme = exports.getContrastTextColor = exports.isLightColor = exports.withOpacity = exports.rgbToHex = exports.hexToRgb = exports.lightenColor = exports.darkenColor = exports.isAndroid = exports.isIOS = exports.isNative = exports.isWeb = exports.setPlatformOS = exports.getPlatformOS = exports.isRTLLocale = exports.normalizeLanguageCode = exports.getNativeLanguageName = exports.getLanguageName = exports.getLanguageMetadata = exports.SUPPORTED_LANGUAGES = exports.TopicSource = exports.TopicType = exports.SECURITY_EVENT_SEVERITY_MAP = exports.DeviceManager = exports.RecoveryPhraseService = exports.SignatureService = exports.IdentityPersistError = exports.IdentityAlreadyExistsError = exports.KeyManager = exports.sessionsArraysEqual = exports.normalizeAndSortSessions = exports.mergeSessions = exports.authenticatedApiCall = exports.withAuthErrorHandling = exports.isAuthenticationError = exports.ensureValidToken = exports.AuthenticationFailedError = exports.SessionSyncRequiredError = exports.OxyAppDataIdentifierError = exports.ServiceCredentialMismatchError = exports.createCrossDomainAuth = exports.CrossDomainAuth = exports.createAuthManager = exports.AuthManager = exports.oxyClient = exports.OXY_CLOUD_URL = exports.OxyAuthenticationTimeoutError = exports.OxyAuthenticationError = exports.OxyServices = void 0;
22
22
  exports.isValidURL = exports.isValidUUID = exports.isValidObject = exports.isValidArray = exports.isRequiredBoolean = exports.isRequiredNumber = exports.isRequiredString = exports.isValidPassword = exports.isValidUsername = exports.isValidEmail = exports.PASSWORD_REGEX = exports.USERNAME_REGEX = exports.EMAIL_REGEX = exports.retryAsync = exports.validateRequiredFields = exports.handleHttpError = exports.createApiError = exports.ErrorCodes = exports.safeJsonParse = exports.buildPaginationParams = exports.buildUrl = exports.buildSearchParams = exports.translate = exports.createDebugLogger = exports.debugError = exports.debugWarn = exports.debugLog = exports.isDev = exports.withRetry = exports.delay = exports.shouldAllowRequest = exports.recordSuccess = exports.recordFailure = exports.calculateBackoffInterval = exports.createCircuitBreakerState = exports.DEFAULT_CIRCUIT_BREAKER_CONFIG = exports.isRetryableError = exports.isNetworkError = exports.isServerError = exports.isRateLimitError = exports.isNotFoundError = exports.isForbiddenError = exports.isUnauthorizedError = exports.isAlreadyRegisteredError = exports.getErrorMessage = exports.getErrorStatus = exports.HttpStatus = exports.getSystemColorScheme = exports.systemPrefersDarkMode = exports.getOppositeTheme = void 0;
23
- exports.packageInfo = exports.getAccountColor = exports.mergeAccountsFromRefreshAll = exports.formatPublicKeyHandle = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.createQuickAccount = exports.buildAccountsArray = exports.updateAvatarVisibility = exports.logPerformance = exports.logPayment = exports.logDevice = exports.logUser = exports.logSession = exports.logApi = exports.logAuth = exports.LogLevel = exports.logger = exports.validateAndSanitizeUserInput = exports.isValidObjectId = exports.sanitizeHTML = exports.sanitizeString = exports.isValidFileType = exports.isValidFileSize = exports.isValidDate = void 0;
23
+ exports.packageInfo = exports.runColdBoot = exports.autoDetectAuthWebUrl = exports.getAccountColor = exports.mergeAccountsFromRefreshAll = exports.formatPublicKeyHandle = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.createQuickAccount = exports.buildAccountsArray = exports.updateAvatarVisibility = exports.logPerformance = exports.logPayment = exports.logDevice = exports.logUser = exports.logSession = exports.logApi = exports.logAuth = exports.LogLevel = exports.logger = exports.validateAndSanitizeUserInput = exports.isValidObjectId = exports.sanitizeHTML = exports.sanitizeString = exports.isValidFileType = exports.isValidFileSize = exports.isValidDate = void 0;
24
24
  // Ensure crypto polyfills are loaded before anything else
25
25
  require("./crypto/polyfill");
26
26
  // ---------------------------------------------------------------------------
@@ -226,6 +226,13 @@ Object.defineProperty(exports, "formatPublicKeyHandle", { enumerable: true, get:
226
226
  Object.defineProperty(exports, "mergeAccountsFromRefreshAll", { enumerable: true, get: function () { return accountUtils_1.mergeAccountsFromRefreshAll; } });
227
227
  Object.defineProperty(exports, "getAccountColor", { enumerable: true, get: function () { return accountUtils_1.getAccountColor; } });
228
228
  // ---------------------------------------------------------------------------
229
+ // Cross-domain SSO infrastructure
230
+ // ---------------------------------------------------------------------------
231
+ var fapiAutoDetect_1 = require("./utils/fapiAutoDetect");
232
+ Object.defineProperty(exports, "autoDetectAuthWebUrl", { enumerable: true, get: function () { return fapiAutoDetect_1.autoDetectAuthWebUrl; } });
233
+ var coldBoot_1 = require("./utils/coldBoot");
234
+ Object.defineProperty(exports, "runColdBoot", { enumerable: true, get: function () { return coldBoot_1.runColdBoot; } });
235
+ // ---------------------------------------------------------------------------
229
236
  // Constants
230
237
  // ---------------------------------------------------------------------------
231
238
  var version_1 = require("./constants/version");
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ /**
3
+ * coldBoot — a pure, ordered, short-circuit runner for "cold boot"
4
+ * authentication resolution.
5
+ *
6
+ * On a fresh page load / app launch the SDK may have several ways to recover an
7
+ * existing session (silent FedCM, a persisted refresh token, a cross-domain
8
+ * claim, an explicit popup flow, …). They must be attempted in a *deterministic
9
+ * order*, and the FIRST one that yields a session wins — every later step is
10
+ * skipped. This module encodes exactly that contract and nothing else.
11
+ *
12
+ * Design constraints (all enforced):
13
+ * - PURE: no DOM, no `navigator`, no `window`, no React, no platform globals.
14
+ * - NO module-level mutable state. Every call to {@link runColdBoot} is fully
15
+ * self-contained, so it is safe under bundler re-evaluation (e.g. the Metro
16
+ * web bundle, which is precisely why the FedCM silent-SSO guard had to live
17
+ * in consumers rather than a core singleton).
18
+ * - Architecture-agnostic: both candidate cross-domain SSO designs consume
19
+ * this same primitive; it knows nothing about HOW a step resolves a session.
20
+ *
21
+ * A step is skipped (without running) when its `enabled` predicate returns
22
+ * false. Any thrown error — from either `enabled` or `run` — is reported via
23
+ * `onStepError` and treated as a non-fatal skip, so one broken recovery path
24
+ * can never prevent a later, healthy one from succeeding.
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.runColdBoot = runColdBoot;
28
+ /**
29
+ * Run the ordered cold-boot steps and resolve to the first recovered session,
30
+ * or `unauthenticated` if none recovers one.
31
+ *
32
+ * Semantics:
33
+ * 1. Iterate `steps` in order.
34
+ * 2. If a step has an `enabled` predicate, call it inside try/catch:
35
+ * - throw → report via `onStepError(id, err)` → treat as disabled → continue.
36
+ * - returns false → continue (skip, `run` not called).
37
+ * 3. Otherwise await `step.run()` inside try/catch:
38
+ * - throw → report via `onStepError(id, err)` → continue.
39
+ * - `{ kind: 'session' }` → return `{ kind: 'session', via: step.id, session }`.
40
+ * - `{ kind: 'skip' }` → continue.
41
+ * 4. After the loop with no winner → `{ kind: 'unauthenticated' }`.
42
+ */
43
+ async function runColdBoot(options) {
44
+ const { steps, onStepError } = options;
45
+ for (const step of steps) {
46
+ if (step.enabled) {
47
+ let isEnabled;
48
+ try {
49
+ isEnabled = step.enabled();
50
+ }
51
+ catch (error) {
52
+ onStepError?.(step.id, error);
53
+ continue;
54
+ }
55
+ if (!isEnabled)
56
+ continue;
57
+ }
58
+ let result;
59
+ try {
60
+ result = await step.run();
61
+ }
62
+ catch (error) {
63
+ onStepError?.(step.id, error);
64
+ continue;
65
+ }
66
+ if (result.kind === 'session') {
67
+ return { kind: 'session', via: step.id, session: result.session };
68
+ }
69
+ }
70
+ return { kind: 'unauthenticated' };
71
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ /**
3
+ * Auto-detect the FAPI (IdP) URL from the current browser hostname.
4
+ *
5
+ * This is the canonical cross-domain IdP-resolution primitive for the Oxy
6
+ * ecosystem. Both candidate cross-domain SSO designs derive `auth.<rp-apex>`
7
+ * through this helper; do not fork it.
8
+ *
9
+ * Clerk-style multi-domain SSO depends on the IdP being reachable on a
10
+ * subdomain of the RP's own apex (e.g. `auth.mention.earth` CNAMEd to the
11
+ * central Oxy IdP). That way every FedCM endpoint, the session cookie,
12
+ * and any popup/redirect target are same-site with the RP — the only way
13
+ * to get first-party cookies in Safari ITP and Firefox Total Cookie
14
+ * Protection.
15
+ *
16
+ * This helper computes `https://auth.<rp-apex>` from
17
+ * `window.location.hostname` so a consuming app doesn't have to pass
18
+ * `authWebUrl` explicitly. Returns `undefined` for environments where
19
+ * auto-detection would be wrong:
20
+ *
21
+ * - SSR / non-browser (no `window`).
22
+ * - `localhost`, `127.0.0.1`, IPv4/IPv6 literals.
23
+ * - Hostnames with fewer than two labels.
24
+ * - Hostnames whose trailing two labels form a known multi-part public
25
+ * suffix (e.g. `co.uk`), where the naive `labels.slice(-2)` apex would be
26
+ * an attacker-registrable suffix like `auth.co.uk` rather than the real
27
+ * registrable domain.
28
+ *
29
+ * When the page is already loaded ON the IdP itself (`auth.<anything>`),
30
+ * the helper returns the current origin so the SDK keeps everything
31
+ * same-origin instead of hopping to a different IdP host.
32
+ *
33
+ * The IdP backend independently derives `iss`, `provider_urls`, and the
34
+ * `fedcm.json` icon URLs from the request host
35
+ * (`packages/auth/server/index.ts`), so an honest CNAME pair is all that
36
+ * is required for end-to-end FedCM correctness — no per-RP config.
37
+ */
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.autoDetectAuthWebUrl = autoDetectAuthWebUrl;
40
+ /**
41
+ * Known multi-part public suffixes where the registrable domain is the LAST
42
+ * THREE labels, not two. Deriving an apex from `labels.slice(-2)` against any
43
+ * of these would yield an attacker-registrable suffix (e.g. `auth.co.uk`),
44
+ * so we bail out instead.
45
+ *
46
+ * This is intentionally a small, explicit allow-list rather than the full
47
+ * Public Suffix List — it covers the suffixes the Oxy ecosystem's RPs use.
48
+ * Any multi-part-TLD RP MUST extend this set (or wire in a proper PSL check)
49
+ * before relying on this helper, otherwise auto-detection silently bails to
50
+ * `undefined` and the consumer must pass `authWebUrl` explicitly.
51
+ */
52
+ const MULTIPART_TLDS = new Set([
53
+ 'co.uk',
54
+ 'com.au',
55
+ 'co.jp',
56
+ 'co.nz',
57
+ 'com.br',
58
+ 'co.za',
59
+ 'com.mx',
60
+ 'co.in',
61
+ 'co.kr',
62
+ 'com.sg',
63
+ ]);
64
+ function autoDetectAuthWebUrl(location = typeof window !== 'undefined' ? window.location : undefined) {
65
+ if (!location)
66
+ return undefined;
67
+ const { hostname, protocol } = location;
68
+ if (!hostname)
69
+ return undefined;
70
+ if (protocol !== 'https:' && protocol !== 'http:')
71
+ return undefined;
72
+ if (hostname === 'localhost' || hostname === '127.0.0.1')
73
+ return undefined;
74
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname))
75
+ return undefined;
76
+ if (hostname.startsWith('['))
77
+ return undefined;
78
+ if (hostname.startsWith('auth.')) {
79
+ return `${protocol}//${hostname}`;
80
+ }
81
+ const labels = hostname.split('.');
82
+ if (labels.length < 2)
83
+ return undefined;
84
+ if (MULTIPART_TLDS.has(labels.slice(-2).join('.')))
85
+ return undefined;
86
+ const apex = labels.slice(-2).join('.');
87
+ return `${protocol}//auth.${apex}`;
88
+ }