@buoy-gg/impersonate 7.0.41 → 7.0.43

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.
Files changed (78) hide show
  1. package/README.md +12 -80
  2. package/lib/commonjs/impersonate/components/DataNukeSettings.js +8 -675
  3. package/lib/commonjs/impersonate/components/ImpersonateBanner.js +1 -221
  4. package/lib/commonjs/impersonate/components/ImpersonateHistoryList.js +1 -181
  5. package/lib/commonjs/impersonate/components/ImpersonateModal.js +1 -319
  6. package/lib/commonjs/impersonate/components/ImpersonateOverlay.js +1 -26
  7. package/lib/commonjs/impersonate/components/ImpersonateStatusBar.js +1 -130
  8. package/lib/commonjs/impersonate/components/UserAvatar.js +1 -146
  9. package/lib/commonjs/impersonate/components/UserCard.js +1 -201
  10. package/lib/commonjs/impersonate/components/UserSearchView.js +1 -227
  11. package/lib/commonjs/impersonate/hooks/asyncStoragePeer.js +1 -17
  12. package/lib/commonjs/impersonate/hooks/asyncStoragePeer.web.js +1 -11
  13. package/lib/commonjs/impersonate/hooks/useAutoClearAsyncStorage.js +1 -134
  14. package/lib/commonjs/impersonate/hooks/useAutoClearReactQuery.js +1 -155
  15. package/lib/commonjs/impersonate/hooks/useAutoClearReactQuery.web.js +1 -20
  16. package/lib/commonjs/impersonate/hooks/useAutoClearRedux.js +1 -188
  17. package/lib/commonjs/impersonate/hooks/useAutoClearRedux.web.js +1 -27
  18. package/lib/commonjs/impersonate/hooks/useImpersonate.js +1 -215
  19. package/lib/commonjs/impersonate/hooks/useImpersonateHistory.js +1 -56
  20. package/lib/commonjs/impersonate/types/index.js +1 -16
  21. package/lib/commonjs/impersonate/types/types.js +1 -1
  22. package/lib/commonjs/impersonate/utils/impersonateListener.js +1 -350
  23. package/lib/commonjs/impersonate/utils/impersonateStore.js +1 -689
  24. package/lib/commonjs/index.js +1 -150
  25. package/lib/commonjs/preset.js +1 -232
  26. package/lib/commonjs/sync/impersonateSyncAdapter.js +1 -170
  27. package/lib/module/impersonate/components/DataNukeSettings.js +8 -670
  28. package/lib/module/impersonate/components/ImpersonateBanner.js +1 -215
  29. package/lib/module/impersonate/components/ImpersonateHistoryList.js +1 -176
  30. package/lib/module/impersonate/components/ImpersonateModal.js +1 -314
  31. package/lib/module/impersonate/components/ImpersonateOverlay.js +1 -21
  32. package/lib/module/impersonate/components/ImpersonateStatusBar.js +1 -125
  33. package/lib/module/impersonate/components/UserAvatar.js +1 -140
  34. package/lib/module/impersonate/components/UserCard.js +1 -196
  35. package/lib/module/impersonate/components/UserSearchView.js +1 -222
  36. package/lib/module/impersonate/hooks/asyncStoragePeer.js +1 -13
  37. package/lib/module/impersonate/hooks/asyncStoragePeer.web.js +1 -6
  38. package/lib/module/impersonate/hooks/useAutoClearAsyncStorage.js +1 -130
  39. package/lib/module/impersonate/hooks/useAutoClearReactQuery.js +1 -151
  40. package/lib/module/impersonate/hooks/useAutoClearReactQuery.web.js +1 -16
  41. package/lib/module/impersonate/hooks/useAutoClearRedux.js +1 -183
  42. package/lib/module/impersonate/hooks/useAutoClearRedux.web.js +1 -22
  43. package/lib/module/impersonate/hooks/useImpersonate.js +1 -212
  44. package/lib/module/impersonate/hooks/useImpersonateHistory.js +1 -52
  45. package/lib/module/impersonate/types/index.js +1 -3
  46. package/lib/module/impersonate/types/types.js +1 -1
  47. package/lib/module/impersonate/utils/impersonateListener.js +1 -341
  48. package/lib/module/impersonate/utils/impersonateStore.js +1 -686
  49. package/lib/module/index.js +1 -117
  50. package/lib/module/preset.js +1 -216
  51. package/lib/module/sync/impersonateSyncAdapter.js +1 -162
  52. package/lib/web/index.mjs +7 -8
  53. package/package.json +3 -6
  54. package/lib/typescript/impersonate/components/DataNukeSettings.d.ts.map +0 -1
  55. package/lib/typescript/impersonate/components/ImpersonateBanner.d.ts.map +0 -1
  56. package/lib/typescript/impersonate/components/ImpersonateHistoryList.d.ts.map +0 -1
  57. package/lib/typescript/impersonate/components/ImpersonateModal.d.ts.map +0 -1
  58. package/lib/typescript/impersonate/components/ImpersonateOverlay.d.ts.map +0 -1
  59. package/lib/typescript/impersonate/components/ImpersonateStatusBar.d.ts.map +0 -1
  60. package/lib/typescript/impersonate/components/UserAvatar.d.ts.map +0 -1
  61. package/lib/typescript/impersonate/components/UserCard.d.ts.map +0 -1
  62. package/lib/typescript/impersonate/components/UserSearchView.d.ts.map +0 -1
  63. package/lib/typescript/impersonate/hooks/asyncStoragePeer.d.ts.map +0 -1
  64. package/lib/typescript/impersonate/hooks/asyncStoragePeer.web.d.ts.map +0 -1
  65. package/lib/typescript/impersonate/hooks/useAutoClearAsyncStorage.d.ts.map +0 -1
  66. package/lib/typescript/impersonate/hooks/useAutoClearReactQuery.d.ts.map +0 -1
  67. package/lib/typescript/impersonate/hooks/useAutoClearReactQuery.web.d.ts.map +0 -1
  68. package/lib/typescript/impersonate/hooks/useAutoClearRedux.d.ts.map +0 -1
  69. package/lib/typescript/impersonate/hooks/useAutoClearRedux.web.d.ts.map +0 -1
  70. package/lib/typescript/impersonate/hooks/useImpersonate.d.ts.map +0 -1
  71. package/lib/typescript/impersonate/hooks/useImpersonateHistory.d.ts.map +0 -1
  72. package/lib/typescript/impersonate/types/index.d.ts.map +0 -1
  73. package/lib/typescript/impersonate/types/types.d.ts.map +0 -1
  74. package/lib/typescript/impersonate/utils/impersonateListener.d.ts.map +0 -1
  75. package/lib/typescript/impersonate/utils/impersonateStore.d.ts.map +0 -1
  76. package/lib/typescript/index.d.ts.map +0 -1
  77. package/lib/typescript/preset.d.ts.map +0 -1
  78. package/lib/typescript/sync/impersonateSyncAdapter.d.ts.map +0 -1
