@robosystems/core 0.17.0 → 0.17.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.
@@ -3,7 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { useEffect, useRef, useState } from 'react';
4
4
  import { CURRENT_APP, isLoginHome } from '../auth-core/config';
5
5
  import { buildLoginHomeUrl, buildReturnTo, isSafeRelativePath, } from '../auth-core/login-home';
6
- import { useSSO } from '../auth-core/sso';
6
+ import { hasPendingBridge, mintBrowserNonce, useSSO } from '../auth-core/sso';
7
7
  import { BrandSpinner } from '../ui-components';
8
8
  /**
9
9
  * Product-app stand-in for the login/register pages under centralized login.
@@ -23,7 +23,7 @@ export function LoginRedirector({ mode = 'login', apiUrl, homePath = '/home', })
23
23
  const [misconfigured, setMisconfigured] = useState(false);
24
24
  const startedRef = useRef(false);
25
25
  useEffect(() => {
26
- var _a;
26
+ var _a, _b;
27
27
  // Guard against StrictMode double-mount: the first run consumes
28
28
  // session_id and strips it from the URL, so a second run would
29
29
  // misread the state as a failed bridge.
@@ -33,7 +33,9 @@ export function LoginRedirector({ mode = 'login', apiUrl, homePath = '/home', })
33
33
  startedRef.current = true;
34
34
  const params = new URLSearchParams(window.location.search);
35
35
  const sessionId = params.get('session_id');
36
- if (sessionId) {
36
+ // A session_id this browser never asked for (a reused or foreign link)
37
+ // is not consumed; the bridge below starts fresh, bound to this browser.
38
+ if (sessionId && hasPendingBridge()) {
37
39
  const returnUrl = params.get('returnUrl');
38
40
  void handleSSOLogin().then((user) => {
39
41
  if (user) {
@@ -58,18 +60,28 @@ export function LoginRedirector({ mode = 'login', apiUrl, homePath = '/home', })
58
60
  setMisconfigured(true);
59
61
  return;
60
62
  }
61
- const localReturnTo = params.get('return_to');
63
+ const localReturnTo = (_a = params.get('return_to')) !== null && _a !== void 0 ? _a : (sessionId ? params.get('returnUrl') : null);
62
64
  const path = localReturnTo && isSafeRelativePath(localReturnTo)
63
65
  ? localReturnTo
64
66
  : undefined;
65
- const reason = (_a = params.get('reason')) !== null && _a !== void 0 ? _a : undefined;
66
- // replace() keeps the redirector page out of history so Back returns
67
- // to the page the user actually came from.
68
- window.location.replace(buildLoginHomeUrl(mode, {
69
- returnTo: buildReturnTo(CURRENT_APP, path),
70
- reason,
71
- forwardParams: params,
72
- }));
67
+ const reason = (_b = params.get('reason')) !== null && _b !== void 0 ? _b : undefined;
68
+ // The nonce binds the handoff to this browser; its hash rides to the
69
+ // login home. replace() keeps the redirector page out of history so Back
70
+ // returns to the page the user actually came from.
71
+ void mintBrowserNonce().then((nonceHash) => {
72
+ // A browser that cannot hold a nonce cannot take a handoff; one that
73
+ // has just come back with a session_id would only go round again.
74
+ if (!nonceHash && sessionId) {
75
+ setBridgeFailed(true);
76
+ return;
77
+ }
78
+ window.location.replace(buildLoginHomeUrl(mode, {
79
+ returnTo: buildReturnTo(CURRENT_APP, path),
80
+ reason,
81
+ forwardParams: params,
82
+ nonceHash: nonceHash !== null && nonceHash !== void 0 ? nonceHash : undefined,
83
+ }));
84
+ });
73
85
  }, [handleSSOLogin, mode, homePath]);
74
86
  if (misconfigured) {
75
87
  return (_jsxs("div", { className: "flex min-h-screen flex-col items-center justify-center gap-4 px-6 text-center", children: [_jsx("p", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: "Sign-in is temporarily unavailable" }), _jsx("p", { className: "max-w-md text-sm text-gray-600 dark:text-gray-400", children: "This page is misconfigured. Please contact support if the problem persists." })] }));
@@ -69,10 +69,10 @@ export declare class RoboSystemsAuthClient {
69
69
  getAPIKeys(): Promise<APIKey[]>;
70
70
  revokeAPIKey(keyId: string): Promise<void>;
71
71
  generateSSOToken(): Promise<SSOTokenResponse>;
72
- ssoExchange(token: string, targetApp: string): Promise<{
72
+ ssoExchange(token: string, targetApp: string, browserNonceHash?: string): Promise<{
73
73
  session_id: string;
74
74
  }>;
75
- ssoComplete(sessionId: string): Promise<AuthResponse>;
75
+ ssoComplete(sessionId: string, browserNonce?: string): Promise<AuthResponse>;
76
76
  checkAuthentication(): Promise<AuthUser | null>;
77
77
  /**
78
78
  * Fetch the deployment's auth posture (which sign-in methods to render).
@@ -503,20 +503,20 @@ export class RoboSystemsAuthClient {
503
503
  });
504
504
  return unwrapSdk(response);
505
505
  }
506
- async ssoExchange(token, targetApp) {
506
+ async ssoExchange(token, targetApp, browserNonceHash) {
507
507
  const response = await ssoTokenExchange({
508
508
  client: this.client,
509
- body: { token, target_app: targetApp },
509
+ body: Object.assign({ token, target_app: targetApp }, (browserNonceHash ? { browser_nonce_hash: browserNonceHash } : {})),
510
510
  });
511
511
  const data = unwrapSdk(response);
512
512
  return {
513
513
  session_id: data.session_id,
514
514
  };
515
515
  }
516
- async ssoComplete(sessionId) {
516
+ async ssoComplete(sessionId, browserNonce) {
517
517
  const response = await completeSsoAuth({
518
518
  client: this.client,
519
- body: { session_id: sessionId },
519
+ body: Object.assign({ session_id: sessionId }, (browserNonce ? { browser_nonce: browserNonce } : {})),
520
520
  });
521
521
  const sdkResponse = this.validateSDKAuthResponse(unwrapSdk(response));
522
522
  // Store JWT token with expiry information if present in response
@@ -41,6 +41,12 @@ export interface LoginHomeUrlOptions {
41
41
  * Params owned by the redirect/bridge flow are dropped.
42
42
  */
