交接文档 · koa/ 仓库

Koa 代码交接手册

写给接手 koa/ 仓库的同事。第 1、2 章讲各文件怎么配合、一个请求从进来到响应出去经过哪些代码;第 3 章逐处讲 9 段最容易改出问题的代码;第 4 章是交接时实际跑出来的几个意外行为;第 5 章是每次改动前过一遍的清单。页面里的代码片段由脚本直接从仓库读出,文件名和行号对应下面的基准提交。

版本
koa 3.3.0
基准提交
7c6bfe7 · 2026-11-14
源码
lib/ 7 个文件,2,126 行
测试
73 个文件,513 个用例
覆盖率
行 99.9% · 分支 98.75%
Node
engines ≥ 18;CI 跑 22 / 24 / 26
上手三步。 npm ci 装依赖(会自动跑 prepare 生成 dist/koa.mjs)→ npm test(Node 自带测试运行器)→ npm run lint(standard 风格)。如果装依赖时加了 --ignore-scripts,要先手动 npm run build,否则 __tests__/load-with-esm.test.js 会因找不到 dist/koa.mjs 失败。

1模块图与文件分工

lib/ 下只有 7 个文件。application.js 负责把请求接进来、把结果写出去;ctx、ctx.request、ctx.response 三个对象各自来自一个原型文件。

Node http.Server handler(req, res) lib/application.js 366 行 class Application extends EventEmitter use() · callback() · handleRequest() · createContext() · onerror() 模块级 respond(ctx):把 ctx 写回 res;加载时给 HttpError 装 instanceof 补丁 依赖 koa-compose · http-errors · statuses · on-finished ctx.request ctx ctx.response lib/request.js 764 行 原型对象,只读解析 req url · path · query · search host · protocol · ip · ips(看 proxy) accepts* · is · fresh · get accepts · type-is · fresh · parseurl content-type lib/context.js 254 行 ctx 的原型 自有:throw · assert · onerror · cookies 其余 47 项用 delegates 转发 inspect · toJSON delegates · http-assert · cookies http-errors · statuses lib/response.js 674 行 原型对象,写 res 的头和状态 body · status · type · length set · append · remove · vary redirect · back · attachment mime-types · content-disposition · vary destroy · on-finished · encodeurl … 委托 29 项 委托 18 项 search-params.js query 对象 ↔ 查询串(39 行) only.js 挑字段给 toJSON 用,三处共用 is-stream.js 判断 Node 流;respond() 也用
实线箭头上的名字是 createContext() 为每个请求创建的对象,它们的原型分别来自三个文件。虚线是 context.js 底部用 delegates 登记的转发:ctx.path 实际读 ctx.request.path,ctx.body = x 实际写 ctx.response.body。request 和 response 之间还互相持有引用(request.response / response.request),例如 request.fresh 要读响应头,response.redirect 要调 ctx.accepts。
文件行数职责谁在用
lib/application.js366入口(package.json 的 main)。Application 类保存配置和中间件数组,生成给 Node 用的请求处理函数;模块级函数 respond() 把 ctx 写回 res;文件末尾额外导出 createHttpError / HttpError / isHttpError。使用者;dist/koa.mjs(构建生成的 ESM 包装)
lib/context.js254ctx 的原型。自己只实现 inspect / toJSON / assert / throw / onerror / cookies,其余 47 个属性和方法转给 request(29 项)和 response(18 项)。application.js
lib/request.js764request 的原型。对 req(IncomingMessage)的解析:URL 各部分、query、主机和协议、客户端 IP、内容协商。app.proxy 为真时信任 X-Forwarded-*。application.js;context.js 委托
lib/response.js674response 的原型。body / status / type / length 的 setter 会连带修改状态码和响应头;set / append / remove 封装 res.setHeader。application.js;context.js 委托
lib/search-params.js39基于 URLSearchParams 的 parse / stringify,替代 Node 的 querystring。request.js
lib/is-stream.js20判断 Node 流,也接受鸭子类型的自定义流。文件里有一条“换成第三方库”的 TODO。application.js、response.js
lib/only.js9从对象挑出非空字段,给各处 toJSON() 用。application.js、request.js、response.js

