Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: sessions sharedworker correctly shared for all deployments #15175

Merged
merged 1 commit into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/connect-explorer/src/actions/trezorConnectActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,17 @@ export const init =
const urlParams = new URLSearchParams(window.location.search);
const coreMode = (urlParams.get('core-mode') as ConnectOptions['coreMode']) || 'auto';

// localhost + dev server
let _sessionsBackgroundUrl = process.env.CONNECT_EXPLORER_FULL_URL
? `${process.env.CONNECT_EXPLORER_FULL_URL}/workers/sessions-background-sharedworker.js`
: window.origin + '/workers/sessions-background-sharedworker.js';

// connect.trezor.io/9 || connect.trezor.io/9.x.y
if (window.location.origin.endsWith('connect.trezor.io')) {
Dismissed Show dismissed Hide dismissed
_sessionsBackgroundUrl =
'https://connect.trezor.io/9/workers/sessions-background-sharedworker.js';
}

const connectOptions = {
coreMode,
transportReconnect: true,
Expand All @@ -158,6 +169,7 @@ export const init =
},
trustedHost: false,
connectSrc: window.__TREZOR_CONNECT_SRC,
_sessionsBackgroundUrl,
...options,
};

Expand Down
2 changes: 1 addition & 1 deletion packages/connect/src/data/connectSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export const parseConnectSettings = (input: Partial<ConnectSettings> = {}) => {
settings._extendWebextensionLifetime = input._extendWebextensionLifetime;
}

if (typeof input._sessionsBackgroundUrl === 'string') {
if (typeof input._sessionsBackgroundUrl === 'string' || input._sessionsBackgroundUrl === null) {
settings._sessionsBackgroundUrl = input._sessionsBackgroundUrl;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/connect/src/types/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export interface ConnectSettingsPublic {
* for internal use only!
* in some exotic setups (suite-web where iframe is embedded locally), you might need to tell connect where it should search for sessions background shared-worker
*/
_sessionsBackgroundUrl?: string;
_sessionsBackgroundUrl?: null | string;
// URL for binary files such as firmware, may be local or remote
binFilesBaseUrl?: string;
// enable firmware hash check automatically when device connects. Requires binFilesBaseUrl to be set.
Expand Down
18 changes: 12 additions & 6 deletions packages/transport/src/transports/webusb.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ import { UsbApi } from '../api/usb';
import { BrowserSessionsBackground } from '../sessions/background-browser';

const defaultSessionsBackgroundUrl =
window.location.origin +
`${process.env.ASSET_PREFIX || ''}/workers/sessions-background-sharedworker.js`
// just in case so that whoever defines ASSET_PREFIX does not need to worry about trailing slashes
.replace(/\/+/g, '/');
'https://connect.trezor.io/9/workers/sessions-background-sharedworker.js';

type WebUsbTransportParams = AbstractTransportParams & { sessionsBackgroundUrl?: string };

Expand All @@ -20,18 +17,27 @@ type WebUsbTransportParams = AbstractTransportParams & { sessionsBackgroundUrl?:
export class WebUsbTransport extends AbstractApiTransport {
public name = 'WebUsbTransport' as const;

private readonly sessionsBackgroundUrl;
private readonly sessionsBackgroundUrl: string | null = defaultSessionsBackgroundUrl;

constructor({ logger, sessionsBackgroundUrl, ...rest }: WebUsbTransportParams) {
super({
api: new UsbApi({ usbInterface: navigator.usb, logger }),
logger,
...rest,
});
this.sessionsBackgroundUrl = sessionsBackgroundUrl ?? defaultSessionsBackgroundUrl;
if (sessionsBackgroundUrl || sessionsBackgroundUrl === null) {
this.sessionsBackgroundUrl = sessionsBackgroundUrl;
}
}

private async trySetSessionsBackground() {
if (!this.sessionsBackgroundUrl) {
this.logger?.log(
'No sessionsBackgroundUrl provided. Falling back to use local module.',
);

return;
}
try {
const response = await fetch(this.sessionsBackgroundUrl, { method: 'HEAD' });
if (!response.ok) {
Expand Down
42 changes: 30 additions & 12 deletions suite-common/connect-init/src/connectInitThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,36 @@ export const connectInitThunk = createThunk(

cardanoConnectPatch(getEnabledNetworks);

// note:
// this way, for local development you will get http://localhost:8000/static/connect/workers/sessions-background-sharedworker.js which is still the not-shared shared-worker
// meaning that testing it together with connect-explorer dev build (http://localhost:8088/workers/sessions-background-sharedworker.js) will not work locally.
// in production however, suite and connect are served from the same domain (trezor.io, sldev.cz) so it will work as expected.
let sessionsBackground: string | undefined;
// suite-web connect (explorer) webusb sync
// ====================================================== ==================== ====================
// localhost:8000 localhost:8088 NO
// https://dev.suite.sldev.cz/suite-web/develop/web/ https://dev.suite.sldev.cz/connect/develop/ YES - connect
// suite.trezor.io/web connect.trezor.io/9(x.y)/ YES - connect

let _sessionsBackgroundUrl: string | null = null;

if (typeof window !== 'undefined' && !isNative()) {
sessionsBackground =
window.location.origin +
resolveStaticPath(
'connect/workers/sessions-background-sharedworker.js',
`${process.env.ASSET_PREFIX || ''}`,
);
if (window.location.origin.includes('localhost')) {
_sessionsBackgroundUrl = null;
} else if (window.location.origin.endsWith('dev.suite.sldev.cz')) {
// we are expecting accompanying connect build at specified location
const assetPrefixArr = (process.env.ASSET_PREFIX || '').split('/').filter(Boolean);
const relevantSegments = assetPrefixArr
.map((segment, index) => {
const first = index === 0;
const last = index === assetPrefixArr.length - 1;
if (segment === 'suite-web' && first) return 'connect';
if (segment === 'web' && last) return null;

return segment;
})
.filter(Boolean);

_sessionsBackgroundUrl = `${window.location.origin}/${relevantSegments.join('/')}/workers/sessions-background-sharedworker.js`;
} else {
_sessionsBackgroundUrl =
'https://connect.trezor.io/9/workers/sessions-background-sharedworker.js';
}
}

// Duplicates `getBinFilesBaseUrlThunk`, because calling any other thunk would change store.getActions() history,
Expand All @@ -135,7 +153,7 @@ export const connectInitThunk = createThunk(
binFilesBaseUrl,
pendingTransportEvent: selectIsPendingTransportEvent(getState()),
transports: selectDebugSettings(getState()).transports,
_sessionsBackgroundUrl: sessionsBackground,
_sessionsBackgroundUrl,
// debug: true, // Enable debug logs in TrezorConnect
});
} catch (error) {
Expand Down
Loading