R1
HttpError 的 instanceof 补丁
lib/application.js:25–43 进程级副作用 3 次提交,2026-09 至 11 月
文件顶部这段代码在 require('koa') 时就执行,改写的是 node_modules 里共享的 http-errors 类。
lib/application.js :25–43 模块加载时执行 25 function isHttpErrorLike (err) {26 if (!err || typeof err !== 'object' ) return false 27 if (!(err instanceof Error)) return false 28 if (typeof err.expose !== 'boolean' ) return false 29 if (typeof err.statusCode !== 'number' ) return false 30 31 const hasMatchingStatusCode = err.status === err.statusCode32 return hasMatchingStatusCode33 }34 35 Object.defineProperty(createHttpError.HttpError, Symbol.hasInstance, {36 configurable: true ,37 value (err) {38 const matchesPrototype = Function.prototype[Symbol.hasInstance].call(this , err)39 if (matchesPrototype) return true 40 if (this !== createHttpError.HttpError) return false 41 return isHttpErrorLike(err)42 }43 })
它在做什么
给 http-errors@2 的 HttpError 类重新定义 Symbol.hasInstance。x instanceof HttpError 先按原型链判断;不成立、且被检查的正好是基类 HttpError 本身时,再用 isHttpErrorLike 按形状判断:是 Error 实例、expose 是布尔、statusCode 是数字、status === statusCode。
为什么这样写
ctx.assert 直接就是 http-assert@1.5.0(context.js:72),它带着自己嵌套的 http-errors@1.8.1;Koa 3 从 #1991 起导出的是顶层 http-errors@2.0.1 的 HttpError(npm ls http-errors 能看到两份)。于是 ctx.assert 抛出的错误 Koa.isHttpError(err) 为真、err instanceof Koa.HttpError 却为假(#1925)。补丁在不换依赖的前提下让两者一致。之后又补了两次:
#2025:第一版完全用形状判断,导致 status 被改过的真 HttpError 反而不算实例,于是加回原型链判断放在最前。
#2033:形状判断原来对子类也生效,class AppError extends HttpError 会把任意 NotFound 都认成 AppError,于是加了 this !== createHttpError.HttpError 这一句。
改的时候注意
这是全局副作用。HttpError 类对象由同一份 http-errors@2 的所有使用者共享,进程里其他用这份 http-errors 的包也会受影响。
38–41 行三句的顺序各有一条测试锁住(见下),调换任何一句都会挂测试。
configurable: true 要保留,否则后续代码和测试没法再 defineProperty。
彻底删掉补丁的前提是换掉 http-assert,或它升级到 http-errors@2。#1998 的说明把这件事放到下一个大版本。
isHttpErrorLike 的 26–27、29 行没有测试覆盖(c8 报告),改这几行要自己补用例。
佐证
测试
__tests__/context/assert.test.js:51 ctx.assert 抛出的错误是 Koa.HttpError 实例
__tests__/context/assert.test.js:63 仍是 http-errors@1 的原始类型,ctx.assert === httpAssert
__tests__/context/assert.test.js:100 子类只按原型链判断(#2033)
__tests__/context/assert.test.js:109 status 被改过仍算实例(#2025)
__tests__/context/assert.test.js:117 普通 Error 不算
提交
1061776 2026-09-02 #1998 引入补丁(纯形状判断)
b786e7b 2026-10-27 #2025 先走原型链
f2ec5f1 2026-11-01 #2033 形状判断只对基类生效
交接时实测
同一个形状符合的普通 Error 对象(status: 500, statusCode: 500, expose: false):require('koa') 之前 instanceof HttpError 为 false,之后为 true;Koa.HttpError === require('http-errors').HttpError 为 true。http-errors@1 创建的 401 错误 instanceof Koa.HttpError 为 true,instanceof Koa.createHttpError.Unauthorized 为 false。
lib/application.js :289–358 中间件链 resolve 后调用 289 function respond (ctx) {290 // allow bypassing koa 291 if (ctx.respond === false ) return 292 293 const res = ctx.res294 295 if (!ctx.writable) return res.end()296 297 let body = ctx.body298 const code = ctx.status299 300 // ignore body 301 if (statuses.empty[code]) {302 // strip headers 303 ctx.body = null 304 return res.end()305 }306 307 if (ctx.method === 'HEAD' ) {308 if (!res.headersSent && !ctx.response.has('Content-Length' )) {309 const { length } = ctx.response310 if (Number.isInteger(length)) ctx.length = length311 }312 return res.end()313 }314 315 // status body 316 if (body === null || body === undefined ) {317 if (ctx.response._explicitNullBody) {318 ctx.response.remove('Content-Type' )319 ctx.response.remove('Transfer-Encoding' )320 ctx.length = 0 321 return res.end()322 }323 if (ctx.req.httpVersionMajor >= 2 ) {324 body = String(code)325 } else {326 body = ctx.message || String(code)327 }328 if (!res.headersSent) {329 ctx.type = 'text' 330 ctx.length = Buffer.byteLength(body)331 }332 return res.end(body)333 }334 335 // responses 336 337 if (Buffer.isBuffer(body)) return res.end(body)338 if (typeof body === 'string' ) return res.end(body)339 340 let stream = null 341 if (body instanceof Blob) stream = Stream.Readable.from(body.stream())342 else if (body instanceof ReadableStream) stream = Stream.Readable.from(body)343 else if (body instanceof Response) stream = Stream.Readable.from(body?.body || '' )344 else if (isStream(body)) stream = body345 346 if (stream) {347 return Stream.pipeline(stream, res, err => {348 if (err && ctx.app.listenerCount('error' )) ctx.onerror(err)349 })350 }351 352 // body: json 353 body = JSON.stringify(body)354 if (!res.headersSent) {355 ctx.length = Buffer.byteLength(body)356 }357 res.end(body)358 }
它在做什么
顺序 条件 行为 行
1 ctx.respond === false什么都不做,使用者自己写 ctx.res 291
2 !ctx.writable(已结束或 socket 不可写)res.end() 收尾295
3 状态码是 204 / 205 / 304 清掉 body,空响应 301–305
4 HEAD 请求 头还没发且没有 Content-Length 时补上长度,不发正文 307–313
5 body 为 null / undefined 显式 null:Content-Length: 0;否则正文用状态文案(HTTP/2 只用数字) 316–333
6 Buffer 或字符串 res.end(body)337–338
7 Blob / ReadableStream / Response / Node 流 转成 Node 可读流,Stream.pipeline 到 res 340–350
8 其他 JSON.stringify 后写出,补 Content-Length353–357
为什么这样写
第 2 条原来是直接 return,socket 已经不可写的响应没人收尾,资源挂着不释放(#1547,399cb6b 改为 res.end())。
第 7 条原来是 body.pipe(res)。.pipe 在客户端中途断开时不会销毁源流,造成内存泄漏(#1834、#1882、#1889,49a3207 改为 Stream.pipeline,它在任一端出错或关闭时销毁另一端)。
348 行先检查 app 上有没有 error 监听器。EventEmitter 在没有监听器时 emit error 会直接抛出;经 callback() 启动时总会有默认监听器,这个判断防的是监听器被移除的情况。
第 3 条是 HTTP 协议要求,204 / 205 / 304 不能带正文。
改的时候注意
新增一种 body 类型要同时改三处:response.js 的 body setter(决定 Content-Type / Length,见 R3)、response.js 的 length getter(254–277,HEAD 分支靠它补长度)、这里的写出分支。只改一处,HEAD 响应和正常响应的头会不一致。
流出错时 error 事件会触发两次(见下方实测)。按 error 事件计数报警的系统要去重,改这里的人不要以为是新引入的问题。
340–343 行依赖 Node 全局的 Blob、ReadableStream、Response,跨 realm(如 vm 沙箱)创建的对象不会命中,会落到 JSON 分支。
不要把 348 行改成无条件 ctx.onerror(err),respond.test.js:857 锁住了“没有监听器不崩”。
佐证
测试
__tests__/application/respond.test.js:11 ctx.respond === false
__tests__/application/respond.test.js:95 HEAD 请求的各类 body
__tests__/application/respond.test.js:227 res 已被写过
__tests__/application/respond.test.js:268 / :388 / :1104 body 缺失、为 null、显式 null
__tests__/application/respond.test.js:829 pipeline 错误处理;:857 没有监听器不崩;:904 客户端断开时销毁流
提交
399cb6b 2025-02-27 不可写时也要 res.end()(#1593)
49a3207 2025-10-22 用 pipeline 修内存泄漏(#1893)
8d5beb3 2024-06-28 支持 Blob / ReadableStream / Response(#1830)
交接时实测(真实 HTTP 请求,Node 24.19)
中间件做了什么 状态码 Content-Type / Length 正文
没有中间件 404 text/plain · 9 Not Found
ctx.status = 400,不给 body400 text/plain · 11 Bad Request
ctx.body = null204 无 空
ctx.body = null; ctx.status = 200200 无 · 0 空
HEAD 请求,ctx.body = 'hello' 200 text/plain · 5 空
流先写出一段再出错 客户端收到 ECONNRESET;app 的 error 事件触发 2 次,是同一个错误对象,两次 err.headerSent 都是 true。调用栈显示一次来自 224 行的 onFinished,一次来自 348 行的 pipeline 回调。
R3
response.body 的 setter
lib/response.js:148–245 每次给 body 赋值 2025-10 以来改过 4 次
ctx.body = x 不只是存值:它还改状态码、推断 Content-Type、设或删 Content-Length,并处理被替换掉的旧流。
lib/response.js :148–181 前半:空值与状态码 148 set body (val) {149 const original = this ._body150 this ._body = val151 152 const cleanupPreviousStream = () => {153 if (original && isStream(original)) {154 original.once('error' , () => {})155 // Only destroy if the new value is not a stream 156 if (!isStream(val)) {157 destroy(original)158 }159 }160 }161 162 // no content 163 164 if (val == null ) {165 if (!statuses.empty[this .status]) {166 if (this .type === 'application/json' ) {167 this ._body = 'null' 168 return 169 }170 this .status = 204 171 }172 if (val === null ) this ._explicitNullBody = true 173 this .remove('Content-Type' )174 this .remove('Content-Length' )175 this .remove('Transfer-Encoding' )176 cleanupPreviousStream()177 return 178 }179 180 // set the status 181 if (!this ._explicitStatus) this .status = 200
lib/response.js :202–245 后半:流、Web 类型与 JSON 202 // stream 203 if (isStream(val)) {204 onFinish(this .res, destroy.bind(null , val))205 if (original !== val) {206 if (original != null ) this .remove('Content-Length' )207 cleanupPreviousStream()208 }209 210 if (setType) this .type = 'bin' 211 return 212 }213 214 // ReadableStream 215 if (val instanceof ReadableStream) {216 if (setType) this .type = 'bin' 217 cleanupPreviousStream()218 return 219 }220 221 // blob 222 if (val instanceof Blob) {223 if (setType) this .type = val.type || 'bin' 224 this .length = val.size225 cleanupPreviousStream()226 return 227 }228 229 // Response 230 if (val instanceof Response) {231 this .status = val.status232 if (setType) this .type = 'bin' 233 const headers = val.headers234 for (const key of headers.keys()) {235 this .set (key, headers.get (key))236 }237 cleanupPreviousStream()238 return 239 }240 241 // json 242 this .remove('Content-Length' )243 if (!this .type || !/\bjson\b/i .test(this .type)) this .type = 'json' 244 cleanupPreviousStream()245 },
它和 status 的 setter 互相调用:
lib/response.js :97–106 status setter 97 set status (code) {98 if (this .headerSent) return 99 100 assert(Number.isInteger(code), 'status code must be a number' )101 assert(code >= 100 && code <= 999 , `invalid status code: ${code}` )102 this ._explicitStatus = true 103 this .res.statusCode = code104 if (this .req.httpVersionMajor < 2 ) this .res.statusMessage = statuses.message[code]105 if (this .body && statuses.empty[code]) this .body = null 106 },
它在做什么
状态码:没显式设过状态(_explicitStatus)就改成 200;赋 null / undefined 时改成 204。
Content-Type:只有还没设时才推断。字符串以 < 开头算 html,否则 text;Buffer、流、ReadableStream、Response 算 bin;Blob 用它自己的 type;对象算 json。
Content-Length:字符串、Buffer、Blob 能算就设;流和对象删掉,留给 respond() 处理。
旧值是流时:新值不是流就销毁旧流;新值也是流就不动。
为什么这样写
_explicitStatus:使用者先写 ctx.status = 404 再给 body,状态码不能被改回 200。
_explicitNullBody:区分“显式赋了 null”和“从没赋值”,respond() 据此回 Content-Length: 0(3.0 的变更,#1528)。
166–169 行:类型已经是 JSON 时赋 null,正文变成字符串 'null',用于 API 返回 JSON 字面量 null(6cf6a95,#1059)。
cleanupPreviousStream:被替换的流不销毁会泄漏(27df3b6)。但 koa-compress 这类中间件会把旧流 pipe 进一个新流再赋回 body,这时销毁旧流会把响应截断,所以新值是流时不销毁(863c211,#1913)。
154 行先挂一个空的 error 监听再 destroy,避免销毁时抛出的错误变成未捕获异常。
243 行用 /\bjson\b/i 判断已有类型,application/vnd.api+json 这类会被保留(40d5d33,3.0 破坏性变更)。
改的时候注意
赋值顺序会改变结果。status 的 setter 在状态码是 204 / 205 / 304 时会把 body 置 null,body 的 setter 又会改 status。实测 ctx.body = 'hi'; ctx.status = 204 得到空的 204;ctx.status = 404; ctx.body = 'hi' 得到带正文的 404。
已知坑: 先 ctx.type = 'json' 再 ctx.body = null、并且没设过状态码时,setter 在 168 行提前 return,状态码停在默认的 404。实测响应是 404 + application/json + 正文 null。现有测试(length.test.js:70)只断言长度为 4,没断言状态码。想要 200 必须自己写 ctx.status = 200。
不要在 body 流上挂 error 监听转给 ctx.onerror。49a3207 专门删掉了这一行,流错误统一由 respond() 的 pipeline 处理,body.test.js:120 锁住了这一点。
同一个流重复赋值(original === val)时不删 Content-Length,respond.test.js:794 锁住。
新增 body 类型时,记得每个分支都要调 cleanupPreviousStream(),漏一个就是泄漏。
佐证
测试
__tests__/response/body.test.js:120 不给流加 error 监听
__tests__/response/body.test.js:130 被新流替换时不销毁旧流;:142 被 null 替换时销毁
__tests__/response/body.test.js:152 替换出错的流不产生未捕获异常
__tests__/response/body.test.js:236 模拟 koa-compress 的包装流
__tests__/response/status.test.js:65–115 204 / 205 / 304 去掉内容相关头
__tests__/response/length.test.js:70 json + null 的长度
提交
6cf6a95 2021-08-17 json 类型下 null 写成 'null'
40d5d33 2025-03-21 已是 json 类型不覆盖
27df3b6 2025-10-23 / 863c211 2025-10-26 旧流清理及其修正
824c1cf 2026-09-19 Blob 保留自身类型(#1987)
lib/context.js :106–168 唯一的错误出口 106 onerror (err) {107 // don't do anything if there is no error. 108 // this allows you to pass `this.onerror` 109 // to node-style callbacks. 110 if (err == null ) return 111 112 // When dealing with cross-globals a normal `instanceof` check doesn't work properly. 113 // See https://github.com/koajs/koa/issues/1466 114 // We can probably remove it once jest fixes https://github.com/facebook/jest/issues/2549. 115 const isNativeError =116 Object.prototype.toString.call(err) === '[object Error]' ||117 err instanceof Error118 if (!isNativeError) err = new Error(util.format('non-error thrown: %j' , err))119 120 let headerSent = false 121 if (this .headerSent || !this .writable) {122 headerSent = err.headerSent = true 123 }124 125 // delegate 126 this .app.emit('error' , err, this )127 128 // nothing we can do here other 129 // than delegate to the app-level 130 // handler and log. 131 if (headerSent) {132 return 133 }134 135 const { res } = this 136 137 // first unset all headers 138 /* istanbul ignore else */ 139 if (typeof res.getHeaderNames === 'function' ) {140 res.getHeaderNames().forEach(name => res.removeHeader(name))141 } else {142 res._headers = {} // Node < 7.7 143 }144 145 // then set those specified 146 const headers = err.headers || {}147 Object.keys(headers).forEach(name => {148 const lowerName = name.toLowerCase()149 const generatedHeader = lowerName === 'content-type' || lowerName === 'content-length' 150 if (generatedHeader) return 151 this .set (name, headers[name])152 })153 154 // force text/plain 155 this .type = 'text' 156 157 let statusCode = err.status || err.statusCode158 159 // default to 500 160 if (typeof statusCode !== 'number' || !statuses.message[statusCode]) statusCode = 500 161 162 // respond 163 const code = statuses.message[statusCode]164 const msg = err.expose ? err.message : code165 this .status = err.status = statusCode166 this .length = Buffer.byteLength(msg)167 res.end(msg)168 },
它在做什么
非 Error 的值包成 Error(115–118 行)。同时用 Object.prototype.toString 判断,是为了认出别的 realm(vm、jest)里创建的 Error(#1466)。
响应头已经发出:标记 err.headerSent,只 emit error,然后返回。
否则:清空所有已设的响应头 → 写入 err.headers(跳过 Content-Type / Content-Length)→ 强制 text/plain。
状态码取 err.status || err.statusCode,必须是 statuses 认识的数字,否则 500。
正文:err.expose 为真用 err.message,否则用标准文案。http-errors 对 4xx 默认 expose = true,5xx 默认 false,所以普通 Error 的 message 不会泄露给客户端。
为什么这样写
清空响应头,是为了不让半成品响应的头(比如已设好的 application/json 和长度)带进错误页。
跳过 err.headers 里的 Content-Type / Length 是 2fecd02 加的。同一个提交让 response.set 对这两个头的多值数组抛断言错误;如果错误处理里原样调用 this.set(err.headers),带着非法头的错误就会让错误处理本身再抛错。这两个头本来也要在 164–166 行重新生成。
set() 的单值校验:
lib/response.js :24–35 Content-Type / Length 只能有一个值 24 function isSingleValueHeader (field) {25 const name = field.toLowerCase()26 return name === 'content-type' || name === 'content-length' 27 }28 29 function normalizeHeader (field, value) {30 const singletonArray = isSingleValueHeader(field) && Array.isArray(value)31 if (!singletonArray) return [field, value]32 33 assert(value.length === 1 , `${field} must contain exactly one value` )34 return [field, value[0 ]]35 }
lib/response.js :550–559 先校验全部,再写入 550 set (field, val) {551 if (this .headerSent || !field) return 552 553 const entries = typeof field === 'string' ? [[field, val]] : Object.entries(field)554 const headers = entries.map(([name, value]) => normalizeHeader(name, value))555 556 headers.forEach(([name, value]) => {557 this .res.setHeader(name, value)558 })559 },
改的时候注意
前面中间件设的头会全部被清掉,CORS 头、trace id 都在内。要在错误响应里带头,放进 err.headers(ctx.throw(401, 'msg', { headers: {...} })),或者在最外层中间件自己 try/catch(docs/error-handling.md)。
onerror 里任何新代码都不能抛错。调用 this.set 前要确认值合法。
set() 先 map 校验所有字段,再 forEach 写入,保证“一项不合法就一项都不写”(set.test.js:86)。不要合成一个循环。
139–143 行的 else 是 Node < 7.7 的兼容代码,测试覆盖不到。engines 已是 ≥ 18,可以删,但请单独一个提交。
日志由 app.onerror(application.js:259–273)打:404、expose 为真、app.silent 时不打。用 ctx.throw(400) 抛的客户端错误默认不会出现在日志里。
佐证
测试
__tests__/context/onerror.test.js:26 清空所有头;:47 写入 err.headers 并忽略非法的 Content-Type / Length
__tests__/context/onerror.test.js:80 头已发出后忽略;:120 / :141 非法状态码回 500
__tests__/context/onerror.test.js:180 别的 realm 的 Error;:212 抛出非 Error 值
__tests__/application/onerror.test.js:28 / :40 404 和 silent 不打日志
__tests__/response/set.test.js:46 单值头拒绝多值;:86 先校验后写入;:99 每个值只读一次
提交
2fecd02 2026-10-09 单值头校验 + onerror 跳过生成头(#2012)
e2030c7 2020-06-13 跨 realm 的 Error 判断(#1468)
0d2f421 2020-05-17 认 err.statusCode(#1460)
交接时实测
中间件做了什么 响应 app error 收到
ctx.throw(403, 'nope')403 · nope nope
throw new Error('secret db detail')500 · Internal Server Error secret db detail
抛出 status = 999 的错误 500 · Internal Server Error x
先 ctx.set('X-A', '1'),再抛带 headers: { 'X-B': '2', 'Content-Type': 'text/html' } 的 400 400 · 无 X-A,有 X-B,类型仍是 text/plain bad
ctx.set('Content-Type', ['a/b', 'c/d'])500 · Internal Server Error Content-Type must contain exactly one value
R5
信任代理时的主机、协议与 IP 解析
lib/request.js:253–295, 422–484, 502–515 proxy: true 时 · 安全 近一个月改了 4 次
这几个 getter 读的是客户端可以伪造的请求头,历史上有 ReDoS 和 Host 伪造两个安全修复,最近又连续修了 4 个边界值。
lib/request.js :253–295 host 与 hostname 253 get host () {254 const proxy = this .app.proxy255 let host = proxy && this .get ('X-Forwarded-Host' )256 if (!host) {257 if (this .req.httpVersionMajor >= 2 ) host = this .get (':authority' )258 if (!host) host = this .get ('Host' )259 }260 if (!host) return '' 261 host = splitCommaSeparatedValues(host, 1 )[0 ]262 // Host header may contain userinfo (e.g., "user@host") which is invalid per RFC 7230. 263 // Use URL parser to correctly extract the host portion. 264 if (host.includes('@' )) {265 try {266 host = new URL(`http://${host}` ).host267 } catch (e) {268 return '' 269 }270 }271 return host272 },273 274 /** 275 * Parse the "Host" header field hostname 276 * and support X-Forwarded-Host when a 277 * proxy is enabled. 278 * 279 * @return {String} hostname 280 * @api public 281 */ 282 283 get hostname () {284 const host = this .host285 if (!host) return '' 286 const isIPv6 = host[0 ] === '[' 287 const hasInvalidIPv6Characters = isIPv6 && INVALID_IPV6_HOST_CHARACTERS.test(host)288 if (hasInvalidIPv6Characters) return '' 289 try {290 if (isIPv6) return new URL(`http://${host}` ).hostname // IPv6 291 return host.split(':' , 1 )[0 ]292 } catch {293 return '' 294 }295 },
lib/request.js :422–427 protocol 422 get protocol () {423 if (this .socket.encrypted) return 'https' 424 if (!this .app.proxy) return 'http' 425 const proto = this .get ('X-Forwarded-Proto' )426 return proto ? splitCommaSeparatedValues(proto, 1 )[0 ].toLowerCase() : 'http' 427 },
lib/request.js :454–484 ips 与 ip 454 get ips () {455 const proxy = this .app.proxy456 const val = this .get (this .app.proxyIpHeader)457 let ips = proxy && val458 ? splitCommaSeparatedValues(val)459 : []460 if (this .app.maxIpsCount > 0 ) {461 ips = ips.slice(-this .app.maxIpsCount)462 }463 return ips464 },465 466 /** 467 * Return request's remote address 468 * When `app.proxy` is `true`, parse 469 * the "X-Forwarded-For" ip address list and return the first one 470 * 471 * @return {String} 472 * @api public 473 */ 474 475 get ip () {476 if (!this [IP]) {477 this [IP] = this .ips[0 ] || this .socket.remoteAddress || '' 478 }479 return this [IP]480 },481 482 set ip (_ip) {483 this [IP] = _ip484 },
lib/request.js :502–515 subdomains 502 get subdomains () {503 const offset = this .app.subdomainOffset504 const hostname = this .hostname505 const domain = hostname.endsWith('.' ) ? hostname.slice(0 , -1 ) : hostname506 if (!domain) return []507 const isIPv6 = domain[0 ] === '[' 508 const ip = isIPv6 ? domain.slice(1 , -1 ) : domain509 if (net.isIP(ip)) return []510 const subdomains = domain511 .split('.' )512 .reverse()513 .slice(offset)514 return subdomains515 },
lib/request.js :762–764 所有逗号切分都走这里 762 function splitCommaSeparatedValues (value, limit) {763 return value.split(',' , limit).map(v => v.trim())764 }
它在做什么
app.proxy 为真时:host 取 X-Forwarded-Host,protocol 取 X-Forwarded-Proto,ips 取 app.proxyIpHeader(默认 X-Forwarded-For)。多值头里 host 和 protocol 取第一个;ip 取 ips[0],没有就用 socket 地址。hostname 从 host 去掉端口(IPv6 交给 URL 解析),subdomains 按 app.subdomainOffset 去掉末尾几段。
为什么这样写
提交 日期 修了什么
5054af62025-02-12 GHSA-593f-38f6-jp5m:原来用 split(/\s*,\s*/) 切分,构造的长空白串能触发 ReDoS。改为先按逗号切再 trim,即 splitCommaSeparatedValues。
55ab9ba2026-02-25 安全修复(fork 合入):Host: evil.com:fake@legit.com 这类带 userinfo 的值,按冒号切会得到攻击者控制的 evil.com,改为交给 URL 解析(264–270 行)。
e812c8d2026-11-01 X-Forwarded-Proto: HTTPS 时 ctx.secure 为假,secure cookie 被拒。改为转小写。
b7ead6f2026-11-01 IPv6 hostname 原来借 this.URL 解析,absolute-form 请求下会拿到 URL 里的另一个主机。改为直接解析 host,并拒绝含 / ? # \ 和空白的值。
2ad36172026-11-14 api.example.com. 末尾的根点让 subdomains 多出一段。
7c6bfe72026-11-14 构造参数 subdomainOffset: 0 被 || 2 吞掉(application.js:97)。
改的时候注意
不要用带 \s* 的正则切分请求头,统一用 splitCommaSeparatedValues。
proxy: true 时 ctx.ip 是 X-Forwarded-For 最左边的值,客户端可以随便填。前面有 N 层可信代理时,应把 maxIpsCount 设为 N,这样取到的是最外层代理写入的真实客户端地址。
ctx.ip 第一次读取后缓存在 Symbol 上(476–479 行),之后改请求头不会变。需要改时用 ctx.request.ip = ...。
host 被 hostname、href、URL、subdomains 和 back()(R7)共用,改它的返回格式会连锁影响这几处。
href 和 URL 都基于 originalUrl,不随 ctx.path = … / ctx.url = … 改写变化,URL 还会缓存(305–318 行)。这是有意的(whatwg-url.test.js:84)。改写过路径后要取路径请用 ctx.path。
改这一块时把 __tests__/request/ 下 host、hostname、subdomains、protocol、ip、ips 六个文件一起跑。
佐证
测试
__tests__/request/host.test.js:98 带 @ 的 Host;:135 无法解析时返回空串
__tests__/request/hostname.test.js:46 IPv6 不受 absolute-form 影响;:68 拒绝含路径字符的 IPv6
__tests__/request/protocol.test.js:36 大小写混合的 X-Forwarded-Proto
__tests__/request/ips.test.js:50 maxIpsCount;__tests__/request/ip.test.js:42 惰性计算并缓存
__tests__/request/subdomains.test.js:19 末尾根点;:78 / :84 offset 为 0;:105 IPv6 不算子域名
__tests__/request/whatwg-url.test.js:27 absolute-form;:84 改写路径后仍跟随 originalUrl
交接时实测
X-Forwarded-For: spoofed, 10.0.0.1, 203.0.113.9:proxy: true 时 ctx.ip 为 spoofed;加上 maxIpsCount: 1 为 203.0.113.9;proxy: false 时为 socket 地址 127.0.0.1。请求 /old?x=1 执行 ctx.path = '/new' 后,ctx.path 为 /new,ctx.URL.pathname 和 ctx.href 仍是旧值。
R6
query 的解析、缓存与原型污染
lib/request.js:174–217 lib/search-params.js:1–39 读写 ctx.query · 安全
查询串里的键直接变成对象的属性名,__proto__、constructor 都可能出现。
lib/request.js :174–189 按查询串缓存解析结果 174 get query () {175 const str = this .querystring176 const c = this ._querycache = this ._querycache || Object.create(null )177 return c[str] || (c[str] = sp.parse(str))178 },179 180 /** 181 * Set query string as an object. 182 * 183 * @param {Object} obj 184 * @api public 185 */ 186 187 set query (obj) {188 this .querystring = sp.stringify(obj)189 },
lib/search-params.js :1–39 全文 1 const URLSearchParams = require ('url' ).URLSearchParams2 3 module .exports = {4 stringify: (obj) => {5 const searchParams = new URLSearchParams()6 const addKey = (k, v, params) => {7 const val = typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ? v : '' 8 params.append(k, val)9 }10 11 for (const [key, value] of Object.entries(obj)) {12 if (Array.isArray(value)) {13 const lgth = value.length14 for (let i = 0 ; i < lgth; i++) {15 addKey(key, value[i], searchParams)16 }17 } else {18 addKey(key, value, searchParams)19 }20 }21 return searchParams.toString()22 },23 24 parse: (str) => {25 const searchParams = new URLSearchParams(str)26 const obj = {}27 for (const key of searchParams.keys()) {28 const values = searchParams.getAll(key)29 const value = values.length <= 1 ? values[0 ] : values30 Object.defineProperty(obj, key, {31 value,32 writable: true ,33 enumerable: true ,34 configurable: true 35 })36 }37 return obj38 }39 }
它在做什么
ctx.query 把查询串解析成对象,同名参数出现多次时值是数组;结果按查询串原文缓存在 this._querycache 里。ctx.query = obj 反向序列化,只认 string / number / boolean,其他值写成空串。
为什么这样写
1e31d65(#2024)修了两处。缓存表原来是 {}:请求 /?__proto__ 时查询串就是 '__proto__',c['__proto__'] 直接返回 Object.prototype 当作 query,之后往 query 上写属性就污染了全局原型;?constructor 同理会返回 Object 构造函数。现在缓存表是 Object.create(null)。
同一提交把 parse 里的 obj[key] = value 改成 Object.defineProperty。前者在 key 为 __proto__ 时会调用原型 setter,改掉 query 对象的原型。
a82feec(#2013):布尔值原来被序列化成空串。
7cf1462(2024-08,3.0 破坏性变更):用 URLSearchParams 替换 Node 的 querystring。
改的时候注意
任何“简化成 obj[key] = value”或“缓存表改回 {}”的改动,都会把 1e31d65 修掉的问题带回来。
缓存返回的是同一个对象,中间件之间共享。不要在 ctx.query 上放临时状态(见下方实测)。
解析结果的值永远是字符串或字符串数组。ctx.query = { n: 1, b: true } 之后再读,得到的是 '1' 和 'true'。
同一请求里每出现一个不同的查询串,缓存表就多一项,不会清理。
佐证
测试
__tests__/request/query.test.js:8 原型相关的键经解析、缓存、回写都保持为普通属性
__tests__/request/query.test.js:41 裸 ?__proto__ / ?constructor 等的缓存;:61 查询串变化后各自缓存
__tests__/lib/search-params.test.js:45 重复的原型键;:63 单个 __proto__ 是可写、可删的自有属性
交接时实测
请求 /?a=1:执行 ctx.query.a = 'mutated',把 ctx.querystring 改成 a=2 再改回 a=1,读到的 ctx.query.a 是 mutated。
lib/response.js :315–381 redirect / back / attachment 315 redirect (url) {316 if (/^https?:\/\//i .test(url)) {317 // formatting url again avoid security escapes 318 url = new URL(url).toString()319 }320 this .set ('Location' , encodeUrl(url))321 322 // status 323 if (!statuses.redirect[this .status]) this .status = 302 324 325 // html 326 if (this .ctx.accepts('html' )) {327 url = escape(url)328 this .type = 'text/html; charset=utf-8' 329 this .body = `Redirecting to ${url}.` 330 return 331 }332 333 // text 334 this .type = 'text/plain; charset=utf-8' 335 this .body = `Redirecting to ${url}.` 336 },337 338 /** 339 * Perform a special-cased "back" to provide Referrer support. 340 * When Referrer is not present, `alt` or "/" is used. 341 * 342 * Examples: 343 * 344 * ctx.back() 345 * ctx.back('/index.html') 346 * 347 * @param {String} [alt] 348 * @api public 349 */ 350 351 back (alt) {352 const referrer = this .ctx.get ('Referrer' )353 if (referrer) {354 // referrer is an absolute URL, check if it's the same origin 355 const url = new URL(referrer, this .ctx.href)356 if (url.host === this .ctx.host) {357 this .redirect(referrer)358 return 359 }360 }361 362 // no referrer, use alt or '/' 363 this .redirect(alt || '/' )364 },365 366 /** 367 * Set Content-Disposition header to "attachment" with optional `filename`. 368 * 369 * @param {String} [filename] 370 * @param {object} [options] 371 * @param {string} [options.type=attachment] 372 * @param {string|boolean} [options.fallback=true] 373 * @api public 374 */ 375 376 attachment (filename, options) {377 if (filename && !this .has('Content-Type' )) {378 this .type = extname(filename)379 }380 this .set ('Content-Disposition' , contentDisposition(filename, options))381 },
它在做什么
redirect(url):绝对 URL 先经 new URL 规范化,再 encodeUrl 写进 Location;当前状态码不是 3xx 就设 302;写一个简短正文,客户端接受 HTML 时先转义。
back(alt):Referer 解析后与当前 host 相同才跳回去,否则跳 alt 或 /。
attachment(filename):设置 Content-Disposition;只有还没有 Content-Type 时才按扩展名推断。
为什么这样写
422c551 2025-07-27,GHSA-jgmv-j7ww-jx2x:back() 原来无条件跳到 Referer,构成开放重定向。
769fd75 2025-10-18:删掉了“以 / 开头就当相对路径放行”的捷径。//evil.com/login 也以 / 开头,浏览器会把它当协议相对地址跳到 evil.com。现在一律 new URL(referrer, ctx.href) 后比较 host。
83128eb 2025-09-16,GHSA-c5vw-j4hf-j526:attachment('x.html') 会把已设好的安全类型改成 text/html,配合内容嗅探可造成 XSS。
ff25eb4 2025-04-06:重定向正文不再把 URL 放进 <a href>,只输出转义后的文本。
改的时候注意
不要恢复 startsWith('/') 一类的快捷判断;凡是“看起来像相对路径”的判断,都先经 URL 解析。
back() 比较的是 host(含端口),依赖 R5 的 host getter;信任代理时 X-Forwarded-Host 也参与比较。
327 行的 HTML 转义不能去掉。
new URL() 遇到无法解析的输入会抛 ERR_INVALID_URL,back() 和 redirect() 都没有 try/catch(见下方实测)。
佐证
测试
__tests__/response/back.test.js:15 同源 Referer;:56 //evil.com 双斜杠
__tests__/response/attachment.test.js:10 GHSA-c5vw-j4hf-j526 一组用例
__tests__/response/redirect.test.js:55 转义 URL
交接时实测
Host 为 example.com:Referer https://example.com/ok → 跳回该地址;//evil.com/x → 跳 /;http://a b/x → back() 抛 ERR_INVALID_URL,在中间件里会变成 500 并进错误日志。redirect('http://[') 同样抛错。也就是说,客户端发一个畸形 Referer 就能让调用 ctx.back() 的路由返回 500。
R8
Application 的装配:选项默认值、默认错误日志、AsyncLocalStorage
lib/application.js:64–122, 188–211 应用启动
只在启动时跑,但决定了每个请求能不能拿到 currentContext、错误会不会被打印。
lib/application.js :92–122 构造函数 92 constructor (options) {93 super ()94 options = options || {}95 this .proxy = options.proxy || false 96 const subdomainOffset = options.subdomainOffset97 this .subdomainOffset = subdomainOffset === 0 ? 0 : subdomainOffset || 2 98 this .proxyIpHeader = options.proxyIpHeader || 'X-Forwarded-For' 99 this .maxIpsCount = options.maxIpsCount || 0 100 this .env = options.env || process.env.NODE_ENV || 'development' 101 this .compose = options.compose || compose102 if (options.keys) this .keys = options.keys103 this .middleware = []104 this .context = Object.create(context)105 this .request = Object.create(request)106 this .response = Object.create(response)107 // util.inspect.custom support for node 6+ 108 /* istanbul ignore else */ 109 if (util.inspect.custom) {110 this [util.inspect.custom] = this .inspect111 }112 if (options.asyncLocalStorage) {113 if (v8.startupSnapshot?.isBuildingSnapshot?.()) {114 this .ctxStorage = null 115 v8.startupSnapshot.addDeserializeCallback(({ app, options }) => {116 app.ctxStorage = getAsyncLocalStorage(options)117 }, { app: this , options })118 } else {119 this .ctxStorage = getAsyncLocalStorage(options)120 }121 }122 }
lib/application.js :64–69 getAsyncLocalStorage 64 function getAsyncLocalStorage (options) {65 if (options.asyncLocalStorage instanceof AsyncLocalStorage) {66 return options.asyncLocalStorage67 }68 return new AsyncLocalStorage()69 }
它在做什么
构造函数读选项,创建三份应用级原型。开启 asyncLocalStorage 时,callback() 让每个请求都在 ctxStorage.run(ctx, …) 里执行(见第 2 章 ①),于是任意异步调用链里都能用 app.currentContext 拿到当前 ctx。正在构建 V8 启动快照时推迟创建 AsyncLocalStorage,快照反序列化后再建。
为什么这样写
AsyncLocalStorage 的位置改过三次:d7894c8(2022-12)做成中间件;e98b8d1(2023-04)挪到 callback() 包住整个 handleRequest,否则在 ctx.onerror 和 app 的 error 监听器里取不到 currentContext;5bc0b46(2024-05)删掉了废弃的中间件导出。
2503a1f(2026-03-28):AsyncLocalStorage 不能进 V8 启动快照,所以构建快照时先置 null,再注册 addDeserializeCallback。
97 行:subdomainOffset 为 0 时要保留 0(7c6bfe7),其余选项仍用 || 取默认值。
改的时候注意
默认的 app.onerror 只在 callback() 那一刻没有 error 监听器时才挂上(191 行)。先 app.on('error', fn) 再启动,默认的 stack 日志就不会打印。测试里或生产上“错误日志消失”多半是这个原因。
compose() 只在 callback() 里调一次。实测用默认的 koa-compose 时,callback() 之后再 app.use() 仍然生效,因为 koa-compose 每次 dispatch 都现读中间件数组。换成自定义 options.compose 就不一定了,不要依赖这个行为。
新增数值型选项时注意 || 默认值 会吞掉 0,参照 97 行写。maxIpsCount 默认值本身就是 0,不受影响。
asyncLocalStorage 传 AsyncLocalStorage 实例会复用它,传任何其他真值(包括字符串)都新建一个。
改 ALS 相关代码要跑 currentContext.test.js,其中快照用例是替换 v8.startupSnapshot 来模拟的,真实快照构建没有测试。
加选项时同步改 80–88 行的 JSDoc 和 docs/api/index.md。
佐证
测试
__tests__/application/currentContext.test.js:59 错误处理里能取到 currentContext;:105 自定义实例;:118 V8 启动快照
__tests__/application/index.test.js:70 保留 0;:81 选项只读一次;:96 其他假值回落到 2
__tests__/application/compose.test.js:9 默认与自定义 compose
交接时实测
先注册 error 监听器再 callback():app.listeners('error') 里没有 app.onerror;不注册时有。callback() 之后 app.use(c => { c.body = 'added-after-callback' }),请求返回 200 和该正文。new Koa({ asyncLocalStorage: 'yes' }) 也会创建 ctxStorage。
R9
ctx.fresh:ETag / Last-Modified 缓存协商
lib/request.js:329–355 Koa 不会自动回 304 依赖 fresh@0.5.2
ctx.fresh 只回答一个问题:请求带来的条件头和响应上已经设好的 ETag / Last-Modified 是否吻合。要不要回 304、什么时候回,都由你的代码决定。判断得太早,或者验证器的写法不对,它就一直返回 false,缓存不会生效,也不报任何错。
lib/request.js :329–355 fresh 与 stale 329 get fresh () {330 const method = this .method331 const s = this .ctx.status332 333 // GET or HEAD for weak freshness validation only 334 if (method !== 'GET' && method !== 'HEAD' ) return false 335 336 // 2xx or 304 as per rfc2616 14.26 337 if ((s >= 200 && s < 300 ) || s === 304 ) {338 return fresh(this .header, this .response.header)339 }340 341 return false 342 },343 344 /** 345 * Check if the request is stale, aka 346 * "Last-Modified" and / or the "ETag" for the 347 * resource has changed. 348 * 349 * @return {Boolean} 350 * @api public 351 */ 352 353 get stale () {354 return !this .fresh355 },
它什么时候算 fresh
判断分两层:Koa 先看请求方法和状态码,过了这两关再交给 fresh 包比较请求头和响应头。下表按执行顺序排列,任何一步否决就直接返回 false。后 5 步的代码在 node_modules/fresh/index.js(npm ci 后可见,不在仓库里)。
顺序 检查 不满足时 位置
1 请求方法是 GET 或 HEAD false request.js:334
2 此刻的响应状态码是 2xx 或 304 false request.js:337
3 请求带了 If-None-Match 或 If-Modified-Since 至少一个 false(无条件请求) fresh:39–41
4 请求的 Cache-Control 里没有 no-cache false(浏览器强制刷新) fresh:46–49
5 有 If-None-Match 且不是 * 时:响应有 ETag,并且列表里有一个与它弱匹配(W/"x" 与 "x" 视为相同) false fresh:52–72
6 有 If-Modified-Since 时:响应有 Last-Modified,且不晚于该时间 false fresh:75–82
7 以上都没否决 返回 true fresh:84
第 5、6 步之间是“且”的关系:两个条件头同时出现时,两个都要满足。
为什么先看请求方法和状态码
方法。 304 Not Modified 只对 GET / HEAD 有意义。按 RFC 7232,其他方法的条件不满足时应该回 412 Precondition Failed。如果 POST 也能被判成 fresh,“fresh 就回 304”的中间件会吞掉写操作的结果:服务端已经执行了写入,客户端却只收到 304。
状态码。 只有成功的响应才谈得上“客户端缓存的副本仍然有效”。404、500 这类响应即使带着匹配的 ETag(比如统一加 ETag 的中间件),也不能回 304,否则客户端会继续用它缓存的旧 200 副本,资源被删除或服务出错都看不出来。RFC 7232 第 5 节要求:去掉条件头后本应返回非 2xx 的请求,服务端要忽略所有条件头。代码注释引用的是更早的 RFC 2616 14.26,规则相同。
304 也算。 内层中间件已经把状态设成 304 后,外层再读 ctx.fresh 仍然是 true,所以叠两层条件判断结果也一样(实测 U)。
状态码读的是当前的 res.statusCode。Koa 的默认值是 404,这正是“判断太早一直为 false”的根源(见下方注意事项第 2 条)。
跟 respond() 的 304 怎么配合
你只需要写 ctx.status = 304,剩下的由已有代码完成:
status 的 setter 发现 body 有值、304 又属于“不能带正文”的状态,就把 body 置为 null(response.js:105,代码见 R3 )。
body 的 setter 走空值分支(response.js:164–178):304 本身就是空状态,所以不会被改成 204;删掉 Content-Type、Content-Length、Transfer-Encoding;原来的 body 是流的话就 destroy 掉。
respond() 第 3 个分支再检查一次空状态,把 body 置 null 后 res.end(),不发正文(下方代码)。在这之后才轮到 HEAD 分支,所以 HEAD 请求的 304 走的是同一条路。
只删和正文有关的头。ETag、Last-Modified、Cache-Control、Vary 都会保留,客户端要用它们更新缓存(实测 A)。
lib/application.js :300–305 respond():304 不发正文 300 // ignore body 301 if (statuses.empty[code]) {302 // strip headers 303 ctx.body = null 304 return res.end()305 }
设成 304 之后再给 ctx.body 赋值不会把正文发出去:_explicitStatus 让状态码停在 304,respond() 还会再清一次。但如果之后又把 ctx.status 改回 200,就会按 200 正常发送(respond.test.js:1071)。
两种常见写法:
写法一:外层统一判断(省带宽,不省生成正文的开销) 示例代码,不在仓库中 // 要注册在会设置 body 的中间件之前 app.use(async (ctx, next) => { await next() if (ctx.fresh) ctx.status = 304 }) app.use(async ctx => { const doc = await loadDoc(ctx.query.id) ctx.body = doc // 状态码随之变成 200 ctx.etag = doc.version // 用 setter:会自动补双引号 ctx.lastModified = doc.updatedAt // 用 setter:转成 HTTP 日期 })
写法二:先判断再生成正文(命中时连查询都省掉,即 docs/api/request.md 的示例) 示例代码,不在仓库中 app.use(async ctx => { const meta = await loadMeta(ctx.query.id) ctx.status = 200 // 不写这行,状态还是默认的 404,fresh 恒为 false ctx.etag = meta.version if (ctx.fresh) { ctx.status = 304 return } ctx.body = await loadDoc(ctx.query.id) })
验证器一定要用这两个 setter 设置:
lib/response.js :418–450 lastModified 与 etag 的 setter 418 set lastModified (val) {419 if (typeof val === 'string' ) val = new Date(val)420 this .set ('Last-Modified' , val.toUTCString())421 },422 423 /** 424 * Get the Last-Modified date in Date form, if it exists. 425 * 426 * @return {Date} 427 * @api public 428 */ 429 430 get lastModified () {431 const date = this .get ('last-modified' )432 if (date) return new Date(date)433 },434 435 /** 436 * Set the ETag of a response. 437 * This will normalize the quotes if necessary. 438 * 439 * this.response.etag = 'md5hashsum'; 440 * this.response.etag = '"md5hashsum"'; 441 * this.response.etag = 'W/"123456789"'; 442 * 443 * @param {String} val 444 * @api public 445 */ 446 447 set etag (val) {448 if (!/^(W\/)?"/ .test(val)) val = `"${val}"` 449 this .set ('ETag' , val)450 },
用的时候注意
Koa 不会自动回 304。 整个 lib/ 只有 request.js 引用了 fresh 包(context.js 只是把 getter 转发出去),respond() 不读 ctx.fresh。不写判断代码的话,带着匹配 ETag 的请求照样拿到 200 和完整正文(实测 B)。
判断时机。 必须等 ETag / Last-Modified 已经设到响应上、状态码已经是 2xx 之后再读。在设置 body 之前读,状态码还是默认的 404,结果恒为 false(实测 C)。提前判断就先写 ctx.status = 200(写法二)。
用 ctx.etag / ctx.lastModified,不要用 ctx.set。 从 af0547d(2025-03-17)起 set() 不再把值转成字符串。ctx.set('ETag', 123) 时响应头里存的是数字 123,fresh 用 === 和请求里的字符串比较,永远不相等(实测 P)。ctx.set('Last-Modified', date) 会发出 Sun Nov 01 2026 16:00:00 GMT+0800 (China Standard Time) 这种不是 HTTP 日期的格式,Koa 自己比较时能通过,但不能指望客户端认它。
两个验证器要么都设,要么只用一个,中途不要去掉。 上次响应里两个都有时,浏览器会同时带 If-None-Match 和 If-Modified-Since。RFC 7232 第 3.3 节说有 If-None-Match 时应忽略 If-Modified-Since,但 fresh@0.5.2 两个都检查。所以只设 ETag 不设 Last-Modified 时,带着旧 If-Modified-Since 的请求一律判为不新鲜(实测 L)。后果是多回了 200,不会错回 304,但缓存等于没开。
If-None-Match: * 不看 ETag,响应没设 ETag 也判为 fresh(实测 K)。RFC 的语义是“资源存在就匹配”。如果某个路由在资源不存在时也回 2xx(比如空列表 200),带 * 的请求会收到 304。
刷新行为。 请求头 Cache-Control: no-cache(浏览器强制刷新时发送)判为不新鲜;Cache-Control: max-age=0(普通刷新)和 Pragma: no-cache 不影响结果(实测 H、I、J)。
只做弱比较,只看 If-None-Match / If-Modified-Since。 不能拿 ctx.fresh 做 PUT / PATCH 的 If-Match 乐观锁:方法不是 GET / HEAD 时它恒为 false,也根本不读 If-Match,412 要自己实现。
Last-Modified 只精确到秒。 ctx.lastModified 会舍掉毫秒,同一秒里的两次修改分不出来(实测 R、S)。需要更细的粒度就用 ETag。
流 body。 设成 304 时原来的流会被 destroy,不会泄漏(实测 V);但流已经打开了(比如文件已经打开),想省掉这次 IO 就用写法二。
改这段代码或升级依赖。 全仓库只有 fresh.test.js 和 stale.test.js 这两个文件、共 4 个用例读 ctx.fresh,覆盖了方法、非 2xx、ETag 匹配和不匹配。If-Modified-Since、状态码已是 304、HEAD、no-cache 这几种情况下 fresh 的结果,本仓库都没有测试。package.json 写的是 "fresh": "~0.5.2",只接受 0.5.x 的补丁版本。要改这段,或者把 fresh 换成更新的大版本,先把上面这些场景补成测试。
佐证
测试
__tests__/request/fresh.test.js:8 非 GET / HEAD 返回 false
__tests__/request/fresh.test.js:16 非 2xx 时即使 ETag 匹配也返回 false
__tests__/request/fresh.test.js:28 / :39 2xx 下 ETag 匹配 / 不匹配
__tests__/request/stale.test.js:8 stale 是 fresh 的反面
__tests__/application/respond.test.js:319 status=304 不发正文、不带 Content-Type;:436 304 加显式 null body
__tests__/response/status.test.js:115 设 304 时去掉 Content-* 头(共用 :65、:89 两个用例,覆盖“先设 body 后设 304”和反过来两种顺序)
__tests__/application/respond.test.js:1071 先 304 再改回 200,按 200 发送
提交
143d8f7 2020-05-15 #1225 把 == 改成 ===,可见历史里这段唯一的逻辑改动;e9494b5 2021-08-17 只是代码风格调整
af0547d 2025-03-17 #1859 set() 不再把值转成字符串,“用 ctx.set 设数字 ETag”的坑由此而来
History.md:313:Koa 2.4.0(2017-11-06)起依赖 fresh@^0.5.2,之后一直没有升级
本仓库是浅克隆,最早的提交是 b7fc526(2019-06-10),这段代码最初是怎么来的,在可见历史里查不到
交接时实测(真实 HTTP 请求,Node 24.19;“外层判断”指写法一的中间件)
场景 请求条件头 ctx.fresh 响应
A 外层判断;内层设 body、ctx.etag = 'v1'、Cache-Control If-None-Match: "v1"true 304,保留 ETag 和 Cache-Control,没有 Content-Type / Length
B 同 A,但没有外层判断 同上 没人读 200 + 完整正文
C 设 body 之前判断(此时状态码 404) 同上 false 200 + 完整正文
D 写法二:先 ctx.status = 200 同上 true 304
E POST 同上 false 200
F HEAD 同上 true 304
G 状态码 404 同上 false 404 + 正文
H 强制刷新 同上 + Cache-Control: no-cache false 200
I / J 普通刷新 / 旧式头 同上 + max-age=0 / Pragma: no-cache true 304
K 没有设 ETag If-None-Match: *true 304
L ETag 匹配,没设 Last-Modified "v1" + If-Modified-Sincefalse 200
N 响应 ETag 为 W/"v1" "v1"true 304
P ctx.set('ETag', 123)123false 200
Q ctx.etag = 123"123"true 304
R Last-Modified 比 IMS 晚 0.5 秒 If-Modified-Sincetrue 304
S Last-Modified 比 IMS 晚 1 秒 同上 false 200
U 设 304 之后再读一次 "v1"true 304
V body 是流 "v1"true 304,流已被 destroy