三层原型链

每个请求拿到的 ctx 不是新建的类实例,而是用 Object.create 叠出来的三层原型链。改哪一层,影响范围不同。

层何时创建ctx 这一列改它会影响
模块原型require 时一次lib/context.js 导出的对象进程里所有 Koa 实例
应用级new Koa() 时app.context = Object.create(context)(application.js:104)这个应用的所有请求。插件常往 app.context 上挂东西
请求级每个请求ctx = Object.create(app.context)(application.js:236)只有这一个请求

request、response 两列结构相同。下面是每个请求都会执行的装配代码,三组对象互相挂引用,originalUrl 在这里定格为请求进来时的 req.url,之后改写 URL 也不会变(见 R5)。

lib/application.js:234–250每个请求的装配
234  createContext (req, res) {235    /** @type {Context} */236    const context = Object.create(this.context)237    /** @type {KoaRequest} */238    const request = (context.request = Object.create(this.request))239    /** @type {KoaResponse} */240    const response = (context.response = Object.create(this.response))241    context.app = request.app = response.app = this242    context.req = request.req = response.req = req243    context.res = request.res = response.res = res244    request.ctx = response.ctx = context245    request.response = response246    response.request = request247    context.originalUrl = request.originalUrl = req.url248    context.state = {}249    return context250  }

委托列表在 context.js 末尾。在 request.js 或 response.js 里加了新属性,不在这里登记,ctx.xxx 就拿不到。登记后还要补 docs/api/context.md 的别名列表(提交 b21f195 就是在补漏)。

lib/context.js:201–220response 委托(request 委托在 225–254 行)
201delegate(proto, 'response')202  .method('attachment')203  .method('redirect')204  .method('remove')205  .method('vary')206  .method('has')207  .method('set')208  .method('append')209  .method('flushHeaders')210  .method('back')211  .access('status')212  .access('message')213  .access('body')214  .access('length')215  .access('type')216  .access('lastModified')217  .access('etag')218  .getter('headerSent')219  .getter('writable')220 

2一个请求的完整路径

正常路径从上往下走 7 步;任何一步出错都汇到右侧的 ctx.onerror。

① listen() → callback() application.js:134 · 188 启动时执行一次:compose(middleware);此刻没有 error 监听就挂上 app.onerror ② handleRequest(req, res) application.js:193 · 234 每个请求一次。createContext() 从三份原型各建一个对象,state = {} ③ ctxStorage.run(ctx, …) application.js:198 可选:开启 asyncLocalStorage 才有,之后 app.currentContext 可用 ④ app.handleRequest(ctx, fn) application.js:219 res.statusCode = 404;onFinished(res, ctx.onerror) 监听响应异常结束 ⑤ fn(ctx):中间件洋葱 koa-compose 按 use() 顺序进入,await next() 返回后逆序退出;中间件改 body / status / 头 .then ⑥ respond(ctx) application.js:289 按优先级只走一个分支(R2 有完整顺序表) ⑦ res.end(body) 或 Stream.pipeline(stream, res) :304–357 响应结束;body 是流时,响应结束后流被 destroy ④ ⑤ ⑦ ctx.onerror(err) context.js:106 来源:④ socket 出错 ⑤ 中间件 reject    ⑦ pipeline 出错(有 error 监听时) 头已发出:只 emit,不碰响应 否则清空头 → err.headers → 文本错误页 app.emit('error', err, ctx) 你注册的 error 监听器在这里收到 app.onerror(err) application.js:259 默认监听器:打印 stack 404、expose 为真、app.silent 时不打印
③ 用虚线框表示只在开启 asyncLocalStorage 时存在。红线是出错路径:onFinished 在 socket 出错或响应异常结束时回调;中间件链 reject 走 .catch;流 body 在写出过程中出错由 Stream.pipeline 的回调上报。三条路径最后都进 ctx.onerror。

