@oxyhq/core 10.0.0 → 10.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.
package/dist/cjs/index.js CHANGED
@@ -20,8 +20,8 @@
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.isWeb = exports.setPlatformOS = exports.getPlatformOS = exports.getPrimaryLanguage = exports.getUserLanguages = exports.isRTLLocale = exports.getNativeLanguageName = exports.getLanguageName = exports.getLanguageMetadata = exports.isSupportedLocale = exports.normalizeLocale = exports.getBaseLanguage = exports.FALLBACK_LOCALE = 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.verifyPublicCardAttestation = exports.parseAttestPayload = exports.parseIdPayload = exports.buildUserDid = exports.ORGANIZATION_CATEGORIES = exports.normalizeProfileLinks = exports.getNormalizedUserHandle = exports.getCanonicalUserHandle = exports.normalizeUserIdentityOrNull = exports.normalizeUserIdentity = exports.getNormalizedUserId = exports.OxyAppDataIdentifierError = exports.ServiceCredentialMismatchError = exports.oxyClient = exports.OXY_CLOUD_URL = exports.OxyAuthenticationTimeoutError = exports.OxyAuthenticationError = exports.OxyServices = void 0;
22
22
  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 = exports.normalizeColorScheme = exports.normalizeTheme = exports.getContrastTextColor = exports.isLightColor = exports.withOpacity = exports.rgbToHex = exports.hexToRgb = exports.lightenColor = exports.darkenColor = exports.isWebBrowser = exports.isAndroid = exports.isIOS = exports.isNative = void 0;
23
- exports.OXY_CROSS_ORIGIN_RESTORE_ATTEMPTED_KEY = exports.OXY_SILENT_OAUTH_ATTEMPTED_KEY = exports.OXY_OAUTH_CODE_VERIFIER_STORAGE_KEY = exports.OXY_OAUTH_STATE_STORAGE_KEY = exports.OXY_AUTHORIZE_URL = exports.DEFAULT_OAUTH_SCOPE = exports.generatePkcePair = exports.generateOAuthState = exports.computeCodeChallenge = exports.buildOAuthAuthorizeUrl = exports.runColdBoot = exports.CENTRAL_IDP_APEX = exports.registrableApex = exports.getAccountColor = 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 = exports.isValidURL = exports.isValidUUID = exports.isValidObject = exports.isValidArray = exports.isRequiredBoolean = exports.isRequiredNumber = exports.isRequiredString = exports.isValidDisplayName = exports.isValidPassword = exports.isValidUsername = exports.isValidEmail = exports.PASSWORD_REGEX = exports.USERNAME_REGEX = exports.EMAIL_REGEX = void 0;
24
- exports.packageInfo = exports.runSessionColdBoot = exports.TOKEN_REFRESH_LEAD_MS = exports.startTokenRefreshScheduler = exports.installAuthRefreshHandler = exports.createAuthRefreshHandler = exports.refreshDeviceSecretArm = exports.refreshPersistedSession = exports.AUTH_STATE_STORAGE_KEY = exports.createMemoryAuthStateStore = exports.createNativeAuthStateStore = exports.createWebAuthStateStore = exports.createAccountDialogController = exports.AccountDialogController = exports.switchableAccountIds = exports.projectSwitchableAccounts = exports.accountIdsOf = exports.activeUserOf = exports.activeSessionIdOf = exports.deviceStateToClientSessions = exports.createSessionClient = exports.createSessionClientHost = exports.SessionClient = exports.redeemHubTicketOnHub = exports.syncHubAfterSignIn = exports.parseHubSyncReturnUrl = exports.normalizeOfficialReturnOrigin = exports.isAllowedDeviceJoinOrigin = exports.isOfficialWebOrigin = exports.isIdpHubOrigin = exports.buildHubSyncUrl = exports.buildIdpHubOrigin = exports.clearOAuthHandshake = exports.readOAuthHandshake = exports.persistOAuthHandshake = exports.normalizeOAuthRedirectUri = void 0;
23
+ exports.OXY_OAUTH_CODE_VERIFIER_STORAGE_KEY = exports.OXY_OAUTH_STATE_STORAGE_KEY = exports.OXY_AUTHORIZE_URL = exports.DEFAULT_OAUTH_SCOPE = exports.generatePkcePair = exports.generateOAuthState = exports.computeCodeChallenge = exports.buildOAuthAuthorizeUrl = exports.runColdBoot = exports.CENTRAL_IDP_APEX = exports.registrableApex = exports.getAccountColor = 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.normalizeMultilineText = exports.normalizeInlineText = exports.validateAndSanitizeUserInput = exports.isValidObjectId = exports.sanitizeHTML = exports.sanitizeString = exports.isValidFileType = exports.isValidFileSize = exports.isValidDate = exports.isValidURL = exports.isValidUUID = exports.isValidObject = exports.isValidArray = exports.isRequiredBoolean = exports.isRequiredNumber = exports.isRequiredString = exports.isValidDisplayName = exports.isValidPassword = exports.isValidUsername = exports.isValidEmail = exports.PASSWORD_REGEX = exports.USERNAME_REGEX = exports.EMAIL_REGEX = void 0;
24
+ exports.packageInfo = exports.runSessionColdBoot = exports.TOKEN_REFRESH_LEAD_MS = exports.startTokenRefreshScheduler = exports.installAuthRefreshHandler = exports.createAuthRefreshHandler = exports.refreshDeviceSecretArm = exports.refreshPersistedSession = exports.AUTH_STATE_STORAGE_KEY = exports.createMemoryAuthStateStore = exports.createNativeAuthStateStore = exports.createWebAuthStateStore = exports.createAccountDialogController = exports.AccountDialogController = exports.switchableAccountIds = exports.projectSwitchableAccounts = exports.accountIdsOf = exports.activeUserOf = exports.activeSessionIdOf = exports.deviceStateToClientSessions = exports.createSessionClient = exports.createSessionClientHost = exports.SessionClient = exports.redeemHubTicketOnHub = exports.syncHubAfterSignIn = exports.parseHubSyncReturnUrl = exports.normalizeOfficialReturnOrigin = exports.isAllowedDeviceJoinOrigin = exports.isOfficialWebOrigin = exports.isIdpHubOrigin = exports.buildHubSyncUrl = exports.buildIdpHubOrigin = exports.clearOAuthHandshake = exports.readOAuthHandshake = exports.persistOAuthHandshake = exports.normalizeOAuthRedirectUri = exports.OXY_CROSS_ORIGIN_RESTORE_ATTEMPTED_KEY = exports.OXY_SILENT_OAUTH_ATTEMPTED_KEY = void 0;
25
25
  // Ensure crypto polyfills are loaded before anything else
