Skip to content
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
7 changes: 4 additions & 3 deletions src/components/gui/gui.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import NotificationsProvider from '../../lib/notifications-provider.jsx';
import TWSecurityManager from '../../containers/tw-security-manager.jsx';
import TWInvalidProjectModal from '../../containers/tw-invalid-project-modal.jsx';
import RoturSession from '../../containers/rotur-session.jsx';
import {hasRotur} from '../../lib/rotur/availability.js';
import RoturExtensionHost from '../../containers/rotur-extension-host.jsx';
import MistWarpGameHost from '../../containers/mistwarp-game-host.jsx';
import RoturLoginModal from '../mw-rotur-login-modal/rotur-login-modal.jsx';
Expand Down Expand Up @@ -860,8 +861,8 @@ const GUIComponent = props => {
{!isPlayerOnly && <TWRestorePointManager />}
{!isPlayerOnly && <MWExtensionManagerModal />}
{!isPlayerOnly && <TWVariableManager />}
{!isPlayerOnly && <MWProductsModal />}
{!isPlayerOnly && <MWGameItemsModal />}
{!isPlayerOnly && hasRotur() && <MWProductsModal />}
{!isPlayerOnly && hasRotur() && <MWGameItemsModal />}
{!isPlayerOnly && <MWHelpModal />}
{!isPlayerOnly && <MWProjectThemeModal />}
{usernameModalVisible && <TWUsernameModal visible={usernameModalVisible} />}
Expand All @@ -879,7 +880,7 @@ const GUIComponent = props => {
{gitModalVisible && <TWGitModal />}
</React.Suspense>
{invalidProjectModalVisible && <TWInvalidProjectModal />}
{roturLoginModalVisible && (
{roturLoginModalVisible && hasRotur() && (
<RoturLoginModal onRequestClose={onRequestCloseRoturLogin} />
)}
<SimpleDialog />
Expand Down
13 changes: 7 additions & 6 deletions src/components/menu-bar/menu-bar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ import {getShortcutKey} from '../../lib/shortcuts/registry.js';
import TWDesktopSettings from './tw-desktop-settings.jsx';
import RoturAccount from './mw-rotur-account.jsx';
import MwEditorNav from './mw-editor-nav.jsx';
import {hasRotur} from '../../lib/rotur/availability.js';
import CollabPresence from './mw-collab-presence.jsx';

import {FEEDBACK_URL} from '../../lib/constants/brand.js';
Expand Down Expand Up @@ -1909,7 +1910,7 @@ class MenuBar extends React.Component {
</MenuItem>
)}</CloudVariablesToggler>
</MenuSection>
<MenuSection>
{hasRotur() && <MenuSection>
<MenuItem onClick={this.handleClickProducts}>
<ShoppingBag size={20} />
<FormattedMessage
Expand All @@ -1926,7 +1927,7 @@ class MenuBar extends React.Component {
id="mw.menuBar.gameItems"
/>
</MenuItem>
</MenuSection>
</MenuSection>}
</MenuBarMenu>
</MenuLabel>
<MenuLabel
Expand Down Expand Up @@ -1954,7 +1955,7 @@ class MenuBar extends React.Component {
place={this.props.isRtl ? 'left' : 'right'}
>
<MenuSection>
<MenuItem
{hasRotur() && <MenuItem
onClick={this.handleClickGitModal}
>
<GitBranch />
Expand All @@ -1963,8 +1964,8 @@ class MenuBar extends React.Component {
description="Menu bar item to open pushed project history"
id="mw.menuBar.git"
/>
</MenuItem>
<MenuItem
</MenuItem>}
{hasRotur() && <MenuItem
onClick={this.handleClickCollaboration}
>
<Handshake size={20} />
Expand All @@ -1973,7 +1974,7 @@ class MenuBar extends React.Component {
description="Menu bar item for live collaboration"
id="tw.menuBar.collaboration"
/>
</MenuItem>
</MenuItem>}
<MenuItem onClick={this.handleClickProjectMetadata}>
<Info />
<FormattedMessage
Expand Down
4 changes: 4 additions & 0 deletions src/components/menu-bar/mw-rotur-account.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
} from '../../reducers/menus.js';
import {openRoturLoginModal, openSettingsModal} from '../../reducers/modals.js';
import communityEnabled from '../../lib/community/enabled.js';
import {hasRotur} from '../../lib/rotur/availability.js';

const logout = onLogout => {
if (onLogout) {
Expand Down Expand Up @@ -69,6 +70,9 @@ const RoturAccount = props => {
logout(props.onLogout);
}, [props.onCloseMenu, props.onLogout]);

// The desktop app has no Rotur, so nobody signs in.
if (!hasRotur()) return null;

if (!props.username) {
return (
<button
Expand Down
5 changes: 4 additions & 1 deletion src/containers/mistwarp-game-host.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import GameMarketplaceModal from '../community/components/GameMarketplaceModal.j
import {getRememberedPlatformProjectState} from '../lib/community/publish.js';
import {MULTIPLAYER_ENABLED} from '../lib/mistwarp-games/config.js';
import {blockProjectPrompts, isProjectPromptBlocked} from '../lib/project-prompt-blocking.js';
import {hasRotur} from '../lib/rotur/availability.js';

class MistWarpGameHost extends React.Component {
constructor (props) {
Expand Down Expand Up @@ -148,7 +149,9 @@ class MistWarpGameHost extends React.Component {
if (!MULTIPLAYER_ENABLED && (method === 'multiplayer.setState' || method === 'multiplayer.sendEvent')) {
return Promise.resolve(false);
}
if (this.isDraftProject()) return this.callForDraft(method, args);
// Offline, as in the desktop app, every project works like an unsaved
// one: saves stay local, and the shop is a preview with no payments.
if (!hasRotur() || this.isDraftProject()) return this.callForDraft(method, args);
const projectId = this.requireProject();
if (method === 'data.load') return loadProjectSave(projectId, 'editor');
if (method === 'data.save') return saveProjectData(projectId, 'editor', args[0]);
Expand Down
3 changes: 3 additions & 0 deletions src/containers/rotur-extension-host.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {getRoturSettings, setRoturSetting} from '../lib/rotur/settings.js';
import {isLoggedIn} from '../lib/rotur/client.js';
import {getState as getRoturIdentityState} from '../lib/rotur/identity.js';
import ProjectActivityScope from '../lib/rotur/project-activity-scope.js';
import {hasRotur, roturOfflineError} from '../lib/rotur/availability.js';
import {
blockProjectPrompts,
isProjectPromptBlocked
Expand Down Expand Up @@ -202,6 +203,7 @@ class RoturExtensionHost extends React.Component {
}

async ensureConsent (requested) {
if (!hasRotur()) throw roturOfflineError();
const scopes = validateProjectScopes(requested);
if (!scopes) {
throw new Error('Projects cannot ask for that Rotur permission');
Expand Down Expand Up @@ -235,6 +237,7 @@ class RoturExtensionHost extends React.Component {
}

async call (method, args) {
if (!hasRotur()) throw roturOfflineError();
const call = authorizeProjectCall(
method,
args,
Expand Down
19 changes: 19 additions & 0 deletions src/lib/rotur/availability.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// MistWarp desktop is offline first, with no Rotur: no sign-in, no Rotur-backed
// community features, no payments, and nothing for projects to call. The
// desktop app's editor runs on tw-editor:// with window.EditorPreload, so
// either of those means desktop.

const ROTUR_OFFLINE_MESSAGE = 'Rotur isn\'t available in the MistWarp desktop app, which works offline.';

/**
* @returns {boolean} Whether this editor can use Rotur at all.
*/
const hasRotur = () => {
if (typeof window === 'undefined') return true;
if (typeof window.EditorPreload !== 'undefined') return false;
return /^https?:$/.test(window.location.protocol);
};

const roturOfflineError = () => Object.assign(new Error(ROTUR_OFFLINE_MESSAGE), {code: 'rotur_offline'});

export {hasRotur, roturOfflineError, ROTUR_OFFLINE_MESSAGE};
9 changes: 8 additions & 1 deletion src/lib/rotur/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from './settings.js';
import {ROTUR_TOKEN_KEY} from './token-key.js';
import * as oauth from './oauth.js';
import {hasRotur, roturOfflineError} from './availability.js';

// What MistWarp asks for when someone signs in with Rotur. Nothing here can
// spend credits, change account settings or read secrets: payments go through
Expand Down Expand Up @@ -238,10 +239,14 @@ const writeRestoreCache = user => {
* needed, or a token from the old sign-in.
* @returns {Promise<string|null>} The token, or null when signed out.
*/
const getAccessToken = async () => (await oauth.getAccessToken()) || loadLegacyToken();
const getAccessToken = async () => {
if (!hasRotur()) return null;
return (await oauth.getAccessToken()) || loadLegacyToken();
};

/** Restore a previous session. */
const restoreSession = async () => {
if (!hasRotur()) return null;
await oauth.completeRedirect();
const token = await getAccessToken();
if (!token) {
Expand Down Expand Up @@ -272,6 +277,7 @@ const restoreSession = async () => {
* @returns {Promise<object>} The signed-in user.
*/
const login = async (extraScopes = [], redirectFallback = true) => {
if (!hasRotur()) throw roturOfflineError();
const scopes = [...new Set([...SIGN_IN_SCOPES, ...extraScopes])];
if (webOrigin) {
const session = await oauth.signIn(scopes, {redirectFallback});
Expand Down Expand Up @@ -694,6 +700,7 @@ const hasScopes = scopes => {
// never leaves the page. Someone can switch scopes off on Rotur's consent
// screen, so reads just find out, and fail quietly if they can't.
const ensureScopes = async (scopes, {prompt = false} = {}) => {
if (!hasRotur()) return false;
const wanted = Array.isArray(scopes) ? scopes.filter(Boolean) : [];
const session = oauth.readSession();
if (session) {
Expand Down
67 changes: 67 additions & 0 deletions test/unit/rotur-desktop-offline.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// The desktop app is offline first: with window.EditorPreload there, nothing
// signs in to Rotur or reaches api.rotur.dev, even with a session stored from
// before.
const roturRequests = [];
const sockets = [];

beforeAll(() => {
window.EditorPreload = {};
global.fetch = jest.fn(url => {
roturRequests.push(String(url));
return Promise.reject(new Error('offline'));
});
global.WebSocket = jest.fn(url => {
sockets.push(String(url));
});
localStorage.setItem('mw:rotur-oauth', JSON.stringify({
accessToken: 'rotur_st_old', refreshToken: 'rrt_old', subject: 'id-1', username: 'sam',
scopes: ['profile'], expiresAt: Date.now() - 1000
}));
localStorage.setItem('mw:rotur-token', 'rotur_legacy');
});

afterAll(() => {
delete window.EditorPreload;
});

const load = () => ({
availability: require('../../src/lib/rotur/availability.js'),
client: require('../../src/lib/rotur/client.js'),
identity: require('../../src/lib/rotur/identity.js'),
host: require('../../src/containers/rotur-extension-host.jsx')
});

test('desktop has no Rotur', () => {
expect(load().availability.hasRotur()).toBe(false);
});

test('a stored session or old token is not restored, and nothing offers to reconnect', async () => {
const {client, identity} = load();
await expect(client.getAccessToken()).resolves.toBe(null);
await expect(client.restoreSession()).resolves.toBe(null);
await identity.restore();
expect(identity.getState().user).toBe(null);
await expect(identity.ensureMistSession()).resolves.toBe(null);
expect(client.isLoggedIn()).toBe(false);
expect(client.needsReconnect()).toBe(false);
});

test('signing in and asking for permissions fail with a clear error', async () => {
const {client} = load();
await expect(client.login()).rejects.toMatchObject({code: 'rotur_offline'});
await expect(client.ensureScopes(['posts:view'], {prompt: true})).resolves.toBe(false);
});

test('projects get "not available offline" from the Rotur bridge', async () => {
const {RoturExtensionHost} = load().host;
const host = new RoturExtensionHost({vm: {runtime: {_mwProjectTrusted: true}}, projectTitle: 'Game'});
host.acquireModalLock = jest.fn();
await expect(host.call('profiles.get', ['sam'])).rejects.toThrow('desktop app');
await expect(host.ensureConsent(['posts:create'])).rejects.toThrow('desktop app');
expect(host.acquireModalLock).not.toHaveBeenCalled();
});

test('nothing reached Rotur', () => {
expect(roturRequests.filter(url => url.includes('rotur.dev'))).toEqual([]);
expect(sockets).toEqual([]);
});
Loading