① 启动:callback() 只跑一次

app.listen() 只是 http.createServer(app.callback()).listen() 的简写。中间件组合和默认错误监听都在 callback() 里一次性决定,之后每个请求只执行内层的 handleRequest。

lib/application.js:188–204启动时执行一次
188  callback () {189    const fn = this.compose(this.middleware)190 191    if (!this.listenerCount('error')) this.on('error', this.onerror)192 193    const handleRequest = (req, res) => {194      const ctx = this.createContext(req, res)195      if (!this.ctxStorage) {196        return this.handleRequest(ctx, fn)197      }198      return this.ctxStorage.run(ctx, async () => {199        return await this.handleRequest(ctx, fn)200      })201    }202 203    return handleRequest204  }

②–④ 建 ctx,挂上兜底

createContext() 的代码见第 1 章。app.handleRequest 先把状态码设成 404,所以没有中间件设置 body 时客户端收到的是 404 Not Found。onFinished 和 .catch 都指向 ctx.onerror,这是 Koa 唯一的错误出口。

lib/application.js:219–226每个请求的主流程
219  handleRequest (ctx, fnMiddleware) {220    const res = ctx.res221    res.statusCode = 404222    const onerror = (err) => ctx.onerror(err)223    const handleResponse = () => respond(ctx)224    onFinished(res, onerror)225    return fnMiddleware(ctx).then(handleResponse).catch(onerror)226  }

⑤ 中间件洋葱

组合逻辑在依赖 koa-compose@4 里(不在本仓库)。dispatch(i) 调第 i 个中间件并把 dispatch(i + 1) 作为 next 传进去;同一个中间件调两次 next() 会得到 next() called multiple times 错误。中间件里对 ctx.body、ctx.status、ctx.set() 的每次赋值都会立刻改 res 上的状态码和头(见 R3),真正写出正文要等到 ⑥。可以通过 new Koa({ compose }) 换掉组合函数(__tests__/application/compose.test.js)。

⑥–⑦ 写出与出错

respond() 的分支顺序见 R2,错误响应的生成见 R4。设置 ctx.respond = false 可以完全跳过 ⑥,由中间件自己操作 ctx.res;docs/api/context.md 明确写了这种用法不受支持。

3最容易改出问题的代码

挑选标准:一改就牵动所有请求的、历史上反复修过的、带安全修复的。按“改坏后影响多大”排序。R9 是为 ETag / 304 缓存协商补的一节,侧重怎么用。每处都附了锁住这段行为的测试和相关提交,改之前先读一遍。

编号位置主要风险影响面最近改动
R1application.js:25–43加载 koa 就改写了共享类的 instanceof进程级2026-11-01
R2application.js:289–358分支顺序就是优先级;流处理关系到内存泄漏每个响应2025-10-22
R3response.js:148–245一个 setter 同时改状态码、类型、长度和旧流每次给 body 赋值2026-09-19
R4context.js:106–168清空响应头再生成错误页;不能在这里再抛错每个错误响应2026-10-09
R5request.js:253–515信任代理头;ReDoS 和 Host 伪造修复都在这proxy: true 时 · 安全2026-11-14
R6request.js:174–217、search-params.js用户输入的键直接变成对象属性读写 ctx.query · 安全2026-10-27
R7response.js:315–381开放重定向、内容嗅探修复redirect / back / attachment · 安全2025-10-18
R8application.js:92–211选项默认值、默认错误日志、AsyncLocalStorage应用启动2026-11-14
R9request.js:329–355只做判断,不会自动回 304;判断时机和验证器写法决定结果用 ETag / 304 的路由2021-08-17
R1

HttpError 的 instanceof 补丁