26
26
  require("./crypto/polyfill");
27
27
  // ---------------------------------------------------------------------------
@@ -233,6 +233,12 @@ Object.defineProperty(exports, "sanitizeHTML", { enumerable: true, get: function
233
233
  Object.defineProperty(exports, "isValidObjectId", { enumerable: true, get: function () { return validationUtils_1.isValidObjectId; } });
234
234
  Object.defineProperty(exports, "validateAndSanitizeUserInput", { enumerable: true, get: function () { return validationUtils_1.validateAndSanitizeUserInput; } });
235
235
  // ---------------------------------------------------------------------------
236
+ // Text normalization
237
+ // ---------------------------------------------------------------------------
238
+ var textNormalization_1 = require("./utils/textNormalization");
239
+ Object.defineProperty(exports, "normalizeInlineText", { enumerable: true, get: function () { return textNormalization_1.normalizeInlineText; } });
240
+ Object.defineProperty(exports, "normalizeMultilineText", { enumerable: true, get: function () { return textNormalization_1.normalizeMultilineText; } });
241
+ // ---------------------------------------------------------------------------
236
242
  // Logging
237
243
  // ---------------------------------------------------------------------------
238
244
  var loggerUtils_1 = require("./utils/loggerUtils");
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ /**
3
+ * Canonical text normalization for the Oxy ecosystem.
4
+ *
5
+ * WHY THIS EXISTS
6
+ * ---------------
7
+ * Third-party text (federated actor display names, spoiler/CW text, image alt
8
+ * text, bios, `<title>` / `og:site_name` of scraped remote pages, …) arrives
9
+ * with the whitespace the remote author's markup happened to contain. A real
10
+ * bug: a remote page served
11
+ *
12
+ * <title>
13
+ * Mi título
14
+ * </title>
15
+ *
16
+ * and the extracted string — newlines and indentation included — was stored
17
+ * verbatim. Clients render text with React Native Web `Text`, which maps to
18
+ * CSS `white-space: pre-wrap`: unlike HTML, newlines and repeated spaces are
19
+ * NOT collapsed at render time, so the user saw a blank line and a six-space
20
+ * indent inside the link preview.
21
+ *
22
+ * Storage-time normalization is therefore the ONLY place this can be fixed:
23
+ * every renderer downstream is faithful by design.
24
+ *
25
+ * WHICH HELPER DO I USE?
26
+ * ----------------------
27
+ * - {@link normalizeInlineText} — the value is conceptually ONE LINE, and a
28
+ * line break in it is always an accident of the source markup: page titles,
29
+ * `siteName`, display names, image `alt`, handles, profile field labels.
30
+ * Every line break becomes a space.
31
+ *
32
+ * - {@link normalizeMultilineText} — the value is a BODY whose line breaks are
33
+ * the author's own paragraphs and must survive: post text, bios/summaries.
34
+ * Line breaks are preserved (capped at one blank line); only the surrounding
35
+ * whitespace noise is cleaned.
36
+ *
37
+ * Using the multiline helper on a title would keep the newlines and reproduce
38
+ * the original bug; using the inline helper on a post body would flatten the
39
+ * author's paragraphs into a single run-on line. Pick deliberately.
40
+ *
41
+ * Neither helper truncates, strips markup, or enforces a character policy —
42
+ * those are separate, product-specific concerns (see `isValidDisplayName` for
43
+ * the display-name character policy). These functions do exactly one thing:
44
+ * normalize whitespace and Unicode form.
45
+ */
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.normalizeInlineText = normalizeInlineText;
48
+ exports.normalizeMultilineText = normalizeMultilineText;
49
+ /**
50
+ * Characters that make a value ineligible for the zero-work fast path, and the
51
+ * whitespace shapes that a normalized INLINE value can never contain.
52
+ *
53
+ * A value that matches nothing here is, by construction, already normalized:
54
+ * it holds only printable ASCII (which is NFC-stable, so `normalize('NFC')`
55
+ * would be a no-op), its only whitespace is the plain space, it has no leading
56
+ * or trailing space, and no run of two spaces. Returning it untouched skips
57
+ * three string allocations — worth it because the common case in the feed
58
+ * hydration hot path is text that is already clean.
59
+ *
60
+ * Non-global (safe for repeated `.test()`; a global regex is stateful).
61
+ */
62
+ const INLINE_NEEDS_NORMALIZATION = /[^\x20-\x7E]|^ | $| {2}/;
63
+ /**
64
+ * Same idea as {@link INLINE_NEEDS_NORMALIZATION}, for MULTILINE values: `\n`
65
+ * joins the printable-ASCII fast-path alphabet, and the additional shapes a
66
+ * normalized body can never contain are a space before a line break (trailing
67
+ * horizontal whitespace) and a run of three line breaks (more than one blank
68
+ * line). A single space AFTER a line break is legal — a one-space indent is
69
+ * the author's, and normalization deliberately preserves it.
70
+ */
71
+ const MULTILINE_NEEDS_NORMALIZATION = /[^\x20-\x7E\n]|^[ \n]|[ \n]$| {2}| \n|\n{3}/;
72
+ /** Any run of whitespace, including tabs, line breaks and Unicode spaces. */
73
+ const ANY_WHITESPACE_RUN = /\s+/g;
74
+ /**
75
+ * Every line-break form, unified to `\n` before the multiline passes run:
76
+ * CRLF (Windows), a lone CR (classic Mac / stray `\r`), and the Unicode LINE
77
+ * SEPARATOR (U+2028) / PARAGRAPH SEPARATOR (U+2029), which are mandatory breaks
78
+ * in Unicode and a well-known hazard in JSON/JS payloads. CRLF must be matched
79
+ * before the lone `\r` alternative or it would yield two breaks. The separators
80
+ * are matched by Unicode property (`\p{Zl}` = U+2028, `\p{Zp}` = U+2029) rather
81
+ * than as literals: a literal U+2028/U+2029 is a LineTerminator and cannot appear
82
+ * inside a regex literal at all.
83
+ */
84
+ const LINE_BREAK_FORMS = /\r\n|\r|\p{Zl}|\p{Zp}/gu;
85
+ /**
86
+ * A run of HORIZONTAL whitespace: any whitespace that is not a line break.
87
+ * `[^\S\n]` is "whitespace, minus `\n`" — it covers the tab, the vertical tab,
88
+ * the form feed and every Unicode space separator (NBSP U+00A0, the U+2000
89
+ * block, the ideographic space U+3000, the zero-width no-break space U+FEFF).
90
+ * Applied AFTER {@link LINE_BREAK_FORMS}, so no line break can hide in it.
91
+ */
92
+ const HORIZONTAL_WHITESPACE_RUN = /[^\S\n]+/g;
93
+ /** Horizontal whitespace at the end of a line — the blank-line spoiler. */
94
+ const TRAILING_HORIZONTAL_WHITESPACE = / +\n/g;
95
+ /** Three or more line breaks: more than one blank line between paragraphs. */
96
+ const EXCESS_BLANK_LINES = /\n{3,}/g;
97
+ /**
98
+ * Normalize a SINGLE-LINE text value: page/link-preview titles, `siteName`,
99
+ * display names, image alt text, handles, profile field labels.
100
+ *
101
+ * A line break in such a value is never meaningful — it is an artifact of the
102
+ * markup the value was extracted from (`<title>\n Título\n</title>`) — and it
103
+ * survives into the UI because RN Web renders `Text` with `white-space:
104
+ * pre-wrap`. So ALL whitespace, line breaks included, collapses to one space.
105
+ *
106
+ * 1. NFC-normalize, so visually identical strings store and compare
107
+ * identically (a decomposed `e`+◌́ recomposes into `é`).
108
+ * 2. Collapse every run of whitespace — spaces, tabs, `\n`, `\r`, and Unicode
109
+ * spaces such as NBSP — to a single plain space.
110
+ * 3. Trim both ends.
111
+ *
112
+ * Length is NOT capped: a maximum length is a product rule of the specific
113
+ * field (see `MAX_DISPLAY_NAME_LENGTH`), not a property of text normalization.
114
+ * Markup is NOT stripped: run the caller's sanitizer first if the source can
115
+ * contain HTML.
116
+ *
117
+ * A value that is empty or whitespace-only returns `''`. Callers decide whether
118
+ * that means "omit the field" (`|| undefined`) or "store an empty string".
119
+ *
120
+ * Idempotent: `f(f(x)) === f(x)`.
121
+ */
122
+ function normalizeInlineText(value) {
123
+ if (!INLINE_NEEDS_NORMALIZATION.test(value)) {
124
+ return value;
125
+ }
126
+ return value.normalize('NFC').replace(ANY_WHITESPACE_RUN, ' ').trim();
127
+ }
128
+ /**
129
+ * Normalize a MULTILINE text BODY: post text, bios, summaries — anywhere the
130
+ * line breaks are the author's paragraphs and must be preserved.
131
+ *
132
+ * Cleans the whitespace noise around those paragraphs without destroying them:
133
+ *
134
+ * 1. NFC-normalize (same rationale as {@link normalizeInlineText}).
135
+ * 2. Unify every line-break form (CRLF, lone CR, U+2028, U+2029) to `\n`.
136
+ * 3. Collapse runs of HORIZONTAL whitespace (spaces, tabs, NBSP and friends)
137
+ * to a single space. Line breaks are untouched.
138
+ * 4. Strip the horizontal whitespace at the END of each line.
139
+ * 5. Collapse three or more line breaks to exactly one blank line (`\n\n`).
140
+ * 6. Trim both ends.
141
+ *
142
+ * STEP 4 MUST PRECEDE STEP 5 — this is the whole point of the function. A
143
+ * "blank" line that actually contains spaces (`"a\n \n \nb"`) breaks the
144
+ * run of `\n` characters, so a bare `\n{3,}` collapse (step 5 alone) never sees
145
+ * it and the extra blank lines survive into the UI. That is exactly the bug in
146
+ * federated post bodies. Removing the trailing horizontal whitespace first
147
+ * turns those lines into real, empty lines, which step 5 then collapses.
148
+ *
149
+ * A single space at the START of a line is preserved: only RUNS of horizontal
150
+ * whitespace collapse, and an indent is not trailing whitespace, so a one-space
151
+ * indent is treated as the author's and left alone.
152
+ *
153
+ * A value that is empty or whitespace-only returns `''`.
154
+ *
155
+ * Idempotent: `f(f(x)) === f(x)`.
156
+ */
157
+ function normalizeMultilineText(value) {
158
+ if (!MULTILINE_NEEDS_NORMALIZATION.test(value)) {
159
+ return value;
160
+ }
161
+ return value
162
+ .normalize('NFC')
163
+ .replace(LINE_BREAK_FORMS, '\n')
164
+ .replace(HORIZONTAL_WHITESPACE_RUN, ' ')
165
+ .replace(TRAILING_HORIZONTAL_WHITESPACE, '\n')
166
+ .replace(EXCESS_BLANK_LINES, '\n\n')
167
+ .trim();
168
+ }