UNPKG

astroboy

Version:

Astroboy(阿童木)is a Nodejs SFB(Separation of Front and Back ends) framework, built on koa2.

51 lines 1.73 kB
"use strict"; /** * CSRF */ const token_1 = require("../lib/token"); class CsrfError extends Error { constructor(code, msg) { super(`code: ${code}, msg: ${msg}`); this.errorContent = { code, msg, }; this.errorType = 'CsrfError'; } } const factory = function (options = {}, app) { let token = new token_1.Token({ saltLength: options.saltLength, secretLength: options.secretLength, }); return async function csrf(ctx, next) { if ((options.excluded || []).indexOf(ctx.method) === -1 && (options.env || []).indexOf(process.env.NODE_ENV) > -1) { const csrfSecret = ctx.cookies.get(options.csrfSecretName); const csrfToken = ctx.header[options.csrfTokenName]; // token 或 secret 不存在 if (!csrfSecret || !csrfToken) { throw new CsrfError(1000, 'CSRF Token Not Found!'); } // token 校验失败 if (!token.verify(csrfSecret, csrfToken)) { throw new CsrfError(1001, 'CSRF token Invalid!'); } } await next(); // 如果返回 HTML 格式数据,则生成 if (ctx.response.is('text/html')) { const secret = token.secretSync(); const newToken = token.create(secret); ctx.cookies.set(options.csrfSecretName, secret, { maxAge: options.maxAge, }); ctx.cookies.set(options.csrfTokenName, newToken, { maxAge: options.maxAge, httpOnly: false, }); } }; }; module.exports = factory; //# sourceMappingURL=astroboy-security-csrf.js.map