-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
377 lines (339 loc) · 15.6 KB
/
App.tsx
File metadata and controls
377 lines (339 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import { AblyCliTerminal, type AblyCliTerminalHandle } from "@ably/react-web-cli";
import { useCallback, useEffect, useRef, useState } from "react";
import { Key, Settings, Shield } from "lucide-react";
import "./App.css";
import { CliDrawer } from "./components/CliDrawer";
import { AuthSettings } from "./components/AuthSettings";
import { AuthScreen } from "./components/AuthScreen";
// Extend Window interface for CLI-specific properties
interface CliWindow extends Window {
__ABLY_CLI_CI_AUTH_TOKEN__?: string;
_sessionId?: string;
}
// Default WebSocket URL - use public endpoint for production, localhost for development
const DEFAULT_WEBSOCKET_URL = "wss://web-cli.ably.com";
// Get WebSocket URL from query parameters only
const getWebSocketUrl = () => {
const urlParams = new URLSearchParams(window.location.search);
const serverParam = urlParams.get("serverUrl");
if (serverParam) {
console.log(`[App.tsx] Found serverUrl param: ${serverParam}`);
return serverParam;
}
return DEFAULT_WEBSOCKET_URL;
};
// Get CI auth token if available
const getCIAuthToken = (): string | undefined => {
return (window as CliWindow).__ABLY_CLI_CI_AUTH_TOKEN__;
};
// Get signed credentials from various sources
const getInitialCredentials = () => {
const urlParams = new URLSearchParams(window.location.search);
// Get the domain from the WebSocket URL for scoping
const wsUrl = getWebSocketUrl();
const wsDomain = new URL(wsUrl).host;
// Check if we should clear credentials (for testing)
if (urlParams.get('clearCredentials') === 'true') {
// Clear new signed format
localStorage.removeItem(`ably.web-cli.signedConfig.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.signature.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.rememberCredentials.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.signedConfig.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.signature.${wsDomain}`);
// Also clear old format (migration)
localStorage.removeItem(`ably.web-cli.apiKey.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.accessToken.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.apiKey.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.accessToken.${wsDomain}`);
// Remove the clearCredentials param from URL
const cleanUrl = new URL(window.location.href);
cleanUrl.searchParams.delete('clearCredentials');
window.history.replaceState(null, '', cleanUrl.toString());
}
// Check query parameters (only in development/test environments)
const qsSignedConfig = urlParams.get('signedConfig');
const qsSignature = urlParams.get('signature');
if (qsSignedConfig && qsSignature) {
// Security check: only allow query param auth in development/test environments
const isProduction = import.meta.env.PROD &&
!window.location.hostname.includes('localhost') &&
!window.location.hostname.includes('127.0.0.1');
if (isProduction) {
console.error('[App] Security Warning: Signed credentials in query parameters are not allowed in production.');
console.error('[App] Credentials contain API keys that can leak through browser history, server logs, and shared URLs.');
// Clear the sensitive query parameters from the URL
const cleanUrl = new URL(window.location.href);
cleanUrl.searchParams.delete('signedConfig');
cleanUrl.searchParams.delete('signature');
cleanUrl.searchParams.delete('clearCredentials');
window.history.replaceState(null, '', cleanUrl.toString());
// Don't use these credentials - fall through to storage check
} else {
console.log('[App] Using signed config from query parameters (dev/test mode)');
return {
signedConfig: qsSignedConfig,
signature: qsSignature,
source: 'query' as const
};
}
}
// Check localStorage for persisted signed credentials (if user chose to remember)
const rememberCredentials = localStorage.getItem(`ably.web-cli.rememberCredentials.${wsDomain}`) === 'true';
if (rememberCredentials) {
const storedSignedConfig = localStorage.getItem(`ably.web-cli.signedConfig.${wsDomain}`);
const storedSignature = localStorage.getItem(`ably.web-cli.signature.${wsDomain}`);
if (storedSignedConfig && storedSignature) {
console.log('[App] Using signed config from localStorage');
return {
signedConfig: storedSignedConfig,
signature: storedSignature,
source: 'localStorage' as const
};
}
}
// Check sessionStorage for session-only signed credentials
const sessionSignedConfig = sessionStorage.getItem(`ably.web-cli.signedConfig.${wsDomain}`);
const sessionSignature = sessionStorage.getItem(`ably.web-cli.signature.${wsDomain}`);
if (sessionSignedConfig && sessionSignature) {
console.log('[App] Using signed config from sessionStorage');
return {
signedConfig: sessionSignedConfig,
signature: sessionSignature,
source: 'session' as const
};
}
// Check for old format credentials (migration)
const oldApiKey = localStorage.getItem(`ably.web-cli.apiKey.${wsDomain}`) ||
sessionStorage.getItem(`ably.web-cli.apiKey.${wsDomain}`);
if (oldApiKey) {
console.warn('[App] Found old credential format. Please re-authenticate with signed credentials.');
// Clear old format
localStorage.removeItem(`ably.web-cli.apiKey.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.accessToken.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.apiKey.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.accessToken.${wsDomain}`);
}
return { signedConfig: undefined, signature: undefined, source: 'none' as const };
};
function App() {
// Read initial mode from URL, default to fullscreen
const initialMode = new URLSearchParams(window.location.search).get("mode") as ("fullscreen" | "drawer") || "fullscreen";
type TermStatus = 'initial' | 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'error';
const [connectionStatus, setConnectionStatus] = useState<TermStatus>('disconnected');
const [displayMode, setDisplayMode] = useState<"fullscreen" | "drawer">(initialMode);
const [showAuthSettings, setShowAuthSettings] = useState(false);
// Initialize signed credentials
const initialCreds = getInitialCredentials();
const [signedConfig, setSignedConfig] = useState<string | undefined>(initialCreds.signedConfig);
const [signature, setSignature] = useState<string | undefined>(initialCreds.signature);
const [isAuthenticated, setIsAuthenticated] = useState(Boolean(initialCreds.signedConfig && initialCreds.signature));
const [authSource, setAuthSource] = useState(initialCreds.source);
// Get the URL and domain early for use in state initialization
const currentWebsocketUrl = getWebSocketUrl();
const wsDomain = new URL(currentWebsocketUrl).host;
const [rememberCredentials, setRememberCredentials] = useState(localStorage.getItem(`ably.web-cli.rememberCredentials.${wsDomain}`) === 'true');
// Store the latest sessionId globally for E2E tests / debugging
const handleSessionId = useCallback((id: string) => {
console.log(`[App] Received sessionId: ${id}`);
(window as CliWindow)._sessionId = id; // Expose for Playwright
}, []);
const handleConnectionChange = useCallback((status: TermStatus) => {
console.log("Connection Status:", status);
setConnectionStatus(status);
}, []);
const handleSessionEnd = useCallback((reason: string) => {
console.log("Session ended:", reason);
}, []);
// Handle authentication
const handleAuthenticate = useCallback(async (newApiKey: string, remember?: boolean) => {
try {
// Optional: Get endpoint configuration from environment variables
// Real implementations should determine these values based on their requirements
const endpoint = import.meta.env.VITE_ABLY_ENDPOINT;
const controlAPIHost = import.meta.env.VITE_ABLY_CONTROL_HOST;
// Call /api/sign endpoint to get signed config
const response = await fetch('/api/sign', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
apiKey: newApiKey,
bypassRateLimit: false,
...(endpoint && { endpoint }),
...(controlAPIHost && { controlAPIHost }),
})
});
if (!response.ok) {
const error = await response.json();
console.error('[App] Failed to sign credentials:', error);
throw new Error(error.error || 'Failed to sign credentials');
}
const { signedConfig: newSignedConfig, signature: newSignature } = await response.json();
// Clear any existing session data when credentials change (domain-scoped)
sessionStorage.removeItem(`ably.cli.sessionId.${wsDomain}`);
sessionStorage.removeItem(`ably.cli.secondarySessionId.${wsDomain}`);
sessionStorage.removeItem(`ably.cli.isSplit.${wsDomain}`);
setSignedConfig(newSignedConfig);
setSignature(newSignature);
setIsAuthenticated(true);
setShowAuthSettings(false);
// Determine if we should remember based on parameter or current state
const shouldRemember = remember !== undefined ? remember : rememberCredentials;
if (shouldRemember) {
// Store in localStorage for persistence (domain-scoped)
localStorage.setItem(`ably.web-cli.signedConfig.${wsDomain}`, newSignedConfig);
localStorage.setItem(`ably.web-cli.signature.${wsDomain}`, newSignature);
localStorage.setItem(`ably.web-cli.rememberCredentials.${wsDomain}`, 'true');
setAuthSource('localStorage');
} else {
// Store only in sessionStorage (domain-scoped)
sessionStorage.setItem(`ably.web-cli.signedConfig.${wsDomain}`, newSignedConfig);
sessionStorage.setItem(`ably.web-cli.signature.${wsDomain}`, newSignature);
// Clear from localStorage if it was there (domain-scoped)
localStorage.removeItem(`ably.web-cli.signedConfig.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.signature.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.rememberCredentials.${wsDomain}`);
setAuthSource('session');
}
setRememberCredentials(shouldRemember);
} catch (error) {
console.error('[App] Authentication error:', error);
throw error;
}
}, [rememberCredentials, wsDomain]);
// Handle auth settings save
const handleAuthSettingsSave = useCallback(async (newApiKey: string, remember: boolean) => {
if (newApiKey) {
await handleAuthenticate(newApiKey, remember);
} else {
// Clear all credentials - go back to auth screen (domain-scoped)
sessionStorage.removeItem(`ably.cli.sessionId.${wsDomain}`);
sessionStorage.removeItem(`ably.cli.secondarySessionId.${wsDomain}`);
sessionStorage.removeItem(`ably.cli.isSplit.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.signedConfig.${wsDomain}`);
sessionStorage.removeItem(`ably.web-cli.signature.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.signedConfig.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.signature.${wsDomain}`);
localStorage.removeItem(`ably.web-cli.rememberCredentials.${wsDomain}`);
setSignedConfig(undefined);
setSignature(undefined);
setIsAuthenticated(false);
setShowAuthSettings(false);
setRememberCredentials(false);
}
}, [handleAuthenticate, wsDomain]);
// Effect to update URL when displayMode changes
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("mode") !== displayMode) {
urlParams.set("mode", displayMode);
window.history.replaceState({}, '', `${window.location.pathname}?${urlParams.toString()}`);
}
}, [displayMode]);
// Prepare the terminal component instance to pass it down
const termRef = useRef<AblyCliTerminalHandle>(null);
const TerminalInstance = useCallback(() => (
isAuthenticated && signedConfig && signature ? (
<AblyCliTerminal
ref={termRef}
signedConfig={signedConfig}
signature={signature}
onConnectionStatusChange={handleConnectionChange}
onSessionEnd={handleSessionEnd}
onSessionId={handleSessionId}
websocketUrl={currentWebsocketUrl}
resumeOnReload={true}
enableSplitScreen={true}
showSplitControl={true}
maxReconnectAttempts={5} /* In the example, limit reconnection attempts for testing, default is 15 */
/>
) : null
), [isAuthenticated, signedConfig, signature, handleConnectionChange, handleSessionEnd, handleSessionId, currentWebsocketUrl]);
// Show auth screen if not authenticated
if (!isAuthenticated) {
return <AuthScreen
onAuthenticate={handleAuthenticate}
rememberCredentials={rememberCredentials}
onRememberChange={setRememberCredentials}
/>;
}
return (
<div className="App fixed">
{/* Updated header with auth button */}
<header className="App-header">
<span className="font-semibold text-base">Ably Web CLI Terminal</span>
<div className="header-info">
<span>Status: <span className={`status status-${connectionStatus}`}>{connectionStatus}</span></span>
<span>Server: {currentWebsocketUrl}</span>
<button
onClick={() => termRef.current?.toggleSplitScreen()}
className="auth-button flex items-center space-x-2 px-3 py-1.5 bg-gray-800 hover:bg-gray-700 rounded-md transition-colors"
title="Toggle Split Screen"
>
Toggle Split
</button>
<button
onClick={() => setShowAuthSettings(true)}
className="auth-button flex items-center space-x-2 px-3 py-1.5 bg-gray-800 hover:bg-gray-700 rounded-md transition-colors"
title="Authentication Settings"
>
{authSource === 'session' ? (
<>
<Key size={16} />
<span className="text-sm">Session Auth</span>
</>
) : authSource === 'localStorage' ? (
<>
<Shield size={16} className="text-green-500" />
<span className="text-sm">Saved Auth</span>
</>
) : authSource === 'query' ? (
<>
<Key size={16} className="text-blue-500" />
<span className="text-sm">Query Params</span>
</>
) : (
<>
<Shield size={16} />
<span className="text-sm">Auth</span>
</>
)}
<Settings size={14} className="ml-1 opacity-50" />
</button>
</div>
<div className="toggle-group">
<button
className={`toggle-segment ${displayMode === 'fullscreen' ? 'active' : ''}`}
onClick={() => setDisplayMode('fullscreen')}
>
Fullscreen
</button>
<button
className={`toggle-segment ${displayMode === 'drawer' ? 'active' : ''}`}
onClick={() => setDisplayMode('drawer')}
>
Drawer
</button>
</div>
</header>
{/* Main content */}
{displayMode === 'fullscreen' ? (
<main className="App-main no-padding">
<div className="Terminal-container">
<TerminalInstance />
</div>
</main>
) : (
<CliDrawer TerminalComponent={TerminalInstance} />
)}
{/* Auth settings modal */}
<AuthSettings
isOpen={showAuthSettings}
onClose={() => setShowAuthSettings(false)}
onSave={handleAuthSettingsSave}
currentSignedConfig={signedConfig}
rememberCredentials={rememberCredentials}
/>
</div>
);
}
export default App;