lib/application.js:25–43进程级副作用3 次提交,2026-09 至 11 月

文件顶部这段代码在 require('koa') 时就执行,改写的是 node_modules 里共享的 http-errors 类。

lib/application.js:25–43模块加载时执行
25function isHttpErrorLike (err) {26  if (!err || typeof err !== 'object') return false27  if (!(err instanceof Error)) return false28  if (typeof err.expose !== 'boolean') return false29  if (typeof err.statusCode !== 'number') return false30 31  const hasMatchingStatusCode = err.status === err.statusCode32  return hasMatchingStatusCode33}34 35Object.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 true40    if (this !== createHttpError.HttpError) return false41    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。

R2

respond():把 ctx 写回 res

lib/application.js:289–358每个响应与 R3 必须同步改

中间件跑完后唯一的写出点。分支按顺序判断,先命中先返回。

lib/application.js:289–358中间件链 resolve 后调用
289function respond (ctx) {290  // allow bypassing koa291  if (ctx.respond === false) return292 293  const res = ctx.res294 295  if (!ctx.writable) return res.end()296 297  let body = ctx.body298  const code = ctx.status299 300  // ignore body301  if (statuses.empty[code]) {302    // strip headers303    ctx.body = null304    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 body316  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 = 0321      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  // responses336 337  if (Buffer.isBuffer(body)) return res.end(body)338  if (typeof body === 'string') return res.end(body)339 340  let stream = null341  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: json353  body = JSON.stringify(body)354  if (!res.headersSent) {355    ctx.length = Buffer.byteLength(body)356  }357  res.end(body)358}

它在做什么

顺序条件行为行
1ctx.respond === false什么都不做,使用者自己写 ctx.res291
2!ctx.writable(已结束或 socket 不可写)res.end() 收尾295
3状态码是 204 / 205 / 304清掉 body,空响应301–305
4HEAD 请求头还没发且没有 Content-Length 时补上长度,不发正文307–313
5body 为 null / undefined显式 null:Content-Length: 0;否则正文用状态文案(HTTP/2 只用数字)316–333
6Buffer 或字符串res.end(body)337–338
7Blob / ReadableStream / Response / Node 流转成 Node 可读流,Stream.pipeline 到 res340–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正文
没有中间件404text/plain · 9Not Found
ctx.status = 400,不给 body400text/plain · 11Bad Request
ctx.body = null204无空
ctx.body = null; ctx.status = 200200无 · 0空
HEAD 请求,ctx.body = 'hello'200text/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 stream156        if (!isStream(val)) {157          destroy(original)158        }159      }160    }161 162    // no content163 164    if (val == null) {165      if (!statuses.empty[this.status]) {166        if (this.type === 'application/json') {167          this._body = 'null'168          return169        }170        this.status = 204171      }172      if (val === null) this._explicitNullBody = true173      this.remove('Content-Type')174      this.remove('Content-Length')175      this.remove('Transfer-Encoding')176      cleanupPreviousStream()177      return178    }179 180    // set the status181    if (!this._explicitStatus) this.status = 200
lib/response.js:202–245后半:流、Web 类型与 JSON
202    // stream203    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      return212    }213 214    // ReadableStream215    if (val instanceof ReadableStream) {216      if (setType) this.type = 'bin'217      cleanupPreviousStream()218      return219    }220 221    // blob222    if (val instanceof Blob) {223      if (setType) this.type = val.type || 'bin'224      this.length = val.size225      cleanupPreviousStream()226      return227    }228 229    // Response230    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      return239    }240 241    // json242    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–106status setter
97  set status (code) {98    if (this.headerSent) return99 100    assert(Number.isInteger(code), 'status code must be a number')101    assert(code >= 100 && code <= 999, `invalid status code: ${code}`)102    this._explicitStatus = true103    this.res.statusCode = code104    if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses.message[code]105    if (this.body && statuses.empty[code]) this.body = null106  },

