diff --git a/src/extensions/rotur/core.js b/src/extensions/rotur/core.js index cb043548e1..b2adc134e0 100644 --- a/src/extensions/rotur/core.js +++ b/src/extensions/rotur/core.js @@ -3,6 +3,35 @@ const BlockType = require('../../extension-support/block-type'); const scopeByOpcode = new Map(); +// The SDK methods the built-in Rotur blocks call, filled in from their specs +// by defineExtension. The fallback host only dispatches these, so code that +// reaches the host through the runtime cannot walk to private SDK internals +// such as the token. Confirmed methods ask before every call. +const projectMethods = new Set([ + 'me.abilities', + 'storage.get', 'storage.set', 'storage.delete', + 'socket.addActivity', 'socket.removeActivity', 'socket.setStatus' +]); +const confirmedMethods = new Map(); +const projectScopes = new Set(); + +const registerSpec = spec => { + if (spec.scope) { + projectScopes.add(spec.scope); + } + if (spec.method) { + projectMethods.add(spec.method); + if (spec.sensitive) { + confirmedMethods.set(spec.method, spec); + } + } +}; + +const confirmLabel = method => { + const spec = confirmedMethods.get(method); + return typeof spec.confirm === 'string' ? spec.confirm : method; +}; + const registerScope = (fullOpcode, scope) => { if (scope) { scopeByOpcode.set(fullOpcode, scope); @@ -24,6 +53,7 @@ const buildBlocks = (extensionId, specs) => specs.map(spec => { return {blockType: BlockType.LABEL, text: spec.label}; } registerScope(`${extensionId}_${spec.opcode}`, spec.scope); + registerSpec(spec); const block = { opcode: spec.opcode, blockType: spec.blockType || BlockType.REPORTER, @@ -35,6 +65,9 @@ const buildBlocks = (extensionId, specs) => specs.map(spec => { if (spec.isEdgeActivated) { block.isEdgeActivated = true; } + if (Object.prototype.hasOwnProperty.call(spec, 'removed')) { + block.hideFromPalette = true; + } return block; }); @@ -144,15 +177,16 @@ const createSdkHost = runtime => { } return clientPromise; }; - const resolveMethod = (rotur, method) => { - const parts = method.split('.'); - let ctx = rotur; - let fn = rotur; - for (const part of parts) { - ctx = fn; - fn = fn && fn[part]; + const checkMethod = method => { + if (typeof method !== 'string' || !projectMethods.has(method)) { + throw new Error(`Projects cannot call Rotur method: ${String(method).slice(0, 80)}`); } - return {fn, ctx}; + }; + const resolveMethod = (rotur, method) => { + checkMethod(method); + const [namespace, name] = method.split('.'); + const ctx = rotur[namespace]; + return {fn: ctx && ctx[name], ctx}; }; const resolveProjectId = () => { try { @@ -180,6 +214,9 @@ const createSdkHost = runtime => { return ''; }, async ensureConsent (scopes) { + if (!Array.isArray(scopes) || !scopes.every(scope => projectScopes.has(scope))) { + throw new Error('Projects cannot ask for that Rotur permission'); + } const known = wantedScopes(); const missing = (scopes || []).filter(scope => !known.includes(scope)); if (missing.length) { @@ -190,12 +227,20 @@ const createSdkHost = runtime => { return true; }, async call (method, args) { + checkMethod(method); + const list = Array.isArray(args) ? args : []; const rotur = await getClient(); const {fn, ctx} = resolveMethod(rotur, method); if (typeof fn !== 'function') { throw new Error(`Unknown Rotur method: ${method}`); } - return fn.apply(ctx, args); + if (confirmedMethods.has(method) && + !(typeof window !== 'undefined' && typeof window.confirm === 'function' && + // eslint-disable-next-line no-alert + window.confirm(`Allow ${projectLabel() || 'this project'} to ${confirmLabel(method)}?`))) { + throw new Error('You cancelled this Rotur action'); + } + return fn.apply(ctx, list); } }; }; @@ -362,6 +407,10 @@ const scrub = value => { }; const run = async (extension, spec, args) => { + // A removed block answers its fixed value without reaching Rotur. + if (Object.prototype.hasOwnProperty.call(spec, 'removed')) { + return spec.removed; + } const runtime = extension.runtime; const host = getHost(runtime); diff --git a/src/extensions/rotur/index.js b/src/extensions/rotur/index.js index b805f9bfd1..1d09e7081d 100644 --- a/src/extensions/rotur/index.js +++ b/src/extensions/rotur/index.js @@ -22,11 +22,11 @@ const account = ext('rotur', 'Rotur Account', [ {opcode: 'myId', blockType: R, text: 'my user id', local: 'id'}, {label: 'Permissions'}, {opcode: 'myPermissions', blockType: R, text: 'permissions I have', local: 'permissions'}, - {opcode: 'allows', blockType: B, text: 'does my login allow [SCOPE]?', args: {SCOPE: 'credits:transfer'}, local: 'allows'}, - {opcode: 'request', blockType: C, text: 'ask to allow [SCOPES]', args: {SCOPES: 'credits:transfer, posts:create'}, local: 'request'}, + {opcode: 'allows', blockType: B, text: 'does my login allow [SCOPE]?', args: {SCOPE: 'posts:create'}, local: 'allows'}, + {opcode: 'request', blockType: C, text: 'ask to allow [SCOPES]', args: {SCOPES: 'account:view, posts:create'}, local: 'request'}, {label: 'Account'}, {opcode: 'accountInfo', blockType: R, text: 'my account info', method: 'me.get', scope: 'account:view', map: () => [], result: r => r}, - {opcode: 'accountField', blockType: R, text: 'my account [FIELD]', args: {FIELD: 'sys.currency'}, method: 'me.get', scope: 'account:view', map: () => [], result: (r, a) => (r && typeof r === 'object' ? r[a.FIELD] : '')}, + {opcode: 'accountField', blockType: R, text: 'my account [FIELD]', args: {FIELD: 'username'}, method: 'me.get', scope: 'account:view', map: () => [], result: (r, a) => (r && typeof r === 'object' ? r[a.FIELD] : '')}, {opcode: 'checkAuth', blockType: B, text: 'is my login valid?', method: 'me.checkAuth', map: () => [], result: r => Boolean(r && r.username)}, {opcode: 'myBadges', blockType: R, text: 'my badges', method: 'me.badges', scope: 'account:view', map: () => [], result: r => JSON.stringify((r && r.badge_names) || [])}, {opcode: 'mySubscription', blockType: R, text: 'my subscription', method: 'me.subscription', scope: 'account:view', map: () => []}, @@ -44,12 +44,17 @@ const account = ext('rotur', 'Rotur Account', [ ]); const economy = ext('roturEconomy', 'Rotur Economy', [ - {opcode: 'balance', blockType: R, text: 'my credits', method: 'me.get', scope: 'credits:view', map: () => [], result: r => (r && typeof r['sys.currency'] === 'number' ? r['sys.currency'] : 0)}, - {opcode: 'pay', blockType: C, text: 'send [AMOUNT] credits to [USER] with message [NOTE]', args: {AMOUNT: num(1), USER: 'username', NOTE: ''}, method: 'me.transfer', scope: 'credits:transfer', sensitive: true, confirm: a => ({type: 'payment', amount: Number(a.AMOUNT) || 0, recipient: String(a.USER || '')}), map: a => [a.USER, Number(a.AMOUNT) || 0, a.NOTE]}, - {opcode: 'dailyWait', blockType: R, text: 'seconds until daily claim', method: 'me.claimTime', scope: 'credits:view', map: () => [], result: r => (r && typeof r.wait_time === 'number' ? r.wait_time : 0)}, - {opcode: 'transactions', blockType: R, text: 'my transaction history', method: 'me.transactions', scope: 'credits:view', map: () => []}, + // Blocks marked removed, here and in the other Rotur extensions, read or + // spent credits, which projects can no longer do through MistWarp: its + // own payments go through Rotur payment requests. They stay, hidden, so + // projects that use them still load, but they do nothing and ask for no + // permission. + {opcode: 'balance', blockType: R, text: 'my credits', removed: 0}, + {opcode: 'pay', blockType: C, text: 'send [AMOUNT] credits to [USER] with message [NOTE]', args: {AMOUNT: num(1), USER: 'username', NOTE: ''}, removed: ''}, + {opcode: 'dailyWait', blockType: R, text: 'seconds until daily claim', removed: 0}, + {opcode: 'transactions', blockType: R, text: 'my transaction history', removed: ''}, {label: 'Gifts'}, - {opcode: 'createGift', blockType: R, text: 'create a gift of [AMOUNT] credits', args: {AMOUNT: num(10)}, method: 'gifts.create', scope: 'gifts:create', sensitive: true, confirm: 'create a credit gift', map: a => [Number(a.AMOUNT) || 0]}, + {opcode: 'createGift', blockType: R, text: 'create a gift of [AMOUNT] credits', args: {AMOUNT: num(10)}, removed: ''}, {opcode: 'giftInfo', blockType: R, text: 'gift info for code [CODE]', args: {CODE: 'code'}, method: 'gifts.get', map: a => [a.CODE]}, {opcode: 'claimGift', blockType: C, text: 'claim gift code [CODE]', args: {CODE: 'code'}, method: 'gifts.claim', scope: 'gifts:claim', sensitive: true, confirm: 'claim this gift', map: a => [a.CODE]}, {opcode: 'cancelGift', blockType: C, text: 'cancel gift [ID]', args: {ID: 'id'}, method: 'gifts.cancel', scope: 'gifts:cancel', map: a => [a.ID]}, @@ -63,7 +68,7 @@ const keys = ext('roturKeys', 'Rotur Keys', [ {opcode: 'myKeys', blockType: R, text: 'my keys', method: 'keys.mine', scope: 'keys:view', map: () => []}, {opcode: 'keyInfo', blockType: R, text: 'details of key [ID]', args: {ID: 'id'}, method: 'keys.get', map: a => [a.ID]}, {opcode: 'userHasKey', blockType: B, text: 'does [USER] own key [KEY]?', args: {USER: 'username', KEY: 'key'}, method: 'keys.check', map: a => [a.USER, a.KEY], result: r => Boolean(r && (r.owns || r.owned || r.has))}, - {opcode: 'buyKey', blockType: C, text: 'buy key [ID]', args: {ID: 'id'}, method: 'keys.buy', sensitive: true, confirm: 'buy this key', map: a => [a.ID]}, + {opcode: 'buyKey', blockType: C, text: 'buy key [ID]', args: {ID: 'id'}, removed: ''}, {opcode: 'cancelKey', blockType: C, text: 'cancel key [ID]', args: {ID: 'id'}, method: 'keys.cancel', sensitive: true, confirm: 'cancel this key', map: a => [a.ID]}, {label: 'Manage my keys'}, {opcode: 'renameKey', blockType: C, text: 'rename key [ID] to [NAME]', args: {ID: 'id', NAME: 'name'}, method: 'keys.rename', scope: 'keys:manage', map: a => [a.ID, a.NAME]}, @@ -120,7 +125,7 @@ const shop = ext('roturShop', 'Rotur Shop', [ {opcode: 'item', blockType: R, text: 'item [NAME]', args: {NAME: 'name'}, method: 'items.get', map: a => [a.NAME]}, {opcode: 'itemsForSale', blockType: R, text: 'items for sale', method: 'items.selling', map: () => []}, {opcode: 'userItems', blockType: R, text: "[USER]'s items", args: {USER: 'username'}, method: 'items.list', map: a => [a.USER]}, - {opcode: 'buyItem', blockType: C, text: 'buy item [NAME]', args: {NAME: 'name'}, method: 'items.buy', scope: 'items:buy', sensitive: true, confirm: 'buy this item', map: a => [a.NAME]}, + {opcode: 'buyItem', blockType: C, text: 'buy item [NAME]', args: {NAME: 'name'}, removed: ''}, {opcode: 'sellItem', blockType: C, text: 'put item [NAME] up for sale', args: {NAME: 'name'}, method: 'items.sell', scope: 'items:sell', map: a => [a.NAME]}, {opcode: 'stopSelling', blockType: C, text: 'stop selling item [NAME]', args: {NAME: 'name'}, method: 'items.stopSelling', scope: 'items:sell', map: a => [a.NAME]}, {opcode: 'setItemPrice', blockType: C, text: 'set price of item [NAME] to [PRICE]', args: {NAME: 'name', PRICE: num(1)}, method: 'items.setPrice', scope: 'items:sell', map: a => [a.NAME, Number(a.PRICE) || 0]}, @@ -128,7 +133,7 @@ const shop = ext('roturShop', 'Rotur Shop', [ {label: 'Cosmetics'}, {opcode: 'cosmeticShop', blockType: R, text: 'cosmetics shop', method: 'cosmetics.shop', map: () => []}, {opcode: 'myCosmetics', blockType: R, text: 'my cosmetics', method: 'cosmetics.mine', scope: 'cosmetics:view', map: () => []}, - {opcode: 'buyCosmetic', blockType: C, text: 'buy cosmetic [ID]', args: {ID: 'id'}, method: 'cosmetics.purchase', scope: 'cosmetics:buy', sensitive: true, confirm: 'buy this cosmetic', map: a => [a.ID]}, + {opcode: 'buyCosmetic', blockType: C, text: 'buy cosmetic [ID]', args: {ID: 'id'}, removed: ''}, {opcode: 'equipCosmetic', blockType: C, text: 'equip cosmetic [ID]', args: {ID: 'id'}, method: 'cosmetics.equip', scope: 'cosmetics:equip', map: a => [a.ID]}, {opcode: 'unequipCosmetic', blockType: C, text: 'unequip cosmetic type [TYPE]', args: {TYPE: 'hat'}, method: 'cosmetics.unequip', scope: 'cosmetics:equip', map: a => [a.TYPE]}, {opcode: 'cosmeticsOf', blockType: R, text: "[USER]'s cosmetics", args: {USER: 'username'}, method: 'cosmetics.forUser', map: a => [a.USER]} @@ -148,8 +153,8 @@ const groups = ext('roturGroups', 'Rotur Groups', [ {opcode: 'groupEvents', blockType: R, text: 'events in group [TAG]', args: {TAG: 'tag'}, method: 'groups.events', scope: 'groups:view', map: a => [a.TAG]}, {label: 'Group economy'}, {opcode: 'groupProducts', blockType: R, text: 'products in group [TAG]', args: {TAG: 'tag'}, method: 'groups.products', scope: 'groups:view', map: a => [a.TAG]}, - {opcode: 'tipGroup', blockType: C, text: 'tip [AMOUNT] credits to group [TAG]', args: {AMOUNT: num(1), TAG: 'tag'}, method: 'groups.sendTip', scope: 'credits:manage', sensitive: true, confirm: 'tip this group', map: a => [a.TAG, Number(a.AMOUNT) || 0]}, - {opcode: 'buyGroupProduct', blockType: C, text: 'buy product [PRODUCT] in group [TAG]', args: {PRODUCT: 'id', TAG: 'tag'}, method: 'groups.purchaseProduct', scope: 'credits:manage', sensitive: true, confirm: 'buy this product', map: a => [a.TAG, a.PRODUCT]} + {opcode: 'tipGroup', blockType: C, text: 'tip [AMOUNT] credits to group [TAG]', args: {AMOUNT: num(1), TAG: 'tag'}, removed: ''}, + {opcode: 'buyGroupProduct', blockType: C, text: 'buy product [PRODUCT] in group [TAG]', args: {PRODUCT: 'id', TAG: 'tag'}, removed: ''} ]); const files = ext('roturFiles', 'Rotur Files', [ diff --git a/test/unit/extension_rotur_sdk_host.js b/test/unit/extension_rotur_sdk_host.js index 8488cb90d0..dd00e883ef 100644 --- a/test/unit/extension_rotur_sdk_host.js +++ b/test/unit/extension_rotur_sdk_host.js @@ -15,6 +15,8 @@ global.localStorage = { }; const logins = []; +const transfers = []; +const cancelledKeys = []; let authValid = true; const systems = []; @@ -25,8 +27,19 @@ class FakeRotur { this.socket = {username: 'sophie', userId: '7'}; this.me = { get: () => Promise.resolve({username: 'sophie', id: '7', 'sys.currency': 42}), - checkAuth: () => Promise.resolve({auth: authValid, username: 'sophie'}) + checkAuth: () => Promise.resolve({auth: authValid, username: 'sophie'}), + transfer: (...args) => { + transfers.push(args); + return Promise.resolve({}); + } }; + this.keys = { + cancel: (...args) => { + cancelledKeys.push(args); + return Promise.resolve({}); + } + }; + this._http = {getToken: () => this.token}; } login (options) { logins.push(options.requires); @@ -43,10 +56,12 @@ require.cache[require.resolve('rotur-sdk')] = { exports: {Rotur: FakeRotur} }; -const {RoturAccount, RoturEconomy} = require('../../src/extensions/rotur'); +const {RoturAccount, RoturEconomy, RoturKeys, RoturShop, RoturGroups, RoturSocial} = require('../../src/extensions/rotur'); new RoturAccount({}).getInfo(); new RoturEconomy({}).getInfo(); +new RoturKeys({}).getInfo(); +new RoturSocial({}).getInfo(); const makeRuntime = (opcodes, projectName = 'test') => ({ projectName, @@ -54,38 +69,38 @@ const makeRuntime = (opcodes, projectName = 'test') => ({ }); test('logs in once with only the scopes the project uses', async t => { - const runtime = makeRuntime(['roturEconomy_balance']); - const economy = new RoturEconomy(runtime); + const runtime = makeRuntime(['rotur_accountField']); + const account = new RoturAccount(runtime); - t.equal(await economy.balance({}), 42); - t.equal(await economy.balance({}), 42); - t.same(logins, [['credits:view']]); + t.equal(await account.accountField({FIELD: 'username'}), 'sophie'); + t.equal(await account.accountField({FIELD: 'username'}), 'sophie'); + t.same(logins, [['account:view']]); t.same(systems, ['MistWarp: test']); t.same(JSON.parse(store['mw:rotur-sdk-token']), { token: 'token-1', - scopes: ['credits:view'], + scopes: ['account:view'], system: 'MistWarp: test' }); t.end(); }); test('reuses a stored token with a matching scope set', async t => { - const economy = new RoturEconomy(makeRuntime(['roturEconomy_balance'])); + const account = new RoturAccount(makeRuntime(['rotur_accountField'])); - t.equal(await economy.balance({}), 42); - t.same(logins, [['credits:view']]); + t.equal(await account.accountField({FIELD: 'username'}), 'sophie'); + t.same(logins, [['account:view']]); t.end(); }); test('logs in again when the stored token no longer validates', async t => { authValid = false; - const economy = new RoturEconomy(makeRuntime(['roturEconomy_balance'])); + const account = new RoturAccount(makeRuntime(['rotur_accountField'])); - t.equal(await economy.balance({}), 42); - t.same(logins, [['credits:view'], ['credits:view']]); + t.equal(await account.accountField({FIELD: 'username'}), 'sophie'); + t.same(logins, [['account:view'], ['account:view']]); t.same(JSON.parse(store['mw:rotur-sdk-token']), { token: 'token-2', - scopes: ['credits:view'], + scopes: ['account:view'], system: 'MistWarp: test' }); authValid = true; @@ -93,27 +108,89 @@ test('logs in again when the stored token no longer validates', async t => { }); test('does not hand another project on the same origin the stored token', async t => { - const economy = new RoturEconomy(makeRuntime(['roturEconomy_balance'], 'other')); + const account = new RoturAccount(makeRuntime(['rotur_accountField'], 'other')); const before = logins.length; - t.equal(await economy.balance({}), 42); + t.equal(await account.accountField({FIELD: 'username'}), 'sophie'); t.equal(logins.length, before + 1); t.equal(systems[systems.length - 1], 'MistWarp: other'); t.end(); }); test('the request block widens the token to cover the extra scope', async t => { - const runtime = makeRuntime(['roturEconomy_balance', 'rotur_request']); + const runtime = makeRuntime(['rotur_accountField', 'rotur_request']); const account = new RoturAccount(runtime); - const economy = new RoturEconomy(runtime); - t.equal(await economy.balance({}), 42); + t.equal(await account.accountField({FIELD: 'username'}), 'sophie'); const before = logins.length; - t.equal(await account.request({SCOPES: 'credits:transfer'}), true); - t.same(logins[before], ['credits:view', 'credits:transfer']); + t.equal(await account.request({SCOPES: 'posts:create'}), true); + t.same(logins[before], ['account:view', 'posts:create']); - t.equal(await account.request({SCOPES: 'credits:transfer'}), true); + t.equal(await account.request({SCOPES: 'posts:create'}), true); t.equal(logins.length, before + 1); t.end(); }); + +test('the removed money blocks load hidden, ask for nothing, and do nothing', async t => { + const runtime = makeRuntime([ + 'roturEconomy_balance', 'roturEconomy_pay', 'roturEconomy_dailyWait', 'roturEconomy_transactions', + 'roturEconomy_createGift', 'roturKeys_buyKey', 'roturGroups_tipGroup', 'roturGroups_buyGroupProduct', + 'roturShop_buyItem', 'roturShop_buyCosmetic' + ]); + const removed = [ + [new RoturEconomy(runtime), {balance: 0, pay: '', dailyWait: 0, transactions: '', createGift: ''}], + [new RoturKeys(runtime), {buyKey: ''}], + [new RoturGroups(runtime), {tipGroup: '', buyGroupProduct: ''}], + [new RoturShop(runtime), {buyItem: '', buyCosmetic: ''}] + ]; + const before = logins.length; + for (const [extension, answers] of removed) { + const blocks = extension.getInfo().blocks.filter(block => block.opcode in answers); + t.equal(blocks.length, Object.keys(answers).length); + t.ok(blocks.every(block => block.hideFromPalette === true)); + for (const [opcode, answer] of Object.entries(answers)) { + t.equal(await extension[opcode]({AMOUNT: 5, USER: 'thief', TAG: 'tag', ID: 'id', PRODUCT: 'id', NAME: 'name'}), answer, opcode); + } + } + t.equal(logins.length, before); + t.end(); +}); + +test('the fallback host only dispatches the methods the blocks use', async t => { + const runtime = makeRuntime(['rotur_accountField']); + await new RoturAccount(runtime).accountField({FIELD: 'username'}); + const host = runtime._roturHostResolved; + for (const method of ['_http.getToken', 'setToken', 'tokens.create', 'constructor.constructor', 'me.get.call']) { + await t.rejects(host.call(method, []), /Projects cannot call/, method); + } + for (const method of [ + 'me.transfer', 'me.currency', 'me.transactions', 'me.dailyWait', 'gifts.create', + 'keys.buy', 'groups.tip', 'groups.buyProduct', 'items.buy', 'cosmetics.buy' + ]) { + await t.rejects(host.call(method, ['thief', 500, ''], {sensitive: false}), /Projects cannot call/, method); + } + t.same(transfers, []); + for (const scope of ['tokens:manage', 'credits:view', 'credits:transfer']) { + await t.rejects(host.ensureConsent([scope]), /cannot ask/, scope); + } + t.end(); +}); + +test('the fallback host confirms sensitive methods even when the caller opts out', async t => { + const runtime = makeRuntime(['rotur_accountField']); + await new RoturAccount(runtime).accountField({FIELD: 'username'}); + const host = runtime._roturHostResolved; + const prompts = []; + global.window.confirm = message => { + prompts.push(message); + return prompts.length > 1; + }; + await t.rejects(host.call('keys.cancel', ['first-key'], {sensitive: false}), /cancelled/); + t.same(cancelledKeys, []); + await host.call('keys.cancel', ['second-key'], {}); + t.same(prompts, ['Allow test to cancel this key?', 'Allow test to cancel this key?']); + t.same(cancelledKeys, [['second-key']]); + delete global.window.confirm; + t.end(); +});