|
| 1 | +/* |
| 2 | + Backlink utility for storing and retrieving navigation back URLs |
| 3 | + Uses sessionStorage to persist backlink data across page navigations |
| 4 | +
|
| 5 | + Example: |
| 6 | +
|
| 7 | + Storing a backlink before navigation |
| 8 | + ```setBacklink('SomeScreen', location.pathname, searchParams.toString());``` |
| 9 | +
|
| 10 | + Or using the location helper (searchParams is optional) |
| 11 | + ```setBacklinkFromLocation('SomeScreen', location, searchParams);``` |
| 12 | +
|
| 13 | + Or store pathname only: |
| 14 | + ```setBacklinkFromLocation('SomeScreen', location);``` |
| 15 | +
|
| 16 | + Consuming a backlink on component mount (one-time read, React Strict Mode safe) |
| 17 | + ``` |
| 18 | + useEffect(() => { |
| 19 | + const url = consumeBacklink('SomeScreen'); |
| 20 | + if (url) setBacklinkState(url); |
| 21 | + }, []); |
| 22 | + ``` |
| 23 | +*/ |
| 24 | + |
| 25 | +const STORAGE_PREFIX = 'backlink:'; |
| 26 | + |
| 27 | +/* |
| 28 | + Validates that a URL is safe for internal navigation |
| 29 | + Rejects external URLs and protocol-relative URLs to prevent open redirect attacks |
| 30 | + @param {string} url - The URL to validate |
| 31 | + @returns {boolean} True if the URL is a safe internal path |
| 32 | +*/ |
| 33 | +function isSafeInternalPath(url) { |
| 34 | + return typeof url === 'string' && |
| 35 | + url.startsWith('/') && |
| 36 | + !url.startsWith('//'); |
| 37 | +} |
| 38 | + |
| 39 | +/* |
| 40 | + Normalizes a search/query string by stripping leading '?' characters |
| 41 | + @param {string} search - The search string to normalize |
| 42 | + @returns {string} Normalized search string without leading '?' |
| 43 | + */ |
| 44 | +function normalizeSearch(search = '') { |
| 45 | + if (!search) return ''; |
| 46 | + return search.replace(/^\?+/, ''); |
| 47 | +} |
| 48 | + |
| 49 | +/* |
| 50 | + Safely executes a sessionStorage operation with error handling |
| 51 | + @param {Function} operation - The sessionStorage operation to perform |
| 52 | + @param {string} context - Description of the operation for error logging |
| 53 | +*/ |
| 54 | +function safeStorageOperation(operation, context) { |
| 55 | + try { |
| 56 | + return operation(); |
| 57 | + } catch (error) { |
| 58 | + // Fail silently in private mode or when storage is disabled |
| 59 | + if (error.name === 'QuotaExceededError' || error.name === 'SecurityError') { |
| 60 | + console.warn(`backlink: ${context} failed - storage may be disabled or quota exceeded`, error); |
| 61 | + } else { |
| 62 | + console.error(`backlink: ${context} error`, error); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/* |
| 68 | + Creates a backlink by storing the current location in sessionStorage |
| 69 | + @param {string} key - Unique identifier for this backlink context (e.g., 'SomeScreen') |
| 70 | + @param {string} pathname - The pathname to store (typically location.pathname) |
| 71 | + @param {string} search - The search/query string to store (typically location.search or searchParams.toString()) |
| 72 | + @param {Object} options - Optional metadata to store with the backlink (cannot override url or timestamp) |
| 73 | + */ |
| 74 | +export function setBacklink(key, pathname, search = '', options = {}) { |
| 75 | + if (!key) { |
| 76 | + console.warn('backlink: setBacklink requires a key'); |
| 77 | + return; |
| 78 | + } |
| 79 | + if (!pathname || typeof pathname !== 'string') { |
| 80 | + console.warn('backlink: setBacklink requires a pathname string'); |
| 81 | + return; |
| 82 | + } |
| 83 | + |
| 84 | + // If 3rd arg is URLSearchParams, normalize it to a string |
| 85 | + if (search instanceof URLSearchParams) { |
| 86 | + search = search.toString(); |
| 87 | + } else if (search != undefined && typeof search === 'object') { |
| 88 | + // 3rd arg is a plain object (not string/null/undefined/URLSearchParams), treat it as options |
| 89 | + options = search; |
| 90 | + search = ''; |
| 91 | + } |
| 92 | + |
| 93 | + const storageKey = STORAGE_PREFIX + key; |
| 94 | + const normalizedSearch = normalizeSearch(search); |
| 95 | + const url = pathname + (normalizedSearch ? '?' + normalizedSearch : ''); |
| 96 | + |
| 97 | + // Defense in depth: validate URL on write as well as read |
| 98 | + if (!isSafeInternalPath(url)) { |
| 99 | + console.warn(`backlink: refusing to store unsafe URL for key "${key}":`, url); |
| 100 | + return; |
| 101 | + } |
| 102 | + |
| 103 | + // options are spread first to prevent overwriting core fields |
| 104 | + const value = JSON.stringify({ |
| 105 | + ...options, |
| 106 | + url, |
| 107 | + timestamp: Date.now(), |
| 108 | + }); |
| 109 | + |
| 110 | + safeStorageOperation(() => sessionStorage.setItem(storageKey, value), 'setBacklink'); |
| 111 | +} |
| 112 | + |
| 113 | +/* |
| 114 | + Convenience helper for React Router locations |
| 115 | + @param {string} key - Unique identifier for this backlink context |
| 116 | + @param {Object} location - React Router location object with pathname and optional search property |
| 117 | + @param {URLSearchParams|string} searchParams - Query parameters as URLSearchParams or string (optional, defaults to location.search) |
| 118 | + @param {Object} options - Optional metadata to store with the backlink |
| 119 | + */ |
| 120 | +export function setBacklinkFromLocation(key, location, searchParams, options = {}) { |
| 121 | + if (!location || typeof location.pathname !== 'string') { |
| 122 | + console.warn('backlink: setBacklinkFromLocation requires a location object with pathname'); |
| 123 | + return; |
| 124 | + } |
| 125 | + |
| 126 | + // Handle overload: if there are only 3 args and the 3rd is a plain object (not URLSearchParams/string/null), treat it as options |
| 127 | + if (arguments.length === 3 && searchParams != undefined && typeof searchParams === 'object' && !(searchParams instanceof URLSearchParams)) { |
| 128 | + options = searchParams; |
| 129 | + searchParams = undefined; |
| 130 | + } |
| 131 | + |
| 132 | + const search = searchParams === undefined |
| 133 | + ? (location.search || '') |
| 134 | + : searchParams === null |
| 135 | + ? '' |
| 136 | + : typeof searchParams === 'string' |
| 137 | + ? searchParams |
| 138 | + : searchParams instanceof URLSearchParams |
| 139 | + ? searchParams.toString() |
| 140 | + : String(searchParams); |
| 141 | + |
| 142 | + setBacklink(key, location.pathname, search, options); |
| 143 | +} |
| 144 | + |
| 145 | +/* |
| 146 | + Retrieves a stored backlink URL |
| 147 | + Returns null if the URL is not found or is not a safe internal path. |
| 148 | + @param {string} key - The unique identifier for this backlink context |
| 149 | + @returns {string|null} The stored backlink URL, or null if not found/invalid |
| 150 | + */ |
| 151 | +export function getBacklink(key) { |
| 152 | + if (!key) { |
| 153 | + console.warn('backlink: getBacklink requires a key'); |
| 154 | + return null; |
| 155 | + } |
| 156 | + |
| 157 | + const storageKey = STORAGE_PREFIX + key; |
| 158 | + const value = safeStorageOperation(() => sessionStorage.getItem(storageKey), 'getBacklink'); |
| 159 | + if (!value) return null; |
| 160 | + |
| 161 | + let url; |
| 162 | + try { |
| 163 | + const parsed = JSON.parse(value); |
| 164 | + url = parsed.url; |
| 165 | + } catch { |
| 166 | + // Fallback for legacy string-only storage |
| 167 | + url = value; |
| 168 | + } |
| 169 | + |
| 170 | + // Validate URL to prevent open redirect attacks |
| 171 | + if (!isSafeInternalPath(url)) { |
| 172 | + console.warn(`backlink: ignoring unsafe URL for key "${key}":`, url); |
| 173 | + return null; |
| 174 | + } |
| 175 | + |
| 176 | + return url; |
| 177 | +} |
| 178 | + |
| 179 | +/* |
| 180 | + Retrieves full backlink data including metadata |
| 181 | + Returns null if the URL is not found or is not a safe internal path |
| 182 | + @param {string} key - The unique identifier for this backlink context |
| 183 | + @returns {Object|null} The stored backlink data with url, timestamp, and any custom options |
| 184 | +*/ |
| 185 | +export function getBacklinkData(key) { |
| 186 | + if (!key) { |
| 187 | + console.warn('backlink: getBacklinkData requires a key'); |
| 188 | + return null; |
| 189 | + } |
| 190 | + |
| 191 | + const storageKey = STORAGE_PREFIX + key; |
| 192 | + const value = safeStorageOperation(() => sessionStorage.getItem(storageKey), 'getBacklinkData'); |
| 193 | + if (!value) return null; |
| 194 | + |
| 195 | + let data; |
| 196 | + try { |
| 197 | + data = JSON.parse(value); |
| 198 | + } catch { |
| 199 | + // Fallback for legacy string-only storage |
| 200 | + data = { url: value, timestamp: null }; |
| 201 | + } |
| 202 | + |
| 203 | + // Validate URL to prevent open redirect attacks |
| 204 | + if (!isSafeInternalPath(data?.url)) { |
| 205 | + console.warn(`backlink: ignoring unsafe URL for key "${key}":`, data?.url); |
| 206 | + return null; |
| 207 | + } |
| 208 | + |
| 209 | + return data; |
| 210 | +} |
| 211 | + |
| 212 | +/* |
| 213 | + Removes a backlink from sessionStorage |
| 214 | + @param {string} key - The unique identifier for this backlink context |
| 215 | + */ |
| 216 | +export function clearBacklink(key) { |
| 217 | + if (!key) { |
| 218 | + console.warn('backlink: clearBacklink requires a key'); |
| 219 | + return; |
| 220 | + } |
| 221 | + |
| 222 | + const storageKey = STORAGE_PREFIX + key; |
| 223 | + safeStorageOperation(() => sessionStorage.removeItem(storageKey), 'clearBacklink'); |
| 224 | +} |
| 225 | + |
| 226 | +/* |
| 227 | + Consumes a backlink - retrieves it and immediately removes it from storage |
| 228 | + This is the most common pattern for "one-time" back navigation |
| 229 | + Returns null if the URL is not found or is not a safe internal path |
| 230 | + @param {string} key - The unique identifier for this backlink context |
| 231 | + @returns {string|null} The stored backlink URL, or null if not found/invalid |
| 232 | + */ |
| 233 | +export function consumeBacklink(key) { |
| 234 | + const url = getBacklink(key); |
| 235 | + if (url) { |
| 236 | + clearBacklink(key); |
| 237 | + } |
| 238 | + return url; |
| 239 | +} |
| 240 | + |
| 241 | +/* |
| 242 | + Consumes a backlink with full data - retrieves data and immediately removes it from storage |
| 243 | + Returns null if the URL is not found or is not a safe internal path |
| 244 | + @param {string} key - The unique identifier for this backlink context |
| 245 | + @returns {Object|null} The stored backlink data, or null if not found/invalid |
| 246 | + */ |
| 247 | +export function consumeBacklinkData(key) { |
| 248 | + const data = getBacklinkData(key); |
| 249 | + if (data) { |
| 250 | + clearBacklink(key); |
| 251 | + } |
| 252 | + return data; |
| 253 | +} |
| 254 | + |
| 255 | +/* |
| 256 | + Factory for creating backlink handlers with a fixed key |
| 257 | + Useful when multiple components share the same backlink context |
| 258 | + @param {string} key - The unique identifier for this backlink context |
| 259 | + @returns {Object} Object with set, setFromLocation, get, getData, clear, consume, and consumeData methods bound to the key |
| 260 | +*/ |
| 261 | +export function createBacklinkHandlers(key) { |
| 262 | + if (!key) { |
| 263 | + throw new Error('backlink: createBacklinkHandlers requires a key'); |
| 264 | + } |
| 265 | + return { |
| 266 | + set: (pathname, search, options) => setBacklink(key, pathname, search, options), |
| 267 | + setFromLocation: (location, searchParams, options) => setBacklinkFromLocation(key, location, searchParams, options), |
| 268 | + get: () => getBacklink(key), |
| 269 | + getData: () => getBacklinkData(key), |
| 270 | + clear: () => clearBacklink(key), |
| 271 | + consume: () => consumeBacklink(key), |
| 272 | + consumeData: () => consumeBacklinkData(key), |
| 273 | + key, |
| 274 | + }; |
| 275 | +} |
0 commit comments