它在做什么

  • 状态码:没显式设过状态(_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)
R4

ctx.onerror 与响应头写入

lib/context.js:106–168lib/response.js:24–35, 550–559每个错误响应

所有错误的出口。它自己出错就没有下一层兜底了。

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) return111 112    // When dealing with cross-globals a normal `instanceof` check doesn't work properly.113    // See https://github.com/koajs/koa/issues/1466114    // 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 = false121    if (this.headerSent || !this.writable) {122      headerSent = err.headerSent = true123    }124 125    // delegate126    this.app.emit('error', err, this)127 128    // nothing we can do here other129    // than delegate to the app-level130    // handler and log.131    if (headerSent) {132      return133    }134 135    const { res } = this136 137    // first unset all headers138    /* istanbul ignore else */139    if (typeof res.getHeaderNames === 'function') {140      res.getHeaderNames().forEach(name => res.removeHeader(name))141    } else {142      res._headers = {} // Node < 7.7143    }144 145    // then set those specified146    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) return151      this.set(name, headers[name])152    })153 154    // force text/plain155    this.type = 'text'156 157    let statusCode = err.status || err.statusCode158 159    // default to 500160    if (typeof statusCode !== 'number' || !statuses.message[statusCode]) statusCode = 500161 162    // respond163    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  },

它在做什么

  1. 非 Error 的值包成 Error(115–118 行)。同时用 Object.prototype.toString 判断,是为了认出别的 realm(vm、jest)里创建的 Error(#1466)。
  2. 响应头已经发出:标记 err.headerSent,只 emit error,然后返回。
  3. 否则:清空所有已设的响应头 → 写入 err.headers(跳过 Content-Type / Content-Length)→ 强制 text/plain。
  4. 状态码取 err.status || err.statusCode,必须是 statuses 认识的数字,否则 500。
  5. 正文: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–35Content-Type / Length 只能有一个值
24function isSingleValueHeader (field) {25  const name = field.toLowerCase()26  return name === 'content-type' || name === 'content-length'27}28 29function 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) return552 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 · nopenope
throw new Error('secret db detail')500 · Internal Server Errorsecret db detail
抛出 status = 999 的错误500 · Internal Server Errorx
先 ctx.set('X-A', '1'),再抛带 headers: { 'X-B': '2', 'Content-Type': 'text/html' } 的 400400 · 无 X-A,有 X-B,类型仍是 text/plainbad
ctx.set('Content-Type', ['a/b', 'c/d'])500 · Internal Server ErrorContent-Type must contain exactly one value
R5

信任代理时的主机、协议与 IP 解析

lib/request.js:253–295, 422–484, 502–515proxy: true 时 · 安全近一个月改了 4 次

这几个 getter 读的是客户端可以伪造的请求头,历史上有 ReDoS 和 Host 伪造两个安全修复,最近又连续修了 4 个边界值。

lib/request.js:253–295host 与 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 hostname276   * and support X-Forwarded-Host when a277   * proxy is enabled.278   *279   * @return {String} hostname280   * @api public281   */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 // IPv6291      return host.split(':', 1)[0]292    } catch {293      return ''294    }295  },
lib/request.js:422–427protocol
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–484ips 与 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 address468   * When `app.proxy` is `true`, parse469   * the "X-Forwarded-For" ip address list and return the first one470   *471   * @return {String}472   * @api public473   */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–515subdomains
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所有逗号切分都走这里
762function 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-12GHSA-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-01X-Forwarded-Proto: HTTPS 时 ctx.secure 为假,secure cookie 被拒。改为转小写。
b7ead6f2026-11-01IPv6 hostname 原来借 this.URL 解析,absolute-form 请求下会拿到 URL 里的另一个主机。改为直接解析 host,并拒绝含 / ? # \ 和空白的值。
2ad36172026-11-14api.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–217lib/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} obj184   * @api public185   */186 187  set query (obj) {188    this.querystring = sp.stringify(obj)189  },
lib/search-params.js:1–39全文
1const URLSearchParams = require('url').URLSearchParams2 3module.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: true35      })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。

