diff --git a/src/community/pages/Project.jsx b/src/community/pages/Project.jsx index 04aed72c26f..86519a34675 100644 --- a/src/community/pages/Project.jsx +++ b/src/community/pages/Project.jsx @@ -22,9 +22,12 @@ import RoturConsentModal from '../components/RoturConsentModal.jsx'; import GameMarketplaceModal from '../components/GameMarketplaceModal.jsx'; import {getBalance} from '../../lib/rotur/client.js'; import { - hasFullGrant, commitGrant, callRotur, - activityAllowed, rememberActivityDecision, isActivityMethod + hasFullGrant, commitGrant, callRotur, grantedScopesFor, + activityAllowed, rememberActivityDecision } from '../../lib/rotur/extension-bridge.js'; +import { + authorizeProjectCall, grantsSilently, validateProjectScopes +} from '../../lib/rotur/project-methods.js'; import {getRoturSettings, setRoturSetting} from '../../lib/rotur/settings.js'; import ProjectActivityScope from '../../lib/rotur/project-activity-scope.js'; import {getUsernameOverride} from '../../lib/rotur/cloud-sync.js'; @@ -817,9 +820,20 @@ const Project = () => { return; } + // The grant key, the project name and whether to ask all come from + // this page. Anything the frame sends besides the scopes and the + // method is ignored, because custom extensions can post here too. + const meta = { + projectId: gamesProjectId, + name: (project && (project.title || project.name)) || '' + }; + if (data.kind === 'consent') { - const scopes = data.scopes || []; - const meta = data.meta || {}; + const scopes = validateProjectScopes(data.scopes); + if (!scopes) { + reply({id: data.id, ok: false, error: 'Projects cannot ask for that Rotur permission'}); + return; + } if (!identity.loggedIn) { reply({id: data.id, ok: true, result: false}); return; @@ -828,7 +842,7 @@ const Project = () => { reply({id: data.id, ok: true, result: true}); return; } - if (meta.authenticatedOnly) { + if (grantsSilently(scopes)) { try { await commitGrant(meta, scopes); reply({id: data.id, ok: true, result: true}); @@ -867,7 +881,16 @@ const Project = () => { } if (data.kind === 'call') { - const {method, args, opts} = data; + const method = data.method; + let call; + try { + if (!identity.loggedIn) throw new Error('Log in to Rotur to use this block'); + call = authorizeProjectCall(method, data.args, grantedScopesFor(meta), gamesProjectId); + } catch (e) { + reply({id: data.id, ok: false, error: String((e && e.message) || e)}); + return; + } + const args = call.args; const perform = async () => { try { const scope = roturActivityScope.current; @@ -877,7 +900,7 @@ const Project = () => { reply({id: data.id, ok: false, error: String((e && e.message) || e)}); } }; - if (isActivityMethod(method)) { + if (call.spec.activity) { const key = (project && project.id) || id || `name:${(project && project.title) || ''}`; const decision = activityAllowed(getRoturSettings().activitySharing, key); if (decision === true) { @@ -919,7 +942,7 @@ const Project = () => { }); return; } - if (opts && opts.sensitive) { + if (call.confirm) { if (isProjectPromptBlocked({id: gamesProjectId})) { reply({id: data.id, ok: false, error: 'You blocked prompts from this project'}); return; @@ -927,8 +950,8 @@ const Project = () => { setRoturModal({ type: 'confirm', data: { - label: (opts && opts.label) || method, - confirmation: (opts && opts.confirmation) || null, + label: call.confirm.label, + confirmation: call.confirm.confirmation || null, username: identity.username }, onAllow: () => { diff --git a/src/containers/rotur-extension-host.jsx b/src/containers/rotur-extension-host.jsx index 9bcbe6a8a62..a488732efbc 100644 --- a/src/containers/rotur-extension-host.jsx +++ b/src/containers/rotur-extension-host.jsx @@ -5,8 +5,11 @@ import bindAll from 'lodash.bindall'; import RoturConsentModal from '../components/mw-rotur-consent-modal/consent-modal.jsx'; import { hasFullGrant, commitGrant, grantedScopesFor, callRotur, - activityAllowed, rememberActivityDecision, isActivityMethod + activityAllowed, rememberActivityDecision } from '../lib/rotur/extension-bridge.js'; +import { + authorizeProjectCall, grantsSilently, validateProjectScopes +} from '../lib/rotur/project-methods.js'; import {getRoturSettings, setRoturSetting} from '../lib/rotur/settings.js'; import {isLoggedIn} from '../lib/rotur/client.js'; import {getState as getRoturIdentityState} from '../lib/rotur/identity.js'; @@ -19,13 +22,15 @@ import { // Attaches a Rotur "host" onto vm.runtime so builtin Rotur extensions can act as // the logged-in user without ever seeing the token. The token stays inside the // GUI's Rotur client (lib/rotur/client.js); this host only exposes identity, -// per-project consent, and gated calls. Mirrors tw-security-manager's modal-lock. +// per-project consent, and allowlisted calls (lib/rotur/project-methods.js). +// The host, not the caller, decides which calls need a grant or a confirmation. +// Mirrors tw-security-manager's modal-lock. class RoturExtensionHost extends React.Component { constructor (props) { super(props); bindAll(this, [ 'handleAllowed', 'handleBlocked', 'handleDenied', 'handleShareThis', 'handleShareAll', 'handleShareNo', - 'getUser', 'ensureConsent', 'ensureActivitySharing', 'call', 'getProjectId' + 'getUser', 'ensureConsent', 'ensureActivitySharing', 'call', 'getProjectId', 'grantMeta' ]); this.nextModalCallbacks = []; this.modalLocked = false; @@ -46,7 +51,7 @@ class RoturExtensionHost extends React.Component { const id = this.getProjectId(); return id ? `https://api.mistwarp.org/thumbnails/${encodeURIComponent(id)}.png` : ''; }, - grantedScopes: () => grantedScopesFor({name: this.props.vm.runtime.projectName || ''}) + grantedScopes: () => grantedScopesFor(this.grantMeta()) }; } @@ -192,14 +197,23 @@ class RoturExtensionHost extends React.Component { return this.currentUser(); } - async ensureConsent (scopes, meta) { + grantMeta () { + return {name: this.props.vm.runtime.projectName || ''}; + } + + async ensureConsent (requested) { + const scopes = validateProjectScopes(requested); + if (!scopes) { + throw new Error('Projects cannot ask for that Rotur permission'); + } if (!this.currentUser().loggedIn) { throw new Error('Log in to Rotur to let this project connect'); } + const meta = this.grantMeta(); if (hasFullGrant(meta, scopes)) { return true; } - if (meta && meta.authenticatedOnly) { + if (grantsSilently(scopes)) { await commitGrant(meta, scopes); return true; } @@ -220,25 +234,31 @@ class RoturExtensionHost extends React.Component { return true; } - async call (method, args, opts) { - if (isActivityMethod(method)) { + async call (method, args) { + const call = authorizeProjectCall( + method, + args, + grantedScopesFor(this.grantMeta()), + this.getProjectId() || 'mistwarp' + ); + if (call.spec.activity) { const allowed = await this.ensureActivitySharing(); if (!allowed) { return ''; } } - if (opts && opts.sensitive) { + if (call.confirm) { const {showModal} = await this.acquireModalLock(); const confirmed = await showModal('confirm', { - label: opts.label || method, - confirmation: opts.confirmation || null, + label: call.confirm.label, + confirmation: call.confirm.confirmation || null, username: this.currentUser().username }); if (!confirmed) { throw new Error('You cancelled this Rotur action'); } } - return this.activityScope.call(method, args); + return this.activityScope.call(method, call.args); } render () { diff --git a/src/lib/rotur/extension-bridge.js b/src/lib/rotur/extension-bridge.js index bc28d440298..adb7658cd5a 100644 --- a/src/lib/rotur/extension-bridge.js +++ b/src/lib/rotur/extension-bridge.js @@ -1,9 +1,12 @@ import {getRotur, ensureScopes} from './client.js'; +import {invokeProjectMethod} from './project-methods.js'; const GRANTS_KEY = 'mw:rotur-grants'; // Per-project consent grants: {[projectKey]: string[] scopes}. The key is the -// platform project id when known, else a name-based fallback. +// platform project id when known, else a name-based fallback. Hosts that know +// the project (the community project page) pass meta.projectId themselves, so +// the project cannot pick which grant it reads. const readGrants = () => { try { return JSON.parse(localStorage.getItem(GRANTS_KEY) || '{}') || {}; @@ -21,6 +24,9 @@ const writeGrants = grants => { }; const projectKey = meta => { + if (meta && meta.projectId) { + return `id:${meta.projectId}`; + } try { const stored = sessionStorage.getItem('mw:mistwarp-current-project'); if (stored) { @@ -104,36 +110,15 @@ const isActivityMethod = method => ( method === 'socket.removeActivity' ); -// Dispatch a dotted method path (e.g. "me.transfer", "posts.feed", -// "socket.setStatus") on the shared Rotur client. The token lives inside the -// client and is never returned. socket.* methods lazily connect the status -// websocket first. -const callRotur = async (method, args) => { +// Run an allowlisted Rotur method (see project-methods.js) on the shared +// client. The token lives inside the client and is never returned. Anything +// outside the allowlist, such as "_http.getToken", is rejected. +const callRotur = (method, args) => { const rotur = getRotur(); if (!rotur.loggedIn) { - throw new Error('Log in to Rotur to use this block'); - } - const parts = method.split('.'); - if (parts[0] === 'socket') { - if (!rotur.socket || !rotur.socket.connected) { - await rotur.connectSocket(); - } - const fn = rotur.socket && rotur.socket[parts[1]]; - if (typeof fn !== 'function') { - throw new Error(`Unknown Rotur socket method: ${method}`); - } - return fn.apply(rotur.socket, args); - } - let ctx = rotur; - let fn = rotur; - for (const part of parts) { - ctx = fn; - fn = fn && fn[part]; - } - if (typeof fn !== 'function') { - throw new Error(`Unknown Rotur method: ${method}`); + return Promise.reject(new Error('Log in to Rotur to use this block')); } - return fn.apply(ctx, args || []); + return invokeProjectMethod(rotur, method, args || []); }; export { diff --git a/src/lib/rotur/project-methods.js b/src/lib/rotur/project-methods.js new file mode 100644 index 00000000000..220df3e1707 --- /dev/null +++ b/src/lib/rotur/project-methods.js @@ -0,0 +1,252 @@ +// The only Rotur SDK methods a project may reach through a Rotur host (the +// editor, the community project page and packaged exports). Each entry lists +// the scopes that cover it (any one is enough; an empty list means it needs no +// grant) and, for actions that spend, give away or destroy something, the +// confirmation the host shows before every call. +// +// The host decides all of this. Nothing the project sends (labels, +// confirmation text, a "sensitive" flag, a project name) is trusted, because a +// custom extension running next to the project can send any message it likes. +// Never resolve a method path that is not a key of this table. + +const text = value => String(typeof value === 'undefined' || value === null ? '' : value).slice(0, 200); +const amount = value => { + const number = Number(value); + return Number.isFinite(number) ? number : 0; +}; + +const PROJECT_METHODS = Object.freeze({ + 'me.abilities': {scopes: []}, + 'me.checkAuth': {scopes: []}, + 'me.get': {scopes: ['account:view', 'credits:view']}, + 'me.badges': {scopes: ['account:view']}, + 'me.subscription': {scopes: ['account:view']}, + 'me.blocked': {scopes: ['blocked:view']}, + 'me.block': {scopes: ['blocked:manage']}, + 'me.unblock': {scopes: ['blocked:manage']}, + 'me.requests': {scopes: ['friends:view']}, + 'me.claimTime': {scopes: ['credits:view']}, + 'me.transactions': {scopes: ['credits:view']}, + 'me.transfer': { + scopes: ['credits:transfer'], + confirm: args => ({ + label: `send ${amount(args[1])} credits to @${text(args[0])}`, + confirmation: {type: 'payment', amount: amount(args[1]), recipient: text(args[0])} + }) + }, + + 'profiles.get': {scopes: []}, + 'profiles.exists': {scopes: []}, + 'profiles.getAvatarUrl': {scopes: []}, + 'standing.get': {scopes: []}, + 'check.banned': {scopes: []}, + 'notifications.list': {scopes: ['notifications:view']}, + + 'gifts.create': { + scopes: ['gifts:create'], + confirm: args => ({label: `create a gift of ${amount(args[0])} credits`}) + }, + 'gifts.get': {scopes: []}, + 'gifts.claim': { + scopes: ['gifts:claim'], + confirm: args => ({label: `claim gift code ${text(args[0])}`}) + }, + 'gifts.cancel': {scopes: ['gifts:cancel']}, + 'gifts.mine': {scopes: ['gifts:view']}, + 'stats.economy': {scopes: []}, + 'stats.mostGained': {scopes: []}, + + 'keys.mine': {scopes: ['keys:view']}, + 'keys.get': {scopes: []}, + 'keys.check': {scopes: []}, + 'keys.buy': { + scopes: [], + confirm: args => ({label: `buy key ${text(args[0])}`}) + }, + 'keys.cancel': { + scopes: [], + confirm: args => ({label: `cancel your subscription to key ${text(args[0])}`}) + }, + 'keys.rename': {scopes: ['keys:manage']}, + 'keys.update': {scopes: ['keys:manage']}, + 'keys.revoke': {scopes: ['keys:manage']}, + 'keys.delete': { + scopes: ['keys:manage'], + confirm: args => ({label: `delete key ${text(args[0])}`}) + }, + 'storage.get': {scopes: ['storage:view'], projectStorage: true}, + 'storage.set': {scopes: ['storage:manage'], projectStorage: true}, + 'storage.delete': {scopes: ['storage:delete'], projectStorage: true}, + + 'status.get': {scopes: []}, + 'socket.setStatus': {scopes: ['account:profile'], activity: true}, + 'socket.addActivity': {scopes: ['account:profile'], activity: true}, + 'socket.removeActivity': {scopes: ['account:profile'], activity: true}, + + 'posts.create': {scopes: ['posts:create']}, + 'posts.feed': {scopes: []}, + 'posts.followingFeed': {scopes: ['posts:view']}, + 'posts.top': {scopes: []}, + 'posts.search': {scopes: []}, + 'posts.like': {scopes: ['posts:like']}, + 'posts.unlike': {scopes: ['posts:like']}, + 'posts.reply': {scopes: ['posts:reply']}, + 'posts.repost': {scopes: ['posts:repost']}, + 'posts.delete': { + scopes: ['posts:delete'], + confirm: args => ({label: `delete post ${text(args[0])}`}) + }, + 'following.follow': {scopes: ['following:follow']}, + 'following.unfollow': {scopes: ['following:unfollow']}, + 'following.followers': {scopes: []}, + 'following.following': {scopes: []}, + 'friends.list': {scopes: ['friends:view']}, + 'friends.request': {scopes: ['friends:request']}, + 'friends.accept': {scopes: ['friends:accept']}, + 'friends.reject': {scopes: ['friends:accept']}, + 'friends.remove': {scopes: ['friends:remove']}, + + 'items.get': {scopes: []}, + 'items.selling': {scopes: []}, + 'items.list': {scopes: []}, + 'items.buy': { + scopes: ['items:buy'], + confirm: args => ({label: `buy item ${text(args[0])}`}) + }, + 'items.sell': {scopes: ['items:sell']}, + 'items.stopSelling': {scopes: ['items:sell']}, + 'items.setPrice': {scopes: ['items:sell']}, + 'items.transfer': { + scopes: ['items:manage'], + confirm: args => ({label: `give item ${text(args[0])} to @${text(args[1])}`}) + }, + 'cosmetics.shop': {scopes: []}, + 'cosmetics.mine': {scopes: ['cosmetics:view']}, + 'cosmetics.purchase': { + scopes: ['cosmetics:buy'], + confirm: args => ({label: `buy cosmetic ${text(args[0])}`}) + }, + 'cosmetics.equip': {scopes: ['cosmetics:equip']}, + 'cosmetics.unequip': {scopes: ['cosmetics:equip']}, + 'cosmetics.forUser': {scopes: []}, + + 'groups.mine': {scopes: ['groups:view']}, + 'groups.search': {scopes: ['groups:view']}, + 'groups.get': {scopes: []}, + 'groups.join': {scopes: ['groups:join']}, + 'groups.requestJoin': {scopes: ['groups:join']}, + 'groups.leave': {scopes: ['groups:leave']}, + 'groups.members': {scopes: ['groups:members.view']}, + 'groups.roles': {scopes: ['groups:view']}, + 'groups.announcements': {scopes: []}, + 'groups.events': {scopes: ['groups:view']}, + 'groups.products': {scopes: ['groups:view']}, + 'groups.sendTip': { + scopes: ['credits:manage'], + confirm: args => ({label: `tip ${amount(args[1])} credits to group ${text(args[0])}`}) + }, + 'groups.purchaseProduct': { + scopes: ['credits:manage'], + confirm: args => ({label: `buy product ${text(args[1])} in group ${text(args[0])}`}) + }, + + 'files.index': {scopes: ['files:view']}, + 'files.getByPath': {scopes: ['files:view']}, + 'files.getByUUID': {scopes: ['files:view']}, + 'files.usage': {scopes: ['files:view']} +}); + +const has = (object, key) => typeof key === 'string' && Object.prototype.hasOwnProperty.call(object, key); + +/** + * @param {string} method Dotted SDK method name sent by a project. + * @returns {object|null} The allowlist entry, or null if projects may not call it. + */ +const projectMethod = method => (has(PROJECT_METHODS, method) ? PROJECT_METHODS[method] : null); + +// Every scope some project block can use. A project may only ask for these. +const PROJECT_SCOPES = new Set(Object.values(PROJECT_METHODS).flatMap(spec => spec.scopes)); + +// Scopes whose only methods ask for confirmation on every call, so granting +// the scope by itself lets the project do nothing without asking again. +const CONFIRMED_ONLY_SCOPES = new Set([...PROJECT_SCOPES].filter(scope => { + const users = Object.values(PROJECT_METHODS).filter(spec => spec.scopes.includes(scope)); + return users.every(spec => spec.confirm); +})); + +/** + * Whether a set of requested scopes can be granted without a consent prompt: + * read-only scopes, and scopes whose every use is confirmed per call. + * @param {string[]} scopes Requested scopes, all known project scopes. + * @returns {boolean} True to grant silently. + */ +const grantsSilently = scopes => scopes.every(scope => scope.endsWith(':view') || CONFIRMED_ONLY_SCOPES.has(scope)); + +/** + * Validate a scope request from a project. + * @param {unknown} scopes Whatever the project sent. + * @returns {string[]|null} The scopes, or null if any is not a project scope. + */ +const validateProjectScopes = scopes => { + if (!Array.isArray(scopes)) return null; + const list = [...new Set(scopes)]; + return list.every(scope => typeof scope === 'string' && PROJECT_SCOPES.has(scope)) ? list : null; +}; + +/** + * Check a call from a project against the allowlist and the project's grant. + * @param {string} method Dotted SDK method name. + * @param {unknown} args Arguments the project sent. + * @param {string[]} granted Scopes this project has been granted. + * @param {string} storageId The project's own storage id, chosen by the host. + * @returns {object} What to run: {spec, args, confirm}. + */ +const authorizeProjectCall = (method, args, granted, storageId) => { + const spec = projectMethod(method); + if (!spec) { + throw new Error(`Projects cannot call Rotur method: ${String(method).slice(0, 80)}`); + } + let list = Array.isArray(args) ? args.slice(0, 8) : []; + if (spec.scopes.length && !spec.confirm && !spec.scopes.some(scope => granted.includes(scope))) { + throw new Error('Rotur access was not granted for this project'); + } + if (spec.projectStorage) { + // A project only ever reaches its own storage bag. + list = [storageId || 'mistwarp', ...list.slice(1)]; + } + return {spec, args: list, confirm: spec.confirm ? spec.confirm(list) : null}; +}; + +/** + * Run an allowlisted method on a Rotur client. The path is a key of the + * allowlist, never something taken straight from a project. + * @param {object} client A rotur-sdk Rotur instance. + * @param {string} method An allowlisted method name. + * @param {Array} args Arguments. + * @returns {Promise} The SDK result. + */ +const invokeProjectMethod = async (client, method, args) => { + if (!projectMethod(method)) { + throw new Error(`Projects cannot call Rotur method: ${String(method).slice(0, 80)}`); + } + const [namespace, name] = method.split('.'); + if (namespace === 'socket' && (!client.socket || !client.socket.connected)) { + await client.connectSocket(); + } + const owner = namespace === 'socket' ? client.socket : client[namespace]; + const fn = owner && owner[name]; + if (typeof fn !== 'function') { + throw new Error(`Rotur method is unavailable: ${method}`); + } + return fn.apply(owner, args); +}; + +export { + PROJECT_METHODS, + PROJECT_SCOPES, + projectMethod, + grantsSilently, + validateProjectScopes, + authorizeProjectCall, + invokeProjectMethod +}; diff --git a/src/packager/scaffolding/account-host.js b/src/packager/scaffolding/account-host.js index 047e3aa729f..ccd664e9d49 100644 --- a/src/packager/scaffolding/account-host.js +++ b/src/packager/scaffolding/account-host.js @@ -1,6 +1,9 @@ import {Rotur} from 'rotur-sdk'; import {scopesUsedByProject} from 'scratch-vm/src/extensions/rotur/core'; import {APP_NAME} from '../../lib/constants/brand'; +import { + authorizeProjectCall, invokeProjectMethod, validateProjectScopes +} from '../../lib/rotur/project-methods'; const ACCOUNT_EXTENSIONS = new Set([ 'rotur', 'roturEconomy', 'roturKeys', 'roturStatus', 'roturSocial', 'roturShop', 'roturGroups', 'roturFiles', @@ -131,23 +134,23 @@ export const createAccountHost = (runtime, options = {}, Client = Rotur) => { projectName: () => title, projectImage: () => '', grantedScopes: () => granted.slice(), - ensureConsent, - async call (method, args = [], opts = {}) { + // Project code (and any extension loaded next to it) can reach this host + // through the VM, so it only gets project scopes and allowlisted methods. + ensureConsent: scopes => { + const valid = validateProjectScopes(scopes); + if (!valid) return Promise.reject(new Error('Projects cannot ask for that Rotur permission')); + return ensureConsent(valid); + }, + async call (method, args = []) { await ready; if (!user.loggedIn) throw new Error('Sign in with Rotur to use this project.'); - if (opts.sensitive && !window.confirm(`${opts.label || method}\n${opts.confirmation ? JSON.stringify(opts.confirmation) : ''}`)) { + const call = authorizeProjectCall(method, args, granted, roturHost.projectId()); + if (call.confirm && !window.confirm(`Allow ${title} to ${call.confirm.label}?`)) { throw new Error('You cancelled this Rotur action'); } if (['socket.addActivity', 'socket.setStatus'].includes(method) && !window.confirm(`Allow ${title} to update your Rotur activity?`)) return ''; - const parts = method.split('.'); - if (parts.some(part => ['__proto__', 'prototype', 'constructor'].includes(part))) throw new Error('Invalid Rotur method'); - if (parts[0] === 'socket' && (!client.socket || !client.socket.connected)) await client.connectSocket(); - let owner = client; - for (const part of parts.slice(0, -1)) owner = owner && owner[part]; - const fn = owner && owner[parts[parts.length - 1]]; - if (typeof fn !== 'function') throw new Error(`Unknown Rotur method: ${method}`); - return fn.apply(owner, args); + return invokeProjectMethod(client, method, call.args); } }; diff --git a/test/unit/community-project-rotur-bridge.test.jsx b/test/unit/community-project-rotur-bridge.test.jsx new file mode 100644 index 00000000000..ca8c015ba2d --- /dev/null +++ b/test/unit/community-project-rotur-bridge.test.jsx @@ -0,0 +1,175 @@ +import React from 'react'; +import {act} from 'react-dom/test-utils'; +import {mount} from 'enzyme'; +import {MemoryRouter, Route, Routes} from 'react-router-dom'; + +import api from '../../src/community/api.js'; +import Project from '../../src/community/pages/Project.jsx'; +import {setMockUserContext} from '../../src/community/UserContext.jsx'; +import rotur from '../../src/community/rotur.js'; + +const mockClient = { + loggedIn: true, + _http: {getToken: () => 'rotur_secret-token'}, + setToken: jest.fn(), + tokens: {create: jest.fn(() => Promise.resolve({token: 'rotur_new-token'}))}, + me: { + transfer: jest.fn(() => Promise.resolve({ok: true})), + get: jest.fn(() => Promise.resolve({username: 'Viewer'})) + }, + profiles: {get: jest.fn(() => Promise.resolve({username: 'someone'}))}, + storage: {get: jest.fn(() => Promise.resolve({data: {}}))} +}; + +jest.mock('../../src/community/UserContext.jsx', () => { + let state = {user: null, loading: true, login: jest.fn()}; + return { + useUser: () => state, + setMockUserContext: next => { + state = next; + } + }; +}); +jest.mock('../../src/lib/themes/custom-themes.js', () => ({ + CustomTheme: {}, + customThemeManager: {themes: {clear: jest.fn()}, loadCustomThemes: jest.fn()} +})); +jest.mock('../../src/community/rotur.js', () => ({ + following: jest.fn() +})); +jest.mock('../../src/lib/rotur/client.js', () => ({ + getBalance: jest.fn(() => Promise.resolve(0)), + getRotur: () => mockClient, + ensureScopes: jest.fn(() => Promise.resolve()) +})); +jest.mock('../../src/lib/community/cached-fetch.js', () => ({ + cachedFetchBuffer: jest.fn(() => Promise.resolve(new ArrayBuffer(0))), + preloadContent: jest.fn(() => Promise.resolve()) +})); + +const Harness = () => ( + + + } /> + + +); + +const flush = async () => { + for (let i = 0; i < 6; i++) { + await Promise.resolve(); + } +}; + +const mountProject = async () => { + rotur.following.mockResolvedValue({following: []}); + jest.spyOn(api, 'getProject').mockResolvedValue({ + project: { + id: 'project-1', + title: 'Project', + owner: 'Creator', + projectJsonUrl: 'https://projects.example/project-1.sb3', + assetsBase: 'https://assets.example/', + hasContent: true, + visibility: 'public' + } + }); + jest.spyOn(api, 'commits').mockResolvedValue({commits: []}); + jest.spyOn(api, 'view').mockResolvedValue({}); + setMockUserContext({user: {username: 'Viewer'}, loading: false, login: jest.fn()}); + const container = document.createElement('div'); + document.body.appendChild(container); + const wrapper = mount(, {attachTo: container}); + await act(flush); + wrapper.update(); + const frame = wrapper.find('iframe').getDOMNode(); + const replies = []; + jest.spyOn(frame.contentWindow, 'postMessage').mockImplementation(message => { + if (message && message.type === 'mw:rotur-result') replies.push(message); + }); + // What a custom extension running inside the player can send. + const send = async data => { + await act(async () => { + window.dispatchEvent(new MessageEvent('message', { + data: {type: 'mw:rotur', ...data}, + source: frame.contentWindow + })); + await flush(); + }); + wrapper.update(); + return replies.find(reply => reply.id === data.id); + }; + return {wrapper, send}; +}; + +describe('community project page Rotur bridge', () => { + afterEach(() => { + localStorage.removeItem('mw:rotur-grants'); + jest.restoreAllMocks(); + }); + + test('never hands the token or private SDK methods to the player', async () => { + const {wrapper, send} = await mountProject(); + for (const [id, method] of [ + [1, '_http.getToken'], [2, 'setToken'], [3, 'tokens.create'], [4, 'constructor.constructor'] + ]) { + const reply = await send({kind: 'call', id, method, args: ['rotur_attacker']}); + expect(reply.ok).toBe(false); + expect(JSON.stringify(reply)).not.toContain('rotur_secret-token'); + } + expect(mockClient.setToken).not.toHaveBeenCalled(); + expect(mockClient.tokens.create).not.toHaveBeenCalled(); + wrapper.unmount(); + }); + + test('a payment always shows the real amount and recipient, whatever the frame claims', async () => { + const {wrapper, send} = await mountProject(); + const pending = send({ + kind: 'call', + id: 5, + method: 'me.transfer', + args: ['thief', 5000, ''], + opts: {sensitive: false, label: 'claim a free hat'} + }); + await pending; + expect(mockClient.me.transfer).not.toHaveBeenCalled(); + expect(wrapper.text()).toContain('Confirm payment'); + expect(wrapper.text()).toContain('5000'); + expect(wrapper.text()).toContain('@thief'); + expect(wrapper.text()).not.toContain('free hat'); + wrapper.unmount(); + }); + + test('the frame cannot skip consent or pick another project grant', async () => { + localStorage.setItem('mw:rotur-grants', JSON.stringify({'name:Other': ['posts:create']})); + const {wrapper, send} = await mountProject(); + const consent = send({ + kind: 'consent', + id: 6, + scopes: ['posts:create'], + meta: {name: 'Other', authenticatedOnly: true} + }); + await consent; + expect(wrapper.text()).toContain('Connect to Rotur'); + const call = await send({kind: 'call', id: 7, method: 'posts.create', args: ['spam']}); + expect(call.ok).toBe(false); + expect(call.error).toContain('not granted'); + const scopeReply = await send({kind: 'consent', id: 8, scopes: ['tokens:manage']}); + expect(scopeReply.ok).toBe(false); + wrapper.unmount(); + }); + + test('allowlisted public reads still work and storage stays on this project', async () => { + const {wrapper, send} = await mountProject(); + const reply = await send({kind: 'call', id: 9, method: 'profiles.get', args: ['someone']}); + expect(reply).toMatchObject({ok: true, result: {username: 'someone'}}); + await send({kind: 'consent', id: 10, scopes: ['storage:view']}); + const storage = await send({kind: 'call', id: 11, method: 'storage.get', args: ['victim-project']}); + expect(storage.ok).toBe(true); + expect(mockClient.storage.get).toHaveBeenCalledWith('project-1'); + wrapper.unmount(); + }); +}); diff --git a/test/unit/packager-account.test.js b/test/unit/packager-account.test.js index 443cea66d1e..df8e49d924e 100644 --- a/test/unit/packager-account.test.js +++ b/test/unit/packager-account.test.js @@ -35,7 +35,39 @@ test('account projects wait for verified login and expose identity to both exten expect(runtime.mistwarpGameHost.getUser()).toEqual(runtime.roturHost.getUser()); expect(runtime.ioDevices.userData.postData).toHaveBeenCalledWith({username: 'player'}); expect(localStorage.length).toBe(0); - await expect(runtime.roturHost.call('constructor.constructor', [])).rejects.toThrow('Invalid Rotur method'); + await expect(runtime.roturHost.call('constructor.constructor', [])).rejects.toThrow('Projects cannot call'); +}); + +test('extensions in an export cannot reach the token or unlisted SDK methods', async () => { + const sdk = client(); + sdk._http = {getToken: jest.fn(() => 'rotur_export-token')}; + sdk.tokens = {create: jest.fn()}; + const runtime = runtimeFor('rotur_username'); + const host = createAccountHost(runtime, {}, function () { return sdk; }); + const ready = host.prepare(); + await document.querySelector('button').onclick(); + await ready; + for (const method of ['_http.getToken', 'tokens.create', 'setToken', '__proto__.constructor']) { + await expect(runtime.roturHost.call(method, [])).rejects.toThrow('Projects cannot call'); + } + expect(sdk._http.getToken).not.toHaveBeenCalled(); + expect(sdk.tokens.create).not.toHaveBeenCalled(); + await expect(runtime.roturHost.ensureConsent(['tokens:manage'])).rejects.toThrow('cannot ask'); +}); + +test('a payment is confirmed with the real amount even when the caller says it is not sensitive', async () => { + const sdk = client(); + sdk.me.transfer = jest.fn(); + const runtime = runtimeFor('roturEconomy_pay'); + const host = createAccountHost(runtime, {title: 'Game'}, function () { return sdk; }); + const ready = host.prepare(); + await document.querySelector('button').onclick(); + await ready; + const confirm = jest.spyOn(window, 'confirm').mockReturnValue(false); + await expect(runtime.roturHost.call('me.transfer', ['thief', 500], {sensitive: false})) + .rejects.toThrow('cancelled'); + expect(confirm).toHaveBeenCalledWith('Allow Game to send 500 credits to @thief?'); + expect(sdk.me.transfer).not.toHaveBeenCalled(); }); test('failed authentication keeps project gated and permits retry', async () => { diff --git a/test/unit/rotur-extension-host.test.js b/test/unit/rotur-extension-host.test.js index 16a20d43056..f7a6538d878 100644 --- a/test/unit/rotur-extension-host.test.js +++ b/test/unit/rotur-extension-host.test.js @@ -38,7 +38,7 @@ test('trusted projects skip Rotur permission prompts', async () => { await expect(host.ensureConsent(['posts:create'], {name: 'Project'})).resolves.toBe(true); await expect(host.ensureActivitySharing()).resolves.toBe(true); - expect(commitGrant).toHaveBeenCalledWith({name: 'Project'}, ['posts:create']); + expect(commitGrant).toHaveBeenCalledWith({name: ''}, ['posts:create']); expect(host.acquireModalLock).not.toHaveBeenCalled(); }); @@ -50,13 +50,13 @@ test('trusted projects still confirm sensitive Rotur actions', async () => { host.acquireModalLock = jest.fn(() => Promise.resolve({showModal})); await host.call('me.transfer', ['other-user', 10, ''], { - sensitive: true, - label: 'me.transfer', - confirmation: {type: 'payment', amount: 10, recipient: 'other-user'} + sensitive: false, + label: 'claim a free hat', + confirmation: {type: 'payment', amount: 1, recipient: 'friend'} }); expect(showModal).toHaveBeenCalledWith('confirm', { - label: 'me.transfer', + label: 'send 10 credits to @other-user', confirmation: {type: 'payment', amount: 10, recipient: 'other-user'}, username: 'user' }); @@ -74,13 +74,37 @@ test('authenticated reads expand scopes without prompting', async () => { authenticatedOnly: true })).resolves.toBe(true); - expect(commitGrant).toHaveBeenCalledWith({ - name: 'Project', - authenticatedOnly: true - }, ['credits:view']); + expect(commitGrant).toHaveBeenCalledWith({name: ''}, ['credits:view']); expect(host.acquireModalLock).not.toHaveBeenCalled(); }); +test('the project cannot skip consent by calling itself authenticated-only', async () => { + const host = new RoturExtensionHost({ + vm: {runtime: {projectName: 'Project'}} + }); + const showModal = jest.fn(() => Promise.resolve(false)); + host.acquireModalLock = jest.fn(() => Promise.resolve({showModal})); + commitGrant.mockClear(); + + await expect(host.ensureConsent(['posts:create'], {name: 'Other', authenticatedOnly: true})) + .resolves.toBe(false); + + expect(showModal).toHaveBeenCalledWith('consent', expect.objectContaining({scopes: ['posts:create']})); + expect(commitGrant).not.toHaveBeenCalled(); + await expect(host.ensureConsent(['tokens:manage'])).rejects.toThrow('cannot ask'); +}); + +test('rejects methods outside the allowlist and ungranted scopes', async () => { + const host = new RoturExtensionHost({ + vm: {runtime: {}} + }); + callRotur.mockClear(); + + await expect(host.call('_http.getToken', [])).rejects.toThrow('Projects cannot call'); + await expect(host.call('posts.create', ['spam'])).rejects.toThrow('not granted'); + expect(callRotur).not.toHaveBeenCalled(); +}); + test('blocked projects cannot reopen Rotur prompts', async () => { sessionStorage.setItem('mw:mistwarp-current-project', JSON.stringify({id: 'blocked-project'})); const host = new RoturExtensionHost({ diff --git a/test/unit/rotur-project-methods.test.js b/test/unit/rotur-project-methods.test.js new file mode 100644 index 00000000000..14021748820 --- /dev/null +++ b/test/unit/rotur-project-methods.test.js @@ -0,0 +1,155 @@ +import {Rotur} from 'rotur-sdk'; +import { + PROJECT_METHODS, + authorizeProjectCall, + grantsSilently, + invokeProjectMethod, + projectMethod, + validateProjectScopes +} from '../../src/lib/rotur/project-methods.js'; + +const roturExtensions = require('scratch-vm/src/extensions/rotur/index.js'); + +// Run every block of every built-in Rotur extension against a recording host, +// so the allowlist is checked against what the extensions really send. +const recordExtensionCalls = async () => { + const calls = []; + for (const Extension of Object.values(roturExtensions)) { + let consented = []; + const host = { + whenReady: () => Promise.resolve(), + getUser: () => ({loggedIn: true, username: 'player', id: '1'}), + projectId: () => 'project-1', + projectName: () => 'Project', + projectImage: () => '', + ensureConsent: scopes => { + consented = scopes; + return Promise.resolve(true); + }, + call: (method, args, opts) => { + calls.push({method, args, opts, scopes: consented}); + return Promise.resolve({}); + } + }; + const runtime = {roturHost: host, targets: []}; + const extension = new Extension(runtime); + for (const block of extension.getInfo().blocks) { + if (!block.opcode) continue; + const args = Object.fromEntries(Object.entries(block.arguments) + .map(([name, arg]) => [name, arg.defaultValue])); + consented = []; + await extension[block.opcode](args); + } + } + return calls; +}; + +test('every method the built-in Rotur extensions call is allowlisted with its scope', async () => { + const calls = await recordExtensionCalls(); + expect(calls.length).toBeGreaterThan(80); + for (const {method, opts, scopes} of calls) { + const spec = projectMethod(method); + expect({method, allowed: Boolean(spec)}).toEqual({method, allowed: true}); + for (const scope of scopes) { + expect({method, scope, covered: spec.scopes.includes(scope)}) + .toEqual({method, scope, covered: true}); + } + if (opts && opts.sensitive) { + expect({method, confirmed: Boolean(spec.confirm)}).toEqual({method, confirmed: true}); + } + } + const used = new Set(calls.map(call => call.method)); + expect(Object.keys(PROJECT_METHODS).filter(method => !used.has(method))).toEqual([]); +}); + +test.each([ + '_http.getToken', + '_http.post', + 'constructor', + 'constructor.constructor', + '__proto__.toString', + 'toString', + 'hasOwnProperty', + 'setToken', + 'logout', + 'tokens.create', + 'tokens.list', + 'validators.generate', + 'signing.sign', + 'me.deleteAccount', + 'me.update', + 'admin.transferCredits', + 'me.transfer.call', + 'socket.token', + 'socket.send', + '' +])('rejects %j', method => { + expect(projectMethod(method)).toBeNull(); + expect(() => authorizeProjectCall(method, [], ['credits:transfer'], 'project-1')) + .toThrow('Projects cannot call Rotur method'); +}); + +test('rejects non-string method names', () => { + for (const method of [null, undefined, 1, {}, ['me', 'get']]) { + expect(() => authorizeProjectCall(method, [], [], 'project-1')).toThrow('Projects cannot call'); + } +}); + +test('the token is never reachable through the dispatcher', async () => { + const client = new Rotur({token: 'rotur_secret-token'}); + await expect(invokeProjectMethod(client, '_http.getToken', [])).rejects.toThrow('Projects cannot call'); + await expect(invokeProjectMethod(client, 'socket.token', [])).rejects.toThrow('Projects cannot call'); +}); + +test('a scoped method needs a grant for one of its scopes', () => { + expect(() => authorizeProjectCall('posts.create', ['hi'], [], 'p')).toThrow('not granted'); + expect(() => authorizeProjectCall('posts.create', ['hi'], ['posts:like'], 'p')).toThrow('not granted'); + expect(authorizeProjectCall('posts.create', ['hi'], ['posts:create'], 'p').args).toEqual(['hi']); + expect(authorizeProjectCall('me.get', [], ['credits:view'], 'p').confirm).toBeNull(); + expect(authorizeProjectCall('profiles.get', ['someone'], [], 'p').args).toEqual(['someone']); +}); + +test('spending methods are confirmed with text the host builds from the arguments', () => { + const call = authorizeProjectCall('me.transfer', ['thief', 999, 'note'], [], 'p'); + expect(call.confirm).toEqual({ + label: 'send 999 credits to @thief', + confirmation: {type: 'payment', amount: 999, recipient: 'thief'} + }); + expect(authorizeProjectCall('groups.sendTip', ['tag', '5'], [], 'p').confirm.label) + .toBe('tip 5 credits to group tag'); + for (const method of [ + 'me.transfer', 'gifts.create', 'gifts.claim', 'keys.buy', 'keys.cancel', 'keys.delete', + 'posts.delete', 'items.buy', 'items.transfer', 'cosmetics.purchase', + 'groups.sendTip', 'groups.purchaseProduct' + ]) { + expect({method, confirm: Boolean(projectMethod(method).confirm)}).toEqual({method, confirm: true}); + } +}); + +test('project storage always uses the host project id', () => { + expect(authorizeProjectCall('storage.get', ['other-project'], ['storage:view'], 'mine').args) + .toEqual(['mine']); + expect(authorizeProjectCall('storage.set', ['other-project', 'k', 'v'], ['storage:manage'], 'mine').args) + .toEqual(['mine', 'k', 'v']); + expect(authorizeProjectCall('storage.delete', ['x', 'k'], ['storage:delete'], '').args) + .toEqual(['mistwarp', 'k']); +}); + +test('projects may only ask for scopes their blocks can use', () => { + expect(validateProjectScopes(['posts:create', 'posts:create', 'credits:view'])) + .toEqual(['posts:create', 'credits:view']); + for (const scope of ['tokens:manage', 'account:delete', 'signing:private', 'account:settings', + 'validators:generate', 'full', 'constructor', 7]) { + expect(validateProjectScopes(['posts:create', scope])).toBeNull(); + } + expect(validateProjectScopes('posts:create')).toBeNull(); +}); + +test('only read scopes and per-call-confirmed scopes are granted without asking', () => { + expect(grantsSilently(['credits:view', 'account:view'])).toBe(true); + expect(grantsSilently(['credits:transfer'])).toBe(true); + expect(grantsSilently(['posts:delete'])).toBe(true); + expect(grantsSilently(['posts:create'])).toBe(false); + expect(grantsSilently(['keys:manage'])).toBe(false); + expect(grantsSilently(['credits:view', 'storage:manage'])).toBe(false); +});