Node.js 服務(wù)器端渲染(SSR)

2021-06-01 10:05 更新

1.11.1 【必須】安全的Vue服務(wù)器端渲染(Vue SSR)

  • 禁止直接將不受信的外部?jī)?nèi)容傳入{{{ data }}}表達(dá)式中

  • 模板內(nèi)容禁止被污染

  1. // bad: 將用戶輸入替換進(jìn)模板
  2. const app = new Vue({
  3. template: appTemplate.replace("word", __USER_INPUT__),
  4. });
  5. renderer.renderToString(app);

  • 對(duì)已渲染的HTML文本內(nèi)容(renderToString后的html內(nèi)容)。如需再拼不受信的外部輸入,應(yīng)先進(jìn)行安全過(guò)濾,具體請(qǐng)參考1.6.3

  1. // bad: 渲染后的html再拼接不受信的外部輸入
  2. return new Promise(((resolve) => {
  3. renderer.renderToString(component, (err, html) => {
  4. let htmlOutput = html;
  5. htmlOutput += `${__USER_INPUT__}`;
  6. resolve(htmlOutput);
  7. });
  8. }));

1.11.2 【必須】安全地使用EJS、LoDash、UnderScore進(jìn)行服務(wù)器端渲染

  • 使用render函數(shù)時(shí),模板內(nèi)容禁止被污染

lodash.Template:

  1. // bad: 將用戶輸入送進(jìn)模板
  2. const compiled = _.template(`<b>${__USER_INPUT__}<%- value %></b>`);
  3. compiled({ value: "hello" });

ejs:

  1. // bad: 將用戶輸入送進(jìn)模板
  2. const ejs = require("ejs");
  3. const people = ["geddy", "neil", "alex"];
  4. const html = ejs.render(`<%= people.join(", "); %>${__USER_INPUT__}`, { people });

  • Ejs、LoDash、UnderScore提供的HTML插值模板默認(rèn)形似<%= data %>,盡管在默認(rèn)情況下<%= data %>存在過(guò)濾,在編寫HTML插值模板時(shí)需注意:

  1. 用戶輸入流入html屬性值時(shí),必須使用雙引號(hào)包裹:<base data-id = "<%= __USER_INPUT__ %>">
  2. 用戶輸入流入<script></script>標(biāo)簽或on*的html屬性中時(shí),如<script>var id = <%= __USER_INPUT__ %></script> ,須按照1.6.3中的做法或白名單方法進(jìn)行過(guò)濾,框架/組件的過(guò)濾在此處不起作用

1.11.3 【必須】在自行實(shí)現(xiàn)狀態(tài)存儲(chǔ)容器并將其JSON.Stringify序列化后注入到HTML時(shí),必須進(jìn)行安全過(guò)濾

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)