From 5db9e906e85a414ae276e7de1033c1539aff8ea5 Mon Sep 17 00:00:00 2001 From: Haoliang Gao Date: Wed, 28 Mar 2018 22:38:39 +0800 Subject: [PATCH] fix: more safe context when locals is from query (#8) --- lib/assets_context.js | 21 +++++++++- package.json | 11 +++--- test/assets.test.js | 38 ++++++++++++++----- .../context-security/app/controller/home.js | 13 +++++++ .../apps/context-security/app/router.js | 7 ++++ .../apps/context-security/app/view/index.js | 0 .../context-security/config/config.default.js | 10 +++++ .../context-security/config/manifest.json | 4 ++ .../apps/context-security/package.json | 3 ++ 9 files changed, 91 insertions(+), 16 deletions(-) create mode 100644 test/fixtures/apps/context-security/app/controller/home.js create mode 100644 test/fixtures/apps/context-security/app/router.js create mode 100644 test/fixtures/apps/context-security/app/view/index.js create mode 100644 test/fixtures/apps/context-security/config/config.default.js create mode 100644 test/fixtures/apps/context-security/config/manifest.json create mode 100644 test/fixtures/apps/context-security/package.json diff --git a/lib/assets_context.js b/lib/assets_context.js index d0dec6f..9c1ff38 100644 --- a/lib/assets_context.js +++ b/lib/assets_context.js @@ -1,6 +1,9 @@ 'use strict'; const assert = require('assert'); +const utility = require('utility'); + +const CONTEXT_TEMPLATE_ID = 'context' + utility.sha1(String(Date.now())); class Assets { constructor(ctx) { @@ -36,8 +39,10 @@ class Assets { } getContext(data) { - data = data || this.assetsContext || {}; - return ``; + data = safeStringify(data || this.assetsContext); + let ret = `\n`; + ret += ``; + return ret; } setEntry(entry) { @@ -70,3 +75,15 @@ function linkTpl({ url }) { function scriptTpl({ url }) { return ``; } + +const escapeMap = { + '<': '<', + '>': '>', +}; +function safeStringify(data) { + if (!data) return ''; + return JSON.stringify(data) + .replace(/[<>]/g, function(ch) { + return escapeMap[ch]; + }); +} diff --git a/package.json b/package.json index 99d22cb..b0ed7e1 100644 --- a/package.json +++ b/package.json @@ -20,18 +20,19 @@ "detect-port": "^1.2.2", "mz": "^2.7.0", "mz-modules": "^2.1.0", - "sdk-base": "^3.4.0" + "sdk-base": "^3.4.0", + "utility": "^1.13.1" }, "devDependencies": { "autod": "^3.0.1", "autod-egg": "^1.1.0", - "egg": "^2.4.1", - "egg-bin": "^4.3.7", + "egg": "^2.5.0", + "egg-bin": "^4.5.0", "egg-ci": "^1.8.0", - "egg-mock": "^3.15.0", + "egg-mock": "^3.16.0", "egg-view-ejs": "^2.0.0", "egg-view-nunjucks": "^2.1.6", - "eslint": "^4.18.2", + "eslint": "^4.19.1", "eslint-config-egg": "^7.0.0", "supertest": "^3.0.0", "webstorm-disable-index": "^1.2.0" diff --git a/test/assets.test.js b/test/assets.test.js index c55196d..5a1ae20 100644 --- a/test/assets.test.js +++ b/test/assets.test.js @@ -28,7 +28,7 @@ describe('test/assets.test.js', () => { .get('/') .expect(/
<\/div>/) .expect(/<\/link>/) - .expect(/