@@ -1,686 +1 @@
1
- "use strict";
2
-
3
- import { assertAccountAccess, getAccountAccess, hasAccountAccess, subscribeAccountAccess } from "@buoy-gg/shared-ui";
4
- /**
5
- * Impersonate Store - State Management with Persistence
6
- *
7
- * Singleton store for managing impersonation state. Uses a subscription
8
- * pattern compatible with React's useSyncExternalStore.
9
- */
10
-
11
- import { impersonateListener, setImpersonateConfig } from "./impersonateListener";
12
-
13
- // =============================================================================
14
- // CONSTANTS
15
- // =============================================================================
16
-
17
- const STORAGE_KEY = "@buoy/impersonate/state";
18
- const MAX_HISTORY = 10;
19
- const DEFAULT_DATA_NUKE_SETTINGS = {
20
- reactQuery: true,
21
- redux: true,
22
- asyncStorage: false,
23
- // Dangerous - default off
24
- mmkv: false // Dangerous - default off
25
- };
26
- const DEFAULT_STATE = {
27
- isActive: false,
28
- isPaused: false,
29
- currentUser: null,
30
- headerKey: "x-impersonate-user-id",
31
- ignorePatterns: [],
32
- dataNukeSettings: DEFAULT_DATA_NUKE_SETTINGS,
33
- showBanner: true,
34
- history: []
35
- };
36
-
37
- // =============================================================================
38
- // TYPES
39
- // =============================================================================
40
-
41
- // Guard to prevent double-execution of data nuking
42
- let isNuking = false;
43
-
44
- // =============================================================================
45
- // SIMPLE STORAGE ABSTRACTION
46
- // =============================================================================
47
-
48
- // Use a simple localStorage-like interface for persistence
49
- // This works on both web and native (via polyfills)
50
- const storage = {
51
- getItem: key => {
52
- try {
53
- if (typeof localStorage !== "undefined") {
54
- return localStorage.getItem(key);
55
- }
56
- // React Native: use AsyncStorage if available
57
- // For now, return null (state won't persist until async storage is loaded)
58
- return null;
59
- } catch {
60
- return null;
61
- }
62
- },
63
- setItem: (key, value) => {
64
- try {
65
- if (typeof localStorage !== "undefined") {
66
- localStorage.setItem(key, value);
67
- }
68
- // React Native: handled separately via async methods
69
- } catch {
70
- // Ignore storage errors
71
- }
72
- },
73
- removeItem: key => {
74
- try {
75
- if (typeof localStorage !== "undefined") {
76
- localStorage.removeItem(key);
77
- }
78
- } catch {
79
- // Ignore
80
- }
81
- }
82
- };
83
-
84
- // =============================================================================
85
- // STORE CLASS
86
- // =============================================================================
87
-
88
- /**
89
- * Singleton store for impersonation state
90
- *
91
- * Features:
92
- * - Subscription pattern for React integration
93
- * - Persistence of settings and history
94
- * - Data nuking on impersonation change
95
- * - Automatic sync with impersonateListener
96
- */
97
- class ImpersonateStore {
98
- state = {
99
- ...DEFAULT_STATE
100
- };
101
- listeners = new Set();
102
- nukeCallbacks = {};
103
- isInitialized = false;
104
- asyncStorageRef = null;
105
- storageReadyPromise = null;
106
- resolveStorageReady = null;
107
- developerDefaults = null;
108
- constructor() {
109
- // Try to load persisted state synchronously
110
- this.loadFromStorage();
111
- Promise.resolve().then(() => {
112
- // Only a sign-out ends the session: access that was admitted and is now
113
- // locked. The license reports "locked" for a moment while it boots or
114
- // reloads, before validation starts, and ending the session then wiped a
115
- // restored impersonation for good. The per-request gate already keeps
116
- // the header off whenever access isn't admitted.
117
- let wasAdmitted = false;
118
- const reconcile = () => {
119
- const status = getAccountAccess().status;
120
- if (status === "admitted") wasAdmitted = true;else if (status === "locked" && wasAdmitted) {
121
- wasAdmitted = false;
122
- this.disposeAccountSession();
123
- }
124
- };
125
- subscribeAccountAccess(reconcile);
126
- reconcile();
127
- });
128
-
129
- // Check if localStorage is available (web) - if so, storage is ready
130
- if (typeof localStorage !== "undefined") {
131
- this.storageReadyPromise = Promise.resolve();
132
- } else {
133
- // React Native - wait for AsyncStorage to be set up
134
- this.storageReadyPromise = new Promise(resolve => {
135
- this.resolveStorageReady = resolve;
136
- });
137
- }
138
- }
139
-
140
- // ===========================================================================
141
- // INITIALIZATION
142
- // ===========================================================================
143
-
144
- /**
145
- * Load persisted state from storage (sync)
146
- */
147
- loadFromStorage() {
148
- try {
149
- const stored = storage.getItem(STORAGE_KEY);
150
- const effectiveDefaults = this.getEffectiveDefaults();
151
- if (stored) {
152
- const parsed = JSON.parse(stored);
153
- this.state = {
154
- ...DEFAULT_STATE,
155
- // Use effective defaults (developer > hardcoded) as fallback
156
- headerKey: parsed.headerKey ?? effectiveDefaults.headerKey,
157
- ignorePatterns: parsed.ignorePatterns ?? DEFAULT_STATE.ignorePatterns,
158
- dataNukeSettings: {
159
- ...effectiveDefaults.dataNukeSettings,
160
- ...parsed.dataNukeSettings
161
- },
162
- showBanner: parsed.showBanner ?? effectiveDefaults.showBanner,
163
- history: parsed.history ?? [],
164
- // Restore active session for persistence across reloads
165
- isActive: parsed.isActive ?? false,
166
- isPaused: parsed.isPaused ?? false,
167
- currentUser: parsed.currentUser ?? null
168
- };
169
-
170
- // If we restored an active session, sync with listener
171
- if (this.state.isActive && this.state.currentUser) {
172
- this.syncWithListener();
173
- }
174
- } else {
175
- // No persisted state - use effective defaults
176
- this.state = {
177
- ...DEFAULT_STATE,
178
- headerKey: effectiveDefaults.headerKey,
179
- dataNukeSettings: effectiveDefaults.dataNukeSettings,
180
- showBanner: effectiveDefaults.showBanner
181
- };
182
- }
183
- this.isInitialized = true;
184
- } catch {
185
- this.isInitialized = true;
186
- }
187
- }
188
-
189
- /**
190
- * Set async storage reference for persistence (call before initializeAsync)
191
- * This ensures all writes use AsyncStorage even before load completes
192
- */
193
- setAsyncStorage(asyncStorage) {
194
- this.asyncStorageRef = asyncStorage;
195
- // Resolve the storage ready promise so persist() can proceed
196
- if (this.resolveStorageReady) {
197
- this.resolveStorageReady();
198
- this.resolveStorageReady = null;
199
- }
200
- }
201
-
202
- /**
203
- * Set developer-provided defaults
204
- * These override hardcoded defaults but are overridden by persisted values
205
- * Call this before the component mounts (in createImpersonateTool)
206
- */
207
- setDeveloperDefaults(defaults) {
208
- this.developerDefaults = defaults;
209
-
210
- // Apply defaults to current state if not already initialized from storage
211
- // Priority: persisted > developer defaults > hardcoded defaults
212
- const effectiveDefaults = this.getEffectiveDefaults();
213
-
214
- // Only apply if we haven't loaded persisted values yet
215
- if (!this.isInitialized) {
216
- this.state = {
217
- ...this.state,
218
- headerKey: effectiveDefaults.headerKey,
219
- dataNukeSettings: effectiveDefaults.dataNukeSettings,
220
- showBanner: effectiveDefaults.showBanner
221
- };
222
- }
223
- }
224
-
225
- /**
226
- * Get effective defaults (developer defaults merged with hardcoded defaults)
227
- */
228
- getEffectiveDefaults() {
229
- return {
230
- headerKey: this.developerDefaults?.headerKey ?? DEFAULT_STATE.headerKey,
231
- dataNukeSettings: {
232
- ...DEFAULT_DATA_NUKE_SETTINGS,
233
- ...this.developerDefaults?.dataNukeSettings
234
- },
235
- showBanner: this.developerDefaults?.showBanner ?? DEFAULT_STATE.showBanner
236
- };
237
- }
238
-
239
- /**
240
- * Get developer defaults (for use in UI to show what the "default" values are)
241
- */
242
- getDeveloperDefaults() {
243
- return this.developerDefaults;
244
- }
245
-
246
- /**
247
- * Initialize with async storage (for React Native)
248
- * Call this in useEffect to load from AsyncStorage
249
- */
250
- async initializeAsync(asyncStorage) {
251
- if (!asyncStorage) return;
252
-
253
- // Store reference for future persistence (in case not already set)
254
- this.asyncStorageRef = asyncStorage;
255
- try {
256
- const stored = await asyncStorage.getItem(STORAGE_KEY);
257
- // eslint-disable-next-line no-console
258
- console.log(`[impersonate] initializeAsync read STORAGE_KEY=${STORAGE_KEY} stored=${stored ? stored.slice(0, 200) : "null"}`);
259
- if (stored) {
260
- const parsed = JSON.parse(stored);
261
- this.state = {
262
- ...this.state,
263
- headerKey: parsed.headerKey ?? this.state.headerKey,
264
- ignorePatterns: parsed.ignorePatterns ?? this.state.ignorePatterns,
265
- dataNukeSettings: {
266
- ...this.state.dataNukeSettings,
267
- ...parsed.dataNukeSettings
268
- },
269
- showBanner: parsed.showBanner ?? this.state.showBanner,
270
- history: parsed.history ?? this.state.history,
271
- // Restore active session
272
- isActive: parsed.isActive ?? this.state.isActive,
273
- isPaused: parsed.isPaused ?? this.state.isPaused,
274
- currentUser: parsed.currentUser ?? this.state.currentUser
275
- };
276
-
277
- // If we restored an active session, sync with listener
278
- if (this.state.isActive && this.state.currentUser) {
279
- this.syncWithListener();
280
- }
281
- this.notify();
282
- }
283
- } catch {
284
- // Persisted blob unreadable — fall through with in-memory defaults.
285
- }
286
- }
287
-
288
- /**
289
- * Register callbacks for data nuking
290
- */
291
- registerNukeCallbacks(callbacks) {
292
- this.nukeCallbacks = {
293
- ...this.nukeCallbacks,
294
- ...callbacks
295
- };
296
- }
297
-
298
- // ===========================================================================
299
- // STATE ACCESS
300
- // ===========================================================================
301
-
302
- /**
303
- * Get current state (creates a copy)
304
- */
305
- getState() {
306
- return {
307
- ...this.state
308
- };
309
- }
310
-
311
- /**
312
- * Get snapshot for useSyncExternalStore
313
- * Returns the same reference if state hasn't changed
314
- */
315
- getSnapshot = () => {
316
- return this.state;
317
- };
318
-
319
- /**
320
- * Subscribe to state changes
321
- * Returns unsubscribe function
322
- */
323
- subscribe = listener => {
324
- this.listeners.add(listener);
325
- return () => this.listeners.delete(listener);
326
- };
327
-
328
- // ===========================================================================
329
- // REMOTE MIRROR MODE
330
- // ===========================================================================
331
-
332
- remoteHandler = null;
333
-
334
- /**
335
- * Remote mirror mode (desktop dashboard): while a handler is set, every
336
- * mutation forwards (method, params) to the synced device instead of
337
- * running locally — header patching, data nuking and persistence all
338
- * happen on the device, and the resulting state comes back via
339
- * replaceState(). Pass null to restore local behavior.
340
- */
341
- setRemoteHandler(handler) {
342
- this.remoteHandler = handler;
343
- }
344
-
345
- /**
346
- * Replace the mirrored state from a synced device snapshot. Does not
347
- * persist or touch the fetch listener — the device owns both.
348
- */
349
- replaceState(state) {
350
- this.state = state;
351
- this.notify();
352
- }
353
-
354
- // ===========================================================================
355
- // IMPERSONATION ACTIONS
356
- // ===========================================================================
357
-
358
- /**
359
- * Start impersonating a user.
360
- *
361
- * Order matters: we update state + listener + UI BEFORE clearing caches,
362
- * so refetches triggered by the cache clear go out with the new user's
363
- * impersonation header. Doing it the other way around (nuke first) makes
364
- * react-query refetch active queries with the OLD identity, producing
365
- * the visual symptom of "I clicked a user and nothing changed."
366
- */
367
- async startImpersonation(user) {
368
- assertAccountAccess();
369
- if (this.remoteHandler) {
370
- this.remoteHandler("startImpersonation", {
371
- user
372
- });
373
- return;
374
- }
375
- const historyEntry = {
376
- user,
377
- lastUsedAt: new Date().toISOString()
378
- };
379
- const newHistory = [historyEntry, ...this.state.history.filter(entry => entry.user.id !== user.id)].slice(0, MAX_HISTORY);
380
- this.state = {
381
- ...this.state,
382
- isActive: true,
383
- currentUser: user,
384
- history: newHistory
385
- };
386
-
387
- // 1) Point the fetch interceptor at the new user. Any request after this
388
- // line carries the new header.
389
- this.syncWithListener();
390
-
391
- // 2) Tell React subscribers right away so the UI updates without waiting
392
- // on AsyncStorage / data nuke.
393
- this.notify();
394
-
395
- // 3) Nuke caches — refetches now use the new identity.
396
- await this.executeDataNuke();
397
-
398
- // 4) Persist for next launch.
399
- await this.persist();
400
- }
401
-
402
- /**
403
- * Stop impersonating.
404
- *
405
- * Same ordering rationale as startImpersonation: clear state + listener
406
- * before nuking caches so subsequent refetches go out without the header.
407
- */
408
- async stopImpersonation() {
409
- if (this.remoteHandler) {
410
- this.remoteHandler("stopImpersonation");
411
- return;
412
- }
413
- // eslint-disable-next-line no-console
414
- console.log(`[impersonate] stopImpersonation: isActive ${this.state.isActive} -> false, listeners=${this.listeners.size}`);
415
- this.state = {
416
- ...this.state,
417
- isActive: false,
418
- isPaused: false,
419
- currentUser: null
420
- };
421
- this.syncWithListener();
422
- this.notify();
423
- await this.executeDataNuke();
424
- await this.persist();
425
- }
426
-
427
- /**
428
- * Pause impersonation (temporarily stop injecting headers)
429
- */
430
- async pauseImpersonation() {
431
- if (this.remoteHandler) {
432
- this.remoteHandler("pauseImpersonation");
433
- return;
434
- }
435
- if (!this.state.isActive || this.state.isPaused) return;
436
- this.state = {
437
- ...this.state,
438
- isPaused: true
439
- };
440
-
441
- // Sync with listener (will stop injecting headers)
442
- this.syncWithListener();
443
-
444
- // Persist
445
- await this.persist();
446
-
447
- // Notify
448
- this.notify();
449
- }
450
-
451
- /**
452
- * Resume impersonation (start injecting headers again)
453
- */
454
- async resumeImpersonation() {
455
- assertAccountAccess();
456
- if (this.remoteHandler) {
457
- this.remoteHandler("resumeImpersonation");
458
- return;
459
- }
460
- if (!this.state.isActive || !this.state.isPaused) return;
461
- this.state = {
462
- ...this.state,
463
- isPaused: false
464
- };
465
-
466
- // Sync with listener (will resume injecting headers)
467
- this.syncWithListener();
468
-
469
- // Persist
470
- await this.persist();
471
-
472
- // Notify
473
- this.notify();
474
- }
475
-
476
- /**
477
- * Quick switch to a user from history
478
- */
479
- async quickSwitch(user) {
480
- return this.startImpersonation(user);
481
- }
482
-
483
- // ===========================================================================
484
- // SETTINGS
485
- // ===========================================================================
486
-
487
- /**
488
- * Update settings (header key, ignore patterns, data nuke settings, show banner)
489
- */
490
- async updateSettings(settings) {
491
- if (this.remoteHandler) {
492
- this.remoteHandler("updateSettings", {
493
- settings
494
- });
495
- return;
496
- }
497
- this.state = {
498
- ...this.state,
499
- headerKey: settings.headerKey ?? this.state.headerKey,
500
- ignorePatterns: settings.ignorePatterns ?? this.state.ignorePatterns,
501
- showBanner: settings.showBanner ?? this.state.showBanner,
502
- dataNukeSettings: settings.dataNukeSettings ? {
503
- ...this.state.dataNukeSettings,
504
- ...settings.dataNukeSettings
505
- } : this.state.dataNukeSettings
506
- };
507
-
508
- // Sync header key with listener
509
- if (settings.headerKey || settings.ignorePatterns) {
510
- this.syncWithListener();
511
- }
512
- await this.persist();
513
- this.notify();
514
- }
515
-
516
- // ===========================================================================
517
- // HISTORY
518
- // ===========================================================================
519
-
520
- /**
521
- * Remove a user from history
522
- */
523
- async removeFromHistory(userId) {
524
- if (this.remoteHandler) {
525
- this.remoteHandler("removeFromHistory", {
526
- userId
527
- });
528
- return;
529
- }
530
- this.state = {
531
- ...this.state,
532
- history: this.state.history.filter(entry => entry.user.id !== userId)
533
- };
534
- await this.persist();
535
- this.notify();
536
- }
537
-
538
- /**
539
- * Clear all history
540
- */
541
- async clearHistory() {
542
- if (this.remoteHandler) {
543
- this.remoteHandler("clearHistory");
544
- return;
545
- }
546
- this.state = {
547
- ...this.state,
548
- history: []
549
- };
550
- await this.persist();
551
- this.notify();
552
- }
553
-
554
- // ===========================================================================
555
- // PRIVATE METHODS
556
- // ===========================================================================
557
-
558
- /**
559
- * Execute data nuking based on current settings
560
- */
561
- async executeDataNuke() {
562
- // Guard against double-execution (can happen with React Strict Mode)
563
- if (isNuking) {
564
- return;
565
- }
566
- isNuking = true;
567
- try {
568
- const {
569
- dataNukeSettings
570
- } = this.state;
571
- const promises = [];
572
- if (dataNukeSettings.reactQuery && this.nukeCallbacks.reactQuery) {
573
- promises.push(Promise.resolve(this.nukeCallbacks.reactQuery()));
574
- }
575
- if (dataNukeSettings.redux && this.nukeCallbacks.redux) {
576
- promises.push(Promise.resolve(this.nukeCallbacks.redux()));
577
- }
578
- if (dataNukeSettings.asyncStorage && this.nukeCallbacks.asyncStorage) {
579
- promises.push(Promise.resolve(this.nukeCallbacks.asyncStorage()));
580
- }
581
- if (dataNukeSettings.mmkv && this.nukeCallbacks.mmkv) {
582
- promises.push(Promise.resolve(this.nukeCallbacks.mmkv()));
583
- }
584
-
585
- // Wait for all, but don't fail if some error
586
- await Promise.allSettled(promises);
587
- } finally {
588
- // Reset flag after a short delay to allow next legitimate call
589
- setTimeout(() => {
590
- isNuking = false;
591
- }, 100);
592
- }
593
- }
594
-
595
- /**
596
- * Sync current state with the impersonateListener
597
- */
598
- /** Remove only the active header override. Sign-out must not nuke host caches. */
599
- disposeAccountSession() {
600
- if (this.remoteHandler || !this.state.isActive) return;
601
- this.state = {
602
- ...this.state,
603
- isActive: false,
604
- isPaused: false,
605
- currentUser: null
606
- };
607
- this.syncWithListener();
608
- this.notify();
609
- void this.persist();
610
- }
611
- syncWithListener() {
612
- // When paused, don't inject headers (pass null userId). Account access is
613
- // checked per request by the gate, not here: a session restored at launch
614
- // syncs before the account check finishes, and reading it once here sent
615
- // no header for the rest of the run, until a pause and resume re-synced.
616
- const shouldInject = this.state.isActive && !this.state.isPaused;
617
- setImpersonateConfig({
618
- headerKey: this.state.headerKey,
619
- userId: shouldInject ? this.state.currentUser?.id ?? null : null,
620
- ignorePatterns: this.state.ignorePatterns.map(p => new RegExp(p)),
621
- gate: hasAccountAccess
622
- });
623
-
624
- // Ensure listener is started
625
- if (!impersonateListener().isListening) {
626
- impersonateListener().startListening();
627
- }
628
- }
629
-
630
- /**
631
- * Persist state to storage
632
- */
633
- async persist() {
634
- // Wait for storage to be ready (AsyncStorage setup on React Native)
635
- if (this.storageReadyPromise) {
636
- await this.storageReadyPromise;
637
- }
638
- const toStore = {
639
- headerKey: this.state.headerKey,
640
- ignorePatterns: this.state.ignorePatterns,
641
- dataNukeSettings: this.state.dataNukeSettings,
642
- showBanner: this.state.showBanner,
643
- history: this.state.history,
644
- // Persist active session for continuity across reloads
645
- isActive: this.state.isActive,
646
- isPaused: this.state.isPaused,
647
- currentUser: this.state.currentUser
648
- };
649
- const serialized = JSON.stringify(toStore);
650
- try {
651
- // Prefer AsyncStorage for React Native
652
- if (this.asyncStorageRef) {
653
- await this.asyncStorageRef.setItem(STORAGE_KEY, serialized);
654
- // eslint-disable-next-line no-console
655
- console.log(`[impersonate] persist -> AsyncStorage isActive=${toStore.isActive} userId=${toStore.currentUser?.id ?? "null"}`);
656
- } else {
657
- // Fall back to localStorage (web)
658
- storage.setItem(STORAGE_KEY, serialized);
659
- // eslint-disable-next-line no-console
660
- console.log(`[impersonate] persist -> localStorage isActive=${toStore.isActive} userId=${toStore.currentUser?.id ?? "null"}`);
661
- }
662
- } catch (e) {
663
- // eslint-disable-next-line no-console
664
- console.warn("[impersonate] persist failed", e);
665
- }
666
- }
667
-
668
- /**
669
- * Notify all listeners of state change
670
- */
671
- notify() {
672
- this.listeners.forEach(listener => {
673
- try {
674
- listener(this.state);
675
- } catch {
676
- // Ignore listener errors
677
- }
678
- });
679
- }
680
- }
681
-
682
- // =============================================================================
683
- // SINGLETON EXPORT
684
- // =============================================================================
685
-
686
- export const impersonateStore = new ImpersonateStore();
1
+ "use strict";import{assertAccountAccess as o,getAccountAccess as d,hasAccountAccess as y,subscribeAccountAccess as f}from"@buoy-gg/shared-ui";import{impersonateListener as h,setImpersonateConfig as m}from"./impersonateListener";const r="@buoy/impersonate/state";const g=10;const l={reactQuery:true,redux:true,asyncStorage:false,mmkv:false};const a={isActive:false,isPaused:false,currentUser:null,headerKey:"x-impersonate-user-id",ignorePatterns:[],dataNukeSettings:l,showBanner:true,history:[]};let n=false;const c={getItem:i=>{try{if(typeof localStorage!=="undefined"){return localStorage.getItem(i)}return null}catch{return null}},setItem:(i,e)=>{try{if(typeof localStorage!=="undefined"){localStorage.setItem(i,e)}}catch{}},removeItem:i=>{try{if(typeof localStorage!=="undefined"){localStorage.removeItem(i)}}catch{}}};class p{state={...a};listeners=new Set;nukeCallbacks={};isInitialized=false;asyncStorageRef=null;storageReadyPromise=null;resolveStorageReady=null;developerDefaults=null;constructor(){this.loadFromStorage();Promise.resolve().then(()=>{let e=false;const t=()=>{const s=d().status;if(s==="admitted")e=true;else if(s==="locked"&&e){e=false;this.disposeAccountSession()}};f(t);t()});if(typeof localStorage!=="undefined"){this.storageReadyPromise=Promise.resolve()}else{this.storageReadyPromise=new Promise(e=>{this.resolveStorageReady=e})}}loadFromStorage(){try{const e=c.getItem(r);const t=this.getEffectiveDefaults();if(e){const s=JSON.parse(e);this.state={...a,headerKey:s.headerKey??t.headerKey,ignorePatterns:s.ignorePatterns??a.ignorePatterns,dataNukeSettings:{...t.dataNukeSettings,...s.dataNukeSettings},showBanner:s.showBanner??t.showBanner,history:s.history??[],isActive:s.isActive??false,isPaused:s.isPaused??false,currentUser:s.currentUser??null};if(this.state.isActive&&this.state.currentUser){this.syncWithListener()}}else{this.state={...a,headerKey:t.headerKey,dataNukeSettings:t.dataNukeSettings,showBanner:t.showBanner}}this.isInitialized=true}catch{this.isInitialized=true}}setAsyncStorage(e){this.asyncStorageRef=e;if(this.resolveStorageReady){this.resolveStorageReady();this.resolveStorageReady=null}}setDeveloperDefaults(e){this.developerDefaults=e;const t=this.getEffectiveDefaults();if(!this.isInitialized){this.state={...this.state,headerKey:t.headerKey,dataNukeSettings:t.dataNukeSettings,showBanner:t.showBanner}}}getEffectiveDefaults(){return{headerKey:this.developerDefaults?.headerKey??a.headerKey,dataNukeSettings:{...l,...this.developerDefaults?.dataNukeSettings},showBanner:this.developerDefaults?.showBanner??a.showBanner}}getDeveloperDefaults(){return this.developerDefaults}async initializeAsync(e){if(!e)return;this.asyncStorageRef=e;try{const t=await e.getItem(r);console.log(`[impersonate] initializeAsync read STORAGE_KEY=${r} stored=${t?t.slice(0,200):"null"}`);if(t){const s=JSON.parse(t);this.state={...this.state,headerKey:s.headerKey??this.state.headerKey,ignorePatterns:s.ignorePatterns??this.state.ignorePatterns,dataNukeSettings:{...this.state.dataNukeSettings,...s.dataNukeSettings},showBanner:s.showBanner??this.state.showBanner,history:s.history??this.state.history,isActive:s.isActive??this.state.isActive,isPaused:s.isPaused??this.state.isPaused,currentUser:s.currentUser??this.state.currentUser};if(this.state.isActive&&this.state.currentUser){this.syncWithListener()}this.notify()}}catch{}}registerNukeCallbacks(e){this.nukeCallbacks={...this.nukeCallbacks,...e}}getState(){return{...this.state}}getSnapshot=()=>{return this.state};subscribe=e=>{this.listeners.add(e);return()=>this.listeners.delete(e)};remoteHandler=null;setRemoteHandler(e){this.remoteHandler=e}replaceState(e){this.state=e;this.notify()}async startImpersonation(e){o();if(this.remoteHandler){this.remoteHandler("startImpersonation",{user:e});return}const t={user:e,lastUsedAt:new Date().toISOString()};const s=[t,...this.state.history.filter(u=>u.user.id!==e.id)].slice(0,g);this.state={...this.state,isActive:true,currentUser:e,history:s};this.syncWithListener();this.notify();await this.executeDataNuke();await this.persist()}async stopImpersonation(){if(this.remoteHandler){this.remoteHandler("stopImpersonation");return}console.log(`[impersonate] stopImpersonation: isActive ${this.state.isActive} -> false, listeners=${this.listeners.size}`);this.state={...this.state,isActive:false,isPaused:false,currentUser:null};this.syncWithListener();this.notify();await this.executeDataNuke();await this.persist()}async pauseImpersonation(){if(this.remoteHandler){this.remoteHandler("pauseImpersonation");return}if(!this.state.isActive||this.state.isPaused)return;this.state={...this.state,isPaused:true};this.syncWithListener();await this.persist();this.notify()}async resumeImpersonation(){o();if(this.remoteHandler){this.remoteHandler("resumeImpersonation");return}if(!this.state.isActive||!this.state.isPaused)return;this.state={...this.state,isPaused:false};this.syncWithListener();await this.persist();this.notify()}async quickSwitch(e){return this.startImpersonation(e)}async updateSettings(e){if(this.remoteHandler){this.remoteHandler("updateSettings",{settings:e});return}this.state={...this.state,headerKey:e.headerKey??this.state.headerKey,ignorePatterns:e.ignorePatterns??this.state.ignorePatterns,showBanner:e.showBanner??this.state.showBanner,dataNukeSettings:e.dataNukeSettings?{...this.state.dataNukeSettings,...e.dataNukeSettings}:this.state.dataNukeSettings};if(e.headerKey||e.ignorePatterns){this.syncWithListener()}await this.persist();this.notify()}async removeFromHistory(e){if(this.remoteHandler){this.remoteHandler("removeFromHistory",{userId:e});return}this.state={...this.state,history:this.state.history.filter(t=>t.user.id!==e)};await this.persist();this.notify()}async clearHistory(){if(this.remoteHandler){this.remoteHandler("clearHistory");return}this.state={...this.state,history:[]};await this.persist();this.notify()}async executeDataNuke(){if(n){return}n=true;try{const{dataNukeSettings:e}=this.state;const t=[];if(e.reactQuery&&this.nukeCallbacks.reactQuery){t.push(Promise.resolve(this.nukeCallbacks.reactQuery()))}if(e.redux&&this.nukeCallbacks.redux){t.push(Promise.resolve(this.nukeCallbacks.redux()))}if(e.asyncStorage&&this.nukeCallbacks.asyncStorage){t.push(Promise.resolve(this.nukeCallbacks.asyncStorage()))}if(e.mmkv&&this.nukeCallbacks.mmkv){t.push(Promise.resolve(this.nukeCallbacks.mmkv()))}await Promise.allSettled(t)}finally{setTimeout(()=>{n=false},100)}}disposeAccountSession(){if(this.remoteHandler||!this.state.isActive)return;this.state={...this.state,isActive:false,isPaused:false,currentUser:null};this.syncWithListener();this.notify();void this.persist()}syncWithListener(){const e=this.state.isActive&&!this.state.isPaused;m({headerKey:this.state.headerKey,userId:e?this.state.currentUser?.id??null:null,ignorePatterns:this.state.ignorePatterns.map(t=>new RegExp(t)),gate:y});if(!h().isListening){h().startListening()}}async persist(){if(this.storageReadyPromise){await this.storageReadyPromise}const e={headerKey:this.state.headerKey,ignorePatterns:this.state.ignorePatterns,dataNukeSettings:this.state.dataNukeSettings,showBanner:this.state.showBanner,history:this.state.history,isActive:this.state.isActive,isPaused:this.state.isPaused,currentUser:this.state.currentUser};const t=JSON.stringify(e);try{if(this.asyncStorageRef){await this.asyncStorageRef.setItem(r,t);console.log(`[impersonate] persist -> AsyncStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`)}else{c.setItem(r,t);console.log(`[impersonate] persist -> localStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`)}}catch(s){console.warn("[impersonate] persist failed",s)}}notify(){this.listeners.forEach(e=>{try{e(this.state)}catch{}})}}export const impersonateStore=new p;