R7

redirect、back() 与 attachment 的安全修复

lib/response.js:315–381安全2 个 GHSA

代码短,但每一行判断都对应一次漏洞修复。看起来“可以简化”的地方,多半就是修复本身。

lib/response.js:315–381redirect / back / attachment
315  redirect (url) {316    if (/^https?:\/\//i.test(url)) {317      // formatting url again avoid security escapes318      url = new URL(url).toString()319    }320    this.set('Location', encodeUrl(url))321 322    // status323    if (!statuses.redirect[this.status]) this.status = 302324 325    // html326    if (this.ctx.accepts('html')) {327      url = escape(url)328      this.type = 'text/html; charset=utf-8'329      this.body = `Redirecting to ${url}.`330      return331    }332 333    // text334    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 public349   */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 origin355      const url = new URL(referrer, this.ctx.href)356      if (url.host === this.ctx.host) {357        this.redirect(referrer)358        return359      }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 public374   */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 || false96    const subdomainOffset = options.subdomainOffset97    this.subdomainOffset = subdomainOffset === 0 ? 0 : subdomainOffset || 298    this.proxyIpHeader = options.proxyIpHeader || 'X-Forwarded-For'99    this.maxIpsCount = options.maxIpsCount || 0100    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 = null115        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–69getAsyncLocalStorage
64function 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–355Koa 不会自动回 304依赖 fresh@0.5.2

ctx.fresh 只回答一个问题:请求带来的条件头和响应上已经设好的 ETag / Last-Modified 是否吻合。要不要回 304、什么时候回,都由你的代码决定。判断得太早,或者验证器的写法不对,它就一直返回 false,缓存不会生效,也不报任何错。

lib/request.js:329–355fresh 与 stale
329  get fresh () {330    const method = this.method331    const s = this.ctx.status332 333    // GET or HEAD for weak freshness validation only334    if (method !== 'GET' && method !== 'HEAD') return false335 336    // 2xx or 304 as per rfc2616 14.26337    if ((s >= 200 && s < 300) || s === 304) {338      return fresh(this.header, this.response.header)339    }340 341    return false342  },343 344  /**345   * Check if the request is stale, aka346   * "Last-Modified" and / or the "ETag" for the347   * resource has changed.348   *349   * @return {Boolean}350   * @api public351   */352 353  get stale () {354    return !this.fresh355  },

它什么时候算 fresh

判断分两层:Koa 先看请求方法和状态码,过了这两关再交给 fresh 包比较请求头和响应头。下表按执行顺序排列,任何一步否决就直接返回 false。后 5 步的代码在 node_modules/fresh/index.js(npm ci 后可见,不在仓库里)。

顺序检查不满足时位置
1请求方法是 GET 或 HEADfalserequest.js:334
2此刻的响应状态码是 2xx 或 304falserequest.js:337
3请求带了 If-None-Match 或 If-Modified-Since 至少一个false(无条件请求)fresh:39–41
4请求的 Cache-Control 里没有 no-cachefalse(浏览器强制刷新)fresh:46–49
5有 If-None-Match 且不是 * 时:响应有 ETag,并且列表里有一个与它弱匹配(W/"x" 与 "x" 视为相同)falsefresh:52–72
6有 If-Modified-Since 时:响应有 Last-Modified,且不晚于该时间falsefresh:75–82
7以上都没否决返回 truefresh: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,剩下的由已有代码完成:

  1. status 的 setter 发现 body 有值、304 又属于“不能带正文”的状态,就把 body 置为 null(response.js:105,代码见 R3)。
  2. body 的 setter 走空值分支(response.js:164–178):304 本身就是空状态,所以不会被改成 204;删掉 Content-Type、Content-Length、Transfer-Encoding;原来的 body 是流的话就 destroy 掉。
  3. respond() 第 3 个分支再检查一次空状态,把 body 置 null 后 res.end(),不发正文(下方代码)。在这之后才轮到 HEAD 分支,所以 HEAD 请求的 304 走的是同一条路。
  4. 只删和正文有关的头。ETag、Last-Modified、Cache-Control、Vary 都会保留,客户端要用它们更新缓存(实测 A)。
lib/application.js:300–305respond():304 不发正文
300  // ignore body301  if (statuses.empty[code]) {302    // strip headers303    ctx.body = null304    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–450lastModified 与 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 public428   */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} val444   * @api public445   */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-ControlIf-None-Match: "v1"true304,保留 ETag 和 Cache-Control,没有 Content-Type / Length
B同 A,但没有外层判断同上没人读200 + 完整正文
C设 body 之前判断(此时状态码 404)同上false200 + 完整正文
D写法二:先 ctx.status = 200同上true304
EPOST同上false200
FHEAD同上true304
G状态码 404同上false404 + 正文
H强制刷新同上 + Cache-Control: no-cachefalse200
I / J普通刷新 / 旧式头同上 + max-age=0 / Pragma: no-cachetrue304
K没有设 ETagIf-None-Match: *true304
LETag 匹配,没设 Last-Modified"v1" + If-Modified-Sincefalse200
N响应 ETag 为 W/"v1""v1"true304
Pctx.set('ETag', 123)123false200
Qctx.etag = 123"123"true304
RLast-Modified 比 IMS 晚 0.5 秒If-Modified-Sincetrue304
SLast-Modified 比 IMS 晚 1 秒同上false200
U设 304 之后再读一次"v1"true304
Vbody 是流"v1"true304,流已被 destroy

4交接时实测到的现象

在仓库的临时副本里装依赖、跑测试、写小脚本发真实请求得到的结果。原仓库没有改动。下面这些不一定是 bug,但接手的人应该知道。

现象位置建议
流 body 写出过程中出错,app 的 error 事件对同一个错误触发两次application.js:224、:348监控侧去重;若要修,需确认 on-finished 与 pipeline 谁负责上报,并补测试
ctx.type = 'json'; ctx.body = null 且未设状态码时返回 404response.js:166–169业务代码显式设 ctx.status;改行为属于破坏性变更
畸形 Referer 让 ctx.back() 抛错,路由返回 500response.js:355可考虑解析失败时按无 Referer 处理,需评估后单独提 PR
ctx.query 返回缓存对象,修改会被后续读取看到request.js:176–177当作只读使用
ctx.set('ETag', 数字) 后 ctx.fresh 恒为 false;ctx.set('Last-Modified', Date) 发出的不是 HTTP 日期response.js:550–559、request.js:338验证器用 ctx.etag / ctx.lastModified 设置(R9)
If-None-Match 和 If-Modified-Since 同时出现时两个都要满足,与 RFC 7232 第 3.3 节不同node_modules/fresh/index.js:52–82两个验证器同时设,或者只用一个(R9)
依赖里同时存在 http-errors@1.8.1(经 http-assert)和 @2.0.1package.jsonR1 补丁的根源,换掉 http-assert 后可移除补丁
首次全量测试有 1 个用例失败:compose.test.js:9 期望 404 实际 400;单文件重跑 3 次、全量重跑 1 次都通过__tests__/application/compose.test.js:29原因没有查明,遇到可疑失败先重跑一次再排查
c8 报告的未覆盖行:application.js 26–27、29、271;context.js 142–143;request.js 101见左改这些行时自己补用例
engines 写 ≥ 18,CI 只测 22 / 24 / 26package.json、.github/workflows/node.js.yml用到新 API 前确认 18 / 20 是否仍需支持

5改动注意事项清单

每次提 PR 前过一遍。勾选状态只保存在你自己的浏览器里。

动手前

写代码时

提交前