43
43
  forwardParams?: URLSearchParams;
44
+ /**
45
+ * SHA-256 of the nonce this browser minted for the bridge it is starting
46
+ * (see `mintBrowserNonce`). The login home passes it into the exchange so
47
+ * the handoff completes only here.
48
+ */
49
+ nonceHash?: string;
44
50
  }
45
51
  /** Build an absolute URL on the login home for the given auth surface. */
46
52
  export declare function buildLoginHomeUrl(mode: 'login' | 'register' | 'logout', options?: LoginHomeUrlOptions): string;
@@ -31,7 +31,7 @@ export function parseReturnTo(raw) {
31
31
  const separator = raw.indexOf(':');
32
32
  const app = separator === -1 ? raw : raw.slice(0, separator);
33
33
  const path = separator === -1 ? null : raw.slice(separator + 1);
34
- if (!APP_CONFIGS[app]) {
34
+ if (!Object.hasOwn(APP_CONFIGS, app)) {
35
35
  return null;
36
36
  }
37
37
  if (path !== null && !isSafeRelativePath(path)) {
@@ -40,7 +40,13 @@ export function parseReturnTo(raw) {
40
40
  return { app, path };
41
41
  }
42
42
  /** Params the redirect/bridge flow owns; never forwarded verbatim. */
43
- const OWNED_PARAMS = new Set(['session_id', 'returnUrl', 'return_to', 'reason']);
43
+ const OWNED_PARAMS = new Set([
44
+ 'session_id',
45
+ 'returnUrl',
46
+ 'return_to',
47
+ 'reason',
48
+ 'nonce_hash',
49
+ ]);
44
50
  /** Build an absolute URL on the login home for the given auth surface. */
45
51
  export function buildLoginHomeUrl(mode, options = {}) {
46
52
  const url = new URL(`/${mode}`, getLoginHomeUrl());
@@ -57,5 +63,8 @@ export function buildLoginHomeUrl(mode, options = {}) {
57
63
  if (options.reason) {
58
64
  url.searchParams.set('reason', options.reason);
59
65
  }
66
+ if (options.nonceHash) {
67
+ url.searchParams.set('nonce_hash', options.nonceHash);
68
+ }
60
69
  return url.toString();
61
70
  }
@@ -1,4 +1,15 @@
1
1
  import type { AppConfig, AuthUser } from './types';
2
+ /**
3
+ * Mint the nonce that binds a bridge to this browser and return its SHA-256.
4
+ *
5
+ * The nonce stays in this origin's sessionStorage; only the hash travels to
6
+ * the login home and into the exchange. Completion presents the nonce, so a
7
+ * handoff minted elsewhere cannot be redeemed here. Returns null where the
8
+ * platform cannot mint one; such a browser cannot complete a handoff.
9
+ */
10
+ export declare function mintBrowserNonce(): Promise<string | null>;
11
+ /** True when this browser started a bridge it has not completed yet. */
12
+ export declare function hasPendingBridge(): boolean;
2
13
  export interface SSORedirectUrlOptions {
3
14
  /**
4
15
  * @deprecated No effect. The return path travels only in the handoff URL;
@@ -6,6 +17,14 @@ export interface SSORedirectUrlOptions {
6
17
  * its own origin) and misrouted later handoffs into the *source* app.
7
18
  */
8
19
  persistSessionHints?: boolean;
20
+ /**
21
+ * SHA-256 of the nonce the target app minted when it started this bridge
22
+ * (`?nonce_hash=` on the login home). With it, the handoff is bound to
23
+ * that browser. Without it, the handoff is unbound: an app on an older
24
+ * core completes it, and an app on this one ignores it and starts a bound
25
+ * bridge of its own.
26
+ */
27
+ nonceHash?: string;
9
28
  }
10
29
  export declare class SSOManager {
11
30
  private authClient;
@@ -21,7 +40,7 @@ export declare class SSOManager {
21
40
  /**
22
41
  * Get SSO redirect URL using secure POST-based flow
23
42
  */
24
- getSSORedirectUrl(targetApp: string, returnUrl?: string, _options?: SSORedirectUrlOptions): Promise<string>;
43
+ getSSORedirectUrl(targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions): Promise<string>;
25
44
  /**
26
45
  * Handle SSO login using secure POST-based flow
27
46
  */
@@ -35,9 +54,14 @@ export declare class SSOManager {
35
54
  */
36
55
  private sanitizeErrorForLogging;
37
56
  /**
38
- * Navigate to another app with secure SSO
57
+ * Navigate to another app with secure SSO.
58
+ *
59
+ * With the target's `nonceHash` (the login home's case), the handoff is
60
+ * bound to that browser; see `SSORedirectUrlOptions.nonceHash` for the
61
+ * case without one. If the handoff cannot be minted, the browser goes to
62
+ * the target's login page to start a bridge of its own.
39
63
  */
40
- navigateToApp(targetApp: string, returnUrl?: string): Promise<void>;
64
+ navigateToApp(targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions): Promise<void>;
41
65
  }
42
66
  /**
43
67
  * Hook for SSO functionality
@@ -46,6 +70,6 @@ export declare function useSSO(apiUrl: string): {
46
70
  checkSSOAuthentication: () => Promise<AuthUser>;
47
71
  handleSSOLogin: () => Promise<AuthUser>;
48
72
  getSSORedirectUrl: (targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions) => Promise<string>;
49
- navigateToApp: (targetApp: string, returnUrl?: string) => Promise<void>;
73
+ navigateToApp: (targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions) => Promise<void>;
50
74
  getAvailableApps: () => AppConfig[];
51
75
  };
package/auth-core/sso.js CHANGED
@@ -2,6 +2,71 @@ import { useMemo } from 'react';
2
2
  import { RoboSystemsAuthClient } from './client';
3
3
  import { APP_CONFIGS } from './config';
4
4
  import { isSafeRelativePath } from './login-home';
5
+ /** Where the browser that starts a bridge keeps the nonce it minted. */
6
+ const BROWSER_NONCE_KEY = 'sso_browser_nonce';
7
+ const toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
8
+ /**
9
+ * Mint the nonce that binds a bridge to this browser and return its SHA-256.
10
+ *
11
+ * The nonce stays in this origin's sessionStorage; only the hash travels to
12
+ * the login home and into the exchange. Completion presents the nonce, so a
13
+ * handoff minted elsewhere cannot be redeemed here. Returns null where the
14
+ * platform cannot mint one; such a browser cannot complete a handoff.
15
+ */
16
+ export async function mintBrowserNonce() {
17
+ try {
18
+ const nonce = toHex(crypto.getRandomValues(new Uint8Array(32)));
19
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(nonce));
20
+ sessionStorage.setItem(BROWSER_NONCE_KEY, nonce);
21
+ return toHex(new Uint8Array(digest));
22
+ }
23
+ catch (error) {
24
+ debugLog('browser nonce unavailable', error);
25
+ return null;
26
+ }
27
+ }
28
+ /** True when this browser started a bridge it has not completed yet. */
29
+ export function hasPendingBridge() {
30
+ try {
31
+ return Boolean(sessionStorage.getItem(BROWSER_NONCE_KEY));
32
+ }
33
+ catch (_a) {
34
+ return false;
35
+ }
36
+ }
37
+ function takeBrowserNonce() {
38
+ let nonce;
39
+ try {
40
+ nonce = sessionStorage.getItem(BROWSER_NONCE_KEY);
41
+ }
42
+ catch (_a) {
43
+ return null;
44
+ }
45
+ try {
46
+ sessionStorage.removeItem(BROWSER_NONCE_KEY);
47
+ }
48
+ catch (error) {
49
+ debugLog('browser nonce could not be cleared', error);
50
+ }
51
+ return nonce;
52
+ }
53
+ function appConfigFor(targetApp) {
54
+ if (!Object.hasOwn(APP_CONFIGS, targetApp)) {
55
+ throw new Error(`Unknown app: ${targetApp}`);
56
+ }
57
+ return APP_CONFIGS[targetApp];
58
+ }
59
+ /**
60
+ * The target's login page, which starts a bound bridge of its own (through
61
+ * the login home) for `returnUrl`.
62
+ */
63
+ function boundBridgeEntryUrl(appConfig, returnUrl) {
64
+ const url = new URL('/login', appConfig.url);
65
+ if (returnUrl && isSafeRelativePath(returnUrl)) {
66
+ url.searchParams.set('return_to', returnUrl);
67
+ }
68
+ return url.toString();
69
+ }
5
70
  // Configuration constants
6
71
  const NAVIGATION_DELAY_MS = 100; // 100ms delay for navigation
7
72
  // Debug logging helper
@@ -56,14 +121,12 @@ export class SSOManager {
56
121
  /**
57
122
  * Get SSO redirect URL using secure POST-based flow
58
123
  */
59
- async getSSORedirectUrl(targetApp, returnUrl, _options = {}) {
124
+ async getSSORedirectUrl(targetApp, returnUrl, options = {}) {
125
+ const appConfig = appConfigFor(targetApp);
60
126
  const ssoData = await this.generateSSOToken();
61
- const appConfig = APP_CONFIGS[targetApp];
62
- if (!appConfig) {
63
- throw new Error(`Unknown app: ${targetApp}`);
64
- }
65
- // Step 1: Exchange SSO token for secure session ID
66
- const exchangeResult = await this.authClient.ssoExchange(ssoData.token, targetApp);
127
+ // Step 1: Exchange SSO token for secure session ID, bound to the browser
128
+ // that minted the nonce when there is one
129
+ const exchangeResult = await this.authClient.ssoExchange(ssoData.token, targetApp, options.nonceHash);
67
130
  // Step 2: Create URL that will trigger the POST-based flow
68
131
  const url = new URL('/login', appConfig.url);
69
132
  // Pass session ID via URL parameters for cross-domain compatibility
@@ -88,9 +151,21 @@ export class SSOManager {
88
151
  if (!finalSessionId) {
89
152
  return null;
90
153
  }
154
+ // Only a bridge this browser started is completed here: the nonce it
155
+ // minted proves it. A session_id arriving without one came from a link,
156
+ // not from this browser's bridge, and is left alone.
157
+ const nonce = takeBrowserNonce();
158
+ if (!nonce) {
159
+ debugLog('session_id present without a pending bridge; ignoring it');
160
+ const newUrl = new URL(window.location.href);
161
+ newUrl.searchParams.delete('session_id');
162
+ newUrl.searchParams.delete('returnUrl');
163
+ window.history.replaceState({}, '', newUrl.toString());
164
+ return null;
165
+ }
91
166
  try {
92
167
  // Complete SSO authentication using session ID
93
- const authResponse = await this.authClient.ssoComplete(finalSessionId);
168
+ const authResponse = await this.authClient.ssoComplete(finalSessionId, nonce);
94
169
  // Clean up both URL parameters and session storage
95
170
  if (sessionId) {
96
171
  // Clean up URL parameters
@@ -164,56 +239,17 @@ export class SSOManager {
164
239
  return String(error);
165
240
  }
166
241
  /**
167
- * Navigate to another app with secure SSO
242
+ * Navigate to another app with secure SSO.
243
+ *
244
+ * With the target's `nonceHash` (the login home's case), the handoff is
245
+ * bound to that browser; see `SSORedirectUrlOptions.nonceHash` for the
246
+ * case without one. If the handoff cannot be minted, the browser goes to
247
+ * the target's login page to start a bridge of its own.
168
248
  */
169
- async navigateToApp(targetApp, returnUrl) {
170
- const appConfig = APP_CONFIGS[targetApp];
171
- if (!appConfig) {
172
- throw new Error(`Unknown app: ${targetApp}`);
173
- }
174
- // Check local auth cache first to avoid unnecessary SSO token generation
175
- if (typeof window !== 'undefined') {
176
- let cachedUser = null;
177
- try {
178
- cachedUser = sessionStorage.getItem('auth_user_cache');
179
- }
180
- catch (error) {
181
- // Storage access error - proceed with SSO flow
182
- debugLog('sessionStorage read failed during navigation cache check', error);
183
- }
184
- if (cachedUser) {
185
- try {
186
- JSON.parse(cachedUser);
187
- // REMOVED: Cache bypass logic that was skipping SSO flow
188
- // Always use proper SSO flow for cross-app authentication
189
- debugLog('Proceeding with full SSO flow for secure cross-app auth');
190
- }
191
- catch (error) {
192
- // Invalid cache, proceed with SSO flow
193
- debugLog('Invalid cache found, proceeding with SSO flow', error);
194
- try {
195
- sessionStorage.removeItem('auth_user_cache');
196
- }
197
- catch (_a) {
198
- // Storage error - continue silently
199
- }
200
- }
201
- }
202
- }
249
+ async navigateToApp(targetApp, returnUrl, options = {}) {
250
+ const appConfig = appConfigFor(targetApp);
203
251
  try {
204
- // Fallback to full SSO flow for stale/missing cache
205
- const ssoData = await this.generateSSOToken();
206
- // Step 2: Exchange token for secure session ID
207
- const exchangeResult = await this.authClient.ssoExchange(ssoData.token, targetApp);
208
- // Step 3: Navigate to target app with secure session handoff
209
- const targetUrl = new URL('/login', appConfig.url);
210
- // Pass session ID via URL parameters for cross-domain compatibility
211
- targetUrl.searchParams.set('session_id', exchangeResult.session_id);
212
- if (returnUrl) {
213
- targetUrl.searchParams.set('returnUrl', returnUrl);
214
- }
215
- // Navigate to target app
216
- window.location.href = targetUrl.toString();
252
+ window.location.href = await this.getSSORedirectUrl(targetApp, returnUrl, options);
217
253
  }
218
254
  catch (error) {
219
255
  if (process.env.NODE_ENV === 'development') {
@@ -222,11 +258,7 @@ export class SSOManager {
222
258
  debugLog('SSO navigation failed, attempting fallback', error);
223
259
  // Fallback to direct navigation
224
260
  try {
225
- const targetUrl = new URL(appConfig.url);
226
- if (returnUrl) {
227
- targetUrl.searchParams.set('returnUrl', returnUrl);
228
- }
229
- window.location.href = targetUrl.toString();
261
+ window.location.href = boundBridgeEntryUrl(appConfig, returnUrl);
230
262
  }
231
263
  catch (locationError) {
232
264
  if (process.env.NODE_ENV === 'development') {
@@ -248,7 +280,7 @@ export function useSSO(apiUrl) {
248
280
  checkSSOAuthentication: () => ssoManager.checkSSOAuthentication(),
249
281
  handleSSOLogin: () => ssoManager.handleSSOLogin(),
250
282
  getSSORedirectUrl: (targetApp, returnUrl, options) => ssoManager.getSSORedirectUrl(targetApp, returnUrl, options),
251
- navigateToApp: (targetApp, returnUrl) => ssoManager.navigateToApp(targetApp, returnUrl),
283
+ navigateToApp: (targetApp, returnUrl, options) => ssoManager.navigateToApp(targetApp, returnUrl, options),
252
284
  getAvailableApps: () => ssoManager.getAvailableApps(),
253
285
  }), [ssoManager]);
254
286
  }
@@ -1,4 +1,5 @@
1
1
  import type { ConsoleConfig } from './types';
2
+ export declare function rowsToCsv(rows: any[]): string;
2
3
  export declare function ConsoleContent({ config, variant, }: {
3
4
  config: ConsoleConfig;
4
5
  /** `panel` drops the page header and fills its container (the drawer). */
@@ -39,7 +39,8 @@ function formatCell(value) {
39
39
  return JSON.stringify(value);
40
40
  return String(value);
41
41
  }
42
- function rowsToCsv(rows) {
42
+ const NUMERIC_TEXT = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
43
+ export function rowsToCsv(rows) {
43
44
  const cols = Object.keys(rows[0]);
44
45
  const escape = (v) => {
45
46
  const s = v === null || v === undefined
@@ -47,10 +48,18 @@ function rowsToCsv(rows) {
47
48
  : typeof v === 'object'
48
49
  ? JSON.stringify(v)
49
50
  : String(v);
50
- return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
51
+ // Text that starts like a formula is neutralised: these values come from
52
+ // the graph, and a spreadsheet would run them. Numbers stay numbers,
53
+ // including the decimals the graph returns as strings.
54
+ const guarded = typeof v === 'number' || NUMERIC_TEXT.test(s) || !/^[=+\-@\t\r]/.test(s)
55
+ ? s
56
+ : `'${s}`;
57
+ return /[",\n\r]/.test(guarded)
58
+ ? `"${guarded.replace(/"/g, '""')}"`
59
+ : guarded;
51
60
  };
52
61
  return [
53
- cols.join(','),
62
+ cols.map(escape).join(','),
54
63
  ...rows.map((row) => cols.map((c) => escape(row[c])).join(',')),
55
64
  ].join('\n');
56
65
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robosystems/core",
3
- "version": "0.17.0",
3
+ "version": "0.17.1",
4
4
  "description": "Shared RoboSystems frontend core library (auth, contexts, task monitoring, UI components) for the RoboSystems Next.js apps",
5
5
  "license": "MIT",
6
6
  "private": false,